audio: Drop ifdef for macOS versions older than 12.0
[qemu/ar7.git] / block.c
blobc1cc313d2167683ee6699ebb60b65ddf56c7d79b
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
5 * Copyright (c) 2020 Virtuozzo International GmbH.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/dirty-bitmap.h"
31 #include "block/fuse.h"
32 #include "block/nbd.h"
33 #include "block/qdict.h"
34 #include "qemu/error-report.h"
35 #include "block/module_block.h"
36 #include "qemu/main-loop.h"
37 #include "qemu/module.h"
38 #include "qapi/error.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qjson.h"
41 #include "qapi/qmp/qnull.h"
42 #include "qapi/qmp/qstring.h"
43 #include "qapi/qobject-output-visitor.h"
44 #include "qapi/qapi-visit-block-core.h"
45 #include "sysemu/block-backend.h"
46 #include "qemu/notify.h"
47 #include "qemu/option.h"
48 #include "qemu/coroutine.h"
49 #include "block/qapi.h"
50 #include "qemu/timer.h"
51 #include "qemu/cutils.h"
52 #include "qemu/id.h"
53 #include "qemu/range.h"
54 #include "qemu/rcu.h"
55 #include "block/coroutines.h"
57 #ifdef CONFIG_BSD
58 #include <sys/ioctl.h>
59 #include <sys/queue.h>
60 #if defined(HAVE_SYS_DISK_H)
61 #include <sys/disk.h>
62 #endif
63 #endif
65 #ifdef _WIN32
66 #include <windows.h>
67 #endif
69 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
71 /* Protected by BQL */
72 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
73 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
75 /* Protected by BQL */
76 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
79 /* Protected by BQL */
80 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
81 QLIST_HEAD_INITIALIZER(bdrv_drivers);
83 static BlockDriverState *bdrv_open_inherit(const char *filename,
84 const char *reference,
85 QDict *options, int flags,
86 BlockDriverState *parent,
87 const BdrvChildClass *child_class,
88 BdrvChildRole child_role,
89 Error **errp);
91 static bool bdrv_recurse_has_child(BlockDriverState *bs,
92 BlockDriverState *child);
94 static void GRAPH_WRLOCK
95 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs);
97 static void GRAPH_WRLOCK
98 bdrv_remove_child(BdrvChild *child, Transaction *tran);
100 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
101 BlockReopenQueue *queue,
102 Transaction *change_child_tran, Error **errp);
103 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
104 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
106 static bool bdrv_backing_overridden(BlockDriverState *bs);
108 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
109 GHashTable *visited, Transaction *tran,
110 Error **errp);
112 /* If non-zero, use only whitelisted block drivers */
113 static int use_bdrv_whitelist;
115 #ifdef _WIN32
116 static int is_windows_drive_prefix(const char *filename)
118 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
119 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
120 filename[1] == ':');
123 int is_windows_drive(const char *filename)
125 if (is_windows_drive_prefix(filename) &&
126 filename[2] == '\0')
127 return 1;
128 if (strstart(filename, "\\\\.\\", NULL) ||
129 strstart(filename, "//./", NULL))
130 return 1;
131 return 0;
133 #endif
135 size_t bdrv_opt_mem_align(BlockDriverState *bs)
137 if (!bs || !bs->drv) {
138 /* page size or 4k (hdd sector size) should be on the safe side */
139 return MAX(4096, qemu_real_host_page_size());
141 IO_CODE();
143 return bs->bl.opt_mem_alignment;
146 size_t bdrv_min_mem_align(BlockDriverState *bs)
148 if (!bs || !bs->drv) {
149 /* page size or 4k (hdd sector size) should be on the safe side */
150 return MAX(4096, qemu_real_host_page_size());
152 IO_CODE();
154 return bs->bl.min_mem_alignment;
157 /* check if the path starts with "<protocol>:" */
158 int path_has_protocol(const char *path)
160 const char *p;
162 #ifdef _WIN32
163 if (is_windows_drive(path) ||
164 is_windows_drive_prefix(path)) {
165 return 0;
167 p = path + strcspn(path, ":/\\");
168 #else
169 p = path + strcspn(path, ":/");
170 #endif
172 return *p == ':';
175 int path_is_absolute(const char *path)
177 #ifdef _WIN32
178 /* specific case for names like: "\\.\d:" */
179 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
180 return 1;
182 return (*path == '/' || *path == '\\');
183 #else
184 return (*path == '/');
185 #endif
188 /* if filename is absolute, just return its duplicate. Otherwise, build a
189 path to it by considering it is relative to base_path. URL are
190 supported. */
191 char *path_combine(const char *base_path, const char *filename)
193 const char *protocol_stripped = NULL;
194 const char *p, *p1;
195 char *result;
196 int len;
198 if (path_is_absolute(filename)) {
199 return g_strdup(filename);
202 if (path_has_protocol(base_path)) {
203 protocol_stripped = strchr(base_path, ':');
204 if (protocol_stripped) {
205 protocol_stripped++;
208 p = protocol_stripped ?: base_path;
210 p1 = strrchr(base_path, '/');
211 #ifdef _WIN32
213 const char *p2;
214 p2 = strrchr(base_path, '\\');
215 if (!p1 || p2 > p1) {
216 p1 = p2;
219 #endif
220 if (p1) {
221 p1++;
222 } else {
223 p1 = base_path;
225 if (p1 > p) {
226 p = p1;
228 len = p - base_path;
230 result = g_malloc(len + strlen(filename) + 1);
231 memcpy(result, base_path, len);
232 strcpy(result + len, filename);
234 return result;
238 * Helper function for bdrv_parse_filename() implementations to remove optional
239 * protocol prefixes (especially "file:") from a filename and for putting the
240 * stripped filename into the options QDict if there is such a prefix.
242 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
243 QDict *options)
245 if (strstart(filename, prefix, &filename)) {
246 /* Stripping the explicit protocol prefix may result in a protocol
247 * prefix being (wrongly) detected (if the filename contains a colon) */
248 if (path_has_protocol(filename)) {
249 GString *fat_filename;
251 /* This means there is some colon before the first slash; therefore,
252 * this cannot be an absolute path */
253 assert(!path_is_absolute(filename));
255 /* And we can thus fix the protocol detection issue by prefixing it
256 * by "./" */
257 fat_filename = g_string_new("./");
258 g_string_append(fat_filename, filename);
260 assert(!path_has_protocol(fat_filename->str));
262 qdict_put(options, "filename",
263 qstring_from_gstring(fat_filename));
264 } else {
265 /* If no protocol prefix was detected, we can use the shortened
266 * filename as-is */
267 qdict_put_str(options, "filename", filename);
273 /* Returns whether the image file is opened as read-only. Note that this can
274 * return false and writing to the image file is still not possible because the
275 * image is inactivated. */
276 bool bdrv_is_read_only(BlockDriverState *bs)
278 IO_CODE();
279 return !(bs->open_flags & BDRV_O_RDWR);
282 static int GRAPH_RDLOCK
283 bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
284 bool ignore_allow_rdw, Error **errp)
286 IO_CODE();
288 /* Do not set read_only if copy_on_read is enabled */
289 if (bs->copy_on_read && read_only) {
290 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
291 bdrv_get_device_or_node_name(bs));
292 return -EINVAL;
295 /* Do not clear read_only if it is prohibited */
296 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
297 !ignore_allow_rdw)
299 error_setg(errp, "Node '%s' is read only",
300 bdrv_get_device_or_node_name(bs));
301 return -EPERM;
304 return 0;
308 * Called by a driver that can only provide a read-only image.
310 * Returns 0 if the node is already read-only or it could switch the node to
311 * read-only because BDRV_O_AUTO_RDONLY is set.
313 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
314 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
315 * is not NULL, it is used as the error message for the Error object.
317 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
318 Error **errp)
320 int ret = 0;
321 IO_CODE();
323 if (!(bs->open_flags & BDRV_O_RDWR)) {
324 return 0;
326 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
327 goto fail;
330 ret = bdrv_can_set_read_only(bs, true, false, NULL);
331 if (ret < 0) {
332 goto fail;
335 bs->open_flags &= ~BDRV_O_RDWR;
337 return 0;
339 fail:
340 error_setg(errp, "%s", errmsg ?: "Image is read-only");
341 return -EACCES;
345 * If @backing is empty, this function returns NULL without setting
346 * @errp. In all other cases, NULL will only be returned with @errp
347 * set.
349 * Therefore, a return value of NULL without @errp set means that
350 * there is no backing file; if @errp is set, there is one but its
351 * absolute filename cannot be generated.
353 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
354 const char *backing,
355 Error **errp)
357 if (backing[0] == '\0') {
358 return NULL;
359 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
360 return g_strdup(backing);
361 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
362 error_setg(errp, "Cannot use relative backing file names for '%s'",
363 backed);
364 return NULL;
365 } else {
366 return path_combine(backed, backing);
371 * If @filename is empty or NULL, this function returns NULL without
372 * setting @errp. In all other cases, NULL will only be returned with
373 * @errp set.
375 static char * GRAPH_RDLOCK
376 bdrv_make_absolute_filename(BlockDriverState *relative_to,
377 const char *filename, Error **errp)
379 char *dir, *full_name;
381 if (!filename || filename[0] == '\0') {
382 return NULL;
383 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
384 return g_strdup(filename);
387 dir = bdrv_dirname(relative_to, errp);
388 if (!dir) {
389 return NULL;
392 full_name = g_strconcat(dir, filename, NULL);
393 g_free(dir);
394 return full_name;
397 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
399 GLOBAL_STATE_CODE();
400 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
403 void bdrv_register(BlockDriver *bdrv)
405 assert(bdrv->format_name);
406 GLOBAL_STATE_CODE();
407 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
410 BlockDriverState *bdrv_new(void)
412 BlockDriverState *bs;
413 int i;
415 GLOBAL_STATE_CODE();
417 bs = g_new0(BlockDriverState, 1);
418 QLIST_INIT(&bs->dirty_bitmaps);
419 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
420 QLIST_INIT(&bs->op_blockers[i]);
422 qemu_mutex_init(&bs->reqs_lock);
423 qemu_mutex_init(&bs->dirty_bitmap_mutex);
424 bs->refcnt = 1;
425 bs->aio_context = qemu_get_aio_context();
427 qemu_co_queue_init(&bs->flush_queue);
429 qemu_co_mutex_init(&bs->bsc_modify_lock);
430 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
432 for (i = 0; i < bdrv_drain_all_count; i++) {
433 bdrv_drained_begin(bs);
436 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
438 return bs;
441 static BlockDriver *bdrv_do_find_format(const char *format_name)
443 BlockDriver *drv1;
444 GLOBAL_STATE_CODE();
446 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
447 if (!strcmp(drv1->format_name, format_name)) {
448 return drv1;
452 return NULL;
455 BlockDriver *bdrv_find_format(const char *format_name)
457 BlockDriver *drv1;
458 int i;
460 GLOBAL_STATE_CODE();
462 drv1 = bdrv_do_find_format(format_name);
463 if (drv1) {
464 return drv1;
467 /* The driver isn't registered, maybe we need to load a module */
468 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
469 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
470 Error *local_err = NULL;
471 int rv = block_module_load(block_driver_modules[i].library_name,
472 &local_err);
473 if (rv > 0) {
474 return bdrv_do_find_format(format_name);
475 } else if (rv < 0) {
476 error_report_err(local_err);
478 break;
481 return NULL;
484 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
486 static const char *whitelist_rw[] = {
487 CONFIG_BDRV_RW_WHITELIST
488 NULL
490 static const char *whitelist_ro[] = {
491 CONFIG_BDRV_RO_WHITELIST
492 NULL
494 const char **p;
496 if (!whitelist_rw[0] && !whitelist_ro[0]) {
497 return 1; /* no whitelist, anything goes */
500 for (p = whitelist_rw; *p; p++) {
501 if (!strcmp(format_name, *p)) {
502 return 1;
505 if (read_only) {
506 for (p = whitelist_ro; *p; p++) {
507 if (!strcmp(format_name, *p)) {
508 return 1;
512 return 0;
515 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
517 GLOBAL_STATE_CODE();
518 return bdrv_format_is_whitelisted(drv->format_name, read_only);
521 bool bdrv_uses_whitelist(void)
523 return use_bdrv_whitelist;
526 typedef struct CreateCo {
527 BlockDriver *drv;
528 char *filename;
529 QemuOpts *opts;
530 int ret;
531 Error *err;
532 } CreateCo;
534 int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
535 QemuOpts *opts, Error **errp)
537 ERRP_GUARD();
538 int ret;
539 GLOBAL_STATE_CODE();
541 if (!drv->bdrv_co_create_opts) {
542 error_setg(errp, "Driver '%s' does not support image creation",
543 drv->format_name);
544 return -ENOTSUP;
547 ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
548 if (ret < 0 && !*errp) {
549 error_setg_errno(errp, -ret, "Could not create image");
552 return ret;
556 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
557 * least the given @minimum_size.
559 * On success, return @blk's actual length.
560 * Otherwise, return -errno.
562 static int64_t coroutine_fn GRAPH_UNLOCKED
563 create_file_fallback_truncate(BlockBackend *blk, int64_t minimum_size,
564 Error **errp)
566 Error *local_err = NULL;
567 int64_t size;
568 int ret;
570 GLOBAL_STATE_CODE();
572 ret = blk_co_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
573 &local_err);
574 if (ret < 0 && ret != -ENOTSUP) {
575 error_propagate(errp, local_err);
576 return ret;
579 size = blk_co_getlength(blk);
580 if (size < 0) {
581 error_free(local_err);
582 error_setg_errno(errp, -size,
583 "Failed to inquire the new image file's length");
584 return size;
587 if (size < minimum_size) {
588 /* Need to grow the image, but we failed to do that */
589 error_propagate(errp, local_err);
590 return -ENOTSUP;
593 error_free(local_err);
594 local_err = NULL;
596 return size;
600 * Helper function for bdrv_create_file_fallback(): Zero the first
601 * sector to remove any potentially pre-existing image header.
603 static int coroutine_fn
604 create_file_fallback_zero_first_sector(BlockBackend *blk,
605 int64_t current_size,
606 Error **errp)
608 int64_t bytes_to_clear;
609 int ret;
611 GLOBAL_STATE_CODE();
613 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
614 if (bytes_to_clear) {
615 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
616 if (ret < 0) {
617 error_setg_errno(errp, -ret,
618 "Failed to clear the new image's first sector");
619 return ret;
623 return 0;
627 * Simple implementation of bdrv_co_create_opts for protocol drivers
628 * which only support creation via opening a file
629 * (usually existing raw storage device)
631 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
632 const char *filename,
633 QemuOpts *opts,
634 Error **errp)
636 ERRP_GUARD();
637 BlockBackend *blk;
638 QDict *options;
639 int64_t size = 0;
640 char *buf = NULL;
641 PreallocMode prealloc;
642 Error *local_err = NULL;
643 int ret;
645 GLOBAL_STATE_CODE();
647 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
648 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
649 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
650 PREALLOC_MODE_OFF, &local_err);
651 g_free(buf);
652 if (local_err) {
653 error_propagate(errp, local_err);
654 return -EINVAL;
657 if (prealloc != PREALLOC_MODE_OFF) {
658 error_setg(errp, "Unsupported preallocation mode '%s'",
659 PreallocMode_str(prealloc));
660 return -ENOTSUP;
663 options = qdict_new();
664 qdict_put_str(options, "driver", drv->format_name);
666 blk = blk_co_new_open(filename, NULL, options,
667 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
668 if (!blk) {
669 error_prepend(errp, "Protocol driver '%s' does not support creating "
670 "new images, so an existing image must be selected as "
671 "the target; however, opening the given target as an "
672 "existing image failed: ",
673 drv->format_name);
674 return -EINVAL;
677 size = create_file_fallback_truncate(blk, size, errp);
678 if (size < 0) {
679 ret = size;
680 goto out;
683 ret = create_file_fallback_zero_first_sector(blk, size, errp);
684 if (ret < 0) {
685 goto out;
688 ret = 0;
689 out:
690 blk_co_unref(blk);
691 return ret;
694 int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
695 Error **errp)
697 QemuOpts *protocol_opts;
698 BlockDriver *drv;
699 QDict *qdict;
700 int ret;
702 GLOBAL_STATE_CODE();
704 drv = bdrv_find_protocol(filename, true, errp);
705 if (drv == NULL) {
706 return -ENOENT;
709 if (!drv->create_opts) {
710 error_setg(errp, "Driver '%s' does not support image creation",
711 drv->format_name);
712 return -ENOTSUP;
716 * 'opts' contains a QemuOptsList with a combination of format and protocol
717 * default values.
719 * The format properly removes its options, but the default values remain
720 * in 'opts->list'. So if the protocol has options with the same name
721 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
722 * of the format, since for overlapping options, the format wins.
724 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
725 * only the set options, and then convert it back to QemuOpts, using the
726 * create_opts of the protocol. So the new QemuOpts, will contain only the
727 * protocol defaults.
729 qdict = qemu_opts_to_qdict(opts, NULL);
730 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
731 if (protocol_opts == NULL) {
732 ret = -EINVAL;
733 goto out;
736 ret = bdrv_co_create(drv, filename, protocol_opts, errp);
737 out:
738 qemu_opts_del(protocol_opts);
739 qobject_unref(qdict);
740 return ret;
743 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
745 Error *local_err = NULL;
746 int ret;
748 IO_CODE();
749 assert(bs != NULL);
750 assert_bdrv_graph_readable();
752 if (!bs->drv) {
753 error_setg(errp, "Block node '%s' is not opened", bs->filename);
754 return -ENOMEDIUM;
757 if (!bs->drv->bdrv_co_delete_file) {
758 error_setg(errp, "Driver '%s' does not support image deletion",
759 bs->drv->format_name);
760 return -ENOTSUP;
763 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
764 if (ret < 0) {
765 error_propagate(errp, local_err);
768 return ret;
771 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
773 Error *local_err = NULL;
774 int ret;
775 IO_CODE();
777 if (!bs) {
778 return;
781 ret = bdrv_co_delete_file(bs, &local_err);
783 * ENOTSUP will happen if the block driver doesn't support
784 * the 'bdrv_co_delete_file' interface. This is a predictable
785 * scenario and shouldn't be reported back to the user.
787 if (ret == -ENOTSUP) {
788 error_free(local_err);
789 } else if (ret < 0) {
790 error_report_err(local_err);
795 * Try to get @bs's logical and physical block size.
796 * On success, store them in @bsz struct and return 0.
797 * On failure return -errno.
798 * @bs must not be empty.
800 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
802 BlockDriver *drv = bs->drv;
803 BlockDriverState *filtered = bdrv_filter_bs(bs);
804 GLOBAL_STATE_CODE();
806 if (drv && drv->bdrv_probe_blocksizes) {
807 return drv->bdrv_probe_blocksizes(bs, bsz);
808 } else if (filtered) {
809 return bdrv_probe_blocksizes(filtered, bsz);
812 return -ENOTSUP;
816 * Try to get @bs's geometry (cyls, heads, sectors).
817 * On success, store them in @geo struct and return 0.
818 * On failure return -errno.
819 * @bs must not be empty.
821 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
823 BlockDriver *drv = bs->drv;
824 BlockDriverState *filtered;
826 GLOBAL_STATE_CODE();
827 GRAPH_RDLOCK_GUARD_MAINLOOP();
829 if (drv && drv->bdrv_probe_geometry) {
830 return drv->bdrv_probe_geometry(bs, geo);
833 filtered = bdrv_filter_bs(bs);
834 if (filtered) {
835 return bdrv_probe_geometry(filtered, geo);
838 return -ENOTSUP;
842 * Create a uniquely-named empty temporary file.
843 * Return the actual file name used upon success, otherwise NULL.
844 * This string should be freed with g_free() when not needed any longer.
846 * Note: creating a temporary file for the caller to (re)open is
847 * inherently racy. Use g_file_open_tmp() instead whenever practical.
849 char *create_tmp_file(Error **errp)
851 int fd;
852 const char *tmpdir;
853 g_autofree char *filename = NULL;
855 tmpdir = g_get_tmp_dir();
856 #ifndef _WIN32
858 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
860 * This function is used to create temporary disk images (like -snapshot),
861 * so the files can become very large. /tmp is often a tmpfs where as
862 * /var/tmp is usually on a disk, so more appropriate for disk images.
864 if (!g_strcmp0(tmpdir, "/tmp")) {
865 tmpdir = "/var/tmp";
867 #endif
869 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
870 fd = g_mkstemp(filename);
871 if (fd < 0) {
872 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
873 filename);
874 return NULL;
876 close(fd);
878 return g_steal_pointer(&filename);
882 * Detect host devices. By convention, /dev/cdrom[N] is always
883 * recognized as a host CDROM.
885 static BlockDriver *find_hdev_driver(const char *filename)
887 int score_max = 0, score;
888 BlockDriver *drv = NULL, *d;
889 GLOBAL_STATE_CODE();
891 QLIST_FOREACH(d, &bdrv_drivers, list) {
892 if (d->bdrv_probe_device) {
893 score = d->bdrv_probe_device(filename);
894 if (score > score_max) {
895 score_max = score;
896 drv = d;
901 return drv;
904 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
906 BlockDriver *drv1;
907 GLOBAL_STATE_CODE();
909 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
910 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
911 return drv1;
915 return NULL;
918 BlockDriver *bdrv_find_protocol(const char *filename,
919 bool allow_protocol_prefix,
920 Error **errp)
922 BlockDriver *drv1;
923 char protocol[128];
924 int len;
925 const char *p;
926 int i;
928 GLOBAL_STATE_CODE();
931 * XXX(hch): we really should not let host device detection
932 * override an explicit protocol specification, but moving this
933 * later breaks access to device names with colons in them.
934 * Thanks to the brain-dead persistent naming schemes on udev-
935 * based Linux systems those actually are quite common.
937 drv1 = find_hdev_driver(filename);
938 if (drv1) {
939 return drv1;
942 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
943 return &bdrv_file;
946 p = strchr(filename, ':');
947 assert(p != NULL);
948 len = p - filename;
949 if (len > sizeof(protocol) - 1)
950 len = sizeof(protocol) - 1;
951 memcpy(protocol, filename, len);
952 protocol[len] = '\0';
954 drv1 = bdrv_do_find_protocol(protocol);
955 if (drv1) {
956 return drv1;
959 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
960 if (block_driver_modules[i].protocol_name &&
961 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
962 int rv = block_module_load(block_driver_modules[i].library_name, errp);
963 if (rv > 0) {
964 drv1 = bdrv_do_find_protocol(protocol);
965 } else if (rv < 0) {
966 return NULL;
968 break;
972 if (!drv1) {
973 error_setg(errp, "Unknown protocol '%s'", protocol);
975 return drv1;
979 * Guess image format by probing its contents.
980 * This is not a good idea when your image is raw (CVE-2008-2004), but
981 * we do it anyway for backward compatibility.
983 * @buf contains the image's first @buf_size bytes.
984 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
985 * but can be smaller if the image file is smaller)
986 * @filename is its filename.
988 * For all block drivers, call the bdrv_probe() method to get its
989 * probing score.
990 * Return the first block driver with the highest probing score.
992 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
993 const char *filename)
995 int score_max = 0, score;
996 BlockDriver *drv = NULL, *d;
997 IO_CODE();
999 QLIST_FOREACH(d, &bdrv_drivers, list) {
1000 if (d->bdrv_probe) {
1001 score = d->bdrv_probe(buf, buf_size, filename);
1002 if (score > score_max) {
1003 score_max = score;
1004 drv = d;
1009 return drv;
1012 static int find_image_format(BlockBackend *file, const char *filename,
1013 BlockDriver **pdrv, Error **errp)
1015 BlockDriver *drv;
1016 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1017 int ret = 0;
1019 GLOBAL_STATE_CODE();
1021 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1022 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1023 *pdrv = &bdrv_raw;
1024 return ret;
1027 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1028 if (ret < 0) {
1029 error_setg_errno(errp, -ret, "Could not read image for determining its "
1030 "format");
1031 *pdrv = NULL;
1032 return ret;
1035 drv = bdrv_probe_all(buf, sizeof(buf), filename);
1036 if (!drv) {
1037 error_setg(errp, "Could not determine image format: No compatible "
1038 "driver found");
1039 *pdrv = NULL;
1040 return -ENOENT;
1043 *pdrv = drv;
1044 return 0;
1048 * Set the current 'total_sectors' value
1049 * Return 0 on success, -errno on error.
1051 int coroutine_fn bdrv_co_refresh_total_sectors(BlockDriverState *bs,
1052 int64_t hint)
1054 BlockDriver *drv = bs->drv;
1055 IO_CODE();
1056 assert_bdrv_graph_readable();
1058 if (!drv) {
1059 return -ENOMEDIUM;
1062 /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
1063 if (bdrv_is_sg(bs))
1064 return 0;
1066 /* query actual device if possible, otherwise just trust the hint */
1067 if (drv->bdrv_co_getlength) {
1068 int64_t length = drv->bdrv_co_getlength(bs);
1069 if (length < 0) {
1070 return length;
1072 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1075 bs->total_sectors = hint;
1077 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1078 return -EFBIG;
1081 return 0;
1085 * Combines a QDict of new block driver @options with any missing options taken
1086 * from @old_options, so that leaving out an option defaults to its old value.
1088 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1089 QDict *old_options)
1091 GLOBAL_STATE_CODE();
1092 if (bs->drv && bs->drv->bdrv_join_options) {
1093 bs->drv->bdrv_join_options(options, old_options);
1094 } else {
1095 qdict_join(options, old_options, false);
1099 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1100 int open_flags,
1101 Error **errp)
1103 Error *local_err = NULL;
1104 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1105 BlockdevDetectZeroesOptions detect_zeroes =
1106 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1107 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1108 GLOBAL_STATE_CODE();
1109 g_free(value);
1110 if (local_err) {
1111 error_propagate(errp, local_err);
1112 return detect_zeroes;
1115 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1116 !(open_flags & BDRV_O_UNMAP))
1118 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1119 "without setting discard operation to unmap");
1122 return detect_zeroes;
1126 * Set open flags for aio engine
1128 * Return 0 on success, -1 if the engine specified is invalid
1130 int bdrv_parse_aio(const char *mode, int *flags)
1132 if (!strcmp(mode, "threads")) {
1133 /* do nothing, default */
1134 } else if (!strcmp(mode, "native")) {
1135 *flags |= BDRV_O_NATIVE_AIO;
1136 #ifdef CONFIG_LINUX_IO_URING
1137 } else if (!strcmp(mode, "io_uring")) {
1138 *flags |= BDRV_O_IO_URING;
1139 #endif
1140 } else {
1141 return -1;
1144 return 0;
1148 * Set open flags for a given discard mode
1150 * Return 0 on success, -1 if the discard mode was invalid.
1152 int bdrv_parse_discard_flags(const char *mode, int *flags)
1154 *flags &= ~BDRV_O_UNMAP;
1156 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1157 /* do nothing */
1158 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1159 *flags |= BDRV_O_UNMAP;
1160 } else {
1161 return -1;
1164 return 0;
1168 * Set open flags for a given cache mode
1170 * Return 0 on success, -1 if the cache mode was invalid.
1172 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1174 *flags &= ~BDRV_O_CACHE_MASK;
1176 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1177 *writethrough = false;
1178 *flags |= BDRV_O_NOCACHE;
1179 } else if (!strcmp(mode, "directsync")) {
1180 *writethrough = true;
1181 *flags |= BDRV_O_NOCACHE;
1182 } else if (!strcmp(mode, "writeback")) {
1183 *writethrough = false;
1184 } else if (!strcmp(mode, "unsafe")) {
1185 *writethrough = false;
1186 *flags |= BDRV_O_NO_FLUSH;
1187 } else if (!strcmp(mode, "writethrough")) {
1188 *writethrough = true;
1189 } else {
1190 return -1;
1193 return 0;
1196 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1198 BlockDriverState *parent = c->opaque;
1199 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1202 static void GRAPH_RDLOCK bdrv_child_cb_drained_begin(BdrvChild *child)
1204 BlockDriverState *bs = child->opaque;
1205 bdrv_do_drained_begin_quiesce(bs, NULL);
1208 static bool GRAPH_RDLOCK bdrv_child_cb_drained_poll(BdrvChild *child)
1210 BlockDriverState *bs = child->opaque;
1211 return bdrv_drain_poll(bs, NULL, false);
1214 static void GRAPH_RDLOCK bdrv_child_cb_drained_end(BdrvChild *child)
1216 BlockDriverState *bs = child->opaque;
1217 bdrv_drained_end(bs);
1220 static int bdrv_child_cb_inactivate(BdrvChild *child)
1222 BlockDriverState *bs = child->opaque;
1223 GLOBAL_STATE_CODE();
1224 assert(bs->open_flags & BDRV_O_INACTIVE);
1225 return 0;
1228 static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1229 GHashTable *visited, Transaction *tran,
1230 Error **errp)
1232 BlockDriverState *bs = child->opaque;
1233 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
1237 * Returns the options and flags that a temporary snapshot should get, based on
1238 * the originally requested flags (the originally requested image will have
1239 * flags like a backing file)
1241 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1242 int parent_flags, QDict *parent_options)
1244 GLOBAL_STATE_CODE();
1245 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1247 /* For temporary files, unconditional cache=unsafe is fine */
1248 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1249 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1251 /* Copy the read-only and discard options from the parent */
1252 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1253 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1255 /* aio=native doesn't work for cache.direct=off, so disable it for the
1256 * temporary snapshot */
1257 *child_flags &= ~BDRV_O_NATIVE_AIO;
1260 static void GRAPH_WRLOCK bdrv_backing_attach(BdrvChild *c)
1262 BlockDriverState *parent = c->opaque;
1263 BlockDriverState *backing_hd = c->bs;
1265 GLOBAL_STATE_CODE();
1266 assert(!parent->backing_blocker);
1267 error_setg(&parent->backing_blocker,
1268 "node is used as backing hd of '%s'",
1269 bdrv_get_device_or_node_name(parent));
1271 bdrv_refresh_filename(backing_hd);
1273 parent->open_flags &= ~BDRV_O_NO_BACKING;
1275 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1276 /* Otherwise we won't be able to commit or stream */
1277 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1278 parent->backing_blocker);
1279 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1280 parent->backing_blocker);
1282 * We do backup in 3 ways:
1283 * 1. drive backup
1284 * The target bs is new opened, and the source is top BDS
1285 * 2. blockdev backup
1286 * Both the source and the target are top BDSes.
1287 * 3. internal backup(used for block replication)
1288 * Both the source and the target are backing file
1290 * In case 1 and 2, neither the source nor the target is the backing file.
1291 * In case 3, we will block the top BDS, so there is only one block job
1292 * for the top BDS and its backing chain.
1294 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1295 parent->backing_blocker);
1296 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1297 parent->backing_blocker);
1300 static void bdrv_backing_detach(BdrvChild *c)
1302 BlockDriverState *parent = c->opaque;
1304 GLOBAL_STATE_CODE();
1305 assert(parent->backing_blocker);
1306 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1307 error_free(parent->backing_blocker);
1308 parent->backing_blocker = NULL;
1311 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1312 const char *filename,
1313 bool backing_mask_protocol,
1314 Error **errp)
1316 BlockDriverState *parent = c->opaque;
1317 bool read_only = bdrv_is_read_only(parent);
1318 int ret;
1319 const char *format_name;
1320 GLOBAL_STATE_CODE();
1322 if (read_only) {
1323 ret = bdrv_reopen_set_read_only(parent, false, errp);
1324 if (ret < 0) {
1325 return ret;
1329 if (base->drv) {
1331 * If the new base image doesn't have a format driver layer, which we
1332 * detect by the fact that @base is a protocol driver, we record
1333 * 'raw' as the format instead of putting the protocol name as the
1334 * backing format
1336 if (backing_mask_protocol && base->drv->protocol_name) {
1337 format_name = "raw";
1338 } else {
1339 format_name = base->drv->format_name;
1341 } else {
1342 format_name = "";
1345 ret = bdrv_change_backing_file(parent, filename, format_name, false);
1346 if (ret < 0) {
1347 error_setg_errno(errp, -ret, "Could not update backing file link");
1350 if (read_only) {
1351 bdrv_reopen_set_read_only(parent, true, NULL);
1354 return ret;
1358 * Returns the options and flags that a generic child of a BDS should
1359 * get, based on the given options and flags for the parent BDS.
1361 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1362 int *child_flags, QDict *child_options,
1363 int parent_flags, QDict *parent_options)
1365 int flags = parent_flags;
1366 GLOBAL_STATE_CODE();
1369 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1370 * Generally, the question to answer is: Should this child be
1371 * format-probed by default?
1375 * Pure and non-filtered data children of non-format nodes should
1376 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1377 * set). This only affects a very limited set of drivers (namely
1378 * quorum and blkverify when this comment was written).
1379 * Force-clear BDRV_O_PROTOCOL then.
1381 if (!parent_is_format &&
1382 (role & BDRV_CHILD_DATA) &&
1383 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1385 flags &= ~BDRV_O_PROTOCOL;
1389 * All children of format nodes (except for COW children) and all
1390 * metadata children in general should never be format-probed.
1391 * Force-set BDRV_O_PROTOCOL then.
1393 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1394 (role & BDRV_CHILD_METADATA))
1396 flags |= BDRV_O_PROTOCOL;
1400 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1401 * the parent.
1403 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1404 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1405 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1407 if (role & BDRV_CHILD_COW) {
1408 /* backing files are opened read-only by default */
1409 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1410 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1411 } else {
1412 /* Inherit the read-only option from the parent if it's not set */
1413 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1414 qdict_copy_default(child_options, parent_options,
1415 BDRV_OPT_AUTO_READ_ONLY);
1419 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1420 * can default to enable it on lower layers regardless of the
1421 * parent option.
1423 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1425 /* Clear flags that only apply to the top layer */
1426 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1428 if (role & BDRV_CHILD_METADATA) {
1429 flags &= ~BDRV_O_NO_IO;
1431 if (role & BDRV_CHILD_COW) {
1432 flags &= ~BDRV_O_TEMPORARY;
1435 *child_flags = flags;
1438 static void GRAPH_WRLOCK bdrv_child_cb_attach(BdrvChild *child)
1440 BlockDriverState *bs = child->opaque;
1442 assert_bdrv_graph_writable();
1443 QLIST_INSERT_HEAD(&bs->children, child, next);
1444 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1446 * Here we handle filters and block/raw-format.c when it behave like
1447 * filter. They generally have a single PRIMARY child, which is also the
1448 * FILTERED child, and that they may have multiple more children, which
1449 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1450 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1451 * into bs->backing on exceptional cases; and bs->backing will be
1452 * nothing else.
1454 assert(!(child->role & BDRV_CHILD_COW));
1455 if (child->role & BDRV_CHILD_PRIMARY) {
1456 assert(child->role & BDRV_CHILD_FILTERED);
1457 assert(!bs->backing);
1458 assert(!bs->file);
1460 if (bs->drv->filtered_child_is_backing) {
1461 bs->backing = child;
1462 } else {
1463 bs->file = child;
1465 } else {
1466 assert(!(child->role & BDRV_CHILD_FILTERED));
1468 } else if (child->role & BDRV_CHILD_COW) {
1469 assert(bs->drv->supports_backing);
1470 assert(!(child->role & BDRV_CHILD_PRIMARY));
1471 assert(!bs->backing);
1472 bs->backing = child;
1473 bdrv_backing_attach(child);
1474 } else if (child->role & BDRV_CHILD_PRIMARY) {
1475 assert(!bs->file);
1476 bs->file = child;
1480 static void GRAPH_WRLOCK bdrv_child_cb_detach(BdrvChild *child)
1482 BlockDriverState *bs = child->opaque;
1484 if (child->role & BDRV_CHILD_COW) {
1485 bdrv_backing_detach(child);
1488 assert_bdrv_graph_writable();
1489 QLIST_REMOVE(child, next);
1490 if (child == bs->backing) {
1491 assert(child != bs->file);
1492 bs->backing = NULL;
1493 } else if (child == bs->file) {
1494 bs->file = NULL;
1498 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1499 const char *filename,
1500 bool backing_mask_protocol,
1501 Error **errp)
1503 if (c->role & BDRV_CHILD_COW) {
1504 return bdrv_backing_update_filename(c, base, filename,
1505 backing_mask_protocol,
1506 errp);
1508 return 0;
1511 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1513 BlockDriverState *bs = c->opaque;
1514 IO_CODE();
1516 return bdrv_get_aio_context(bs);
1519 const BdrvChildClass child_of_bds = {
1520 .parent_is_bds = true,
1521 .get_parent_desc = bdrv_child_get_parent_desc,
1522 .inherit_options = bdrv_inherited_options,
1523 .drained_begin = bdrv_child_cb_drained_begin,
1524 .drained_poll = bdrv_child_cb_drained_poll,
1525 .drained_end = bdrv_child_cb_drained_end,
1526 .attach = bdrv_child_cb_attach,
1527 .detach = bdrv_child_cb_detach,
1528 .inactivate = bdrv_child_cb_inactivate,
1529 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
1530 .update_filename = bdrv_child_cb_update_filename,
1531 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1534 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1536 IO_CODE();
1537 return c->klass->get_parent_aio_context(c);
1540 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1542 int open_flags = flags;
1543 GLOBAL_STATE_CODE();
1546 * Clear flags that are internal to the block layer before opening the
1547 * image.
1549 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1551 return open_flags;
1554 static void update_flags_from_options(int *flags, QemuOpts *opts)
1556 GLOBAL_STATE_CODE();
1558 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1560 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1561 *flags |= BDRV_O_NO_FLUSH;
1564 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1565 *flags |= BDRV_O_NOCACHE;
1568 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1569 *flags |= BDRV_O_RDWR;
1572 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1573 *flags |= BDRV_O_AUTO_RDONLY;
1577 static void update_options_from_flags(QDict *options, int flags)
1579 GLOBAL_STATE_CODE();
1580 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1581 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1583 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1584 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1585 flags & BDRV_O_NO_FLUSH);
1587 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1588 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1590 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1591 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1592 flags & BDRV_O_AUTO_RDONLY);
1596 static void bdrv_assign_node_name(BlockDriverState *bs,
1597 const char *node_name,
1598 Error **errp)
1600 char *gen_node_name = NULL;
1601 GLOBAL_STATE_CODE();
1603 if (!node_name) {
1604 node_name = gen_node_name = id_generate(ID_BLOCK);
1605 } else if (!id_wellformed(node_name)) {
1607 * Check for empty string or invalid characters, but not if it is
1608 * generated (generated names use characters not available to the user)
1610 error_setg(errp, "Invalid node-name: '%s'", node_name);
1611 return;
1614 /* takes care of avoiding namespaces collisions */
1615 if (blk_by_name(node_name)) {
1616 error_setg(errp, "node-name=%s is conflicting with a device id",
1617 node_name);
1618 goto out;
1621 /* takes care of avoiding duplicates node names */
1622 if (bdrv_find_node(node_name)) {
1623 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1624 goto out;
1627 /* Make sure that the node name isn't truncated */
1628 if (strlen(node_name) >= sizeof(bs->node_name)) {
1629 error_setg(errp, "Node name too long");
1630 goto out;
1633 /* copy node name into the bs and insert it into the graph list */
1634 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1635 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1636 out:
1637 g_free(gen_node_name);
1640 static int no_coroutine_fn GRAPH_UNLOCKED
1641 bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, const char *node_name,
1642 QDict *options, int open_flags, Error **errp)
1644 Error *local_err = NULL;
1645 int i, ret;
1646 GLOBAL_STATE_CODE();
1648 bdrv_assign_node_name(bs, node_name, &local_err);
1649 if (local_err) {
1650 error_propagate(errp, local_err);
1651 return -EINVAL;
1654 bs->drv = drv;
1655 bs->opaque = g_malloc0(drv->instance_size);
1657 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1658 if (drv->bdrv_open) {
1659 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1660 } else {
1661 ret = 0;
1664 if (ret < 0) {
1665 if (local_err) {
1666 error_propagate(errp, local_err);
1667 } else if (bs->filename[0]) {
1668 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1669 } else {
1670 error_setg_errno(errp, -ret, "Could not open image");
1672 goto open_failed;
1675 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1676 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1679 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1680 * drivers that pass read/write requests through to a child the trouble of
1681 * declaring support explicitly.
1683 * Drivers must not propagate this flag accidentally when they initiate I/O
1684 * to a bounce buffer. That case should be rare though.
1686 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1687 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1689 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
1690 if (ret < 0) {
1691 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1692 return ret;
1695 bdrv_graph_rdlock_main_loop();
1696 bdrv_refresh_limits(bs, NULL, &local_err);
1697 bdrv_graph_rdunlock_main_loop();
1699 if (local_err) {
1700 error_propagate(errp, local_err);
1701 return -EINVAL;
1704 assert(bdrv_opt_mem_align(bs) != 0);
1705 assert(bdrv_min_mem_align(bs) != 0);
1706 assert(is_power_of_2(bs->bl.request_alignment));
1708 for (i = 0; i < bs->quiesce_counter; i++) {
1709 if (drv->bdrv_drain_begin) {
1710 drv->bdrv_drain_begin(bs);
1714 return 0;
1715 open_failed:
1716 bs->drv = NULL;
1718 bdrv_graph_wrlock();
1719 if (bs->file != NULL) {
1720 bdrv_unref_child(bs, bs->file);
1721 assert(!bs->file);
1723 bdrv_graph_wrunlock();
1725 g_free(bs->opaque);
1726 bs->opaque = NULL;
1727 return ret;
1731 * Create and open a block node.
1733 * @options is a QDict of options to pass to the block drivers, or NULL for an
1734 * empty set of options. The reference to the QDict belongs to the block layer
1735 * after the call (even on failure), so if the caller intends to reuse the
1736 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1738 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1739 const char *node_name,
1740 QDict *options, int flags,
1741 Error **errp)
1743 BlockDriverState *bs;
1744 int ret;
1746 GLOBAL_STATE_CODE();
1748 bs = bdrv_new();
1749 bs->open_flags = flags;
1750 bs->options = options ?: qdict_new();
1751 bs->explicit_options = qdict_clone_shallow(bs->options);
1752 bs->opaque = NULL;
1754 update_options_from_flags(bs->options, flags);
1756 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1757 if (ret < 0) {
1758 qobject_unref(bs->explicit_options);
1759 bs->explicit_options = NULL;
1760 qobject_unref(bs->options);
1761 bs->options = NULL;
1762 bdrv_unref(bs);
1763 return NULL;
1766 return bs;
1769 /* Create and open a block node. */
1770 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1771 int flags, Error **errp)
1773 GLOBAL_STATE_CODE();
1774 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1777 QemuOptsList bdrv_runtime_opts = {
1778 .name = "bdrv_common",
1779 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1780 .desc = {
1782 .name = "node-name",
1783 .type = QEMU_OPT_STRING,
1784 .help = "Node name of the block device node",
1787 .name = "driver",
1788 .type = QEMU_OPT_STRING,
1789 .help = "Block driver to use for the node",
1792 .name = BDRV_OPT_CACHE_DIRECT,
1793 .type = QEMU_OPT_BOOL,
1794 .help = "Bypass software writeback cache on the host",
1797 .name = BDRV_OPT_CACHE_NO_FLUSH,
1798 .type = QEMU_OPT_BOOL,
1799 .help = "Ignore flush requests",
1802 .name = BDRV_OPT_READ_ONLY,
1803 .type = QEMU_OPT_BOOL,
1804 .help = "Node is opened in read-only mode",
1807 .name = BDRV_OPT_AUTO_READ_ONLY,
1808 .type = QEMU_OPT_BOOL,
1809 .help = "Node can become read-only if opening read-write fails",
1812 .name = "detect-zeroes",
1813 .type = QEMU_OPT_STRING,
1814 .help = "try to optimize zero writes (off, on, unmap)",
1817 .name = BDRV_OPT_DISCARD,
1818 .type = QEMU_OPT_STRING,
1819 .help = "discard operation (ignore/off, unmap/on)",
1822 .name = BDRV_OPT_FORCE_SHARE,
1823 .type = QEMU_OPT_BOOL,
1824 .help = "always accept other writers (default: off)",
1826 { /* end of list */ }
1830 QemuOptsList bdrv_create_opts_simple = {
1831 .name = "simple-create-opts",
1832 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1833 .desc = {
1835 .name = BLOCK_OPT_SIZE,
1836 .type = QEMU_OPT_SIZE,
1837 .help = "Virtual disk size"
1840 .name = BLOCK_OPT_PREALLOC,
1841 .type = QEMU_OPT_STRING,
1842 .help = "Preallocation mode (allowed values: off)"
1844 { /* end of list */ }
1849 * Common part for opening disk images and files
1851 * Removes all processed options from *options.
1853 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1854 QDict *options, Error **errp)
1856 int ret, open_flags;
1857 const char *filename;
1858 const char *driver_name = NULL;
1859 const char *node_name = NULL;
1860 const char *discard;
1861 QemuOpts *opts;
1862 BlockDriver *drv;
1863 Error *local_err = NULL;
1864 bool ro;
1866 GLOBAL_STATE_CODE();
1868 bdrv_graph_rdlock_main_loop();
1869 assert(bs->file == NULL);
1870 assert(options != NULL && bs->options != options);
1871 bdrv_graph_rdunlock_main_loop();
1873 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1874 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1875 ret = -EINVAL;
1876 goto fail_opts;
1879 update_flags_from_options(&bs->open_flags, opts);
1881 driver_name = qemu_opt_get(opts, "driver");
1882 drv = bdrv_find_format(driver_name);
1883 assert(drv != NULL);
1885 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1887 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1888 error_setg(errp,
1889 BDRV_OPT_FORCE_SHARE
1890 "=on can only be used with read-only images");
1891 ret = -EINVAL;
1892 goto fail_opts;
1895 if (file != NULL) {
1896 bdrv_graph_rdlock_main_loop();
1897 bdrv_refresh_filename(blk_bs(file));
1898 bdrv_graph_rdunlock_main_loop();
1900 filename = blk_bs(file)->filename;
1901 } else {
1903 * Caution: while qdict_get_try_str() is fine, getting
1904 * non-string types would require more care. When @options
1905 * come from -blockdev or blockdev_add, its members are typed
1906 * according to the QAPI schema, but when they come from
1907 * -drive, they're all QString.
1909 filename = qdict_get_try_str(options, "filename");
1912 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1913 error_setg(errp, "The '%s' block driver requires a file name",
1914 drv->format_name);
1915 ret = -EINVAL;
1916 goto fail_opts;
1919 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1920 drv->format_name);
1922 ro = bdrv_is_read_only(bs);
1924 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1925 if (!ro && bdrv_is_whitelisted(drv, true)) {
1926 bdrv_graph_rdlock_main_loop();
1927 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1928 bdrv_graph_rdunlock_main_loop();
1929 } else {
1930 ret = -ENOTSUP;
1932 if (ret < 0) {
1933 error_setg(errp,
1934 !ro && bdrv_is_whitelisted(drv, true)
1935 ? "Driver '%s' can only be used for read-only devices"
1936 : "Driver '%s' is not whitelisted",
1937 drv->format_name);
1938 goto fail_opts;
1942 /* bdrv_new() and bdrv_close() make it so */
1943 assert(qatomic_read(&bs->copy_on_read) == 0);
1945 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1946 if (!ro) {
1947 bdrv_enable_copy_on_read(bs);
1948 } else {
1949 error_setg(errp, "Can't use copy-on-read on read-only device");
1950 ret = -EINVAL;
1951 goto fail_opts;
1955 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1956 if (discard != NULL) {
1957 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1958 error_setg(errp, "Invalid discard option");
1959 ret = -EINVAL;
1960 goto fail_opts;
1964 bs->detect_zeroes =
1965 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1966 if (local_err) {
1967 error_propagate(errp, local_err);
1968 ret = -EINVAL;
1969 goto fail_opts;
1972 if (filename != NULL) {
1973 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1974 } else {
1975 bs->filename[0] = '\0';
1977 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1979 /* Open the image, either directly or using a protocol */
1980 open_flags = bdrv_open_flags(bs, bs->open_flags);
1981 node_name = qemu_opt_get(opts, "node-name");
1983 assert(!drv->protocol_name || file == NULL);
1984 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1985 if (ret < 0) {
1986 goto fail_opts;
1989 qemu_opts_del(opts);
1990 return 0;
1992 fail_opts:
1993 qemu_opts_del(opts);
1994 return ret;
1997 static QDict *parse_json_filename(const char *filename, Error **errp)
1999 ERRP_GUARD();
2000 QObject *options_obj;
2001 QDict *options;
2002 int ret;
2003 GLOBAL_STATE_CODE();
2005 ret = strstart(filename, "json:", &filename);
2006 assert(ret);
2008 options_obj = qobject_from_json(filename, errp);
2009 if (!options_obj) {
2010 error_prepend(errp, "Could not parse the JSON options: ");
2011 return NULL;
2014 options = qobject_to(QDict, options_obj);
2015 if (!options) {
2016 qobject_unref(options_obj);
2017 error_setg(errp, "Invalid JSON object given");
2018 return NULL;
2021 qdict_flatten(options);
2023 return options;
2026 static void parse_json_protocol(QDict *options, const char **pfilename,
2027 Error **errp)
2029 QDict *json_options;
2030 Error *local_err = NULL;
2031 GLOBAL_STATE_CODE();
2033 /* Parse json: pseudo-protocol */
2034 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2035 return;
2038 json_options = parse_json_filename(*pfilename, &local_err);
2039 if (local_err) {
2040 error_propagate(errp, local_err);
2041 return;
2044 /* Options given in the filename have lower priority than options
2045 * specified directly */
2046 qdict_join(options, json_options, false);
2047 qobject_unref(json_options);
2048 *pfilename = NULL;
2052 * Fills in default options for opening images and converts the legacy
2053 * filename/flags pair to option QDict entries.
2054 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2055 * block driver has been specified explicitly.
2057 static int bdrv_fill_options(QDict **options, const char *filename,
2058 int *flags, Error **errp)
2060 const char *drvname;
2061 bool protocol = *flags & BDRV_O_PROTOCOL;
2062 bool parse_filename = false;
2063 BlockDriver *drv = NULL;
2064 Error *local_err = NULL;
2066 GLOBAL_STATE_CODE();
2069 * Caution: while qdict_get_try_str() is fine, getting non-string
2070 * types would require more care. When @options come from
2071 * -blockdev or blockdev_add, its members are typed according to
2072 * the QAPI schema, but when they come from -drive, they're all
2073 * QString.
2075 drvname = qdict_get_try_str(*options, "driver");
2076 if (drvname) {
2077 drv = bdrv_find_format(drvname);
2078 if (!drv) {
2079 error_setg(errp, "Unknown driver '%s'", drvname);
2080 return -ENOENT;
2082 /* If the user has explicitly specified the driver, this choice should
2083 * override the BDRV_O_PROTOCOL flag */
2084 protocol = drv->protocol_name;
2087 if (protocol) {
2088 *flags |= BDRV_O_PROTOCOL;
2089 } else {
2090 *flags &= ~BDRV_O_PROTOCOL;
2093 /* Translate cache options from flags into options */
2094 update_options_from_flags(*options, *flags);
2096 /* Fetch the file name from the options QDict if necessary */
2097 if (protocol && filename) {
2098 if (!qdict_haskey(*options, "filename")) {
2099 qdict_put_str(*options, "filename", filename);
2100 parse_filename = true;
2101 } else {
2102 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2103 "the same time");
2104 return -EINVAL;
2108 /* Find the right block driver */
2109 /* See cautionary note on accessing @options above */
2110 filename = qdict_get_try_str(*options, "filename");
2112 if (!drvname && protocol) {
2113 if (filename) {
2114 drv = bdrv_find_protocol(filename, parse_filename, errp);
2115 if (!drv) {
2116 return -EINVAL;
2119 drvname = drv->format_name;
2120 qdict_put_str(*options, "driver", drvname);
2121 } else {
2122 error_setg(errp, "Must specify either driver or file");
2123 return -EINVAL;
2127 assert(drv || !protocol);
2129 /* Driver-specific filename parsing */
2130 if (drv && drv->bdrv_parse_filename && parse_filename) {
2131 drv->bdrv_parse_filename(filename, *options, &local_err);
2132 if (local_err) {
2133 error_propagate(errp, local_err);
2134 return -EINVAL;
2137 if (!drv->bdrv_needs_filename) {
2138 qdict_del(*options, "filename");
2142 return 0;
2145 typedef struct BlockReopenQueueEntry {
2146 bool prepared;
2147 BDRVReopenState state;
2148 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2149 } BlockReopenQueueEntry;
2152 * Return the flags that @bs will have after the reopens in @q have
2153 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2154 * return the current flags.
2156 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2158 BlockReopenQueueEntry *entry;
2160 if (q != NULL) {
2161 QTAILQ_FOREACH(entry, q, entry) {
2162 if (entry->state.bs == bs) {
2163 return entry->state.flags;
2168 return bs->open_flags;
2171 /* Returns whether the image file can be written to after the reopen queue @q
2172 * has been successfully applied, or right now if @q is NULL. */
2173 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2174 BlockReopenQueue *q)
2176 int flags = bdrv_reopen_get_flags(q, bs);
2178 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2182 * Return whether the BDS can be written to. This is not necessarily
2183 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2184 * be written to but do not count as read-only images.
2186 bool bdrv_is_writable(BlockDriverState *bs)
2188 IO_CODE();
2189 return bdrv_is_writable_after_reopen(bs, NULL);
2192 static char *bdrv_child_user_desc(BdrvChild *c)
2194 GLOBAL_STATE_CODE();
2195 return c->klass->get_parent_desc(c);
2199 * Check that @a allows everything that @b needs. @a and @b must reference same
2200 * child node.
2202 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2204 const char *child_bs_name;
2205 g_autofree char *a_user = NULL;
2206 g_autofree char *b_user = NULL;
2207 g_autofree char *perms = NULL;
2209 assert(a->bs);
2210 assert(a->bs == b->bs);
2211 GLOBAL_STATE_CODE();
2213 if ((b->perm & a->shared_perm) == b->perm) {
2214 return true;
2217 child_bs_name = bdrv_get_node_name(b->bs);
2218 a_user = bdrv_child_user_desc(a);
2219 b_user = bdrv_child_user_desc(b);
2220 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2222 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2223 "both required by %s (uses node '%s' as '%s' child) and "
2224 "unshared by %s (uses node '%s' as '%s' child).",
2225 child_bs_name, perms,
2226 b_user, child_bs_name, b->name,
2227 a_user, child_bs_name, a->name);
2229 return false;
2232 static bool GRAPH_RDLOCK
2233 bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2235 BdrvChild *a, *b;
2236 GLOBAL_STATE_CODE();
2239 * During the loop we'll look at each pair twice. That's correct because
2240 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2241 * directions.
2243 QLIST_FOREACH(a, &bs->parents, next_parent) {
2244 QLIST_FOREACH(b, &bs->parents, next_parent) {
2245 if (a == b) {
2246 continue;
2249 if (!bdrv_a_allow_b(a, b, errp)) {
2250 return true;
2255 return false;
2258 static void GRAPH_RDLOCK
2259 bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2260 BdrvChild *c, BdrvChildRole role,
2261 BlockReopenQueue *reopen_queue,
2262 uint64_t parent_perm, uint64_t parent_shared,
2263 uint64_t *nperm, uint64_t *nshared)
2265 assert(bs->drv && bs->drv->bdrv_child_perm);
2266 GLOBAL_STATE_CODE();
2267 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2268 parent_perm, parent_shared,
2269 nperm, nshared);
2270 /* TODO Take force_share from reopen_queue */
2271 if (child_bs && child_bs->force_share) {
2272 *nshared = BLK_PERM_ALL;
2277 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2278 * nodes that are already in the @list, of course) so that final list is
2279 * topologically sorted. Return the result (GSList @list object is updated, so
2280 * don't use old reference after function call).
2282 * On function start @list must be already topologically sorted and for any node
2283 * in the @list the whole subtree of the node must be in the @list as well. The
2284 * simplest way to satisfy this criteria: use only result of
2285 * bdrv_topological_dfs() or NULL as @list parameter.
2287 static GSList * GRAPH_RDLOCK
2288 bdrv_topological_dfs(GSList *list, GHashTable *found, BlockDriverState *bs)
2290 BdrvChild *child;
2291 g_autoptr(GHashTable) local_found = NULL;
2293 GLOBAL_STATE_CODE();
2295 if (!found) {
2296 assert(!list);
2297 found = local_found = g_hash_table_new(NULL, NULL);
2300 if (g_hash_table_contains(found, bs)) {
2301 return list;
2303 g_hash_table_add(found, bs);
2305 QLIST_FOREACH(child, &bs->children, next) {
2306 list = bdrv_topological_dfs(list, found, child->bs);
2309 return g_slist_prepend(list, bs);
2312 typedef struct BdrvChildSetPermState {
2313 BdrvChild *child;
2314 uint64_t old_perm;
2315 uint64_t old_shared_perm;
2316 } BdrvChildSetPermState;
2318 static void bdrv_child_set_perm_abort(void *opaque)
2320 BdrvChildSetPermState *s = opaque;
2322 GLOBAL_STATE_CODE();
2324 s->child->perm = s->old_perm;
2325 s->child->shared_perm = s->old_shared_perm;
2328 static TransactionActionDrv bdrv_child_set_pem_drv = {
2329 .abort = bdrv_child_set_perm_abort,
2330 .clean = g_free,
2333 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2334 uint64_t shared, Transaction *tran)
2336 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2337 GLOBAL_STATE_CODE();
2339 *s = (BdrvChildSetPermState) {
2340 .child = c,
2341 .old_perm = c->perm,
2342 .old_shared_perm = c->shared_perm,
2345 c->perm = perm;
2346 c->shared_perm = shared;
2348 tran_add(tran, &bdrv_child_set_pem_drv, s);
2351 static void GRAPH_RDLOCK bdrv_drv_set_perm_commit(void *opaque)
2353 BlockDriverState *bs = opaque;
2354 uint64_t cumulative_perms, cumulative_shared_perms;
2355 GLOBAL_STATE_CODE();
2357 if (bs->drv->bdrv_set_perm) {
2358 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2359 &cumulative_shared_perms);
2360 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2364 static void GRAPH_RDLOCK bdrv_drv_set_perm_abort(void *opaque)
2366 BlockDriverState *bs = opaque;
2367 GLOBAL_STATE_CODE();
2369 if (bs->drv->bdrv_abort_perm_update) {
2370 bs->drv->bdrv_abort_perm_update(bs);
2374 TransactionActionDrv bdrv_drv_set_perm_drv = {
2375 .abort = bdrv_drv_set_perm_abort,
2376 .commit = bdrv_drv_set_perm_commit,
2380 * After calling this function, the transaction @tran may only be completed
2381 * while holding a reader lock for the graph.
2383 static int GRAPH_RDLOCK
2384 bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared_perm,
2385 Transaction *tran, Error **errp)
2387 GLOBAL_STATE_CODE();
2388 if (!bs->drv) {
2389 return 0;
2392 if (bs->drv->bdrv_check_perm) {
2393 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2394 if (ret < 0) {
2395 return ret;
2399 if (tran) {
2400 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2403 return 0;
2406 typedef struct BdrvReplaceChildState {
2407 BdrvChild *child;
2408 BlockDriverState *old_bs;
2409 } BdrvReplaceChildState;
2411 static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
2413 BdrvReplaceChildState *s = opaque;
2414 GLOBAL_STATE_CODE();
2416 bdrv_schedule_unref(s->old_bs);
2419 static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
2421 BdrvReplaceChildState *s = opaque;
2422 BlockDriverState *new_bs = s->child->bs;
2424 GLOBAL_STATE_CODE();
2425 assert_bdrv_graph_writable();
2427 /* old_bs reference is transparently moved from @s to @s->child */
2428 if (!s->child->bs) {
2430 * The parents were undrained when removing old_bs from the child. New
2431 * requests can't have been made, though, because the child was empty.
2433 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2434 * undraining the parent in the first place. Once this is done, having
2435 * new_bs drained when calling bdrv_replace_child_tran() is not a
2436 * requirement any more.
2438 bdrv_parent_drained_begin_single(s->child);
2439 assert(!bdrv_parent_drained_poll_single(s->child));
2441 assert(s->child->quiesced_parent);
2442 bdrv_replace_child_noperm(s->child, s->old_bs);
2444 bdrv_unref(new_bs);
2447 static TransactionActionDrv bdrv_replace_child_drv = {
2448 .commit = bdrv_replace_child_commit,
2449 .abort = bdrv_replace_child_abort,
2450 .clean = g_free,
2454 * bdrv_replace_child_tran
2456 * Note: real unref of old_bs is done only on commit.
2458 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2459 * kept drained until the transaction is completed.
2461 * After calling this function, the transaction @tran may only be completed
2462 * while holding a writer lock for the graph.
2464 * The function doesn't update permissions, caller is responsible for this.
2466 static void GRAPH_WRLOCK
2467 bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2468 Transaction *tran)
2470 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2472 assert(child->quiesced_parent);
2473 assert(!new_bs || new_bs->quiesce_counter);
2475 *s = (BdrvReplaceChildState) {
2476 .child = child,
2477 .old_bs = child->bs,
2479 tran_add(tran, &bdrv_replace_child_drv, s);
2481 if (new_bs) {
2482 bdrv_ref(new_bs);
2485 bdrv_replace_child_noperm(child, new_bs);
2486 /* old_bs reference is transparently moved from @child to @s */
2490 * Refresh permissions in @bs subtree. The function is intended to be called
2491 * after some graph modification that was done without permission update.
2493 * After calling this function, the transaction @tran may only be completed
2494 * while holding a reader lock for the graph.
2496 static int GRAPH_RDLOCK
2497 bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2498 Transaction *tran, Error **errp)
2500 BlockDriver *drv = bs->drv;
2501 BdrvChild *c;
2502 int ret;
2503 uint64_t cumulative_perms, cumulative_shared_perms;
2504 GLOBAL_STATE_CODE();
2506 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2508 /* Write permissions never work with read-only images */
2509 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2510 !bdrv_is_writable_after_reopen(bs, q))
2512 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2513 error_setg(errp, "Block node is read-only");
2514 } else {
2515 error_setg(errp, "Read-only block node '%s' cannot support "
2516 "read-write users", bdrv_get_node_name(bs));
2519 return -EPERM;
2523 * Unaligned requests will automatically be aligned to bl.request_alignment
2524 * and without RESIZE we can't extend requests to write to space beyond the
2525 * end of the image, so it's required that the image size is aligned.
2527 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2528 !(cumulative_perms & BLK_PERM_RESIZE))
2530 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2531 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2532 "Image size is not a multiple of request "
2533 "alignment");
2534 return -EPERM;
2538 /* Check this node */
2539 if (!drv) {
2540 return 0;
2543 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2544 errp);
2545 if (ret < 0) {
2546 return ret;
2549 /* Drivers that never have children can omit .bdrv_child_perm() */
2550 if (!drv->bdrv_child_perm) {
2551 assert(QLIST_EMPTY(&bs->children));
2552 return 0;
2555 /* Check all children */
2556 QLIST_FOREACH(c, &bs->children, next) {
2557 uint64_t cur_perm, cur_shared;
2559 bdrv_child_perm(bs, c->bs, c, c->role, q,
2560 cumulative_perms, cumulative_shared_perms,
2561 &cur_perm, &cur_shared);
2562 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2565 return 0;
2569 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2570 * a topologically sorted subgraph.
2572 * After calling this function, the transaction @tran may only be completed
2573 * while holding a reader lock for the graph.
2575 static int GRAPH_RDLOCK
2576 bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2577 Error **errp)
2579 int ret;
2580 BlockDriverState *bs;
2581 GLOBAL_STATE_CODE();
2583 for ( ; list; list = list->next) {
2584 bs = list->data;
2586 if (bdrv_parent_perms_conflict(bs, errp)) {
2587 return -EINVAL;
2590 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2591 if (ret < 0) {
2592 return ret;
2596 return 0;
2600 * @list is any list of nodes. List is completed by all subtrees and
2601 * topologically sorted. It's not a problem if some node occurs in the @list
2602 * several times.
2604 * After calling this function, the transaction @tran may only be completed
2605 * while holding a reader lock for the graph.
2607 static int GRAPH_RDLOCK
2608 bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2609 Error **errp)
2611 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2612 g_autoptr(GSList) refresh_list = NULL;
2614 for ( ; list; list = list->next) {
2615 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2618 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2621 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2622 uint64_t *shared_perm)
2624 BdrvChild *c;
2625 uint64_t cumulative_perms = 0;
2626 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2628 GLOBAL_STATE_CODE();
2630 QLIST_FOREACH(c, &bs->parents, next_parent) {
2631 cumulative_perms |= c->perm;
2632 cumulative_shared_perms &= c->shared_perm;
2635 *perm = cumulative_perms;
2636 *shared_perm = cumulative_shared_perms;
2639 char *bdrv_perm_names(uint64_t perm)
2641 struct perm_name {
2642 uint64_t perm;
2643 const char *name;
2644 } permissions[] = {
2645 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2646 { BLK_PERM_WRITE, "write" },
2647 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2648 { BLK_PERM_RESIZE, "resize" },
2649 { 0, NULL }
2652 GString *result = g_string_sized_new(30);
2653 struct perm_name *p;
2655 for (p = permissions; p->name; p++) {
2656 if (perm & p->perm) {
2657 if (result->len > 0) {
2658 g_string_append(result, ", ");
2660 g_string_append(result, p->name);
2664 return g_string_free(result, FALSE);
2669 * @tran is allowed to be NULL. In this case no rollback is possible.
2671 * After calling this function, the transaction @tran may only be completed
2672 * while holding a reader lock for the graph.
2674 static int GRAPH_RDLOCK
2675 bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran, Error **errp)
2677 int ret;
2678 Transaction *local_tran = NULL;
2679 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2680 GLOBAL_STATE_CODE();
2682 if (!tran) {
2683 tran = local_tran = tran_new();
2686 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2688 if (local_tran) {
2689 tran_finalize(local_tran, ret);
2692 return ret;
2695 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2696 Error **errp)
2698 Error *local_err = NULL;
2699 Transaction *tran = tran_new();
2700 int ret;
2702 GLOBAL_STATE_CODE();
2704 bdrv_child_set_perm(c, perm, shared, tran);
2706 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2708 tran_finalize(tran, ret);
2710 if (ret < 0) {
2711 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2712 /* tighten permissions */
2713 error_propagate(errp, local_err);
2714 } else {
2716 * Our caller may intend to only loosen restrictions and
2717 * does not expect this function to fail. Errors are not
2718 * fatal in such a case, so we can just hide them from our
2719 * caller.
2721 error_free(local_err);
2722 ret = 0;
2726 return ret;
2729 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2731 uint64_t parent_perms, parent_shared;
2732 uint64_t perms, shared;
2734 GLOBAL_STATE_CODE();
2736 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2737 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2738 parent_perms, parent_shared, &perms, &shared);
2740 return bdrv_child_try_set_perm(c, perms, shared, errp);
2744 * Default implementation for .bdrv_child_perm() for block filters:
2745 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2746 * filtered child.
2748 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2749 BdrvChildRole role,
2750 BlockReopenQueue *reopen_queue,
2751 uint64_t perm, uint64_t shared,
2752 uint64_t *nperm, uint64_t *nshared)
2754 GLOBAL_STATE_CODE();
2755 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2756 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2759 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2760 BdrvChildRole role,
2761 BlockReopenQueue *reopen_queue,
2762 uint64_t perm, uint64_t shared,
2763 uint64_t *nperm, uint64_t *nshared)
2765 assert(role & BDRV_CHILD_COW);
2766 GLOBAL_STATE_CODE();
2769 * We want consistent read from backing files if the parent needs it.
2770 * No other operations are performed on backing files.
2772 perm &= BLK_PERM_CONSISTENT_READ;
2775 * If the parent can deal with changing data, we're okay with a
2776 * writable and resizable backing file.
2777 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2779 if (shared & BLK_PERM_WRITE) {
2780 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2781 } else {
2782 shared = 0;
2785 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2787 if (bs->open_flags & BDRV_O_INACTIVE) {
2788 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2791 *nperm = perm;
2792 *nshared = shared;
2795 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2796 BdrvChildRole role,
2797 BlockReopenQueue *reopen_queue,
2798 uint64_t perm, uint64_t shared,
2799 uint64_t *nperm, uint64_t *nshared)
2801 int flags;
2803 GLOBAL_STATE_CODE();
2804 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2806 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2809 * Apart from the modifications below, the same permissions are
2810 * forwarded and left alone as for filters
2812 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2813 perm, shared, &perm, &shared);
2815 if (role & BDRV_CHILD_METADATA) {
2816 /* Format drivers may touch metadata even if the guest doesn't write */
2817 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2818 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2822 * bs->file always needs to be consistent because of the
2823 * metadata. We can never allow other users to resize or write
2824 * to it.
2826 if (!(flags & BDRV_O_NO_IO)) {
2827 perm |= BLK_PERM_CONSISTENT_READ;
2829 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2832 if (role & BDRV_CHILD_DATA) {
2834 * Technically, everything in this block is a subset of the
2835 * BDRV_CHILD_METADATA path taken above, and so this could
2836 * be an "else if" branch. However, that is not obvious, and
2837 * this function is not performance critical, therefore we let
2838 * this be an independent "if".
2842 * We cannot allow other users to resize the file because the
2843 * format driver might have some assumptions about the size
2844 * (e.g. because it is stored in metadata, or because the file
2845 * is split into fixed-size data files).
2847 shared &= ~BLK_PERM_RESIZE;
2850 * WRITE_UNCHANGED often cannot be performed as such on the
2851 * data file. For example, the qcow2 driver may still need to
2852 * write copied clusters on copy-on-read.
2854 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2855 perm |= BLK_PERM_WRITE;
2859 * If the data file is written to, the format driver may
2860 * expect to be able to resize it by writing beyond the EOF.
2862 if (perm & BLK_PERM_WRITE) {
2863 perm |= BLK_PERM_RESIZE;
2867 if (bs->open_flags & BDRV_O_INACTIVE) {
2868 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2871 *nperm = perm;
2872 *nshared = shared;
2875 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2876 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2877 uint64_t perm, uint64_t shared,
2878 uint64_t *nperm, uint64_t *nshared)
2880 GLOBAL_STATE_CODE();
2881 if (role & BDRV_CHILD_FILTERED) {
2882 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2883 BDRV_CHILD_COW)));
2884 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2885 perm, shared, nperm, nshared);
2886 } else if (role & BDRV_CHILD_COW) {
2887 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2888 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2889 perm, shared, nperm, nshared);
2890 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2891 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2892 perm, shared, nperm, nshared);
2893 } else {
2894 g_assert_not_reached();
2898 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2900 static const uint64_t permissions[] = {
2901 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2902 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2903 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2904 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2907 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2908 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2910 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2912 return permissions[qapi_perm];
2916 * Replaces the node that a BdrvChild points to without updating permissions.
2918 * If @new_bs is non-NULL, the parent of @child must already be drained through
2919 * @child.
2921 static void GRAPH_WRLOCK
2922 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
2924 BlockDriverState *old_bs = child->bs;
2925 int new_bs_quiesce_counter;
2927 assert(!child->frozen);
2930 * If we want to change the BdrvChild to point to a drained node as its new
2931 * child->bs, we need to make sure that its new parent is drained, too. In
2932 * other words, either child->quiesce_parent must already be true or we must
2933 * be able to set it and keep the parent's quiesce_counter consistent with
2934 * that, but without polling or starting new requests (this function
2935 * guarantees that it doesn't poll, and starting new requests would be
2936 * against the invariants of drain sections).
2938 * To keep things simple, we pick the first option (child->quiesce_parent
2939 * must already be true). We also generalise the rule a bit to make it
2940 * easier to verify in callers and more likely to be covered in test cases:
2941 * The parent must be quiesced through this child even if new_bs isn't
2942 * currently drained.
2944 * The only exception is for callers that always pass new_bs == NULL. In
2945 * this case, we obviously never need to consider the case of a drained
2946 * new_bs, so we can keep the callers simpler by allowing them not to drain
2947 * the parent.
2949 assert(!new_bs || child->quiesced_parent);
2950 assert(old_bs != new_bs);
2951 GLOBAL_STATE_CODE();
2953 if (old_bs && new_bs) {
2954 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2957 if (old_bs) {
2958 if (child->klass->detach) {
2959 child->klass->detach(child);
2961 QLIST_REMOVE(child, next_parent);
2964 child->bs = new_bs;
2966 if (new_bs) {
2967 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2968 if (child->klass->attach) {
2969 child->klass->attach(child);
2974 * If the parent was drained through this BdrvChild previously, but new_bs
2975 * is not drained, allow requests to come in only after the new node has
2976 * been attached.
2978 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2979 if (!new_bs_quiesce_counter && child->quiesced_parent) {
2980 bdrv_parent_drained_end_single(child);
2985 * Free the given @child.
2987 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2988 * unused (i.e. not in a children list).
2990 static void bdrv_child_free(BdrvChild *child)
2992 assert(!child->bs);
2993 GLOBAL_STATE_CODE();
2994 GRAPH_RDLOCK_GUARD_MAINLOOP();
2996 assert(!child->next.le_prev); /* not in children list */
2998 g_free(child->name);
2999 g_free(child);
3002 typedef struct BdrvAttachChildCommonState {
3003 BdrvChild *child;
3004 AioContext *old_parent_ctx;
3005 AioContext *old_child_ctx;
3006 } BdrvAttachChildCommonState;
3008 static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
3010 BdrvAttachChildCommonState *s = opaque;
3011 BlockDriverState *bs = s->child->bs;
3013 GLOBAL_STATE_CODE();
3014 assert_bdrv_graph_writable();
3016 bdrv_replace_child_noperm(s->child, NULL);
3018 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
3019 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
3022 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
3023 Transaction *tran;
3024 GHashTable *visited;
3025 bool ret;
3027 tran = tran_new();
3029 /* No need to visit `child`, because it has been detached already */
3030 visited = g_hash_table_new(NULL, NULL);
3031 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
3032 visited, tran, &error_abort);
3033 g_hash_table_destroy(visited);
3035 /* transaction is supposed to always succeed */
3036 assert(ret == true);
3037 tran_commit(tran);
3040 bdrv_schedule_unref(bs);
3041 bdrv_child_free(s->child);
3044 static TransactionActionDrv bdrv_attach_child_common_drv = {
3045 .abort = bdrv_attach_child_common_abort,
3046 .clean = g_free,
3050 * Common part of attaching bdrv child to bs or to blk or to job
3052 * Function doesn't update permissions, caller is responsible for this.
3054 * After calling this function, the transaction @tran may only be completed
3055 * while holding a writer lock for the graph.
3057 * Returns new created child.
3059 * Both @parent_bs and @child_bs can move to a different AioContext in this
3060 * function.
3062 static BdrvChild * GRAPH_WRLOCK
3063 bdrv_attach_child_common(BlockDriverState *child_bs,
3064 const char *child_name,
3065 const BdrvChildClass *child_class,
3066 BdrvChildRole child_role,
3067 uint64_t perm, uint64_t shared_perm,
3068 void *opaque,
3069 Transaction *tran, Error **errp)
3071 BdrvChild *new_child;
3072 AioContext *parent_ctx;
3073 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3075 assert(child_class->get_parent_desc);
3076 GLOBAL_STATE_CODE();
3078 new_child = g_new(BdrvChild, 1);
3079 *new_child = (BdrvChild) {
3080 .bs = NULL,
3081 .name = g_strdup(child_name),
3082 .klass = child_class,
3083 .role = child_role,
3084 .perm = perm,
3085 .shared_perm = shared_perm,
3086 .opaque = opaque,
3090 * If the AioContexts don't match, first try to move the subtree of
3091 * child_bs into the AioContext of the new parent. If this doesn't work,
3092 * try moving the parent into the AioContext of child_bs instead.
3094 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3095 if (child_ctx != parent_ctx) {
3096 Error *local_err = NULL;
3097 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3098 &local_err);
3100 if (ret < 0 && child_class->change_aio_ctx) {
3101 Transaction *aio_ctx_tran = tran_new();
3102 GHashTable *visited = g_hash_table_new(NULL, NULL);
3103 bool ret_child;
3105 g_hash_table_add(visited, new_child);
3106 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3107 visited, aio_ctx_tran,
3108 NULL);
3109 if (ret_child == true) {
3110 error_free(local_err);
3111 ret = 0;
3113 tran_finalize(aio_ctx_tran, ret_child == true ? 0 : -1);
3114 g_hash_table_destroy(visited);
3117 if (ret < 0) {
3118 error_propagate(errp, local_err);
3119 bdrv_child_free(new_child);
3120 return NULL;
3124 bdrv_ref(child_bs);
3126 * Let every new BdrvChild start with a drained parent. Inserting the child
3127 * in the graph with bdrv_replace_child_noperm() will undrain it if
3128 * @child_bs is not drained.
3130 * The child was only just created and is not yet visible in global state
3131 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3132 * could have sent requests and polling is not necessary.
3134 * Note that this means that the parent isn't fully drained yet, we only
3135 * stop new requests from coming in. This is fine, we don't care about the
3136 * old requests here, they are not for this child. If another place enters a
3137 * drain section for the same parent, but wants it to be fully quiesced, it
3138 * will not run most of the the code in .drained_begin() again (which is not
3139 * a problem, we already did this), but it will still poll until the parent
3140 * is fully quiesced, so it will not be negatively affected either.
3142 bdrv_parent_drained_begin_single(new_child);
3143 bdrv_replace_child_noperm(new_child, child_bs);
3145 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3146 *s = (BdrvAttachChildCommonState) {
3147 .child = new_child,
3148 .old_parent_ctx = parent_ctx,
3149 .old_child_ctx = child_ctx,
3151 tran_add(tran, &bdrv_attach_child_common_drv, s);
3153 return new_child;
3157 * Function doesn't update permissions, caller is responsible for this.
3159 * Both @parent_bs and @child_bs can move to a different AioContext in this
3160 * function.
3162 * After calling this function, the transaction @tran may only be completed
3163 * while holding a writer lock for the graph.
3165 static BdrvChild * GRAPH_WRLOCK
3166 bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3167 BlockDriverState *child_bs,
3168 const char *child_name,
3169 const BdrvChildClass *child_class,
3170 BdrvChildRole child_role,
3171 Transaction *tran,
3172 Error **errp)
3174 uint64_t perm, shared_perm;
3176 assert(parent_bs->drv);
3177 GLOBAL_STATE_CODE();
3179 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3180 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3181 child_bs->node_name, child_name, parent_bs->node_name);
3182 return NULL;
3185 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3186 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3187 perm, shared_perm, &perm, &shared_perm);
3189 return bdrv_attach_child_common(child_bs, child_name, child_class,
3190 child_role, perm, shared_perm, parent_bs,
3191 tran, errp);
3195 * This function steals the reference to child_bs from the caller.
3196 * That reference is later dropped by bdrv_root_unref_child().
3198 * On failure NULL is returned, errp is set and the reference to
3199 * child_bs is also dropped.
3201 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3202 const char *child_name,
3203 const BdrvChildClass *child_class,
3204 BdrvChildRole child_role,
3205 uint64_t perm, uint64_t shared_perm,
3206 void *opaque, Error **errp)
3208 int ret;
3209 BdrvChild *child;
3210 Transaction *tran = tran_new();
3212 GLOBAL_STATE_CODE();
3214 child = bdrv_attach_child_common(child_bs, child_name, child_class,
3215 child_role, perm, shared_perm, opaque,
3216 tran, errp);
3217 if (!child) {
3218 ret = -EINVAL;
3219 goto out;
3222 ret = bdrv_refresh_perms(child_bs, tran, errp);
3224 out:
3225 tran_finalize(tran, ret);
3227 bdrv_schedule_unref(child_bs);
3229 return ret < 0 ? NULL : child;
3233 * This function transfers the reference to child_bs from the caller
3234 * to parent_bs. That reference is later dropped by parent_bs on
3235 * bdrv_close() or if someone calls bdrv_unref_child().
3237 * On failure NULL is returned, errp is set and the reference to
3238 * child_bs is also dropped.
3240 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3241 BlockDriverState *child_bs,
3242 const char *child_name,
3243 const BdrvChildClass *child_class,
3244 BdrvChildRole child_role,
3245 Error **errp)
3247 int ret;
3248 BdrvChild *child;
3249 Transaction *tran = tran_new();
3251 GLOBAL_STATE_CODE();
3253 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3254 child_class, child_role, tran, errp);
3255 if (!child) {
3256 ret = -EINVAL;
3257 goto out;
3260 ret = bdrv_refresh_perms(parent_bs, tran, errp);
3261 if (ret < 0) {
3262 goto out;
3265 out:
3266 tran_finalize(tran, ret);
3268 bdrv_schedule_unref(child_bs);
3270 return ret < 0 ? NULL : child;
3273 /* Callers must ensure that child->frozen is false. */
3274 void bdrv_root_unref_child(BdrvChild *child)
3276 BlockDriverState *child_bs = child->bs;
3278 GLOBAL_STATE_CODE();
3279 bdrv_replace_child_noperm(child, NULL);
3280 bdrv_child_free(child);
3282 if (child_bs) {
3284 * Update permissions for old node. We're just taking a parent away, so
3285 * we're loosening restrictions. Errors of permission update are not
3286 * fatal in this case, ignore them.
3288 bdrv_refresh_perms(child_bs, NULL, NULL);
3291 * When the parent requiring a non-default AioContext is removed, the
3292 * node moves back to the main AioContext
3294 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3295 NULL);
3298 bdrv_schedule_unref(child_bs);
3301 typedef struct BdrvSetInheritsFrom {
3302 BlockDriverState *bs;
3303 BlockDriverState *old_inherits_from;
3304 } BdrvSetInheritsFrom;
3306 static void bdrv_set_inherits_from_abort(void *opaque)
3308 BdrvSetInheritsFrom *s = opaque;
3310 s->bs->inherits_from = s->old_inherits_from;
3313 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3314 .abort = bdrv_set_inherits_from_abort,
3315 .clean = g_free,
3318 /* @tran is allowed to be NULL. In this case no rollback is possible */
3319 static void bdrv_set_inherits_from(BlockDriverState *bs,
3320 BlockDriverState *new_inherits_from,
3321 Transaction *tran)
3323 if (tran) {
3324 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3326 *s = (BdrvSetInheritsFrom) {
3327 .bs = bs,
3328 .old_inherits_from = bs->inherits_from,
3331 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3334 bs->inherits_from = new_inherits_from;
3338 * Clear all inherits_from pointers from children and grandchildren of
3339 * @root that point to @root, where necessary.
3340 * @tran is allowed to be NULL. In this case no rollback is possible
3342 static void GRAPH_WRLOCK
3343 bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3344 Transaction *tran)
3346 BdrvChild *c;
3348 if (child->bs->inherits_from == root) {
3350 * Remove inherits_from only when the last reference between root and
3351 * child->bs goes away.
3353 QLIST_FOREACH(c, &root->children, next) {
3354 if (c != child && c->bs == child->bs) {
3355 break;
3358 if (c == NULL) {
3359 bdrv_set_inherits_from(child->bs, NULL, tran);
3363 QLIST_FOREACH(c, &child->bs->children, next) {
3364 bdrv_unset_inherits_from(root, c, tran);
3368 /* Callers must ensure that child->frozen is false. */
3369 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3371 GLOBAL_STATE_CODE();
3372 if (child == NULL) {
3373 return;
3376 bdrv_unset_inherits_from(parent, child, NULL);
3377 bdrv_root_unref_child(child);
3381 static void GRAPH_RDLOCK
3382 bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3384 BdrvChild *c;
3385 GLOBAL_STATE_CODE();
3386 QLIST_FOREACH(c, &bs->parents, next_parent) {
3387 if (c->klass->change_media) {
3388 c->klass->change_media(c, load);
3393 /* Return true if you can reach parent going through child->inherits_from
3394 * recursively. If parent or child are NULL, return false */
3395 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3396 BlockDriverState *parent)
3398 while (child && child != parent) {
3399 child = child->inherits_from;
3402 return child != NULL;
3406 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3407 * mostly used for COW backing children (role = COW), but also for
3408 * filtered children (role = FILTERED | PRIMARY).
3410 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3412 if (bs->drv && bs->drv->is_filter) {
3413 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3414 } else {
3415 return BDRV_CHILD_COW;
3420 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3421 * callers which don't need their own reference any more must call bdrv_unref().
3423 * If the respective child is already present (i.e. we're detaching a node),
3424 * that child node must be drained.
3426 * Function doesn't update permissions, caller is responsible for this.
3428 * Both @parent_bs and @child_bs can move to a different AioContext in this
3429 * function.
3431 * After calling this function, the transaction @tran may only be completed
3432 * while holding a writer lock for the graph.
3434 static int GRAPH_WRLOCK
3435 bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3436 BlockDriverState *child_bs,
3437 bool is_backing,
3438 Transaction *tran, Error **errp)
3440 bool update_inherits_from =
3441 bdrv_inherits_from_recursive(child_bs, parent_bs);
3442 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3443 BdrvChildRole role;
3445 GLOBAL_STATE_CODE();
3447 if (!parent_bs->drv) {
3449 * Node without drv is an object without a class :/. TODO: finally fix
3450 * qcow2 driver to never clear bs->drv and implement format corruption
3451 * handling in other way.
3453 error_setg(errp, "Node corrupted");
3454 return -EINVAL;
3457 if (child && child->frozen) {
3458 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3459 child->name, parent_bs->node_name, child->bs->node_name);
3460 return -EPERM;
3463 if (is_backing && !parent_bs->drv->is_filter &&
3464 !parent_bs->drv->supports_backing)
3466 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3467 "files", parent_bs->drv->format_name, parent_bs->node_name);
3468 return -EINVAL;
3471 if (parent_bs->drv->is_filter) {
3472 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3473 } else if (is_backing) {
3474 role = BDRV_CHILD_COW;
3475 } else {
3477 * We only can use same role as it is in existing child. We don't have
3478 * infrastructure to determine role of file child in generic way
3480 if (!child) {
3481 error_setg(errp, "Cannot set file child to format node without "
3482 "file child");
3483 return -EINVAL;
3485 role = child->role;
3488 if (child) {
3489 assert(child->bs->quiesce_counter);
3490 bdrv_unset_inherits_from(parent_bs, child, tran);
3491 bdrv_remove_child(child, tran);
3494 if (!child_bs) {
3495 goto out;
3498 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3499 is_backing ? "backing" : "file",
3500 &child_of_bds, role,
3501 tran, errp);
3502 if (!child) {
3503 return -EINVAL;
3508 * If inherits_from pointed recursively to bs then let's update it to
3509 * point directly to bs (else it will become NULL).
3511 if (update_inherits_from) {
3512 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3515 out:
3516 bdrv_refresh_limits(parent_bs, tran, NULL);
3518 return 0;
3522 * Both @bs and @backing_hd can move to a different AioContext in this
3523 * function.
3525 * If a backing child is already present (i.e. we're detaching a node), that
3526 * child node must be drained.
3528 int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3529 BlockDriverState *backing_hd,
3530 Error **errp)
3532 int ret;
3533 Transaction *tran = tran_new();
3535 GLOBAL_STATE_CODE();
3536 assert(bs->quiesce_counter > 0);
3537 if (bs->backing) {
3538 assert(bs->backing->bs->quiesce_counter > 0);
3541 ret = bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3542 if (ret < 0) {
3543 goto out;
3546 ret = bdrv_refresh_perms(bs, tran, errp);
3547 out:
3548 tran_finalize(tran, ret);
3549 return ret;
3552 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3553 Error **errp)
3555 BlockDriverState *drain_bs;
3556 int ret;
3557 GLOBAL_STATE_CODE();
3559 bdrv_graph_rdlock_main_loop();
3560 drain_bs = bs->backing ? bs->backing->bs : bs;
3561 bdrv_graph_rdunlock_main_loop();
3563 bdrv_ref(drain_bs);
3564 bdrv_drained_begin(drain_bs);
3565 bdrv_graph_wrlock();
3566 ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
3567 bdrv_graph_wrunlock();
3568 bdrv_drained_end(drain_bs);
3569 bdrv_unref(drain_bs);
3571 return ret;
3575 * Opens the backing file for a BlockDriverState if not yet open
3577 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3578 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3579 * itself, all options starting with "${bdref_key}." are considered part of the
3580 * BlockdevRef.
3582 * TODO Can this be unified with bdrv_open_image()?
3584 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3585 const char *bdref_key, Error **errp)
3587 ERRP_GUARD();
3588 char *backing_filename = NULL;
3589 char *bdref_key_dot;
3590 const char *reference = NULL;
3591 int ret = 0;
3592 bool implicit_backing = false;
3593 BlockDriverState *backing_hd;
3594 QDict *options;
3595 QDict *tmp_parent_options = NULL;
3596 Error *local_err = NULL;
3598 GLOBAL_STATE_CODE();
3599 GRAPH_RDLOCK_GUARD_MAINLOOP();
3601 if (bs->backing != NULL) {
3602 goto free_exit;
3605 /* NULL means an empty set of options */
3606 if (parent_options == NULL) {
3607 tmp_parent_options = qdict_new();
3608 parent_options = tmp_parent_options;
3611 bs->open_flags &= ~BDRV_O_NO_BACKING;
3613 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3614 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3615 g_free(bdref_key_dot);
3618 * Caution: while qdict_get_try_str() is fine, getting non-string
3619 * types would require more care. When @parent_options come from
3620 * -blockdev or blockdev_add, its members are typed according to
3621 * the QAPI schema, but when they come from -drive, they're all
3622 * QString.
3624 reference = qdict_get_try_str(parent_options, bdref_key);
3625 if (reference || qdict_haskey(options, "file.filename")) {
3626 /* keep backing_filename NULL */
3627 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3628 qobject_unref(options);
3629 goto free_exit;
3630 } else {
3631 if (qdict_size(options) == 0) {
3632 /* If the user specifies options that do not modify the
3633 * backing file's behavior, we might still consider it the
3634 * implicit backing file. But it's easier this way, and
3635 * just specifying some of the backing BDS's options is
3636 * only possible with -drive anyway (otherwise the QAPI
3637 * schema forces the user to specify everything). */
3638 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3641 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3642 if (local_err) {
3643 ret = -EINVAL;
3644 error_propagate(errp, local_err);
3645 qobject_unref(options);
3646 goto free_exit;
3650 if (!bs->drv || !bs->drv->supports_backing) {
3651 ret = -EINVAL;
3652 error_setg(errp, "Driver doesn't support backing files");
3653 qobject_unref(options);
3654 goto free_exit;
3657 if (!reference &&
3658 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3659 qdict_put_str(options, "driver", bs->backing_format);
3662 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3663 &child_of_bds, bdrv_backing_role(bs), errp);
3664 if (!backing_hd) {
3665 bs->open_flags |= BDRV_O_NO_BACKING;
3666 error_prepend(errp, "Could not open backing file: ");
3667 ret = -EINVAL;
3668 goto free_exit;
3671 if (implicit_backing) {
3672 bdrv_refresh_filename(backing_hd);
3673 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3674 backing_hd->filename);
3677 /* Hook up the backing file link; drop our reference, bs owns the
3678 * backing_hd reference now */
3679 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3680 bdrv_unref(backing_hd);
3682 if (ret < 0) {
3683 goto free_exit;
3686 qdict_del(parent_options, bdref_key);
3688 free_exit:
3689 g_free(backing_filename);
3690 qobject_unref(tmp_parent_options);
3691 return ret;
3694 static BlockDriverState *
3695 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3696 BlockDriverState *parent, const BdrvChildClass *child_class,
3697 BdrvChildRole child_role, bool allow_none, Error **errp)
3699 BlockDriverState *bs = NULL;
3700 QDict *image_options;
3701 char *bdref_key_dot;
3702 const char *reference;
3704 assert(child_class != NULL);
3706 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3707 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3708 g_free(bdref_key_dot);
3711 * Caution: while qdict_get_try_str() is fine, getting non-string
3712 * types would require more care. When @options come from
3713 * -blockdev or blockdev_add, its members are typed according to
3714 * the QAPI schema, but when they come from -drive, they're all
3715 * QString.
3717 reference = qdict_get_try_str(options, bdref_key);
3718 if (!filename && !reference && !qdict_size(image_options)) {
3719 if (!allow_none) {
3720 error_setg(errp, "A block device must be specified for \"%s\"",
3721 bdref_key);
3723 qobject_unref(image_options);
3724 goto done;
3727 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3728 parent, child_class, child_role, errp);
3729 if (!bs) {
3730 goto done;
3733 done:
3734 qdict_del(options, bdref_key);
3735 return bs;
3739 * Opens a disk image whose options are given as BlockdevRef in another block
3740 * device's options.
3742 * If allow_none is true, no image will be opened if filename is false and no
3743 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3745 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3746 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3747 * itself, all options starting with "${bdref_key}." are considered part of the
3748 * BlockdevRef.
3750 * The BlockdevRef will be removed from the options QDict.
3752 * @parent can move to a different AioContext in this function.
3754 BdrvChild *bdrv_open_child(const char *filename,
3755 QDict *options, const char *bdref_key,
3756 BlockDriverState *parent,
3757 const BdrvChildClass *child_class,
3758 BdrvChildRole child_role,
3759 bool allow_none, Error **errp)
3761 BlockDriverState *bs;
3762 BdrvChild *child;
3764 GLOBAL_STATE_CODE();
3766 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3767 child_role, allow_none, errp);
3768 if (bs == NULL) {
3769 return NULL;
3772 bdrv_graph_wrlock();
3773 child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3774 errp);
3775 bdrv_graph_wrunlock();
3777 return child;
3781 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3783 * @parent can move to a different AioContext in this function.
3785 int bdrv_open_file_child(const char *filename,
3786 QDict *options, const char *bdref_key,
3787 BlockDriverState *parent, Error **errp)
3789 BdrvChildRole role;
3791 /* commit_top and mirror_top don't use this function */
3792 assert(!parent->drv->filtered_child_is_backing);
3793 role = parent->drv->is_filter ?
3794 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3796 if (!bdrv_open_child(filename, options, bdref_key, parent,
3797 &child_of_bds, role, false, errp))
3799 return -EINVAL;
3802 return 0;
3806 * TODO Future callers may need to specify parent/child_class in order for
3807 * option inheritance to work. Existing callers use it for the root node.
3809 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3811 BlockDriverState *bs = NULL;
3812 QObject *obj = NULL;
3813 QDict *qdict = NULL;
3814 const char *reference = NULL;
3815 Visitor *v = NULL;
3817 GLOBAL_STATE_CODE();
3819 if (ref->type == QTYPE_QSTRING) {
3820 reference = ref->u.reference;
3821 } else {
3822 BlockdevOptions *options = &ref->u.definition;
3823 assert(ref->type == QTYPE_QDICT);
3825 v = qobject_output_visitor_new(&obj);
3826 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3827 visit_complete(v, &obj);
3829 qdict = qobject_to(QDict, obj);
3830 qdict_flatten(qdict);
3832 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3833 * compatibility with other callers) rather than what we want as the
3834 * real defaults. Apply the defaults here instead. */
3835 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3836 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3837 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3838 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3842 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3843 obj = NULL;
3844 qobject_unref(obj);
3845 visit_free(v);
3846 return bs;
3849 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3850 int flags,
3851 QDict *snapshot_options,
3852 Error **errp)
3854 ERRP_GUARD();
3855 g_autofree char *tmp_filename = NULL;
3856 int64_t total_size;
3857 QemuOpts *opts = NULL;
3858 BlockDriverState *bs_snapshot = NULL;
3859 int ret;
3861 GLOBAL_STATE_CODE();
3863 /* if snapshot, we create a temporary backing file and open it
3864 instead of opening 'filename' directly */
3866 /* Get the required size from the image */
3867 total_size = bdrv_getlength(bs);
3869 if (total_size < 0) {
3870 error_setg_errno(errp, -total_size, "Could not get image size");
3871 goto out;
3874 /* Create the temporary image */
3875 tmp_filename = create_tmp_file(errp);
3876 if (!tmp_filename) {
3877 goto out;
3880 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3881 &error_abort);
3882 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3883 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3884 qemu_opts_del(opts);
3885 if (ret < 0) {
3886 error_prepend(errp, "Could not create temporary overlay '%s': ",
3887 tmp_filename);
3888 goto out;
3891 /* Prepare options QDict for the temporary file */
3892 qdict_put_str(snapshot_options, "file.driver", "file");
3893 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3894 qdict_put_str(snapshot_options, "driver", "qcow2");
3896 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3897 snapshot_options = NULL;
3898 if (!bs_snapshot) {
3899 goto out;
3902 ret = bdrv_append(bs_snapshot, bs, errp);
3903 if (ret < 0) {
3904 bs_snapshot = NULL;
3905 goto out;
3908 out:
3909 qobject_unref(snapshot_options);
3910 return bs_snapshot;
3914 * Opens a disk image (raw, qcow2, vmdk, ...)
3916 * options is a QDict of options to pass to the block drivers, or NULL for an
3917 * empty set of options. The reference to the QDict belongs to the block layer
3918 * after the call (even on failure), so if the caller intends to reuse the
3919 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3921 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3922 * If it is not NULL, the referenced BDS will be reused.
3924 * The reference parameter may be used to specify an existing block device which
3925 * should be opened. If specified, neither options nor a filename may be given,
3926 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3928 static BlockDriverState * no_coroutine_fn
3929 bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
3930 int flags, BlockDriverState *parent,
3931 const BdrvChildClass *child_class, BdrvChildRole child_role,
3932 Error **errp)
3934 int ret;
3935 BlockBackend *file = NULL;
3936 BlockDriverState *bs;
3937 BlockDriver *drv = NULL;
3938 BdrvChild *child;
3939 const char *drvname;
3940 const char *backing;
3941 Error *local_err = NULL;
3942 QDict *snapshot_options = NULL;
3943 int snapshot_flags = 0;
3945 assert(!child_class || !flags);
3946 assert(!child_class == !parent);
3947 GLOBAL_STATE_CODE();
3948 assert(!qemu_in_coroutine());
3950 /* TODO We'll eventually have to take a writer lock in this function */
3951 GRAPH_RDLOCK_GUARD_MAINLOOP();
3953 if (reference) {
3954 bool options_non_empty = options ? qdict_size(options) : false;
3955 qobject_unref(options);
3957 if (filename || options_non_empty) {
3958 error_setg(errp, "Cannot reference an existing block device with "
3959 "additional options or a new filename");
3960 return NULL;
3963 bs = bdrv_lookup_bs(reference, reference, errp);
3964 if (!bs) {
3965 return NULL;
3968 bdrv_ref(bs);
3969 return bs;
3972 bs = bdrv_new();
3974 /* NULL means an empty set of options */
3975 if (options == NULL) {
3976 options = qdict_new();
3979 /* json: syntax counts as explicit options, as if in the QDict */
3980 parse_json_protocol(options, &filename, &local_err);
3981 if (local_err) {
3982 goto fail;
3985 bs->explicit_options = qdict_clone_shallow(options);
3987 if (child_class) {
3988 bool parent_is_format;
3990 if (parent->drv) {
3991 parent_is_format = parent->drv->is_format;
3992 } else {
3994 * parent->drv is not set yet because this node is opened for
3995 * (potential) format probing. That means that @parent is going
3996 * to be a format node.
3998 parent_is_format = true;
4001 bs->inherits_from = parent;
4002 child_class->inherit_options(child_role, parent_is_format,
4003 &flags, options,
4004 parent->open_flags, parent->options);
4007 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
4008 if (ret < 0) {
4009 goto fail;
4013 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4014 * Caution: getting a boolean member of @options requires care.
4015 * When @options come from -blockdev or blockdev_add, members are
4016 * typed according to the QAPI schema, but when they come from
4017 * -drive, they're all QString.
4019 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
4020 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
4021 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
4022 } else {
4023 flags &= ~BDRV_O_RDWR;
4026 if (flags & BDRV_O_SNAPSHOT) {
4027 snapshot_options = qdict_new();
4028 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
4029 flags, options);
4030 /* Let bdrv_backing_options() override "read-only" */
4031 qdict_del(options, BDRV_OPT_READ_ONLY);
4032 bdrv_inherited_options(BDRV_CHILD_COW, true,
4033 &flags, options, flags, options);
4036 bs->open_flags = flags;
4037 bs->options = options;
4038 options = qdict_clone_shallow(options);
4040 /* Find the right image format driver */
4041 /* See cautionary note on accessing @options above */
4042 drvname = qdict_get_try_str(options, "driver");
4043 if (drvname) {
4044 drv = bdrv_find_format(drvname);
4045 if (!drv) {
4046 error_setg(errp, "Unknown driver: '%s'", drvname);
4047 goto fail;
4051 assert(drvname || !(flags & BDRV_O_PROTOCOL));
4053 /* See cautionary note on accessing @options above */
4054 backing = qdict_get_try_str(options, "backing");
4055 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
4056 (backing && *backing == '\0'))
4058 if (backing) {
4059 warn_report("Use of \"backing\": \"\" is deprecated; "
4060 "use \"backing\": null instead");
4062 flags |= BDRV_O_NO_BACKING;
4063 qdict_del(bs->explicit_options, "backing");
4064 qdict_del(bs->options, "backing");
4065 qdict_del(options, "backing");
4068 /* Open image file without format layer. This BlockBackend is only used for
4069 * probing, the block drivers will do their own bdrv_open_child() for the
4070 * same BDS, which is why we put the node name back into options. */
4071 if ((flags & BDRV_O_PROTOCOL) == 0) {
4072 BlockDriverState *file_bs;
4074 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
4075 &child_of_bds, BDRV_CHILD_IMAGE,
4076 true, &local_err);
4077 if (local_err) {
4078 goto fail;
4080 if (file_bs != NULL) {
4081 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4082 * looking at the header to guess the image format. This works even
4083 * in cases where a guest would not see a consistent state. */
4084 AioContext *ctx = bdrv_get_aio_context(file_bs);
4085 file = blk_new(ctx, 0, BLK_PERM_ALL);
4086 blk_insert_bs(file, file_bs, &local_err);
4087 bdrv_unref(file_bs);
4089 if (local_err) {
4090 goto fail;
4093 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4097 /* Image format probing */
4098 bs->probed = !drv;
4099 if (!drv && file) {
4100 ret = find_image_format(file, filename, &drv, &local_err);
4101 if (ret < 0) {
4102 goto fail;
4105 * This option update would logically belong in bdrv_fill_options(),
4106 * but we first need to open bs->file for the probing to work, while
4107 * opening bs->file already requires the (mostly) final set of options
4108 * so that cache mode etc. can be inherited.
4110 * Adding the driver later is somewhat ugly, but it's not an option
4111 * that would ever be inherited, so it's correct. We just need to make
4112 * sure to update both bs->options (which has the full effective
4113 * options for bs) and options (which has file.* already removed).
4115 qdict_put_str(bs->options, "driver", drv->format_name);
4116 qdict_put_str(options, "driver", drv->format_name);
4117 } else if (!drv) {
4118 error_setg(errp, "Must specify either driver or file");
4119 goto fail;
4122 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4123 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->protocol_name);
4124 /* file must be NULL if a protocol BDS is about to be created
4125 * (the inverse results in an error message from bdrv_open_common()) */
4126 assert(!(flags & BDRV_O_PROTOCOL) || !file);
4128 /* Open the image */
4129 ret = bdrv_open_common(bs, file, options, &local_err);
4130 if (ret < 0) {
4131 goto fail;
4134 if (file) {
4135 blk_unref(file);
4136 file = NULL;
4139 /* If there is a backing file, use it */
4140 if ((flags & BDRV_O_NO_BACKING) == 0) {
4141 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4142 if (ret < 0) {
4143 goto close_and_fail;
4147 /* Remove all children options and references
4148 * from bs->options and bs->explicit_options */
4149 QLIST_FOREACH(child, &bs->children, next) {
4150 char *child_key_dot;
4151 child_key_dot = g_strdup_printf("%s.", child->name);
4152 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4153 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4154 qdict_del(bs->explicit_options, child->name);
4155 qdict_del(bs->options, child->name);
4156 g_free(child_key_dot);
4159 /* Check if any unknown options were used */
4160 if (qdict_size(options) != 0) {
4161 const QDictEntry *entry = qdict_first(options);
4162 if (flags & BDRV_O_PROTOCOL) {
4163 error_setg(errp, "Block protocol '%s' doesn't support the option "
4164 "'%s'", drv->format_name, entry->key);
4165 } else {
4166 error_setg(errp,
4167 "Block format '%s' does not support the option '%s'",
4168 drv->format_name, entry->key);
4171 goto close_and_fail;
4174 bdrv_parent_cb_change_media(bs, true);
4176 qobject_unref(options);
4177 options = NULL;
4179 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4180 * temporary snapshot afterwards. */
4181 if (snapshot_flags) {
4182 BlockDriverState *snapshot_bs;
4183 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4184 snapshot_options, &local_err);
4185 snapshot_options = NULL;
4186 if (local_err) {
4187 goto close_and_fail;
4189 /* We are not going to return bs but the overlay on top of it
4190 * (snapshot_bs); thus, we have to drop the strong reference to bs
4191 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4192 * though, because the overlay still has a reference to it. */
4193 bdrv_unref(bs);
4194 bs = snapshot_bs;
4197 return bs;
4199 fail:
4200 blk_unref(file);
4201 qobject_unref(snapshot_options);
4202 qobject_unref(bs->explicit_options);
4203 qobject_unref(bs->options);
4204 qobject_unref(options);
4205 bs->options = NULL;
4206 bs->explicit_options = NULL;
4207 bdrv_unref(bs);
4208 error_propagate(errp, local_err);
4209 return NULL;
4211 close_and_fail:
4212 bdrv_unref(bs);
4213 qobject_unref(snapshot_options);
4214 qobject_unref(options);
4215 error_propagate(errp, local_err);
4216 return NULL;
4219 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4220 QDict *options, int flags, Error **errp)
4222 GLOBAL_STATE_CODE();
4224 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4225 NULL, 0, errp);
4228 /* Return true if the NULL-terminated @list contains @str */
4229 static bool is_str_in_list(const char *str, const char *const *list)
4231 if (str && list) {
4232 int i;
4233 for (i = 0; list[i] != NULL; i++) {
4234 if (!strcmp(str, list[i])) {
4235 return true;
4239 return false;
4243 * Check that every option set in @bs->options is also set in
4244 * @new_opts.
4246 * Options listed in the common_options list and in
4247 * @bs->drv->mutable_opts are skipped.
4249 * Return 0 on success, otherwise return -EINVAL and set @errp.
4251 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4252 const QDict *new_opts, Error **errp)
4254 const QDictEntry *e;
4255 /* These options are common to all block drivers and are handled
4256 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4257 const char *const common_options[] = {
4258 "node-name", "discard", "cache.direct", "cache.no-flush",
4259 "read-only", "auto-read-only", "detect-zeroes", NULL
4262 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4263 if (!qdict_haskey(new_opts, e->key) &&
4264 !is_str_in_list(e->key, common_options) &&
4265 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4266 error_setg(errp, "Option '%s' cannot be reset "
4267 "to its default value", e->key);
4268 return -EINVAL;
4272 return 0;
4276 * Returns true if @child can be reached recursively from @bs
4278 static bool GRAPH_RDLOCK
4279 bdrv_recurse_has_child(BlockDriverState *bs, BlockDriverState *child)
4281 BdrvChild *c;
4283 if (bs == child) {
4284 return true;
4287 QLIST_FOREACH(c, &bs->children, next) {
4288 if (bdrv_recurse_has_child(c->bs, child)) {
4289 return true;
4293 return false;
4297 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4298 * reopen of multiple devices.
4300 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4301 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4302 * be created and initialized. This newly created BlockReopenQueue should be
4303 * passed back in for subsequent calls that are intended to be of the same
4304 * atomic 'set'.
4306 * bs is the BlockDriverState to add to the reopen queue.
4308 * options contains the changed options for the associated bs
4309 * (the BlockReopenQueue takes ownership)
4311 * flags contains the open flags for the associated bs
4313 * returns a pointer to bs_queue, which is either the newly allocated
4314 * bs_queue, or the existing bs_queue being used.
4316 * bs is drained here and undrained by bdrv_reopen_queue_free().
4318 * To be called with bs->aio_context locked.
4320 static BlockReopenQueue * GRAPH_RDLOCK
4321 bdrv_reopen_queue_child(BlockReopenQueue *bs_queue, BlockDriverState *bs,
4322 QDict *options, const BdrvChildClass *klass,
4323 BdrvChildRole role, bool parent_is_format,
4324 QDict *parent_options, int parent_flags,
4325 bool keep_old_opts)
4327 assert(bs != NULL);
4329 BlockReopenQueueEntry *bs_entry;
4330 BdrvChild *child;
4331 QDict *old_options, *explicit_options, *options_copy;
4332 int flags;
4333 QemuOpts *opts;
4335 GLOBAL_STATE_CODE();
4338 * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
4339 * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
4340 * in practice.
4342 bdrv_drained_begin(bs);
4344 if (bs_queue == NULL) {
4345 bs_queue = g_new0(BlockReopenQueue, 1);
4346 QTAILQ_INIT(bs_queue);
4349 if (!options) {
4350 options = qdict_new();
4353 /* Check if this BlockDriverState is already in the queue */
4354 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4355 if (bs == bs_entry->state.bs) {
4356 break;
4361 * Precedence of options:
4362 * 1. Explicitly passed in options (highest)
4363 * 2. Retained from explicitly set options of bs
4364 * 3. Inherited from parent node
4365 * 4. Retained from effective options of bs
4368 /* Old explicitly set values (don't overwrite by inherited value) */
4369 if (bs_entry || keep_old_opts) {
4370 old_options = qdict_clone_shallow(bs_entry ?
4371 bs_entry->state.explicit_options :
4372 bs->explicit_options);
4373 bdrv_join_options(bs, options, old_options);
4374 qobject_unref(old_options);
4377 explicit_options = qdict_clone_shallow(options);
4379 /* Inherit from parent node */
4380 if (parent_options) {
4381 flags = 0;
4382 klass->inherit_options(role, parent_is_format, &flags, options,
4383 parent_flags, parent_options);
4384 } else {
4385 flags = bdrv_get_flags(bs);
4388 if (keep_old_opts) {
4389 /* Old values are used for options that aren't set yet */
4390 old_options = qdict_clone_shallow(bs->options);
4391 bdrv_join_options(bs, options, old_options);
4392 qobject_unref(old_options);
4395 /* We have the final set of options so let's update the flags */
4396 options_copy = qdict_clone_shallow(options);
4397 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4398 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4399 update_flags_from_options(&flags, opts);
4400 qemu_opts_del(opts);
4401 qobject_unref(options_copy);
4403 /* bdrv_open_inherit() sets and clears some additional flags internally */
4404 flags &= ~BDRV_O_PROTOCOL;
4405 if (flags & BDRV_O_RDWR) {
4406 flags |= BDRV_O_ALLOW_RDWR;
4409 if (!bs_entry) {
4410 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4411 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4412 } else {
4413 qobject_unref(bs_entry->state.options);
4414 qobject_unref(bs_entry->state.explicit_options);
4417 bs_entry->state.bs = bs;
4418 bs_entry->state.options = options;
4419 bs_entry->state.explicit_options = explicit_options;
4420 bs_entry->state.flags = flags;
4423 * If keep_old_opts is false then it means that unspecified
4424 * options must be reset to their original value. We don't allow
4425 * resetting 'backing' but we need to know if the option is
4426 * missing in order to decide if we have to return an error.
4428 if (!keep_old_opts) {
4429 bs_entry->state.backing_missing =
4430 !qdict_haskey(options, "backing") &&
4431 !qdict_haskey(options, "backing.driver");
4434 QLIST_FOREACH(child, &bs->children, next) {
4435 QDict *new_child_options = NULL;
4436 bool child_keep_old = keep_old_opts;
4438 /* reopen can only change the options of block devices that were
4439 * implicitly created and inherited options. For other (referenced)
4440 * block devices, a syntax like "backing.foo" results in an error. */
4441 if (child->bs->inherits_from != bs) {
4442 continue;
4445 /* Check if the options contain a child reference */
4446 if (qdict_haskey(options, child->name)) {
4447 const char *childref = qdict_get_try_str(options, child->name);
4449 * The current child must not be reopened if the child
4450 * reference is null or points to a different node.
4452 if (g_strcmp0(childref, child->bs->node_name)) {
4453 continue;
4456 * If the child reference points to the current child then
4457 * reopen it with its existing set of options (note that
4458 * it can still inherit new options from the parent).
4460 child_keep_old = true;
4461 } else {
4462 /* Extract child options ("child-name.*") */
4463 char *child_key_dot = g_strdup_printf("%s.", child->name);
4464 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4465 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4466 g_free(child_key_dot);
4469 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4470 child->klass, child->role, bs->drv->is_format,
4471 options, flags, child_keep_old);
4474 return bs_queue;
4477 /* To be called with bs->aio_context locked */
4478 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4479 BlockDriverState *bs,
4480 QDict *options, bool keep_old_opts)
4482 GLOBAL_STATE_CODE();
4483 GRAPH_RDLOCK_GUARD_MAINLOOP();
4485 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4486 NULL, 0, keep_old_opts);
4489 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4491 GLOBAL_STATE_CODE();
4492 if (bs_queue) {
4493 BlockReopenQueueEntry *bs_entry, *next;
4494 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4495 bdrv_drained_end(bs_entry->state.bs);
4496 qobject_unref(bs_entry->state.explicit_options);
4497 qobject_unref(bs_entry->state.options);
4498 g_free(bs_entry);
4500 g_free(bs_queue);
4505 * Reopen multiple BlockDriverStates atomically & transactionally.
4507 * The queue passed in (bs_queue) must have been built up previous
4508 * via bdrv_reopen_queue().
4510 * Reopens all BDS specified in the queue, with the appropriate
4511 * flags. All devices are prepared for reopen, and failure of any
4512 * device will cause all device changes to be abandoned, and intermediate
4513 * data cleaned up.
4515 * If all devices prepare successfully, then the changes are committed
4516 * to all devices.
4518 * All affected nodes must be drained between bdrv_reopen_queue() and
4519 * bdrv_reopen_multiple().
4521 * To be called from the main thread, with all other AioContexts unlocked.
4523 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4525 int ret = -1;
4526 BlockReopenQueueEntry *bs_entry, *next;
4527 Transaction *tran = tran_new();
4528 g_autoptr(GSList) refresh_list = NULL;
4530 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4531 assert(bs_queue != NULL);
4532 GLOBAL_STATE_CODE();
4534 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4535 ret = bdrv_flush(bs_entry->state.bs);
4536 if (ret < 0) {
4537 error_setg_errno(errp, -ret, "Error flushing drive");
4538 goto abort;
4542 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4543 assert(bs_entry->state.bs->quiesce_counter > 0);
4544 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4545 if (ret < 0) {
4546 goto abort;
4548 bs_entry->prepared = true;
4551 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4552 BDRVReopenState *state = &bs_entry->state;
4554 refresh_list = g_slist_prepend(refresh_list, state->bs);
4555 if (state->old_backing_bs) {
4556 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4558 if (state->old_file_bs) {
4559 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4564 * Note that file-posix driver rely on permission update done during reopen
4565 * (even if no permission changed), because it wants "new" permissions for
4566 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4567 * in raw_reopen_prepare() which is called with "old" permissions.
4569 bdrv_graph_rdlock_main_loop();
4570 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4571 bdrv_graph_rdunlock_main_loop();
4573 if (ret < 0) {
4574 goto abort;
4578 * If we reach this point, we have success and just need to apply the
4579 * changes.
4581 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4582 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4583 * children are usually goes after parents in reopen-queue, so go from last
4584 * to first element.
4586 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4587 bdrv_reopen_commit(&bs_entry->state);
4590 bdrv_graph_wrlock();
4591 tran_commit(tran);
4592 bdrv_graph_wrunlock();
4594 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4595 BlockDriverState *bs = bs_entry->state.bs;
4597 if (bs->drv->bdrv_reopen_commit_post) {
4598 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4602 ret = 0;
4603 goto cleanup;
4605 abort:
4606 bdrv_graph_wrlock();
4607 tran_abort(tran);
4608 bdrv_graph_wrunlock();
4610 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4611 if (bs_entry->prepared) {
4612 bdrv_reopen_abort(&bs_entry->state);
4616 cleanup:
4617 bdrv_reopen_queue_free(bs_queue);
4619 return ret;
4622 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4623 Error **errp)
4625 BlockReopenQueue *queue;
4627 GLOBAL_STATE_CODE();
4629 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4631 return bdrv_reopen_multiple(queue, errp);
4634 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4635 Error **errp)
4637 QDict *opts = qdict_new();
4639 GLOBAL_STATE_CODE();
4641 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4643 return bdrv_reopen(bs, opts, true, errp);
4647 * Take a BDRVReopenState and check if the value of 'backing' in the
4648 * reopen_state->options QDict is valid or not.
4650 * If 'backing' is missing from the QDict then return 0.
4652 * If 'backing' contains the node name of the backing file of
4653 * reopen_state->bs then return 0.
4655 * If 'backing' contains a different node name (or is null) then check
4656 * whether the current backing file can be replaced with the new one.
4657 * If that's the case then reopen_state->replace_backing_bs is set to
4658 * true and reopen_state->new_backing_bs contains a pointer to the new
4659 * backing BlockDriverState (or NULL).
4661 * After calling this function, the transaction @tran may only be completed
4662 * while holding a writer lock for the graph.
4664 * Return 0 on success, otherwise return < 0 and set @errp.
4666 * @reopen_state->bs can move to a different AioContext in this function.
4668 static int GRAPH_UNLOCKED
4669 bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4670 bool is_backing, Transaction *tran,
4671 Error **errp)
4673 BlockDriverState *bs = reopen_state->bs;
4674 BlockDriverState *new_child_bs;
4675 BlockDriverState *old_child_bs;
4677 const char *child_name = is_backing ? "backing" : "file";
4678 QObject *value;
4679 const char *str;
4680 bool has_child;
4681 int ret;
4683 GLOBAL_STATE_CODE();
4685 value = qdict_get(reopen_state->options, child_name);
4686 if (value == NULL) {
4687 return 0;
4690 bdrv_graph_rdlock_main_loop();
4692 switch (qobject_type(value)) {
4693 case QTYPE_QNULL:
4694 assert(is_backing); /* The 'file' option does not allow a null value */
4695 new_child_bs = NULL;
4696 break;
4697 case QTYPE_QSTRING:
4698 str = qstring_get_str(qobject_to(QString, value));
4699 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4700 if (new_child_bs == NULL) {
4701 ret = -EINVAL;
4702 goto out_rdlock;
4705 has_child = bdrv_recurse_has_child(new_child_bs, bs);
4706 if (has_child) {
4707 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4708 "cycle", str, child_name, bs->node_name);
4709 ret = -EINVAL;
4710 goto out_rdlock;
4712 break;
4713 default:
4715 * The options QDict has been flattened, so 'backing' and 'file'
4716 * do not allow any other data type here.
4718 g_assert_not_reached();
4721 old_child_bs = is_backing ? child_bs(bs->backing) : child_bs(bs->file);
4722 if (old_child_bs == new_child_bs) {
4723 ret = 0;
4724 goto out_rdlock;
4727 if (old_child_bs) {
4728 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4729 ret = 0;
4730 goto out_rdlock;
4733 if (old_child_bs->implicit) {
4734 error_setg(errp, "Cannot replace implicit %s child of %s",
4735 child_name, bs->node_name);
4736 ret = -EPERM;
4737 goto out_rdlock;
4741 if (bs->drv->is_filter && !old_child_bs) {
4743 * Filters always have a file or a backing child, so we are trying to
4744 * change wrong child
4746 error_setg(errp, "'%s' is a %s filter node that does not support a "
4747 "%s child", bs->node_name, bs->drv->format_name, child_name);
4748 ret = -EINVAL;
4749 goto out_rdlock;
4752 if (is_backing) {
4753 reopen_state->old_backing_bs = old_child_bs;
4754 } else {
4755 reopen_state->old_file_bs = old_child_bs;
4758 if (old_child_bs) {
4759 bdrv_ref(old_child_bs);
4760 bdrv_drained_begin(old_child_bs);
4763 bdrv_graph_rdunlock_main_loop();
4764 bdrv_graph_wrlock();
4766 ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4767 tran, errp);
4769 bdrv_graph_wrunlock();
4771 if (old_child_bs) {
4772 bdrv_drained_end(old_child_bs);
4773 bdrv_unref(old_child_bs);
4776 return ret;
4778 out_rdlock:
4779 bdrv_graph_rdunlock_main_loop();
4780 return ret;
4784 * Prepares a BlockDriverState for reopen. All changes are staged in the
4785 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4786 * the block driver layer .bdrv_reopen_prepare()
4788 * bs is the BlockDriverState to reopen
4789 * flags are the new open flags
4790 * queue is the reopen queue
4792 * Returns 0 on success, non-zero on error. On error errp will be set
4793 * as well.
4795 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4796 * It is the responsibility of the caller to then call the abort() or
4797 * commit() for any other BDS that have been left in a prepare() state
4799 * After calling this function, the transaction @change_child_tran may only be
4800 * completed while holding a writer lock for the graph.
4802 static int GRAPH_UNLOCKED
4803 bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4804 Transaction *change_child_tran, Error **errp)
4806 int ret = -1;
4807 int old_flags;
4808 Error *local_err = NULL;
4809 BlockDriver *drv;
4810 QemuOpts *opts;
4811 QDict *orig_reopen_opts;
4812 char *discard = NULL;
4813 bool read_only;
4814 bool drv_prepared = false;
4816 assert(reopen_state != NULL);
4817 assert(reopen_state->bs->drv != NULL);
4818 GLOBAL_STATE_CODE();
4819 drv = reopen_state->bs->drv;
4821 /* This function and each driver's bdrv_reopen_prepare() remove
4822 * entries from reopen_state->options as they are processed, so
4823 * we need to make a copy of the original QDict. */
4824 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4826 /* Process generic block layer options */
4827 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4828 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4829 ret = -EINVAL;
4830 goto error;
4833 /* This was already called in bdrv_reopen_queue_child() so the flags
4834 * are up-to-date. This time we simply want to remove the options from
4835 * QemuOpts in order to indicate that they have been processed. */
4836 old_flags = reopen_state->flags;
4837 update_flags_from_options(&reopen_state->flags, opts);
4838 assert(old_flags == reopen_state->flags);
4840 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4841 if (discard != NULL) {
4842 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4843 error_setg(errp, "Invalid discard option");
4844 ret = -EINVAL;
4845 goto error;
4849 reopen_state->detect_zeroes =
4850 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4851 if (local_err) {
4852 error_propagate(errp, local_err);
4853 ret = -EINVAL;
4854 goto error;
4857 /* All other options (including node-name and driver) must be unchanged.
4858 * Put them back into the QDict, so that they are checked at the end
4859 * of this function. */
4860 qemu_opts_to_qdict(opts, reopen_state->options);
4862 /* If we are to stay read-only, do not allow permission change
4863 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4864 * not set, or if the BDS still has copy_on_read enabled */
4865 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4867 bdrv_graph_rdlock_main_loop();
4868 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4869 bdrv_graph_rdunlock_main_loop();
4870 if (local_err) {
4871 error_propagate(errp, local_err);
4872 goto error;
4875 if (drv->bdrv_reopen_prepare) {
4877 * If a driver-specific option is missing, it means that we
4878 * should reset it to its default value.
4879 * But not all options allow that, so we need to check it first.
4881 ret = bdrv_reset_options_allowed(reopen_state->bs,
4882 reopen_state->options, errp);
4883 if (ret) {
4884 goto error;
4887 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4888 if (ret) {
4889 if (local_err != NULL) {
4890 error_propagate(errp, local_err);
4891 } else {
4892 bdrv_graph_rdlock_main_loop();
4893 bdrv_refresh_filename(reopen_state->bs);
4894 bdrv_graph_rdunlock_main_loop();
4895 error_setg(errp, "failed while preparing to reopen image '%s'",
4896 reopen_state->bs->filename);
4898 goto error;
4900 } else {
4901 /* It is currently mandatory to have a bdrv_reopen_prepare()
4902 * handler for each supported drv. */
4903 bdrv_graph_rdlock_main_loop();
4904 error_setg(errp, "Block format '%s' used by node '%s' "
4905 "does not support reopening files", drv->format_name,
4906 bdrv_get_device_or_node_name(reopen_state->bs));
4907 bdrv_graph_rdunlock_main_loop();
4908 ret = -1;
4909 goto error;
4912 drv_prepared = true;
4915 * We must provide the 'backing' option if the BDS has a backing
4916 * file or if the image file has a backing file name as part of
4917 * its metadata. Otherwise the 'backing' option can be omitted.
4919 bdrv_graph_rdlock_main_loop();
4920 if (drv->supports_backing && reopen_state->backing_missing &&
4921 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4922 error_setg(errp, "backing is missing for '%s'",
4923 reopen_state->bs->node_name);
4924 bdrv_graph_rdunlock_main_loop();
4925 ret = -EINVAL;
4926 goto error;
4928 bdrv_graph_rdunlock_main_loop();
4931 * Allow changing the 'backing' option. The new value can be
4932 * either a reference to an existing node (using its node name)
4933 * or NULL to simply detach the current backing file.
4935 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4936 change_child_tran, errp);
4937 if (ret < 0) {
4938 goto error;
4940 qdict_del(reopen_state->options, "backing");
4942 /* Allow changing the 'file' option. In this case NULL is not allowed */
4943 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4944 change_child_tran, errp);
4945 if (ret < 0) {
4946 goto error;
4948 qdict_del(reopen_state->options, "file");
4950 /* Options that are not handled are only okay if they are unchanged
4951 * compared to the old state. It is expected that some options are only
4952 * used for the initial open, but not reopen (e.g. filename) */
4953 if (qdict_size(reopen_state->options)) {
4954 const QDictEntry *entry = qdict_first(reopen_state->options);
4956 GRAPH_RDLOCK_GUARD_MAINLOOP();
4958 do {
4959 QObject *new = entry->value;
4960 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4962 /* Allow child references (child_name=node_name) as long as they
4963 * point to the current child (i.e. everything stays the same). */
4964 if (qobject_type(new) == QTYPE_QSTRING) {
4965 BdrvChild *child;
4966 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4967 if (!strcmp(child->name, entry->key)) {
4968 break;
4972 if (child) {
4973 if (!strcmp(child->bs->node_name,
4974 qstring_get_str(qobject_to(QString, new)))) {
4975 continue; /* Found child with this name, skip option */
4981 * TODO: When using -drive to specify blockdev options, all values
4982 * will be strings; however, when using -blockdev, blockdev-add or
4983 * filenames using the json:{} pseudo-protocol, they will be
4984 * correctly typed.
4985 * In contrast, reopening options are (currently) always strings
4986 * (because you can only specify them through qemu-io; all other
4987 * callers do not specify any options).
4988 * Therefore, when using anything other than -drive to create a BDS,
4989 * this cannot detect non-string options as unchanged, because
4990 * qobject_is_equal() always returns false for objects of different
4991 * type. In the future, this should be remedied by correctly typing
4992 * all options. For now, this is not too big of an issue because
4993 * the user can simply omit options which cannot be changed anyway,
4994 * so they will stay unchanged.
4996 if (!qobject_is_equal(new, old)) {
4997 error_setg(errp, "Cannot change the option '%s'", entry->key);
4998 ret = -EINVAL;
4999 goto error;
5001 } while ((entry = qdict_next(reopen_state->options, entry)));
5004 ret = 0;
5006 /* Restore the original reopen_state->options QDict */
5007 qobject_unref(reopen_state->options);
5008 reopen_state->options = qobject_ref(orig_reopen_opts);
5010 error:
5011 if (ret < 0 && drv_prepared) {
5012 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
5013 * call drv->bdrv_reopen_abort() before signaling an error
5014 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
5015 * when the respective bdrv_reopen_prepare() has failed) */
5016 if (drv->bdrv_reopen_abort) {
5017 drv->bdrv_reopen_abort(reopen_state);
5020 qemu_opts_del(opts);
5021 qobject_unref(orig_reopen_opts);
5022 g_free(discard);
5023 return ret;
5027 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5028 * makes them final by swapping the staging BlockDriverState contents into
5029 * the active BlockDriverState contents.
5031 static void GRAPH_UNLOCKED bdrv_reopen_commit(BDRVReopenState *reopen_state)
5033 BlockDriver *drv;
5034 BlockDriverState *bs;
5035 BdrvChild *child;
5037 assert(reopen_state != NULL);
5038 bs = reopen_state->bs;
5039 drv = bs->drv;
5040 assert(drv != NULL);
5041 GLOBAL_STATE_CODE();
5043 /* If there are any driver level actions to take */
5044 if (drv->bdrv_reopen_commit) {
5045 drv->bdrv_reopen_commit(reopen_state);
5048 GRAPH_RDLOCK_GUARD_MAINLOOP();
5050 /* set BDS specific flags now */
5051 qobject_unref(bs->explicit_options);
5052 qobject_unref(bs->options);
5053 qobject_ref(reopen_state->explicit_options);
5054 qobject_ref(reopen_state->options);
5056 bs->explicit_options = reopen_state->explicit_options;
5057 bs->options = reopen_state->options;
5058 bs->open_flags = reopen_state->flags;
5059 bs->detect_zeroes = reopen_state->detect_zeroes;
5061 /* Remove child references from bs->options and bs->explicit_options.
5062 * Child options were already removed in bdrv_reopen_queue_child() */
5063 QLIST_FOREACH(child, &bs->children, next) {
5064 qdict_del(bs->explicit_options, child->name);
5065 qdict_del(bs->options, child->name);
5067 /* backing is probably removed, so it's not handled by previous loop */
5068 qdict_del(bs->explicit_options, "backing");
5069 qdict_del(bs->options, "backing");
5071 bdrv_refresh_limits(bs, NULL, NULL);
5072 bdrv_refresh_total_sectors(bs, bs->total_sectors);
5076 * Abort the reopen, and delete and free the staged changes in
5077 * reopen_state
5079 static void GRAPH_UNLOCKED bdrv_reopen_abort(BDRVReopenState *reopen_state)
5081 BlockDriver *drv;
5083 assert(reopen_state != NULL);
5084 drv = reopen_state->bs->drv;
5085 assert(drv != NULL);
5086 GLOBAL_STATE_CODE();
5088 if (drv->bdrv_reopen_abort) {
5089 drv->bdrv_reopen_abort(reopen_state);
5094 static void bdrv_close(BlockDriverState *bs)
5096 BdrvAioNotifier *ban, *ban_next;
5097 BdrvChild *child, *next;
5099 GLOBAL_STATE_CODE();
5100 assert(!bs->refcnt);
5102 bdrv_drained_begin(bs); /* complete I/O */
5103 bdrv_flush(bs);
5104 bdrv_drain(bs); /* in case flush left pending I/O */
5106 if (bs->drv) {
5107 if (bs->drv->bdrv_close) {
5108 /* Must unfreeze all children, so bdrv_unref_child() works */
5109 bs->drv->bdrv_close(bs);
5111 bs->drv = NULL;
5114 bdrv_graph_wrlock();
5115 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
5116 bdrv_unref_child(bs, child);
5119 assert(!bs->backing);
5120 assert(!bs->file);
5121 bdrv_graph_wrunlock();
5123 g_free(bs->opaque);
5124 bs->opaque = NULL;
5125 qatomic_set(&bs->copy_on_read, 0);
5126 bs->backing_file[0] = '\0';
5127 bs->backing_format[0] = '\0';
5128 bs->total_sectors = 0;
5129 bs->encrypted = false;
5130 bs->sg = false;
5131 qobject_unref(bs->options);
5132 qobject_unref(bs->explicit_options);
5133 bs->options = NULL;
5134 bs->explicit_options = NULL;
5135 qobject_unref(bs->full_open_options);
5136 bs->full_open_options = NULL;
5137 g_free(bs->block_status_cache);
5138 bs->block_status_cache = NULL;
5140 bdrv_release_named_dirty_bitmaps(bs);
5141 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5143 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5144 g_free(ban);
5146 QLIST_INIT(&bs->aio_notifiers);
5147 bdrv_drained_end(bs);
5150 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5151 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5152 * gets called.
5154 if (bs->quiesce_counter) {
5155 bdrv_drain_all_end_quiesce(bs);
5159 void bdrv_close_all(void)
5161 GLOBAL_STATE_CODE();
5162 assert(job_next(NULL) == NULL);
5164 /* Drop references from requests still in flight, such as canceled block
5165 * jobs whose AIO context has not been polled yet */
5166 bdrv_drain_all();
5168 blk_remove_all_bs();
5169 blockdev_close_all_bdrv_states();
5171 assert(QTAILQ_EMPTY(&all_bdrv_states));
5174 static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
5176 GQueue *queue;
5177 GHashTable *found;
5178 bool ret;
5180 if (c->klass->stay_at_node) {
5181 return false;
5184 /* If the child @c belongs to the BDS @to, replacing the current
5185 * c->bs by @to would mean to create a loop.
5187 * Such a case occurs when appending a BDS to a backing chain.
5188 * For instance, imagine the following chain:
5190 * guest device -> node A -> further backing chain...
5192 * Now we create a new BDS B which we want to put on top of this
5193 * chain, so we first attach A as its backing node:
5195 * node B
5198 * guest device -> node A -> further backing chain...
5200 * Finally we want to replace A by B. When doing that, we want to
5201 * replace all pointers to A by pointers to B -- except for the
5202 * pointer from B because (1) that would create a loop, and (2)
5203 * that pointer should simply stay intact:
5205 * guest device -> node B
5208 * node A -> further backing chain...
5210 * In general, when replacing a node A (c->bs) by a node B (@to),
5211 * if A is a child of B, that means we cannot replace A by B there
5212 * because that would create a loop. Silently detaching A from B
5213 * is also not really an option. So overall just leaving A in
5214 * place there is the most sensible choice.
5216 * We would also create a loop in any cases where @c is only
5217 * indirectly referenced by @to. Prevent this by returning false
5218 * if @c is found (by breadth-first search) anywhere in the whole
5219 * subtree of @to.
5222 ret = true;
5223 found = g_hash_table_new(NULL, NULL);
5224 g_hash_table_add(found, to);
5225 queue = g_queue_new();
5226 g_queue_push_tail(queue, to);
5228 while (!g_queue_is_empty(queue)) {
5229 BlockDriverState *v = g_queue_pop_head(queue);
5230 BdrvChild *c2;
5232 QLIST_FOREACH(c2, &v->children, next) {
5233 if (c2 == c) {
5234 ret = false;
5235 break;
5238 if (g_hash_table_contains(found, c2->bs)) {
5239 continue;
5242 g_queue_push_tail(queue, c2->bs);
5243 g_hash_table_add(found, c2->bs);
5247 g_queue_free(queue);
5248 g_hash_table_destroy(found);
5250 return ret;
5253 static void bdrv_remove_child_commit(void *opaque)
5255 GLOBAL_STATE_CODE();
5256 bdrv_child_free(opaque);
5259 static TransactionActionDrv bdrv_remove_child_drv = {
5260 .commit = bdrv_remove_child_commit,
5264 * Function doesn't update permissions, caller is responsible for this.
5266 * @child->bs (if non-NULL) must be drained.
5268 * After calling this function, the transaction @tran may only be completed
5269 * while holding a writer lock for the graph.
5271 static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
5273 if (!child) {
5274 return;
5277 if (child->bs) {
5278 assert(child->quiesced_parent);
5279 bdrv_replace_child_tran(child, NULL, tran);
5282 tran_add(tran, &bdrv_remove_child_drv, child);
5286 * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
5287 * until the transaction is completed.
5289 * After calling this function, the transaction @tran may only be completed
5290 * while holding a writer lock for the graph.
5292 static int GRAPH_WRLOCK
5293 bdrv_replace_node_noperm(BlockDriverState *from,
5294 BlockDriverState *to,
5295 bool auto_skip, Transaction *tran,
5296 Error **errp)
5298 BdrvChild *c, *next;
5300 GLOBAL_STATE_CODE();
5302 assert(from->quiesce_counter);
5303 assert(to->quiesce_counter);
5305 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5306 assert(c->bs == from);
5307 if (!should_update_child(c, to)) {
5308 if (auto_skip) {
5309 continue;
5311 error_setg(errp, "Should not change '%s' link to '%s'",
5312 c->name, from->node_name);
5313 return -EINVAL;
5315 if (c->frozen) {
5316 error_setg(errp, "Cannot change '%s' link to '%s'",
5317 c->name, from->node_name);
5318 return -EPERM;
5320 bdrv_replace_child_tran(c, to, tran);
5323 return 0;
5327 * Switch all parents of @from to point to @to instead. @from and @to must be in
5328 * the same AioContext and both must be drained.
5330 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5331 * if it creates a parent-child relation loop or if parent is block-job.
5333 * With auto_skip=false the error is returned if from has a parent which should
5334 * not be updated.
5336 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5337 * case backing link of the cow-parent of @to is removed.
5339 static int GRAPH_WRLOCK
5340 bdrv_replace_node_common(BlockDriverState *from, BlockDriverState *to,
5341 bool auto_skip, bool detach_subchain, Error **errp)
5343 Transaction *tran = tran_new();
5344 g_autoptr(GSList) refresh_list = NULL;
5345 BlockDriverState *to_cow_parent = NULL;
5346 int ret;
5348 GLOBAL_STATE_CODE();
5350 assert(from->quiesce_counter);
5351 assert(to->quiesce_counter);
5352 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5354 if (detach_subchain) {
5355 assert(bdrv_chain_contains(from, to));
5356 assert(from != to);
5357 for (to_cow_parent = from;
5358 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5359 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5366 * Do the replacement without permission update.
5367 * Replacement may influence the permissions, we should calculate new
5368 * permissions based on new graph. If we fail, we'll roll-back the
5369 * replacement.
5371 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5372 if (ret < 0) {
5373 goto out;
5376 if (detach_subchain) {
5377 /* to_cow_parent is already drained because from is drained */
5378 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5381 refresh_list = g_slist_prepend(refresh_list, to);
5382 refresh_list = g_slist_prepend(refresh_list, from);
5384 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5385 if (ret < 0) {
5386 goto out;
5389 ret = 0;
5391 out:
5392 tran_finalize(tran, ret);
5393 return ret;
5396 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5397 Error **errp)
5399 return bdrv_replace_node_common(from, to, true, false, errp);
5402 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5404 BlockDriverState *child_bs;
5405 int ret;
5407 GLOBAL_STATE_CODE();
5409 bdrv_graph_rdlock_main_loop();
5410 child_bs = bdrv_filter_or_cow_bs(bs);
5411 bdrv_graph_rdunlock_main_loop();
5413 bdrv_drained_begin(child_bs);
5414 bdrv_graph_wrlock();
5415 ret = bdrv_replace_node_common(bs, child_bs, true, true, errp);
5416 bdrv_graph_wrunlock();
5417 bdrv_drained_end(child_bs);
5419 return ret;
5423 * Add new bs contents at the top of an image chain while the chain is
5424 * live, while keeping required fields on the top layer.
5426 * This will modify the BlockDriverState fields, and swap contents
5427 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5429 * bs_new must not be attached to a BlockBackend and must not have backing
5430 * child.
5432 * This function does not create any image files.
5434 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5435 Error **errp)
5437 int ret;
5438 BdrvChild *child;
5439 Transaction *tran = tran_new();
5441 GLOBAL_STATE_CODE();
5443 bdrv_graph_rdlock_main_loop();
5444 assert(!bs_new->backing);
5445 bdrv_graph_rdunlock_main_loop();
5447 bdrv_drained_begin(bs_top);
5448 bdrv_drained_begin(bs_new);
5450 bdrv_graph_wrlock();
5452 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5453 &child_of_bds, bdrv_backing_role(bs_new),
5454 tran, errp);
5455 if (!child) {
5456 ret = -EINVAL;
5457 goto out;
5460 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5461 if (ret < 0) {
5462 goto out;
5465 ret = bdrv_refresh_perms(bs_new, tran, errp);
5466 out:
5467 tran_finalize(tran, ret);
5469 bdrv_refresh_limits(bs_top, NULL, NULL);
5470 bdrv_graph_wrunlock();
5472 bdrv_drained_end(bs_top);
5473 bdrv_drained_end(bs_new);
5475 return ret;
5478 /* Not for empty child */
5479 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5480 Error **errp)
5482 int ret;
5483 Transaction *tran = tran_new();
5484 g_autoptr(GSList) refresh_list = NULL;
5485 BlockDriverState *old_bs = child->bs;
5487 GLOBAL_STATE_CODE();
5489 bdrv_ref(old_bs);
5490 bdrv_drained_begin(old_bs);
5491 bdrv_drained_begin(new_bs);
5492 bdrv_graph_wrlock();
5494 bdrv_replace_child_tran(child, new_bs, tran);
5496 refresh_list = g_slist_prepend(refresh_list, old_bs);
5497 refresh_list = g_slist_prepend(refresh_list, new_bs);
5499 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5501 tran_finalize(tran, ret);
5503 bdrv_graph_wrunlock();
5504 bdrv_drained_end(old_bs);
5505 bdrv_drained_end(new_bs);
5506 bdrv_unref(old_bs);
5508 return ret;
5511 static void bdrv_delete(BlockDriverState *bs)
5513 assert(bdrv_op_blocker_is_empty(bs));
5514 assert(!bs->refcnt);
5515 GLOBAL_STATE_CODE();
5517 /* remove from list, if necessary */
5518 if (bs->node_name[0] != '\0') {
5519 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5521 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5523 bdrv_close(bs);
5525 qemu_mutex_destroy(&bs->reqs_lock);
5527 g_free(bs);
5532 * Replace @bs by newly created block node.
5534 * @options is a QDict of options to pass to the block drivers, or NULL for an
5535 * empty set of options. The reference to the QDict belongs to the block layer
5536 * after the call (even on failure), so if the caller intends to reuse the
5537 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5539 * The caller must make sure that @bs stays in the same AioContext, i.e.
5540 * @options must not refer to nodes in a different AioContext.
5542 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5543 int flags, Error **errp)
5545 ERRP_GUARD();
5546 int ret;
5547 AioContext *ctx = bdrv_get_aio_context(bs);
5548 BlockDriverState *new_node_bs = NULL;
5549 const char *drvname, *node_name;
5550 BlockDriver *drv;
5552 drvname = qdict_get_try_str(options, "driver");
5553 if (!drvname) {
5554 error_setg(errp, "driver is not specified");
5555 goto fail;
5558 drv = bdrv_find_format(drvname);
5559 if (!drv) {
5560 error_setg(errp, "Unknown driver: '%s'", drvname);
5561 goto fail;
5564 node_name = qdict_get_try_str(options, "node-name");
5566 GLOBAL_STATE_CODE();
5568 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5569 errp);
5570 assert(bdrv_get_aio_context(bs) == ctx);
5572 options = NULL; /* bdrv_new_open_driver() eats options */
5573 if (!new_node_bs) {
5574 error_prepend(errp, "Could not create node: ");
5575 goto fail;
5579 * Make sure that @bs doesn't go away until we have successfully attached
5580 * all of its parents to @new_node_bs and undrained it again.
5582 bdrv_ref(bs);
5583 bdrv_drained_begin(bs);
5584 bdrv_drained_begin(new_node_bs);
5585 bdrv_graph_wrlock();
5586 ret = bdrv_replace_node(bs, new_node_bs, errp);
5587 bdrv_graph_wrunlock();
5588 bdrv_drained_end(new_node_bs);
5589 bdrv_drained_end(bs);
5590 bdrv_unref(bs);
5592 if (ret < 0) {
5593 error_prepend(errp, "Could not replace node: ");
5594 goto fail;
5597 return new_node_bs;
5599 fail:
5600 qobject_unref(options);
5601 bdrv_unref(new_node_bs);
5602 return NULL;
5606 * Run consistency checks on an image
5608 * Returns 0 if the check could be completed (it doesn't mean that the image is
5609 * free of errors) or -errno when an internal error occurred. The results of the
5610 * check are stored in res.
5612 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5613 BdrvCheckResult *res, BdrvCheckMode fix)
5615 IO_CODE();
5616 assert_bdrv_graph_readable();
5617 if (bs->drv == NULL) {
5618 return -ENOMEDIUM;
5620 if (bs->drv->bdrv_co_check == NULL) {
5621 return -ENOTSUP;
5624 memset(res, 0, sizeof(*res));
5625 return bs->drv->bdrv_co_check(bs, res, fix);
5629 * Return values:
5630 * 0 - success
5631 * -EINVAL - backing format specified, but no file
5632 * -ENOSPC - can't update the backing file because no space is left in the
5633 * image file header
5634 * -ENOTSUP - format driver doesn't support changing the backing file
5636 int coroutine_fn
5637 bdrv_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
5638 const char *backing_fmt, bool require)
5640 BlockDriver *drv = bs->drv;
5641 int ret;
5643 IO_CODE();
5645 if (!drv) {
5646 return -ENOMEDIUM;
5649 /* Backing file format doesn't make sense without a backing file */
5650 if (backing_fmt && !backing_file) {
5651 return -EINVAL;
5654 if (require && backing_file && !backing_fmt) {
5655 return -EINVAL;
5658 if (drv->bdrv_co_change_backing_file != NULL) {
5659 ret = drv->bdrv_co_change_backing_file(bs, backing_file, backing_fmt);
5660 } else {
5661 ret = -ENOTSUP;
5664 if (ret == 0) {
5665 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5666 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5667 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5668 backing_file ?: "");
5670 return ret;
5674 * Finds the first non-filter node above bs in the chain between
5675 * active and bs. The returned node is either an immediate parent of
5676 * bs, or there are only filter nodes between the two.
5678 * Returns NULL if bs is not found in active's image chain,
5679 * or if active == bs.
5681 * Returns the bottommost base image if bs == NULL.
5683 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5684 BlockDriverState *bs)
5687 GLOBAL_STATE_CODE();
5689 bs = bdrv_skip_filters(bs);
5690 active = bdrv_skip_filters(active);
5692 while (active) {
5693 BlockDriverState *next = bdrv_backing_chain_next(active);
5694 if (bs == next) {
5695 return active;
5697 active = next;
5700 return NULL;
5703 /* Given a BDS, searches for the base layer. */
5704 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5706 GLOBAL_STATE_CODE();
5708 return bdrv_find_overlay(bs, NULL);
5712 * Return true if at least one of the COW (backing) and filter links
5713 * between @bs and @base is frozen. @errp is set if that's the case.
5714 * @base must be reachable from @bs, or NULL.
5716 static bool GRAPH_RDLOCK
5717 bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5718 Error **errp)
5720 BlockDriverState *i;
5721 BdrvChild *child;
5723 GLOBAL_STATE_CODE();
5725 for (i = bs; i != base; i = child_bs(child)) {
5726 child = bdrv_filter_or_cow_child(i);
5728 if (child && child->frozen) {
5729 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5730 child->name, i->node_name, child->bs->node_name);
5731 return true;
5735 return false;
5739 * Freeze all COW (backing) and filter links between @bs and @base.
5740 * If any of the links is already frozen the operation is aborted and
5741 * none of the links are modified.
5742 * @base must be reachable from @bs, or NULL.
5743 * Returns 0 on success. On failure returns < 0 and sets @errp.
5745 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5746 Error **errp)
5748 BlockDriverState *i;
5749 BdrvChild *child;
5751 GLOBAL_STATE_CODE();
5753 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5754 return -EPERM;
5757 for (i = bs; i != base; i = child_bs(child)) {
5758 child = bdrv_filter_or_cow_child(i);
5759 if (child && child->bs->never_freeze) {
5760 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5761 child->name, child->bs->node_name);
5762 return -EPERM;
5766 for (i = bs; i != base; i = child_bs(child)) {
5767 child = bdrv_filter_or_cow_child(i);
5768 if (child) {
5769 child->frozen = true;
5773 return 0;
5777 * Unfreeze all COW (backing) and filter links between @bs and @base.
5778 * The caller must ensure that all links are frozen before using this
5779 * function.
5780 * @base must be reachable from @bs, or NULL.
5782 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5784 BlockDriverState *i;
5785 BdrvChild *child;
5787 GLOBAL_STATE_CODE();
5789 for (i = bs; i != base; i = child_bs(child)) {
5790 child = bdrv_filter_or_cow_child(i);
5791 if (child) {
5792 assert(child->frozen);
5793 child->frozen = false;
5799 * Drops images above 'base' up to and including 'top', and sets the image
5800 * above 'top' to have base as its backing file.
5802 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5803 * information in 'bs' can be properly updated.
5805 * E.g., this will convert the following chain:
5806 * bottom <- base <- intermediate <- top <- active
5808 * to
5810 * bottom <- base <- active
5812 * It is allowed for bottom==base, in which case it converts:
5814 * base <- intermediate <- top <- active
5816 * to
5818 * base <- active
5820 * If backing_file_str is non-NULL, it will be used when modifying top's
5821 * overlay image metadata.
5823 * Error conditions:
5824 * if active == top, that is considered an error
5827 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5828 const char *backing_file_str,
5829 bool backing_mask_protocol)
5831 BlockDriverState *explicit_top = top;
5832 bool update_inherits_from;
5833 BdrvChild *c;
5834 Error *local_err = NULL;
5835 int ret = -EIO;
5836 g_autoptr(GSList) updated_children = NULL;
5837 GSList *p;
5839 GLOBAL_STATE_CODE();
5841 bdrv_ref(top);
5842 bdrv_drained_begin(base);
5843 bdrv_graph_wrlock();
5845 if (!top->drv || !base->drv) {
5846 goto exit_wrlock;
5849 /* Make sure that base is in the backing chain of top */
5850 if (!bdrv_chain_contains(top, base)) {
5851 goto exit_wrlock;
5854 /* If 'base' recursively inherits from 'top' then we should set
5855 * base->inherits_from to top->inherits_from after 'top' and all
5856 * other intermediate nodes have been dropped.
5857 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5858 * it because no one inherits from it. We use explicit_top for that. */
5859 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5860 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5862 /* success - we can delete the intermediate states, and link top->base */
5863 if (!backing_file_str) {
5864 bdrv_refresh_filename(base);
5865 backing_file_str = base->filename;
5868 QLIST_FOREACH(c, &top->parents, next_parent) {
5869 updated_children = g_slist_prepend(updated_children, c);
5873 * It seems correct to pass detach_subchain=true here, but it triggers
5874 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5875 * another drained section, which modify the graph (for example, removing
5876 * the child, which we keep in updated_children list). So, it's a TODO.
5878 * Note, bug triggered if pass detach_subchain=true here and run
5879 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5880 * That's a FIXME.
5882 bdrv_replace_node_common(top, base, false, false, &local_err);
5883 bdrv_graph_wrunlock();
5885 if (local_err) {
5886 error_report_err(local_err);
5887 goto exit;
5890 for (p = updated_children; p; p = p->next) {
5891 c = p->data;
5893 if (c->klass->update_filename) {
5894 ret = c->klass->update_filename(c, base, backing_file_str,
5895 backing_mask_protocol,
5896 &local_err);
5897 if (ret < 0) {
5899 * TODO: Actually, we want to rollback all previous iterations
5900 * of this loop, and (which is almost impossible) previous
5901 * bdrv_replace_node()...
5903 * Note, that c->klass->update_filename may lead to permission
5904 * update, so it's a bad idea to call it inside permission
5905 * update transaction of bdrv_replace_node.
5907 error_report_err(local_err);
5908 goto exit;
5913 if (update_inherits_from) {
5914 base->inherits_from = explicit_top->inherits_from;
5917 ret = 0;
5918 goto exit;
5920 exit_wrlock:
5921 bdrv_graph_wrunlock();
5922 exit:
5923 bdrv_drained_end(base);
5924 bdrv_unref(top);
5925 return ret;
5929 * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
5930 * sums the size of all data-bearing children. (This excludes backing
5931 * children.)
5933 static int64_t coroutine_fn GRAPH_RDLOCK
5934 bdrv_sum_allocated_file_size(BlockDriverState *bs)
5936 BdrvChild *child;
5937 int64_t child_size, sum = 0;
5939 QLIST_FOREACH(child, &bs->children, next) {
5940 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5941 BDRV_CHILD_FILTERED))
5943 child_size = bdrv_co_get_allocated_file_size(child->bs);
5944 if (child_size < 0) {
5945 return child_size;
5947 sum += child_size;
5951 return sum;
5955 * Length of a allocated file in bytes. Sparse files are counted by actual
5956 * allocated space. Return < 0 if error or unknown.
5958 int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
5960 BlockDriver *drv = bs->drv;
5961 IO_CODE();
5962 assert_bdrv_graph_readable();
5964 if (!drv) {
5965 return -ENOMEDIUM;
5967 if (drv->bdrv_co_get_allocated_file_size) {
5968 return drv->bdrv_co_get_allocated_file_size(bs);
5971 if (drv->protocol_name) {
5973 * Protocol drivers default to -ENOTSUP (most of their data is
5974 * not stored in any of their children (if they even have any),
5975 * so there is no generic way to figure it out).
5977 return -ENOTSUP;
5978 } else if (drv->is_filter) {
5979 /* Filter drivers default to the size of their filtered child */
5980 return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
5981 } else {
5982 /* Other drivers default to summing their children's sizes */
5983 return bdrv_sum_allocated_file_size(bs);
5988 * bdrv_measure:
5989 * @drv: Format driver
5990 * @opts: Creation options for new image
5991 * @in_bs: Existing image containing data for new image (may be NULL)
5992 * @errp: Error object
5993 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5994 * or NULL on error
5996 * Calculate file size required to create a new image.
5998 * If @in_bs is given then space for allocated clusters and zero clusters
5999 * from that image are included in the calculation. If @opts contains a
6000 * backing file that is shared by @in_bs then backing clusters may be omitted
6001 * from the calculation.
6003 * If @in_bs is NULL then the calculation includes no allocated clusters
6004 * unless a preallocation option is given in @opts.
6006 * Note that @in_bs may use a different BlockDriver from @drv.
6008 * If an error occurs the @errp pointer is set.
6010 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
6011 BlockDriverState *in_bs, Error **errp)
6013 IO_CODE();
6014 if (!drv->bdrv_measure) {
6015 error_setg(errp, "Block driver '%s' does not support size measurement",
6016 drv->format_name);
6017 return NULL;
6020 return drv->bdrv_measure(opts, in_bs, errp);
6024 * Return number of sectors on success, -errno on error.
6026 int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
6028 BlockDriver *drv = bs->drv;
6029 IO_CODE();
6030 assert_bdrv_graph_readable();
6032 if (!drv)
6033 return -ENOMEDIUM;
6035 if (bs->bl.has_variable_length) {
6036 int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
6037 if (ret < 0) {
6038 return ret;
6041 return bs->total_sectors;
6045 * This wrapper is written by hand because this function is in the hot I/O path,
6046 * via blk_get_geometry.
6048 int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
6050 BlockDriver *drv = bs->drv;
6051 IO_CODE();
6053 if (!drv)
6054 return -ENOMEDIUM;
6056 if (bs->bl.has_variable_length) {
6057 int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6058 if (ret < 0) {
6059 return ret;
6063 return bs->total_sectors;
6067 * Return length in bytes on success, -errno on error.
6068 * The length is always a multiple of BDRV_SECTOR_SIZE.
6070 int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
6072 int64_t ret;
6073 IO_CODE();
6074 assert_bdrv_graph_readable();
6076 ret = bdrv_co_nb_sectors(bs);
6077 if (ret < 0) {
6078 return ret;
6080 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
6081 return -EFBIG;
6083 return ret * BDRV_SECTOR_SIZE;
6086 bool bdrv_is_sg(BlockDriverState *bs)
6088 IO_CODE();
6089 return bs->sg;
6093 * Return whether the given node supports compressed writes.
6095 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
6097 BlockDriverState *filtered;
6098 IO_CODE();
6100 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
6101 return false;
6104 filtered = bdrv_filter_bs(bs);
6105 if (filtered) {
6107 * Filters can only forward compressed writes, so we have to
6108 * check the child.
6110 return bdrv_supports_compressed_writes(filtered);
6113 return true;
6116 const char *bdrv_get_format_name(BlockDriverState *bs)
6118 IO_CODE();
6119 return bs->drv ? bs->drv->format_name : NULL;
6122 static int qsort_strcmp(const void *a, const void *b)
6124 return strcmp(*(char *const *)a, *(char *const *)b);
6127 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
6128 void *opaque, bool read_only)
6130 BlockDriver *drv;
6131 int count = 0;
6132 int i;
6133 const char **formats = NULL;
6135 GLOBAL_STATE_CODE();
6137 QLIST_FOREACH(drv, &bdrv_drivers, list) {
6138 if (drv->format_name) {
6139 bool found = false;
6141 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
6142 continue;
6145 i = count;
6146 while (formats && i && !found) {
6147 found = !strcmp(formats[--i], drv->format_name);
6150 if (!found) {
6151 formats = g_renew(const char *, formats, count + 1);
6152 formats[count++] = drv->format_name;
6157 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
6158 const char *format_name = block_driver_modules[i].format_name;
6160 if (format_name) {
6161 bool found = false;
6162 int j = count;
6164 if (use_bdrv_whitelist &&
6165 !bdrv_format_is_whitelisted(format_name, read_only)) {
6166 continue;
6169 while (formats && j && !found) {
6170 found = !strcmp(formats[--j], format_name);
6173 if (!found) {
6174 formats = g_renew(const char *, formats, count + 1);
6175 formats[count++] = format_name;
6180 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6182 for (i = 0; i < count; i++) {
6183 it(opaque, formats[i]);
6186 g_free(formats);
6189 /* This function is to find a node in the bs graph */
6190 BlockDriverState *bdrv_find_node(const char *node_name)
6192 BlockDriverState *bs;
6194 assert(node_name);
6195 GLOBAL_STATE_CODE();
6197 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6198 if (!strcmp(node_name, bs->node_name)) {
6199 return bs;
6202 return NULL;
6205 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6206 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6207 Error **errp)
6209 BlockDeviceInfoList *list;
6210 BlockDriverState *bs;
6212 GLOBAL_STATE_CODE();
6213 GRAPH_RDLOCK_GUARD_MAINLOOP();
6215 list = NULL;
6216 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6217 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6218 if (!info) {
6219 qapi_free_BlockDeviceInfoList(list);
6220 return NULL;
6222 QAPI_LIST_PREPEND(list, info);
6225 return list;
6228 typedef struct XDbgBlockGraphConstructor {
6229 XDbgBlockGraph *graph;
6230 GHashTable *graph_nodes;
6231 } XDbgBlockGraphConstructor;
6233 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6235 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6237 gr->graph = g_new0(XDbgBlockGraph, 1);
6238 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6240 return gr;
6243 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6245 XDbgBlockGraph *graph = gr->graph;
6247 g_hash_table_destroy(gr->graph_nodes);
6248 g_free(gr);
6250 return graph;
6253 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6255 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6257 if (ret != 0) {
6258 return ret;
6262 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6263 * answer of g_hash_table_lookup.
6265 ret = g_hash_table_size(gr->graph_nodes) + 1;
6266 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6268 return ret;
6271 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6272 XDbgBlockGraphNodeType type, const char *name)
6274 XDbgBlockGraphNode *n;
6276 n = g_new0(XDbgBlockGraphNode, 1);
6278 n->id = xdbg_graph_node_num(gr, node);
6279 n->type = type;
6280 n->name = g_strdup(name);
6282 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6285 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6286 const BdrvChild *child)
6288 BlockPermission qapi_perm;
6289 XDbgBlockGraphEdge *edge;
6290 GLOBAL_STATE_CODE();
6292 edge = g_new0(XDbgBlockGraphEdge, 1);
6294 edge->parent = xdbg_graph_node_num(gr, parent);
6295 edge->child = xdbg_graph_node_num(gr, child->bs);
6296 edge->name = g_strdup(child->name);
6298 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6299 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6301 if (flag & child->perm) {
6302 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6304 if (flag & child->shared_perm) {
6305 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6309 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6313 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6315 BlockBackend *blk;
6316 BlockJob *job;
6317 BlockDriverState *bs;
6318 BdrvChild *child;
6319 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6321 GLOBAL_STATE_CODE();
6323 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6324 char *allocated_name = NULL;
6325 const char *name = blk_name(blk);
6327 if (!*name) {
6328 name = allocated_name = blk_get_attached_dev_id(blk);
6330 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6331 name);
6332 g_free(allocated_name);
6333 if (blk_root(blk)) {
6334 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6338 WITH_JOB_LOCK_GUARD() {
6339 for (job = block_job_next_locked(NULL); job;
6340 job = block_job_next_locked(job)) {
6341 GSList *el;
6343 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6344 job->job.id);
6345 for (el = job->nodes; el; el = el->next) {
6346 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6351 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6352 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6353 bs->node_name);
6354 QLIST_FOREACH(child, &bs->children, next) {
6355 xdbg_graph_add_edge(gr, bs, child);
6359 return xdbg_graph_finalize(gr);
6362 BlockDriverState *bdrv_lookup_bs(const char *device,
6363 const char *node_name,
6364 Error **errp)
6366 BlockBackend *blk;
6367 BlockDriverState *bs;
6369 GLOBAL_STATE_CODE();
6371 if (device) {
6372 blk = blk_by_name(device);
6374 if (blk) {
6375 bs = blk_bs(blk);
6376 if (!bs) {
6377 error_setg(errp, "Device '%s' has no medium", device);
6380 return bs;
6384 if (node_name) {
6385 bs = bdrv_find_node(node_name);
6387 if (bs) {
6388 return bs;
6392 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6393 device ? device : "",
6394 node_name ? node_name : "");
6395 return NULL;
6398 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6399 * return false. If either argument is NULL, return false. */
6400 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6403 GLOBAL_STATE_CODE();
6405 while (top && top != base) {
6406 top = bdrv_filter_or_cow_bs(top);
6409 return top != NULL;
6412 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6414 GLOBAL_STATE_CODE();
6415 if (!bs) {
6416 return QTAILQ_FIRST(&graph_bdrv_states);
6418 return QTAILQ_NEXT(bs, node_list);
6421 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6423 GLOBAL_STATE_CODE();
6424 if (!bs) {
6425 return QTAILQ_FIRST(&all_bdrv_states);
6427 return QTAILQ_NEXT(bs, bs_list);
6430 const char *bdrv_get_node_name(const BlockDriverState *bs)
6432 IO_CODE();
6433 return bs->node_name;
6436 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6438 BdrvChild *c;
6439 const char *name;
6440 IO_CODE();
6442 /* If multiple parents have a name, just pick the first one. */
6443 QLIST_FOREACH(c, &bs->parents, next_parent) {
6444 if (c->klass->get_name) {
6445 name = c->klass->get_name(c);
6446 if (name && *name) {
6447 return name;
6452 return NULL;
6455 /* TODO check what callers really want: bs->node_name or blk_name() */
6456 const char *bdrv_get_device_name(const BlockDriverState *bs)
6458 IO_CODE();
6459 return bdrv_get_parent_name(bs) ?: "";
6462 /* This can be used to identify nodes that might not have a device
6463 * name associated. Since node and device names live in the same
6464 * namespace, the result is unambiguous. The exception is if both are
6465 * absent, then this returns an empty (non-null) string. */
6466 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6468 IO_CODE();
6469 return bdrv_get_parent_name(bs) ?: bs->node_name;
6472 int bdrv_get_flags(BlockDriverState *bs)
6474 IO_CODE();
6475 return bs->open_flags;
6478 int bdrv_has_zero_init_1(BlockDriverState *bs)
6480 GLOBAL_STATE_CODE();
6481 return 1;
6484 int coroutine_mixed_fn bdrv_has_zero_init(BlockDriverState *bs)
6486 BlockDriverState *filtered;
6487 GLOBAL_STATE_CODE();
6489 if (!bs->drv) {
6490 return 0;
6493 /* If BS is a copy on write image, it is initialized to
6494 the contents of the base image, which may not be zeroes. */
6495 if (bdrv_cow_child(bs)) {
6496 return 0;
6498 if (bs->drv->bdrv_has_zero_init) {
6499 return bs->drv->bdrv_has_zero_init(bs);
6502 filtered = bdrv_filter_bs(bs);
6503 if (filtered) {
6504 return bdrv_has_zero_init(filtered);
6507 /* safe default */
6508 return 0;
6511 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6513 IO_CODE();
6514 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6515 return false;
6518 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6521 void bdrv_get_backing_filename(BlockDriverState *bs,
6522 char *filename, int filename_size)
6524 IO_CODE();
6525 pstrcpy(filename, filename_size, bs->backing_file);
6528 int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6530 int ret;
6531 BlockDriver *drv = bs->drv;
6532 IO_CODE();
6533 assert_bdrv_graph_readable();
6535 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6536 if (!drv) {
6537 return -ENOMEDIUM;
6539 if (!drv->bdrv_co_get_info) {
6540 BlockDriverState *filtered = bdrv_filter_bs(bs);
6541 if (filtered) {
6542 return bdrv_co_get_info(filtered, bdi);
6544 return -ENOTSUP;
6546 memset(bdi, 0, sizeof(*bdi));
6547 ret = drv->bdrv_co_get_info(bs, bdi);
6548 if (bdi->subcluster_size == 0) {
6550 * If the driver left this unset, subclusters are not supported.
6551 * Then it is safe to treat each cluster as having only one subcluster.
6553 bdi->subcluster_size = bdi->cluster_size;
6555 if (ret < 0) {
6556 return ret;
6559 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6560 return -EINVAL;
6563 return 0;
6566 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6567 Error **errp)
6569 BlockDriver *drv = bs->drv;
6570 IO_CODE();
6571 if (drv && drv->bdrv_get_specific_info) {
6572 return drv->bdrv_get_specific_info(bs, errp);
6574 return NULL;
6577 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6579 BlockDriver *drv = bs->drv;
6580 IO_CODE();
6581 if (!drv || !drv->bdrv_get_specific_stats) {
6582 return NULL;
6584 return drv->bdrv_get_specific_stats(bs);
6587 void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6589 IO_CODE();
6590 assert_bdrv_graph_readable();
6592 if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
6593 return;
6596 bs->drv->bdrv_co_debug_event(bs, event);
6599 static BlockDriverState * GRAPH_RDLOCK
6600 bdrv_find_debug_node(BlockDriverState *bs)
6602 GLOBAL_STATE_CODE();
6603 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6604 bs = bdrv_primary_bs(bs);
6607 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6608 assert(bs->drv->bdrv_debug_remove_breakpoint);
6609 return bs;
6612 return NULL;
6615 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6616 const char *tag)
6618 GLOBAL_STATE_CODE();
6619 GRAPH_RDLOCK_GUARD_MAINLOOP();
6621 bs = bdrv_find_debug_node(bs);
6622 if (bs) {
6623 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6626 return -ENOTSUP;
6629 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6631 GLOBAL_STATE_CODE();
6632 GRAPH_RDLOCK_GUARD_MAINLOOP();
6634 bs = bdrv_find_debug_node(bs);
6635 if (bs) {
6636 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6639 return -ENOTSUP;
6642 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6644 GLOBAL_STATE_CODE();
6645 GRAPH_RDLOCK_GUARD_MAINLOOP();
6647 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6648 bs = bdrv_primary_bs(bs);
6651 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6652 return bs->drv->bdrv_debug_resume(bs, tag);
6655 return -ENOTSUP;
6658 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6660 GLOBAL_STATE_CODE();
6661 GRAPH_RDLOCK_GUARD_MAINLOOP();
6663 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6664 bs = bdrv_primary_bs(bs);
6667 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6668 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6671 return false;
6674 /* backing_file can either be relative, or absolute, or a protocol. If it is
6675 * relative, it must be relative to the chain. So, passing in bs->filename
6676 * from a BDS as backing_file should not be done, as that may be relative to
6677 * the CWD rather than the chain. */
6678 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6679 const char *backing_file)
6681 char *filename_full = NULL;
6682 char *backing_file_full = NULL;
6683 char *filename_tmp = NULL;
6684 int is_protocol = 0;
6685 bool filenames_refreshed = false;
6686 BlockDriverState *curr_bs = NULL;
6687 BlockDriverState *retval = NULL;
6688 BlockDriverState *bs_below;
6690 GLOBAL_STATE_CODE();
6691 GRAPH_RDLOCK_GUARD_MAINLOOP();
6693 if (!bs || !bs->drv || !backing_file) {
6694 return NULL;
6697 filename_full = g_malloc(PATH_MAX);
6698 backing_file_full = g_malloc(PATH_MAX);
6700 is_protocol = path_has_protocol(backing_file);
6703 * Being largely a legacy function, skip any filters here
6704 * (because filters do not have normal filenames, so they cannot
6705 * match anyway; and allowing json:{} filenames is a bit out of
6706 * scope).
6708 for (curr_bs = bdrv_skip_filters(bs);
6709 bdrv_cow_child(curr_bs) != NULL;
6710 curr_bs = bs_below)
6712 bs_below = bdrv_backing_chain_next(curr_bs);
6714 if (bdrv_backing_overridden(curr_bs)) {
6716 * If the backing file was overridden, we can only compare
6717 * directly against the backing node's filename.
6720 if (!filenames_refreshed) {
6722 * This will automatically refresh all of the
6723 * filenames in the rest of the backing chain, so we
6724 * only need to do this once.
6726 bdrv_refresh_filename(bs_below);
6727 filenames_refreshed = true;
6730 if (strcmp(backing_file, bs_below->filename) == 0) {
6731 retval = bs_below;
6732 break;
6734 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6736 * If either of the filename paths is actually a protocol, then
6737 * compare unmodified paths; otherwise make paths relative.
6739 char *backing_file_full_ret;
6741 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6742 retval = bs_below;
6743 break;
6745 /* Also check against the full backing filename for the image */
6746 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6747 NULL);
6748 if (backing_file_full_ret) {
6749 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6750 g_free(backing_file_full_ret);
6751 if (equal) {
6752 retval = bs_below;
6753 break;
6756 } else {
6757 /* If not an absolute filename path, make it relative to the current
6758 * image's filename path */
6759 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6760 NULL);
6761 /* We are going to compare canonicalized absolute pathnames */
6762 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6763 g_free(filename_tmp);
6764 continue;
6766 g_free(filename_tmp);
6768 /* We need to make sure the backing filename we are comparing against
6769 * is relative to the current image filename (or absolute) */
6770 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6771 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6772 g_free(filename_tmp);
6773 continue;
6775 g_free(filename_tmp);
6777 if (strcmp(backing_file_full, filename_full) == 0) {
6778 retval = bs_below;
6779 break;
6784 g_free(filename_full);
6785 g_free(backing_file_full);
6786 return retval;
6789 void bdrv_init(void)
6791 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6792 use_bdrv_whitelist = 1;
6793 #endif
6794 module_call_init(MODULE_INIT_BLOCK);
6797 void bdrv_init_with_whitelist(void)
6799 use_bdrv_whitelist = 1;
6800 bdrv_init();
6803 int bdrv_activate(BlockDriverState *bs, Error **errp)
6805 BdrvChild *child, *parent;
6806 Error *local_err = NULL;
6807 int ret;
6808 BdrvDirtyBitmap *bm;
6810 GLOBAL_STATE_CODE();
6811 GRAPH_RDLOCK_GUARD_MAINLOOP();
6813 if (!bs->drv) {
6814 return -ENOMEDIUM;
6817 QLIST_FOREACH(child, &bs->children, next) {
6818 bdrv_activate(child->bs, &local_err);
6819 if (local_err) {
6820 error_propagate(errp, local_err);
6821 return -EINVAL;
6826 * Update permissions, they may differ for inactive nodes.
6828 * Note that the required permissions of inactive images are always a
6829 * subset of the permissions required after activating the image. This
6830 * allows us to just get the permissions upfront without restricting
6831 * bdrv_co_invalidate_cache().
6833 * It also means that in error cases, we don't have to try and revert to
6834 * the old permissions (which is an operation that could fail, too). We can
6835 * just keep the extended permissions for the next time that an activation
6836 * of the image is tried.
6838 if (bs->open_flags & BDRV_O_INACTIVE) {
6839 bs->open_flags &= ~BDRV_O_INACTIVE;
6840 ret = bdrv_refresh_perms(bs, NULL, errp);
6841 if (ret < 0) {
6842 bs->open_flags |= BDRV_O_INACTIVE;
6843 return ret;
6846 ret = bdrv_invalidate_cache(bs, errp);
6847 if (ret < 0) {
6848 bs->open_flags |= BDRV_O_INACTIVE;
6849 return ret;
6852 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6853 bdrv_dirty_bitmap_skip_store(bm, false);
6856 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6857 if (ret < 0) {
6858 bs->open_flags |= BDRV_O_INACTIVE;
6859 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6860 return ret;
6864 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6865 if (parent->klass->activate) {
6866 parent->klass->activate(parent, &local_err);
6867 if (local_err) {
6868 bs->open_flags |= BDRV_O_INACTIVE;
6869 error_propagate(errp, local_err);
6870 return -EINVAL;
6875 return 0;
6878 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6880 Error *local_err = NULL;
6881 IO_CODE();
6883 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6884 assert_bdrv_graph_readable();
6886 if (bs->drv->bdrv_co_invalidate_cache) {
6887 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6888 if (local_err) {
6889 error_propagate(errp, local_err);
6890 return -EINVAL;
6894 return 0;
6897 void bdrv_activate_all(Error **errp)
6899 BlockDriverState *bs;
6900 BdrvNextIterator it;
6902 GLOBAL_STATE_CODE();
6903 GRAPH_RDLOCK_GUARD_MAINLOOP();
6905 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6906 int ret;
6908 ret = bdrv_activate(bs, errp);
6909 if (ret < 0) {
6910 bdrv_next_cleanup(&it);
6911 return;
6916 static bool GRAPH_RDLOCK
6917 bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6919 BdrvChild *parent;
6920 GLOBAL_STATE_CODE();
6922 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6923 if (parent->klass->parent_is_bds) {
6924 BlockDriverState *parent_bs = parent->opaque;
6925 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6926 return true;
6931 return false;
6934 static int GRAPH_RDLOCK bdrv_inactivate_recurse(BlockDriverState *bs)
6936 BdrvChild *child, *parent;
6937 int ret;
6938 uint64_t cumulative_perms, cumulative_shared_perms;
6940 GLOBAL_STATE_CODE();
6942 if (!bs->drv) {
6943 return -ENOMEDIUM;
6946 /* Make sure that we don't inactivate a child before its parent.
6947 * It will be covered by recursion from the yet active parent. */
6948 if (bdrv_has_bds_parent(bs, true)) {
6949 return 0;
6952 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6954 /* Inactivate this node */
6955 if (bs->drv->bdrv_inactivate) {
6956 ret = bs->drv->bdrv_inactivate(bs);
6957 if (ret < 0) {
6958 return ret;
6962 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6963 if (parent->klass->inactivate) {
6964 ret = parent->klass->inactivate(parent);
6965 if (ret < 0) {
6966 return ret;
6971 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6972 &cumulative_shared_perms);
6973 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6974 /* Our inactive parents still need write access. Inactivation failed. */
6975 return -EPERM;
6978 bs->open_flags |= BDRV_O_INACTIVE;
6981 * Update permissions, they may differ for inactive nodes.
6982 * We only tried to loosen restrictions, so errors are not fatal, ignore
6983 * them.
6985 bdrv_refresh_perms(bs, NULL, NULL);
6987 /* Recursively inactivate children */
6988 QLIST_FOREACH(child, &bs->children, next) {
6989 ret = bdrv_inactivate_recurse(child->bs);
6990 if (ret < 0) {
6991 return ret;
6995 return 0;
6998 int bdrv_inactivate_all(void)
7000 BlockDriverState *bs = NULL;
7001 BdrvNextIterator it;
7002 int ret = 0;
7004 GLOBAL_STATE_CODE();
7005 GRAPH_RDLOCK_GUARD_MAINLOOP();
7007 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
7008 /* Nodes with BDS parents are covered by recursion from the last
7009 * parent that gets inactivated. Don't inactivate them a second
7010 * time if that has already happened. */
7011 if (bdrv_has_bds_parent(bs, false)) {
7012 continue;
7014 ret = bdrv_inactivate_recurse(bs);
7015 if (ret < 0) {
7016 bdrv_next_cleanup(&it);
7017 break;
7021 return ret;
7024 /**************************************************************/
7025 /* removable device support */
7028 * Return TRUE if the media is present
7030 bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
7032 BlockDriver *drv = bs->drv;
7033 BdrvChild *child;
7034 IO_CODE();
7035 assert_bdrv_graph_readable();
7037 if (!drv) {
7038 return false;
7040 if (drv->bdrv_co_is_inserted) {
7041 return drv->bdrv_co_is_inserted(bs);
7043 QLIST_FOREACH(child, &bs->children, next) {
7044 if (!bdrv_co_is_inserted(child->bs)) {
7045 return false;
7048 return true;
7052 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
7054 void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
7056 BlockDriver *drv = bs->drv;
7057 IO_CODE();
7058 assert_bdrv_graph_readable();
7060 if (drv && drv->bdrv_co_eject) {
7061 drv->bdrv_co_eject(bs, eject_flag);
7066 * Lock or unlock the media (if it is locked, the user won't be able
7067 * to eject it manually).
7069 void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
7071 BlockDriver *drv = bs->drv;
7072 IO_CODE();
7073 assert_bdrv_graph_readable();
7074 trace_bdrv_lock_medium(bs, locked);
7076 if (drv && drv->bdrv_co_lock_medium) {
7077 drv->bdrv_co_lock_medium(bs, locked);
7081 /* Get a reference to bs */
7082 void bdrv_ref(BlockDriverState *bs)
7084 GLOBAL_STATE_CODE();
7085 bs->refcnt++;
7088 /* Release a previously grabbed reference to bs.
7089 * If after releasing, reference count is zero, the BlockDriverState is
7090 * deleted. */
7091 void bdrv_unref(BlockDriverState *bs)
7093 GLOBAL_STATE_CODE();
7094 if (!bs) {
7095 return;
7097 assert(bs->refcnt > 0);
7098 if (--bs->refcnt == 0) {
7099 bdrv_delete(bs);
7103 static void bdrv_schedule_unref_bh(void *opaque)
7105 BlockDriverState *bs = opaque;
7107 bdrv_unref(bs);
7111 * Release a BlockDriverState reference while holding the graph write lock.
7113 * Calling bdrv_unref() directly is forbidden while holding the graph lock
7114 * because bdrv_close() both involves polling and taking the graph lock
7115 * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7116 * possibly closing @bs until the graph lock is released.
7118 void bdrv_schedule_unref(BlockDriverState *bs)
7120 if (!bs) {
7121 return;
7123 aio_bh_schedule_oneshot(qemu_get_aio_context(), bdrv_schedule_unref_bh, bs);
7126 struct BdrvOpBlocker {
7127 Error *reason;
7128 QLIST_ENTRY(BdrvOpBlocker) list;
7131 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
7133 BdrvOpBlocker *blocker;
7134 GLOBAL_STATE_CODE();
7136 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7137 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
7138 blocker = QLIST_FIRST(&bs->op_blockers[op]);
7139 error_propagate_prepend(errp, error_copy(blocker->reason),
7140 "Node '%s' is busy: ",
7141 bdrv_get_device_or_node_name(bs));
7142 return true;
7144 return false;
7147 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
7149 BdrvOpBlocker *blocker;
7150 GLOBAL_STATE_CODE();
7151 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7153 blocker = g_new0(BdrvOpBlocker, 1);
7154 blocker->reason = reason;
7155 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
7158 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
7160 BdrvOpBlocker *blocker, *next;
7161 GLOBAL_STATE_CODE();
7162 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7163 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
7164 if (blocker->reason == reason) {
7165 QLIST_REMOVE(blocker, list);
7166 g_free(blocker);
7171 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
7173 int i;
7174 GLOBAL_STATE_CODE();
7175 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7176 bdrv_op_block(bs, i, reason);
7180 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
7182 int i;
7183 GLOBAL_STATE_CODE();
7184 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7185 bdrv_op_unblock(bs, i, reason);
7189 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
7191 int i;
7192 GLOBAL_STATE_CODE();
7193 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7194 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
7195 return false;
7198 return true;
7202 * Must not be called while holding the lock of an AioContext other than the
7203 * current one.
7205 void bdrv_img_create(const char *filename, const char *fmt,
7206 const char *base_filename, const char *base_fmt,
7207 char *options, uint64_t img_size, int flags, bool quiet,
7208 Error **errp)
7210 QemuOptsList *create_opts = NULL;
7211 QemuOpts *opts = NULL;
7212 const char *backing_fmt, *backing_file;
7213 int64_t size;
7214 BlockDriver *drv, *proto_drv;
7215 Error *local_err = NULL;
7216 int ret = 0;
7218 GLOBAL_STATE_CODE();
7220 /* Find driver and parse its options */
7221 drv = bdrv_find_format(fmt);
7222 if (!drv) {
7223 error_setg(errp, "Unknown file format '%s'", fmt);
7224 return;
7227 proto_drv = bdrv_find_protocol(filename, true, errp);
7228 if (!proto_drv) {
7229 return;
7232 if (!drv->create_opts) {
7233 error_setg(errp, "Format driver '%s' does not support image creation",
7234 drv->format_name);
7235 return;
7238 if (!proto_drv->create_opts) {
7239 error_setg(errp, "Protocol driver '%s' does not support image creation",
7240 proto_drv->format_name);
7241 return;
7244 /* Create parameter list */
7245 create_opts = qemu_opts_append(create_opts, drv->create_opts);
7246 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7248 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7250 /* Parse -o options */
7251 if (options) {
7252 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7253 goto out;
7257 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7258 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7259 } else if (img_size != UINT64_C(-1)) {
7260 error_setg(errp, "The image size must be specified only once");
7261 goto out;
7264 if (base_filename) {
7265 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
7266 NULL)) {
7267 error_setg(errp, "Backing file not supported for file format '%s'",
7268 fmt);
7269 goto out;
7273 if (base_fmt) {
7274 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
7275 error_setg(errp, "Backing file format not supported for file "
7276 "format '%s'", fmt);
7277 goto out;
7281 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7282 if (backing_file) {
7283 if (!strcmp(filename, backing_file)) {
7284 error_setg(errp, "Error: Trying to create an image with the "
7285 "same filename as the backing file");
7286 goto out;
7288 if (backing_file[0] == '\0') {
7289 error_setg(errp, "Expected backing file name, got empty string");
7290 goto out;
7294 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7296 /* The size for the image must always be specified, unless we have a backing
7297 * file and we have not been forbidden from opening it. */
7298 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
7299 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7300 BlockDriverState *bs;
7301 char *full_backing;
7302 int back_flags;
7303 QDict *backing_options = NULL;
7305 full_backing =
7306 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7307 &local_err);
7308 if (local_err) {
7309 goto out;
7311 assert(full_backing);
7314 * No need to do I/O here, which allows us to open encrypted
7315 * backing images without needing the secret
7317 back_flags = flags;
7318 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7319 back_flags |= BDRV_O_NO_IO;
7321 backing_options = qdict_new();
7322 if (backing_fmt) {
7323 qdict_put_str(backing_options, "driver", backing_fmt);
7325 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7327 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7328 &local_err);
7329 g_free(full_backing);
7330 if (!bs) {
7331 error_append_hint(&local_err, "Could not open backing image.\n");
7332 goto out;
7333 } else {
7334 if (!backing_fmt) {
7335 error_setg(&local_err,
7336 "Backing file specified without backing format");
7337 error_append_hint(&local_err, "Detected format of %s.\n",
7338 bs->drv->format_name);
7339 goto out;
7341 if (size == -1) {
7342 /* Opened BS, have no size */
7343 size = bdrv_getlength(bs);
7344 if (size < 0) {
7345 error_setg_errno(errp, -size, "Could not get size of '%s'",
7346 backing_file);
7347 bdrv_unref(bs);
7348 goto out;
7350 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7352 bdrv_unref(bs);
7354 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7355 } else if (backing_file && !backing_fmt) {
7356 error_setg(&local_err,
7357 "Backing file specified without backing format");
7358 goto out;
7361 /* Parameter 'size' is not needed for detached LUKS header */
7362 if (size == -1 &&
7363 !(!strcmp(fmt, "luks") &&
7364 qemu_opt_get_bool(opts, "detached-header", false))) {
7365 error_setg(errp, "Image creation needs a size parameter");
7366 goto out;
7369 if (!quiet) {
7370 printf("Formatting '%s', fmt=%s ", filename, fmt);
7371 qemu_opts_print(opts, " ");
7372 puts("");
7373 fflush(stdout);
7376 ret = bdrv_create(drv, filename, opts, &local_err);
7378 if (ret == -EFBIG) {
7379 /* This is generally a better message than whatever the driver would
7380 * deliver (especially because of the cluster_size_hint), since that
7381 * is most probably not much different from "image too large". */
7382 const char *cluster_size_hint = "";
7383 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7384 cluster_size_hint = " (try using a larger cluster size)";
7386 error_setg(errp, "The image size is too large for file format '%s'"
7387 "%s", fmt, cluster_size_hint);
7388 error_free(local_err);
7389 local_err = NULL;
7392 out:
7393 qemu_opts_del(opts);
7394 qemu_opts_free(create_opts);
7395 error_propagate(errp, local_err);
7398 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7400 IO_CODE();
7401 return bs ? bs->aio_context : qemu_get_aio_context();
7404 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7406 Coroutine *self = qemu_coroutine_self();
7407 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7408 AioContext *new_ctx;
7409 IO_CODE();
7412 * Increase bs->in_flight to ensure that this operation is completed before
7413 * moving the node to a different AioContext. Read new_ctx only afterwards.
7415 bdrv_inc_in_flight(bs);
7417 new_ctx = bdrv_get_aio_context(bs);
7418 aio_co_reschedule_self(new_ctx);
7419 return old_ctx;
7422 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7424 IO_CODE();
7425 aio_co_reschedule_self(old_ctx);
7426 bdrv_dec_in_flight(bs);
7429 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7431 GLOBAL_STATE_CODE();
7432 QLIST_REMOVE(ban, list);
7433 g_free(ban);
7436 static void bdrv_detach_aio_context(BlockDriverState *bs)
7438 BdrvAioNotifier *baf, *baf_tmp;
7440 assert(!bs->walking_aio_notifiers);
7441 GLOBAL_STATE_CODE();
7442 bs->walking_aio_notifiers = true;
7443 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7444 if (baf->deleted) {
7445 bdrv_do_remove_aio_context_notifier(baf);
7446 } else {
7447 baf->detach_aio_context(baf->opaque);
7450 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7451 * remove remaining aio notifiers if we aren't called again.
7453 bs->walking_aio_notifiers = false;
7455 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7456 bs->drv->bdrv_detach_aio_context(bs);
7459 bs->aio_context = NULL;
7462 static void bdrv_attach_aio_context(BlockDriverState *bs,
7463 AioContext *new_context)
7465 BdrvAioNotifier *ban, *ban_tmp;
7466 GLOBAL_STATE_CODE();
7468 bs->aio_context = new_context;
7470 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7471 bs->drv->bdrv_attach_aio_context(bs, new_context);
7474 assert(!bs->walking_aio_notifiers);
7475 bs->walking_aio_notifiers = true;
7476 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7477 if (ban->deleted) {
7478 bdrv_do_remove_aio_context_notifier(ban);
7479 } else {
7480 ban->attached_aio_context(new_context, ban->opaque);
7483 bs->walking_aio_notifiers = false;
7486 typedef struct BdrvStateSetAioContext {
7487 AioContext *new_ctx;
7488 BlockDriverState *bs;
7489 } BdrvStateSetAioContext;
7491 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7492 GHashTable *visited,
7493 Transaction *tran,
7494 Error **errp)
7496 GLOBAL_STATE_CODE();
7497 if (g_hash_table_contains(visited, c)) {
7498 return true;
7500 g_hash_table_add(visited, c);
7503 * A BdrvChildClass that doesn't handle AioContext changes cannot
7504 * tolerate any AioContext changes
7506 if (!c->klass->change_aio_ctx) {
7507 char *user = bdrv_child_user_desc(c);
7508 error_setg(errp, "Changing iothreads is not supported by %s", user);
7509 g_free(user);
7510 return false;
7512 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7513 assert(!errp || *errp);
7514 return false;
7516 return true;
7519 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7520 GHashTable *visited, Transaction *tran,
7521 Error **errp)
7523 GLOBAL_STATE_CODE();
7524 if (g_hash_table_contains(visited, c)) {
7525 return true;
7527 g_hash_table_add(visited, c);
7528 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7531 static void bdrv_set_aio_context_clean(void *opaque)
7533 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7534 BlockDriverState *bs = (BlockDriverState *) state->bs;
7536 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7537 bdrv_drained_end(bs);
7539 g_free(state);
7542 static void bdrv_set_aio_context_commit(void *opaque)
7544 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7545 BlockDriverState *bs = (BlockDriverState *) state->bs;
7546 AioContext *new_context = state->new_ctx;
7548 bdrv_detach_aio_context(bs);
7549 bdrv_attach_aio_context(bs, new_context);
7552 static TransactionActionDrv set_aio_context = {
7553 .commit = bdrv_set_aio_context_commit,
7554 .clean = bdrv_set_aio_context_clean,
7558 * Changes the AioContext used for fd handlers, timers, and BHs by this
7559 * BlockDriverState and all its children and parents.
7561 * Must be called from the main AioContext.
7563 * @visited will accumulate all visited BdrvChild objects. The caller is
7564 * responsible for freeing the list afterwards.
7566 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7567 GHashTable *visited, Transaction *tran,
7568 Error **errp)
7570 BdrvChild *c;
7571 BdrvStateSetAioContext *state;
7573 GLOBAL_STATE_CODE();
7575 if (bdrv_get_aio_context(bs) == ctx) {
7576 return true;
7579 bdrv_graph_rdlock_main_loop();
7580 QLIST_FOREACH(c, &bs->parents, next_parent) {
7581 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7582 bdrv_graph_rdunlock_main_loop();
7583 return false;
7587 QLIST_FOREACH(c, &bs->children, next) {
7588 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7589 bdrv_graph_rdunlock_main_loop();
7590 return false;
7593 bdrv_graph_rdunlock_main_loop();
7595 state = g_new(BdrvStateSetAioContext, 1);
7596 *state = (BdrvStateSetAioContext) {
7597 .new_ctx = ctx,
7598 .bs = bs,
7601 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7602 bdrv_drained_begin(bs);
7604 tran_add(tran, &set_aio_context, state);
7606 return true;
7610 * Change bs's and recursively all of its parents' and children's AioContext
7611 * to the given new context, returning an error if that isn't possible.
7613 * If ignore_child is not NULL, that child (and its subgraph) will not
7614 * be touched.
7616 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7617 BdrvChild *ignore_child, Error **errp)
7619 Transaction *tran;
7620 GHashTable *visited;
7621 int ret;
7622 GLOBAL_STATE_CODE();
7625 * Recursion phase: go through all nodes of the graph.
7626 * Take care of checking that all nodes support changing AioContext
7627 * and drain them, building a linear list of callbacks to run if everything
7628 * is successful (the transaction itself).
7630 tran = tran_new();
7631 visited = g_hash_table_new(NULL, NULL);
7632 if (ignore_child) {
7633 g_hash_table_add(visited, ignore_child);
7635 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7636 g_hash_table_destroy(visited);
7639 * Linear phase: go through all callbacks collected in the transaction.
7640 * Run all callbacks collected in the recursion to switch every node's
7641 * AioContext (transaction commit), or undo all changes done in the
7642 * recursion (transaction abort).
7645 if (!ret) {
7646 /* Just run clean() callbacks. No AioContext changed. */
7647 tran_abort(tran);
7648 return -EPERM;
7651 tran_commit(tran);
7652 return 0;
7655 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7656 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7657 void (*detach_aio_context)(void *opaque), void *opaque)
7659 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7660 *ban = (BdrvAioNotifier){
7661 .attached_aio_context = attached_aio_context,
7662 .detach_aio_context = detach_aio_context,
7663 .opaque = opaque
7665 GLOBAL_STATE_CODE();
7667 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7670 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7671 void (*attached_aio_context)(AioContext *,
7672 void *),
7673 void (*detach_aio_context)(void *),
7674 void *opaque)
7676 BdrvAioNotifier *ban, *ban_next;
7677 GLOBAL_STATE_CODE();
7679 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7680 if (ban->attached_aio_context == attached_aio_context &&
7681 ban->detach_aio_context == detach_aio_context &&
7682 ban->opaque == opaque &&
7683 ban->deleted == false)
7685 if (bs->walking_aio_notifiers) {
7686 ban->deleted = true;
7687 } else {
7688 bdrv_do_remove_aio_context_notifier(ban);
7690 return;
7694 abort();
7697 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7698 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7699 bool force,
7700 Error **errp)
7702 GLOBAL_STATE_CODE();
7703 if (!bs->drv) {
7704 error_setg(errp, "Node is ejected");
7705 return -ENOMEDIUM;
7707 if (!bs->drv->bdrv_amend_options) {
7708 error_setg(errp, "Block driver '%s' does not support option amendment",
7709 bs->drv->format_name);
7710 return -ENOTSUP;
7712 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7713 cb_opaque, force, errp);
7717 * This function checks whether the given @to_replace is allowed to be
7718 * replaced by a node that always shows the same data as @bs. This is
7719 * used for example to verify whether the mirror job can replace
7720 * @to_replace by the target mirrored from @bs.
7721 * To be replaceable, @bs and @to_replace may either be guaranteed to
7722 * always show the same data (because they are only connected through
7723 * filters), or some driver may allow replacing one of its children
7724 * because it can guarantee that this child's data is not visible at
7725 * all (for example, for dissenting quorum children that have no other
7726 * parents).
7728 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7729 BlockDriverState *to_replace)
7731 BlockDriverState *filtered;
7733 GLOBAL_STATE_CODE();
7735 if (!bs || !bs->drv) {
7736 return false;
7739 if (bs == to_replace) {
7740 return true;
7743 /* See what the driver can do */
7744 if (bs->drv->bdrv_recurse_can_replace) {
7745 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7748 /* For filters without an own implementation, we can recurse on our own */
7749 filtered = bdrv_filter_bs(bs);
7750 if (filtered) {
7751 return bdrv_recurse_can_replace(filtered, to_replace);
7754 /* Safe default */
7755 return false;
7759 * Check whether the given @node_name can be replaced by a node that
7760 * has the same data as @parent_bs. If so, return @node_name's BDS;
7761 * NULL otherwise.
7763 * @node_name must be a (recursive) *child of @parent_bs (or this
7764 * function will return NULL).
7766 * The result (whether the node can be replaced or not) is only valid
7767 * for as long as no graph or permission changes occur.
7769 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7770 const char *node_name, Error **errp)
7772 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7774 GLOBAL_STATE_CODE();
7776 if (!to_replace_bs) {
7777 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7778 return NULL;
7781 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7782 return NULL;
7785 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7786 * most non filter in order to prevent data corruption.
7787 * Another benefit is that this tests exclude backing files which are
7788 * blocked by the backing blockers.
7790 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7791 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7792 "because it cannot be guaranteed that doing so would not "
7793 "lead to an abrupt change of visible data",
7794 node_name, parent_bs->node_name);
7795 return NULL;
7798 return to_replace_bs;
7802 * Iterates through the list of runtime option keys that are said to
7803 * be "strong" for a BDS. An option is called "strong" if it changes
7804 * a BDS's data. For example, the null block driver's "size" and
7805 * "read-zeroes" options are strong, but its "latency-ns" option is
7806 * not.
7808 * If a key returned by this function ends with a dot, all options
7809 * starting with that prefix are strong.
7811 static const char *const *strong_options(BlockDriverState *bs,
7812 const char *const *curopt)
7814 static const char *const global_options[] = {
7815 "driver", "filename", NULL
7818 if (!curopt) {
7819 return &global_options[0];
7822 curopt++;
7823 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7824 curopt = bs->drv->strong_runtime_opts;
7827 return (curopt && *curopt) ? curopt : NULL;
7831 * Copies all strong runtime options from bs->options to the given
7832 * QDict. The set of strong option keys is determined by invoking
7833 * strong_options().
7835 * Returns true iff any strong option was present in bs->options (and
7836 * thus copied to the target QDict) with the exception of "filename"
7837 * and "driver". The caller is expected to use this value to decide
7838 * whether the existence of strong options prevents the generation of
7839 * a plain filename.
7841 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7843 bool found_any = false;
7844 const char *const *option_name = NULL;
7846 if (!bs->drv) {
7847 return false;
7850 while ((option_name = strong_options(bs, option_name))) {
7851 bool option_given = false;
7853 assert(strlen(*option_name) > 0);
7854 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7855 QObject *entry = qdict_get(bs->options, *option_name);
7856 if (!entry) {
7857 continue;
7860 qdict_put_obj(d, *option_name, qobject_ref(entry));
7861 option_given = true;
7862 } else {
7863 const QDictEntry *entry;
7864 for (entry = qdict_first(bs->options); entry;
7865 entry = qdict_next(bs->options, entry))
7867 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7868 qdict_put_obj(d, qdict_entry_key(entry),
7869 qobject_ref(qdict_entry_value(entry)));
7870 option_given = true;
7875 /* While "driver" and "filename" need to be included in a JSON filename,
7876 * their existence does not prohibit generation of a plain filename. */
7877 if (!found_any && option_given &&
7878 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7880 found_any = true;
7884 if (!qdict_haskey(d, "driver")) {
7885 /* Drivers created with bdrv_new_open_driver() may not have a
7886 * @driver option. Add it here. */
7887 qdict_put_str(d, "driver", bs->drv->format_name);
7890 return found_any;
7893 /* Note: This function may return false positives; it may return true
7894 * even if opening the backing file specified by bs's image header
7895 * would result in exactly bs->backing. */
7896 static bool GRAPH_RDLOCK bdrv_backing_overridden(BlockDriverState *bs)
7898 GLOBAL_STATE_CODE();
7899 if (bs->backing) {
7900 return strcmp(bs->auto_backing_file,
7901 bs->backing->bs->filename);
7902 } else {
7903 /* No backing BDS, so if the image header reports any backing
7904 * file, it must have been suppressed */
7905 return bs->auto_backing_file[0] != '\0';
7909 /* Updates the following BDS fields:
7910 * - exact_filename: A filename which may be used for opening a block device
7911 * which (mostly) equals the given BDS (even without any
7912 * other options; so reading and writing must return the same
7913 * results, but caching etc. may be different)
7914 * - full_open_options: Options which, when given when opening a block device
7915 * (without a filename), result in a BDS (mostly)
7916 * equalling the given one
7917 * - filename: If exact_filename is set, it is copied here. Otherwise,
7918 * full_open_options is converted to a JSON object, prefixed with
7919 * "json:" (for use through the JSON pseudo protocol) and put here.
7921 void bdrv_refresh_filename(BlockDriverState *bs)
7923 BlockDriver *drv = bs->drv;
7924 BdrvChild *child;
7925 BlockDriverState *primary_child_bs;
7926 QDict *opts;
7927 bool backing_overridden;
7928 bool generate_json_filename; /* Whether our default implementation should
7929 fill exact_filename (false) or not (true) */
7931 GLOBAL_STATE_CODE();
7933 if (!drv) {
7934 return;
7937 /* This BDS's file name may depend on any of its children's file names, so
7938 * refresh those first */
7939 QLIST_FOREACH(child, &bs->children, next) {
7940 bdrv_refresh_filename(child->bs);
7943 if (bs->implicit) {
7944 /* For implicit nodes, just copy everything from the single child */
7945 child = QLIST_FIRST(&bs->children);
7946 assert(QLIST_NEXT(child, next) == NULL);
7948 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7949 child->bs->exact_filename);
7950 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7952 qobject_unref(bs->full_open_options);
7953 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7955 return;
7958 backing_overridden = bdrv_backing_overridden(bs);
7960 if (bs->open_flags & BDRV_O_NO_IO) {
7961 /* Without I/O, the backing file does not change anything.
7962 * Therefore, in such a case (primarily qemu-img), we can
7963 * pretend the backing file has not been overridden even if
7964 * it technically has been. */
7965 backing_overridden = false;
7968 /* Gather the options QDict */
7969 opts = qdict_new();
7970 generate_json_filename = append_strong_runtime_options(opts, bs);
7971 generate_json_filename |= backing_overridden;
7973 if (drv->bdrv_gather_child_options) {
7974 /* Some block drivers may not want to present all of their children's
7975 * options, or name them differently from BdrvChild.name */
7976 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7977 } else {
7978 QLIST_FOREACH(child, &bs->children, next) {
7979 if (child == bs->backing && !backing_overridden) {
7980 /* We can skip the backing BDS if it has not been overridden */
7981 continue;
7984 qdict_put(opts, child->name,
7985 qobject_ref(child->bs->full_open_options));
7988 if (backing_overridden && !bs->backing) {
7989 /* Force no backing file */
7990 qdict_put_null(opts, "backing");
7994 qobject_unref(bs->full_open_options);
7995 bs->full_open_options = opts;
7997 primary_child_bs = bdrv_primary_bs(bs);
7999 if (drv->bdrv_refresh_filename) {
8000 /* Obsolete information is of no use here, so drop the old file name
8001 * information before refreshing it */
8002 bs->exact_filename[0] = '\0';
8004 drv->bdrv_refresh_filename(bs);
8005 } else if (primary_child_bs) {
8007 * Try to reconstruct valid information from the underlying
8008 * file -- this only works for format nodes (filter nodes
8009 * cannot be probed and as such must be selected by the user
8010 * either through an options dict, or through a special
8011 * filename which the filter driver must construct in its
8012 * .bdrv_refresh_filename() implementation).
8015 bs->exact_filename[0] = '\0';
8018 * We can use the underlying file's filename if:
8019 * - it has a filename,
8020 * - the current BDS is not a filter,
8021 * - the file is a protocol BDS, and
8022 * - opening that file (as this BDS's format) will automatically create
8023 * the BDS tree we have right now, that is:
8024 * - the user did not significantly change this BDS's behavior with
8025 * some explicit (strong) options
8026 * - no non-file child of this BDS has been overridden by the user
8027 * Both of these conditions are represented by generate_json_filename.
8029 if (primary_child_bs->exact_filename[0] &&
8030 primary_child_bs->drv->protocol_name &&
8031 !drv->is_filter && !generate_json_filename)
8033 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8037 if (bs->exact_filename[0]) {
8038 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
8039 } else {
8040 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
8041 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8042 json->str) >= sizeof(bs->filename)) {
8043 /* Give user a hint if we truncated things. */
8044 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
8046 g_string_free(json, true);
8050 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
8052 BlockDriver *drv = bs->drv;
8053 BlockDriverState *child_bs;
8055 GLOBAL_STATE_CODE();
8057 if (!drv) {
8058 error_setg(errp, "Node '%s' is ejected", bs->node_name);
8059 return NULL;
8062 if (drv->bdrv_dirname) {
8063 return drv->bdrv_dirname(bs, errp);
8066 child_bs = bdrv_primary_bs(bs);
8067 if (child_bs) {
8068 return bdrv_dirname(child_bs, errp);
8071 bdrv_refresh_filename(bs);
8072 if (bs->exact_filename[0] != '\0') {
8073 return path_combine(bs->exact_filename, "");
8076 error_setg(errp, "Cannot generate a base directory for %s nodes",
8077 drv->format_name);
8078 return NULL;
8082 * Hot add/remove a BDS's child. So the user can take a child offline when
8083 * it is broken and take a new child online
8085 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8086 Error **errp)
8088 GLOBAL_STATE_CODE();
8089 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8090 error_setg(errp, "The node %s does not support adding a child",
8091 bdrv_get_device_or_node_name(parent_bs));
8092 return;
8096 * Non-zoned block drivers do not follow zoned storage constraints
8097 * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8098 * drivers in a graph.
8100 if (!parent_bs->drv->supports_zoned_children &&
8101 child_bs->bl.zoned == BLK_Z_HM) {
8103 * The host-aware model allows zoned storage constraints and random
8104 * write. Allow mixing host-aware and non-zoned drivers. Using
8105 * host-aware device as a regular device.
8107 error_setg(errp, "Cannot add a %s child to a %s parent",
8108 child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
8109 parent_bs->drv->supports_zoned_children ?
8110 "support zoned children" : "not support zoned children");
8111 return;
8114 if (!QLIST_EMPTY(&child_bs->parents)) {
8115 error_setg(errp, "The node %s already has a parent",
8116 child_bs->node_name);
8117 return;
8120 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8123 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8125 BdrvChild *tmp;
8127 GLOBAL_STATE_CODE();
8128 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8129 error_setg(errp, "The node %s does not support removing a child",
8130 bdrv_get_device_or_node_name(parent_bs));
8131 return;
8134 QLIST_FOREACH(tmp, &parent_bs->children, next) {
8135 if (tmp == child) {
8136 break;
8140 if (!tmp) {
8141 error_setg(errp, "The node %s does not have a child named %s",
8142 bdrv_get_device_or_node_name(parent_bs),
8143 bdrv_get_device_or_node_name(child->bs));
8144 return;
8147 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8150 int bdrv_make_empty(BdrvChild *c, Error **errp)
8152 BlockDriver *drv = c->bs->drv;
8153 int ret;
8155 GLOBAL_STATE_CODE();
8156 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
8158 if (!drv->bdrv_make_empty) {
8159 error_setg(errp, "%s does not support emptying nodes",
8160 drv->format_name);
8161 return -ENOTSUP;
8164 ret = drv->bdrv_make_empty(c->bs);
8165 if (ret < 0) {
8166 error_setg_errno(errp, -ret, "Failed to empty %s",
8167 c->bs->filename);
8168 return ret;
8171 return 0;
8175 * Return the child that @bs acts as an overlay for, and from which data may be
8176 * copied in COW or COR operations. Usually this is the backing file.
8178 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8180 IO_CODE();
8182 if (!bs || !bs->drv) {
8183 return NULL;
8186 if (bs->drv->is_filter) {
8187 return NULL;
8190 if (!bs->backing) {
8191 return NULL;
8194 assert(bs->backing->role & BDRV_CHILD_COW);
8195 return bs->backing;
8199 * If @bs acts as a filter for exactly one of its children, return
8200 * that child.
8202 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8204 BdrvChild *c;
8205 IO_CODE();
8207 if (!bs || !bs->drv) {
8208 return NULL;
8211 if (!bs->drv->is_filter) {
8212 return NULL;
8215 /* Only one of @backing or @file may be used */
8216 assert(!(bs->backing && bs->file));
8218 c = bs->backing ?: bs->file;
8219 if (!c) {
8220 return NULL;
8223 assert(c->role & BDRV_CHILD_FILTERED);
8224 return c;
8228 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8229 * whichever is non-NULL.
8231 * Return NULL if both are NULL.
8233 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8235 BdrvChild *cow_child = bdrv_cow_child(bs);
8236 BdrvChild *filter_child = bdrv_filter_child(bs);
8237 IO_CODE();
8239 /* Filter nodes cannot have COW backing files */
8240 assert(!(cow_child && filter_child));
8242 return cow_child ?: filter_child;
8246 * Return the primary child of this node: For filters, that is the
8247 * filtered child. For other nodes, that is usually the child storing
8248 * metadata.
8249 * (A generally more helpful description is that this is (usually) the
8250 * child that has the same filename as @bs.)
8252 * Drivers do not necessarily have a primary child; for example quorum
8253 * does not.
8255 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8257 BdrvChild *c, *found = NULL;
8258 IO_CODE();
8260 QLIST_FOREACH(c, &bs->children, next) {
8261 if (c->role & BDRV_CHILD_PRIMARY) {
8262 assert(!found);
8263 found = c;
8267 return found;
8270 static BlockDriverState * GRAPH_RDLOCK
8271 bdrv_do_skip_filters(BlockDriverState *bs, bool stop_on_explicit_filter)
8273 BdrvChild *c;
8275 if (!bs) {
8276 return NULL;
8279 while (!(stop_on_explicit_filter && !bs->implicit)) {
8280 c = bdrv_filter_child(bs);
8281 if (!c) {
8283 * A filter that is embedded in a working block graph must
8284 * have a child. Assert this here so this function does
8285 * not return a filter node that is not expected by the
8286 * caller.
8288 assert(!bs->drv || !bs->drv->is_filter);
8289 break;
8291 bs = c->bs;
8294 * Note that this treats nodes with bs->drv == NULL as not being
8295 * filters (bs->drv == NULL should be replaced by something else
8296 * anyway).
8297 * The advantage of this behavior is that this function will thus
8298 * always return a non-NULL value (given a non-NULL @bs).
8301 return bs;
8305 * Return the first BDS that has not been added implicitly or that
8306 * does not have a filtered child down the chain starting from @bs
8307 * (including @bs itself).
8309 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8311 GLOBAL_STATE_CODE();
8312 return bdrv_do_skip_filters(bs, true);
8316 * Return the first BDS that does not have a filtered child down the
8317 * chain starting from @bs (including @bs itself).
8319 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8321 IO_CODE();
8322 return bdrv_do_skip_filters(bs, false);
8326 * For a backing chain, return the first non-filter backing image of
8327 * the first non-filter image.
8329 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8331 IO_CODE();
8332 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8336 * Check whether [offset, offset + bytes) overlaps with the cached
8337 * block-status data region.
8339 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8340 * which is what bdrv_bsc_is_data()'s interface needs.
8341 * Otherwise, *pnum is not touched.
8343 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8344 int64_t offset, int64_t bytes,
8345 int64_t *pnum)
8347 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8348 bool overlaps;
8350 overlaps =
8351 qatomic_read(&bsc->valid) &&
8352 ranges_overlap(offset, bytes, bsc->data_start,
8353 bsc->data_end - bsc->data_start);
8355 if (overlaps && pnum) {
8356 *pnum = bsc->data_end - offset;
8359 return overlaps;
8363 * See block_int.h for this function's documentation.
8365 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8367 IO_CODE();
8368 RCU_READ_LOCK_GUARD();
8369 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8373 * See block_int.h for this function's documentation.
8375 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8376 int64_t offset, int64_t bytes)
8378 IO_CODE();
8379 RCU_READ_LOCK_GUARD();
8381 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8382 qatomic_set(&bs->block_status_cache->valid, false);
8387 * See block_int.h for this function's documentation.
8389 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8391 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8392 BdrvBlockStatusCache *old_bsc;
8393 IO_CODE();
8395 *new_bsc = (BdrvBlockStatusCache) {
8396 .valid = true,
8397 .data_start = offset,
8398 .data_end = offset + bytes,
8401 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8403 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8404 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8405 if (old_bsc) {
8406 g_free_rcu(old_bsc, rcu);