test-bdrv-drain: Don't yield in .bdrv_co_drained_begin/end()
[qemu/ar7.git] / block.c
blob385ed3cd53993e4a23ceabab6408b96be040365f
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/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
51 #include "qemu/id.h"
52 #include "qemu/range.h"
53 #include "qemu/rcu.h"
54 #include "block/coroutines.h"
56 #ifdef CONFIG_BSD
57 #include <sys/ioctl.h>
58 #include <sys/queue.h>
59 #if defined(HAVE_SYS_DISK_H)
60 #include <sys/disk.h>
61 #endif
62 #endif
64 #ifdef _WIN32
65 #include <windows.h>
66 #endif
68 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
70 /* Protected by BQL */
71 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
74 /* Protected by BQL */
75 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
78 /* Protected by BQL */
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
82 static BlockDriverState *bdrv_open_inherit(const char *filename,
83 const char *reference,
84 QDict *options, int flags,
85 BlockDriverState *parent,
86 const BdrvChildClass *child_class,
87 BdrvChildRole child_role,
88 Error **errp);
90 static bool bdrv_recurse_has_child(BlockDriverState *bs,
91 BlockDriverState *child);
93 static void bdrv_replace_child_noperm(BdrvChild *child,
94 BlockDriverState *new_bs);
95 static void bdrv_remove_child(BdrvChild *child, Transaction *tran);
97 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
98 BlockReopenQueue *queue,
99 Transaction *change_child_tran, Error **errp);
100 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
101 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
103 static bool bdrv_backing_overridden(BlockDriverState *bs);
105 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
106 GHashTable *visited, Transaction *tran,
107 Error **errp);
109 /* If non-zero, use only whitelisted block drivers */
110 static int use_bdrv_whitelist;
112 #ifdef _WIN32
113 static int is_windows_drive_prefix(const char *filename)
115 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
116 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
117 filename[1] == ':');
120 int is_windows_drive(const char *filename)
122 if (is_windows_drive_prefix(filename) &&
123 filename[2] == '\0')
124 return 1;
125 if (strstart(filename, "\\\\.\\", NULL) ||
126 strstart(filename, "//./", NULL))
127 return 1;
128 return 0;
130 #endif
132 size_t bdrv_opt_mem_align(BlockDriverState *bs)
134 if (!bs || !bs->drv) {
135 /* page size or 4k (hdd sector size) should be on the safe side */
136 return MAX(4096, qemu_real_host_page_size());
138 IO_CODE();
140 return bs->bl.opt_mem_alignment;
143 size_t bdrv_min_mem_align(BlockDriverState *bs)
145 if (!bs || !bs->drv) {
146 /* page size or 4k (hdd sector size) should be on the safe side */
147 return MAX(4096, qemu_real_host_page_size());
149 IO_CODE();
151 return bs->bl.min_mem_alignment;
154 /* check if the path starts with "<protocol>:" */
155 int path_has_protocol(const char *path)
157 const char *p;
159 #ifdef _WIN32
160 if (is_windows_drive(path) ||
161 is_windows_drive_prefix(path)) {
162 return 0;
164 p = path + strcspn(path, ":/\\");
165 #else
166 p = path + strcspn(path, ":/");
167 #endif
169 return *p == ':';
172 int path_is_absolute(const char *path)
174 #ifdef _WIN32
175 /* specific case for names like: "\\.\d:" */
176 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
177 return 1;
179 return (*path == '/' || *path == '\\');
180 #else
181 return (*path == '/');
182 #endif
185 /* if filename is absolute, just return its duplicate. Otherwise, build a
186 path to it by considering it is relative to base_path. URL are
187 supported. */
188 char *path_combine(const char *base_path, const char *filename)
190 const char *protocol_stripped = NULL;
191 const char *p, *p1;
192 char *result;
193 int len;
195 if (path_is_absolute(filename)) {
196 return g_strdup(filename);
199 if (path_has_protocol(base_path)) {
200 protocol_stripped = strchr(base_path, ':');
201 if (protocol_stripped) {
202 protocol_stripped++;
205 p = protocol_stripped ?: base_path;
207 p1 = strrchr(base_path, '/');
208 #ifdef _WIN32
210 const char *p2;
211 p2 = strrchr(base_path, '\\');
212 if (!p1 || p2 > p1) {
213 p1 = p2;
216 #endif
217 if (p1) {
218 p1++;
219 } else {
220 p1 = base_path;
222 if (p1 > p) {
223 p = p1;
225 len = p - base_path;
227 result = g_malloc(len + strlen(filename) + 1);
228 memcpy(result, base_path, len);
229 strcpy(result + len, filename);
231 return result;
235 * Helper function for bdrv_parse_filename() implementations to remove optional
236 * protocol prefixes (especially "file:") from a filename and for putting the
237 * stripped filename into the options QDict if there is such a prefix.
239 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
240 QDict *options)
242 if (strstart(filename, prefix, &filename)) {
243 /* Stripping the explicit protocol prefix may result in a protocol
244 * prefix being (wrongly) detected (if the filename contains a colon) */
245 if (path_has_protocol(filename)) {
246 GString *fat_filename;
248 /* This means there is some colon before the first slash; therefore,
249 * this cannot be an absolute path */
250 assert(!path_is_absolute(filename));
252 /* And we can thus fix the protocol detection issue by prefixing it
253 * by "./" */
254 fat_filename = g_string_new("./");
255 g_string_append(fat_filename, filename);
257 assert(!path_has_protocol(fat_filename->str));
259 qdict_put(options, "filename",
260 qstring_from_gstring(fat_filename));
261 } else {
262 /* If no protocol prefix was detected, we can use the shortened
263 * filename as-is */
264 qdict_put_str(options, "filename", filename);
270 /* Returns whether the image file is opened as read-only. Note that this can
271 * return false and writing to the image file is still not possible because the
272 * image is inactivated. */
273 bool bdrv_is_read_only(BlockDriverState *bs)
275 IO_CODE();
276 return !(bs->open_flags & BDRV_O_RDWR);
279 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
280 bool ignore_allow_rdw, Error **errp)
282 IO_CODE();
284 /* Do not set read_only if copy_on_read is enabled */
285 if (bs->copy_on_read && read_only) {
286 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
287 bdrv_get_device_or_node_name(bs));
288 return -EINVAL;
291 /* Do not clear read_only if it is prohibited */
292 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
293 !ignore_allow_rdw)
295 error_setg(errp, "Node '%s' is read only",
296 bdrv_get_device_or_node_name(bs));
297 return -EPERM;
300 return 0;
304 * Called by a driver that can only provide a read-only image.
306 * Returns 0 if the node is already read-only or it could switch the node to
307 * read-only because BDRV_O_AUTO_RDONLY is set.
309 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
310 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
311 * is not NULL, it is used as the error message for the Error object.
313 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
314 Error **errp)
316 int ret = 0;
317 IO_CODE();
319 if (!(bs->open_flags & BDRV_O_RDWR)) {
320 return 0;
322 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
323 goto fail;
326 ret = bdrv_can_set_read_only(bs, true, false, NULL);
327 if (ret < 0) {
328 goto fail;
331 bs->open_flags &= ~BDRV_O_RDWR;
333 return 0;
335 fail:
336 error_setg(errp, "%s", errmsg ?: "Image is read-only");
337 return -EACCES;
341 * If @backing is empty, this function returns NULL without setting
342 * @errp. In all other cases, NULL will only be returned with @errp
343 * set.
345 * Therefore, a return value of NULL without @errp set means that
346 * there is no backing file; if @errp is set, there is one but its
347 * absolute filename cannot be generated.
349 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
350 const char *backing,
351 Error **errp)
353 if (backing[0] == '\0') {
354 return NULL;
355 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
356 return g_strdup(backing);
357 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
358 error_setg(errp, "Cannot use relative backing file names for '%s'",
359 backed);
360 return NULL;
361 } else {
362 return path_combine(backed, backing);
367 * If @filename is empty or NULL, this function returns NULL without
368 * setting @errp. In all other cases, NULL will only be returned with
369 * @errp set.
371 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
372 const char *filename, Error **errp)
374 char *dir, *full_name;
376 if (!filename || filename[0] == '\0') {
377 return NULL;
378 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
379 return g_strdup(filename);
382 dir = bdrv_dirname(relative_to, errp);
383 if (!dir) {
384 return NULL;
387 full_name = g_strconcat(dir, filename, NULL);
388 g_free(dir);
389 return full_name;
392 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
394 GLOBAL_STATE_CODE();
395 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
398 void bdrv_register(BlockDriver *bdrv)
400 assert(bdrv->format_name);
401 GLOBAL_STATE_CODE();
402 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
405 BlockDriverState *bdrv_new(void)
407 BlockDriverState *bs;
408 int i;
410 GLOBAL_STATE_CODE();
412 bs = g_new0(BlockDriverState, 1);
413 QLIST_INIT(&bs->dirty_bitmaps);
414 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
415 QLIST_INIT(&bs->op_blockers[i]);
417 qemu_co_mutex_init(&bs->reqs_lock);
418 qemu_mutex_init(&bs->dirty_bitmap_mutex);
419 bs->refcnt = 1;
420 bs->aio_context = qemu_get_aio_context();
422 qemu_co_queue_init(&bs->flush_queue);
424 qemu_co_mutex_init(&bs->bsc_modify_lock);
425 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
427 for (i = 0; i < bdrv_drain_all_count; i++) {
428 bdrv_drained_begin(bs);
431 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
433 return bs;
436 static BlockDriver *bdrv_do_find_format(const char *format_name)
438 BlockDriver *drv1;
439 GLOBAL_STATE_CODE();
441 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
442 if (!strcmp(drv1->format_name, format_name)) {
443 return drv1;
447 return NULL;
450 BlockDriver *bdrv_find_format(const char *format_name)
452 BlockDriver *drv1;
453 int i;
455 GLOBAL_STATE_CODE();
457 drv1 = bdrv_do_find_format(format_name);
458 if (drv1) {
459 return drv1;
462 /* The driver isn't registered, maybe we need to load a module */
463 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
464 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
465 Error *local_err = NULL;
466 int rv = block_module_load(block_driver_modules[i].library_name,
467 &local_err);
468 if (rv > 0) {
469 return bdrv_do_find_format(format_name);
470 } else if (rv < 0) {
471 error_report_err(local_err);
473 break;
476 return NULL;
479 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
481 static const char *whitelist_rw[] = {
482 CONFIG_BDRV_RW_WHITELIST
483 NULL
485 static const char *whitelist_ro[] = {
486 CONFIG_BDRV_RO_WHITELIST
487 NULL
489 const char **p;
491 if (!whitelist_rw[0] && !whitelist_ro[0]) {
492 return 1; /* no whitelist, anything goes */
495 for (p = whitelist_rw; *p; p++) {
496 if (!strcmp(format_name, *p)) {
497 return 1;
500 if (read_only) {
501 for (p = whitelist_ro; *p; p++) {
502 if (!strcmp(format_name, *p)) {
503 return 1;
507 return 0;
510 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
512 GLOBAL_STATE_CODE();
513 return bdrv_format_is_whitelisted(drv->format_name, read_only);
516 bool bdrv_uses_whitelist(void)
518 return use_bdrv_whitelist;
521 typedef struct CreateCo {
522 BlockDriver *drv;
523 char *filename;
524 QemuOpts *opts;
525 int ret;
526 Error *err;
527 } CreateCo;
529 static void coroutine_fn bdrv_create_co_entry(void *opaque)
531 Error *local_err = NULL;
532 int ret;
534 CreateCo *cco = opaque;
535 assert(cco->drv);
536 GLOBAL_STATE_CODE();
538 ret = cco->drv->bdrv_co_create_opts(cco->drv,
539 cco->filename, cco->opts, &local_err);
540 error_propagate(&cco->err, local_err);
541 cco->ret = ret;
544 int bdrv_create(BlockDriver *drv, const char* filename,
545 QemuOpts *opts, Error **errp)
547 int ret;
549 GLOBAL_STATE_CODE();
551 Coroutine *co;
552 CreateCo cco = {
553 .drv = drv,
554 .filename = g_strdup(filename),
555 .opts = opts,
556 .ret = NOT_DONE,
557 .err = NULL,
560 if (!drv->bdrv_co_create_opts) {
561 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
562 ret = -ENOTSUP;
563 goto out;
566 if (qemu_in_coroutine()) {
567 /* Fast-path if already in coroutine context */
568 bdrv_create_co_entry(&cco);
569 } else {
570 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
571 qemu_coroutine_enter(co);
572 while (cco.ret == NOT_DONE) {
573 aio_poll(qemu_get_aio_context(), true);
577 ret = cco.ret;
578 if (ret < 0) {
579 if (cco.err) {
580 error_propagate(errp, cco.err);
581 } else {
582 error_setg_errno(errp, -ret, "Could not create image");
586 out:
587 g_free(cco.filename);
588 return ret;
592 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
593 * least the given @minimum_size.
595 * On success, return @blk's actual length.
596 * Otherwise, return -errno.
598 static int64_t create_file_fallback_truncate(BlockBackend *blk,
599 int64_t minimum_size, Error **errp)
601 Error *local_err = NULL;
602 int64_t size;
603 int ret;
605 GLOBAL_STATE_CODE();
607 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
608 &local_err);
609 if (ret < 0 && ret != -ENOTSUP) {
610 error_propagate(errp, local_err);
611 return ret;
614 size = blk_getlength(blk);
615 if (size < 0) {
616 error_free(local_err);
617 error_setg_errno(errp, -size,
618 "Failed to inquire the new image file's length");
619 return size;
622 if (size < minimum_size) {
623 /* Need to grow the image, but we failed to do that */
624 error_propagate(errp, local_err);
625 return -ENOTSUP;
628 error_free(local_err);
629 local_err = NULL;
631 return size;
635 * Helper function for bdrv_create_file_fallback(): Zero the first
636 * sector to remove any potentially pre-existing image header.
638 static int coroutine_fn
639 create_file_fallback_zero_first_sector(BlockBackend *blk,
640 int64_t current_size,
641 Error **errp)
643 int64_t bytes_to_clear;
644 int ret;
646 GLOBAL_STATE_CODE();
648 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
649 if (bytes_to_clear) {
650 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
651 if (ret < 0) {
652 error_setg_errno(errp, -ret,
653 "Failed to clear the new image's first sector");
654 return ret;
658 return 0;
662 * Simple implementation of bdrv_co_create_opts for protocol drivers
663 * which only support creation via opening a file
664 * (usually existing raw storage device)
666 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
667 const char *filename,
668 QemuOpts *opts,
669 Error **errp)
671 BlockBackend *blk;
672 QDict *options;
673 int64_t size = 0;
674 char *buf = NULL;
675 PreallocMode prealloc;
676 Error *local_err = NULL;
677 int ret;
679 GLOBAL_STATE_CODE();
681 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
682 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
683 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
684 PREALLOC_MODE_OFF, &local_err);
685 g_free(buf);
686 if (local_err) {
687 error_propagate(errp, local_err);
688 return -EINVAL;
691 if (prealloc != PREALLOC_MODE_OFF) {
692 error_setg(errp, "Unsupported preallocation mode '%s'",
693 PreallocMode_str(prealloc));
694 return -ENOTSUP;
697 options = qdict_new();
698 qdict_put_str(options, "driver", drv->format_name);
700 blk = blk_new_open(filename, NULL, options,
701 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
702 if (!blk) {
703 error_prepend(errp, "Protocol driver '%s' does not support image "
704 "creation, and opening the image failed: ",
705 drv->format_name);
706 return -EINVAL;
709 size = create_file_fallback_truncate(blk, size, errp);
710 if (size < 0) {
711 ret = size;
712 goto out;
715 ret = create_file_fallback_zero_first_sector(blk, size, errp);
716 if (ret < 0) {
717 goto out;
720 ret = 0;
721 out:
722 blk_unref(blk);
723 return ret;
726 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
728 QemuOpts *protocol_opts;
729 BlockDriver *drv;
730 QDict *qdict;
731 int ret;
733 GLOBAL_STATE_CODE();
735 drv = bdrv_find_protocol(filename, true, errp);
736 if (drv == NULL) {
737 return -ENOENT;
740 if (!drv->create_opts) {
741 error_setg(errp, "Driver '%s' does not support image creation",
742 drv->format_name);
743 return -ENOTSUP;
747 * 'opts' contains a QemuOptsList with a combination of format and protocol
748 * default values.
750 * The format properly removes its options, but the default values remain
751 * in 'opts->list'. So if the protocol has options with the same name
752 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
753 * of the format, since for overlapping options, the format wins.
755 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
756 * only the set options, and then convert it back to QemuOpts, using the
757 * create_opts of the protocol. So the new QemuOpts, will contain only the
758 * protocol defaults.
760 qdict = qemu_opts_to_qdict(opts, NULL);
761 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
762 if (protocol_opts == NULL) {
763 ret = -EINVAL;
764 goto out;
767 ret = bdrv_create(drv, filename, protocol_opts, errp);
768 out:
769 qemu_opts_del(protocol_opts);
770 qobject_unref(qdict);
771 return ret;
774 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
776 Error *local_err = NULL;
777 int ret;
779 IO_CODE();
780 assert(bs != NULL);
782 if (!bs->drv) {
783 error_setg(errp, "Block node '%s' is not opened", bs->filename);
784 return -ENOMEDIUM;
787 if (!bs->drv->bdrv_co_delete_file) {
788 error_setg(errp, "Driver '%s' does not support image deletion",
789 bs->drv->format_name);
790 return -ENOTSUP;
793 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
794 if (ret < 0) {
795 error_propagate(errp, local_err);
798 return ret;
801 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
803 Error *local_err = NULL;
804 int ret;
805 IO_CODE();
807 if (!bs) {
808 return;
811 ret = bdrv_co_delete_file(bs, &local_err);
813 * ENOTSUP will happen if the block driver doesn't support
814 * the 'bdrv_co_delete_file' interface. This is a predictable
815 * scenario and shouldn't be reported back to the user.
817 if (ret == -ENOTSUP) {
818 error_free(local_err);
819 } else if (ret < 0) {
820 error_report_err(local_err);
825 * Try to get @bs's logical and physical block size.
826 * On success, store them in @bsz struct and return 0.
827 * On failure return -errno.
828 * @bs must not be empty.
830 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
832 BlockDriver *drv = bs->drv;
833 BlockDriverState *filtered = bdrv_filter_bs(bs);
834 GLOBAL_STATE_CODE();
836 if (drv && drv->bdrv_probe_blocksizes) {
837 return drv->bdrv_probe_blocksizes(bs, bsz);
838 } else if (filtered) {
839 return bdrv_probe_blocksizes(filtered, bsz);
842 return -ENOTSUP;
846 * Try to get @bs's geometry (cyls, heads, sectors).
847 * On success, store them in @geo struct and return 0.
848 * On failure return -errno.
849 * @bs must not be empty.
851 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
853 BlockDriver *drv = bs->drv;
854 BlockDriverState *filtered = bdrv_filter_bs(bs);
855 GLOBAL_STATE_CODE();
857 if (drv && drv->bdrv_probe_geometry) {
858 return drv->bdrv_probe_geometry(bs, geo);
859 } else if (filtered) {
860 return bdrv_probe_geometry(filtered, geo);
863 return -ENOTSUP;
867 * Create a uniquely-named empty temporary file.
868 * Return the actual file name used upon success, otherwise NULL.
869 * This string should be freed with g_free() when not needed any longer.
871 * Note: creating a temporary file for the caller to (re)open is
872 * inherently racy. Use g_file_open_tmp() instead whenever practical.
874 char *create_tmp_file(Error **errp)
876 int fd;
877 const char *tmpdir;
878 g_autofree char *filename = NULL;
880 tmpdir = g_get_tmp_dir();
881 #ifndef _WIN32
883 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
885 * This function is used to create temporary disk images (like -snapshot),
886 * so the files can become very large. /tmp is often a tmpfs where as
887 * /var/tmp is usually on a disk, so more appropriate for disk images.
889 if (!g_strcmp0(tmpdir, "/tmp")) {
890 tmpdir = "/var/tmp";
892 #endif
894 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
895 fd = g_mkstemp(filename);
896 if (fd < 0) {
897 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
898 filename);
899 return NULL;
901 close(fd);
903 return g_steal_pointer(&filename);
907 * Detect host devices. By convention, /dev/cdrom[N] is always
908 * recognized as a host CDROM.
910 static BlockDriver *find_hdev_driver(const char *filename)
912 int score_max = 0, score;
913 BlockDriver *drv = NULL, *d;
914 GLOBAL_STATE_CODE();
916 QLIST_FOREACH(d, &bdrv_drivers, list) {
917 if (d->bdrv_probe_device) {
918 score = d->bdrv_probe_device(filename);
919 if (score > score_max) {
920 score_max = score;
921 drv = d;
926 return drv;
929 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
931 BlockDriver *drv1;
932 GLOBAL_STATE_CODE();
934 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
935 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
936 return drv1;
940 return NULL;
943 BlockDriver *bdrv_find_protocol(const char *filename,
944 bool allow_protocol_prefix,
945 Error **errp)
947 BlockDriver *drv1;
948 char protocol[128];
949 int len;
950 const char *p;
951 int i;
953 GLOBAL_STATE_CODE();
954 /* TODO Drivers without bdrv_file_open must be specified explicitly */
957 * XXX(hch): we really should not let host device detection
958 * override an explicit protocol specification, but moving this
959 * later breaks access to device names with colons in them.
960 * Thanks to the brain-dead persistent naming schemes on udev-
961 * based Linux systems those actually are quite common.
963 drv1 = find_hdev_driver(filename);
964 if (drv1) {
965 return drv1;
968 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
969 return &bdrv_file;
972 p = strchr(filename, ':');
973 assert(p != NULL);
974 len = p - filename;
975 if (len > sizeof(protocol) - 1)
976 len = sizeof(protocol) - 1;
977 memcpy(protocol, filename, len);
978 protocol[len] = '\0';
980 drv1 = bdrv_do_find_protocol(protocol);
981 if (drv1) {
982 return drv1;
985 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
986 if (block_driver_modules[i].protocol_name &&
987 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
988 int rv = block_module_load(block_driver_modules[i].library_name, errp);
989 if (rv > 0) {
990 drv1 = bdrv_do_find_protocol(protocol);
991 } else if (rv < 0) {
992 return NULL;
994 break;
998 if (!drv1) {
999 error_setg(errp, "Unknown protocol '%s'", protocol);
1001 return drv1;
1005 * Guess image format by probing its contents.
1006 * This is not a good idea when your image is raw (CVE-2008-2004), but
1007 * we do it anyway for backward compatibility.
1009 * @buf contains the image's first @buf_size bytes.
1010 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1011 * but can be smaller if the image file is smaller)
1012 * @filename is its filename.
1014 * For all block drivers, call the bdrv_probe() method to get its
1015 * probing score.
1016 * Return the first block driver with the highest probing score.
1018 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1019 const char *filename)
1021 int score_max = 0, score;
1022 BlockDriver *drv = NULL, *d;
1023 IO_CODE();
1025 QLIST_FOREACH(d, &bdrv_drivers, list) {
1026 if (d->bdrv_probe) {
1027 score = d->bdrv_probe(buf, buf_size, filename);
1028 if (score > score_max) {
1029 score_max = score;
1030 drv = d;
1035 return drv;
1038 static int find_image_format(BlockBackend *file, const char *filename,
1039 BlockDriver **pdrv, Error **errp)
1041 BlockDriver *drv;
1042 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1043 int ret = 0;
1045 GLOBAL_STATE_CODE();
1047 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1048 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1049 *pdrv = &bdrv_raw;
1050 return ret;
1053 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1054 if (ret < 0) {
1055 error_setg_errno(errp, -ret, "Could not read image for determining its "
1056 "format");
1057 *pdrv = NULL;
1058 return ret;
1061 drv = bdrv_probe_all(buf, sizeof(buf), filename);
1062 if (!drv) {
1063 error_setg(errp, "Could not determine image format: No compatible "
1064 "driver found");
1065 *pdrv = NULL;
1066 return -ENOENT;
1069 *pdrv = drv;
1070 return 0;
1074 * Set the current 'total_sectors' value
1075 * Return 0 on success, -errno on error.
1077 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1079 BlockDriver *drv = bs->drv;
1080 IO_CODE();
1082 if (!drv) {
1083 return -ENOMEDIUM;
1086 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1087 if (bdrv_is_sg(bs))
1088 return 0;
1090 /* query actual device if possible, otherwise just trust the hint */
1091 if (drv->bdrv_getlength) {
1092 int64_t length = drv->bdrv_getlength(bs);
1093 if (length < 0) {
1094 return length;
1096 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1099 bs->total_sectors = hint;
1101 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1102 return -EFBIG;
1105 return 0;
1109 * Combines a QDict of new block driver @options with any missing options taken
1110 * from @old_options, so that leaving out an option defaults to its old value.
1112 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1113 QDict *old_options)
1115 GLOBAL_STATE_CODE();
1116 if (bs->drv && bs->drv->bdrv_join_options) {
1117 bs->drv->bdrv_join_options(options, old_options);
1118 } else {
1119 qdict_join(options, old_options, false);
1123 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1124 int open_flags,
1125 Error **errp)
1127 Error *local_err = NULL;
1128 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1129 BlockdevDetectZeroesOptions detect_zeroes =
1130 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1131 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1132 GLOBAL_STATE_CODE();
1133 g_free(value);
1134 if (local_err) {
1135 error_propagate(errp, local_err);
1136 return detect_zeroes;
1139 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1140 !(open_flags & BDRV_O_UNMAP))
1142 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1143 "without setting discard operation to unmap");
1146 return detect_zeroes;
1150 * Set open flags for aio engine
1152 * Return 0 on success, -1 if the engine specified is invalid
1154 int bdrv_parse_aio(const char *mode, int *flags)
1156 if (!strcmp(mode, "threads")) {
1157 /* do nothing, default */
1158 } else if (!strcmp(mode, "native")) {
1159 *flags |= BDRV_O_NATIVE_AIO;
1160 #ifdef CONFIG_LINUX_IO_URING
1161 } else if (!strcmp(mode, "io_uring")) {
1162 *flags |= BDRV_O_IO_URING;
1163 #endif
1164 } else {
1165 return -1;
1168 return 0;
1172 * Set open flags for a given discard mode
1174 * Return 0 on success, -1 if the discard mode was invalid.
1176 int bdrv_parse_discard_flags(const char *mode, int *flags)
1178 *flags &= ~BDRV_O_UNMAP;
1180 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1181 /* do nothing */
1182 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1183 *flags |= BDRV_O_UNMAP;
1184 } else {
1185 return -1;
1188 return 0;
1192 * Set open flags for a given cache mode
1194 * Return 0 on success, -1 if the cache mode was invalid.
1196 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1198 *flags &= ~BDRV_O_CACHE_MASK;
1200 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1201 *writethrough = false;
1202 *flags |= BDRV_O_NOCACHE;
1203 } else if (!strcmp(mode, "directsync")) {
1204 *writethrough = true;
1205 *flags |= BDRV_O_NOCACHE;
1206 } else if (!strcmp(mode, "writeback")) {
1207 *writethrough = false;
1208 } else if (!strcmp(mode, "unsafe")) {
1209 *writethrough = false;
1210 *flags |= BDRV_O_NO_FLUSH;
1211 } else if (!strcmp(mode, "writethrough")) {
1212 *writethrough = true;
1213 } else {
1214 return -1;
1217 return 0;
1220 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1222 BlockDriverState *parent = c->opaque;
1223 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1226 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1228 BlockDriverState *bs = child->opaque;
1229 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1232 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1234 BlockDriverState *bs = child->opaque;
1235 return bdrv_drain_poll(bs, false, NULL, false);
1238 static void bdrv_child_cb_drained_end(BdrvChild *child,
1239 int *drained_end_counter)
1241 BlockDriverState *bs = child->opaque;
1242 bdrv_drained_end_no_poll(bs, drained_end_counter);
1245 static int bdrv_child_cb_inactivate(BdrvChild *child)
1247 BlockDriverState *bs = child->opaque;
1248 GLOBAL_STATE_CODE();
1249 assert(bs->open_flags & BDRV_O_INACTIVE);
1250 return 0;
1253 static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1254 GHashTable *visited, Transaction *tran,
1255 Error **errp)
1257 BlockDriverState *bs = child->opaque;
1258 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
1262 * Returns the options and flags that a temporary snapshot should get, based on
1263 * the originally requested flags (the originally requested image will have
1264 * flags like a backing file)
1266 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1267 int parent_flags, QDict *parent_options)
1269 GLOBAL_STATE_CODE();
1270 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1272 /* For temporary files, unconditional cache=unsafe is fine */
1273 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1274 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1276 /* Copy the read-only and discard options from the parent */
1277 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1278 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1280 /* aio=native doesn't work for cache.direct=off, so disable it for the
1281 * temporary snapshot */
1282 *child_flags &= ~BDRV_O_NATIVE_AIO;
1285 static void bdrv_backing_attach(BdrvChild *c)
1287 BlockDriverState *parent = c->opaque;
1288 BlockDriverState *backing_hd = c->bs;
1290 GLOBAL_STATE_CODE();
1291 assert(!parent->backing_blocker);
1292 error_setg(&parent->backing_blocker,
1293 "node is used as backing hd of '%s'",
1294 bdrv_get_device_or_node_name(parent));
1296 bdrv_refresh_filename(backing_hd);
1298 parent->open_flags &= ~BDRV_O_NO_BACKING;
1300 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1301 /* Otherwise we won't be able to commit or stream */
1302 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1303 parent->backing_blocker);
1304 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1305 parent->backing_blocker);
1307 * We do backup in 3 ways:
1308 * 1. drive backup
1309 * The target bs is new opened, and the source is top BDS
1310 * 2. blockdev backup
1311 * Both the source and the target are top BDSes.
1312 * 3. internal backup(used for block replication)
1313 * Both the source and the target are backing file
1315 * In case 1 and 2, neither the source nor the target is the backing file.
1316 * In case 3, we will block the top BDS, so there is only one block job
1317 * for the top BDS and its backing chain.
1319 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1320 parent->backing_blocker);
1321 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1322 parent->backing_blocker);
1325 static void bdrv_backing_detach(BdrvChild *c)
1327 BlockDriverState *parent = c->opaque;
1329 GLOBAL_STATE_CODE();
1330 assert(parent->backing_blocker);
1331 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1332 error_free(parent->backing_blocker);
1333 parent->backing_blocker = NULL;
1336 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1337 const char *filename, Error **errp)
1339 BlockDriverState *parent = c->opaque;
1340 bool read_only = bdrv_is_read_only(parent);
1341 int ret;
1342 GLOBAL_STATE_CODE();
1344 if (read_only) {
1345 ret = bdrv_reopen_set_read_only(parent, false, errp);
1346 if (ret < 0) {
1347 return ret;
1351 ret = bdrv_change_backing_file(parent, filename,
1352 base->drv ? base->drv->format_name : "",
1353 false);
1354 if (ret < 0) {
1355 error_setg_errno(errp, -ret, "Could not update backing file link");
1358 if (read_only) {
1359 bdrv_reopen_set_read_only(parent, true, NULL);
1362 return ret;
1366 * Returns the options and flags that a generic child of a BDS should
1367 * get, based on the given options and flags for the parent BDS.
1369 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1370 int *child_flags, QDict *child_options,
1371 int parent_flags, QDict *parent_options)
1373 int flags = parent_flags;
1374 GLOBAL_STATE_CODE();
1377 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1378 * Generally, the question to answer is: Should this child be
1379 * format-probed by default?
1383 * Pure and non-filtered data children of non-format nodes should
1384 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1385 * set). This only affects a very limited set of drivers (namely
1386 * quorum and blkverify when this comment was written).
1387 * Force-clear BDRV_O_PROTOCOL then.
1389 if (!parent_is_format &&
1390 (role & BDRV_CHILD_DATA) &&
1391 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1393 flags &= ~BDRV_O_PROTOCOL;
1397 * All children of format nodes (except for COW children) and all
1398 * metadata children in general should never be format-probed.
1399 * Force-set BDRV_O_PROTOCOL then.
1401 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1402 (role & BDRV_CHILD_METADATA))
1404 flags |= BDRV_O_PROTOCOL;
1408 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1409 * the parent.
1411 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1412 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1413 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1415 if (role & BDRV_CHILD_COW) {
1416 /* backing files are opened read-only by default */
1417 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1418 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1419 } else {
1420 /* Inherit the read-only option from the parent if it's not set */
1421 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1422 qdict_copy_default(child_options, parent_options,
1423 BDRV_OPT_AUTO_READ_ONLY);
1427 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1428 * can default to enable it on lower layers regardless of the
1429 * parent option.
1431 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1433 /* Clear flags that only apply to the top layer */
1434 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1436 if (role & BDRV_CHILD_METADATA) {
1437 flags &= ~BDRV_O_NO_IO;
1439 if (role & BDRV_CHILD_COW) {
1440 flags &= ~BDRV_O_TEMPORARY;
1443 *child_flags = flags;
1446 static void bdrv_child_cb_attach(BdrvChild *child)
1448 BlockDriverState *bs = child->opaque;
1450 assert_bdrv_graph_writable(bs);
1451 QLIST_INSERT_HEAD(&bs->children, child, next);
1452 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1454 * Here we handle filters and block/raw-format.c when it behave like
1455 * filter. They generally have a single PRIMARY child, which is also the
1456 * FILTERED child, and that they may have multiple more children, which
1457 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1458 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1459 * into bs->backing on exceptional cases; and bs->backing will be
1460 * nothing else.
1462 assert(!(child->role & BDRV_CHILD_COW));
1463 if (child->role & BDRV_CHILD_PRIMARY) {
1464 assert(child->role & BDRV_CHILD_FILTERED);
1465 assert(!bs->backing);
1466 assert(!bs->file);
1468 if (bs->drv->filtered_child_is_backing) {
1469 bs->backing = child;
1470 } else {
1471 bs->file = child;
1473 } else {
1474 assert(!(child->role & BDRV_CHILD_FILTERED));
1476 } else if (child->role & BDRV_CHILD_COW) {
1477 assert(bs->drv->supports_backing);
1478 assert(!(child->role & BDRV_CHILD_PRIMARY));
1479 assert(!bs->backing);
1480 bs->backing = child;
1481 bdrv_backing_attach(child);
1482 } else if (child->role & BDRV_CHILD_PRIMARY) {
1483 assert(!bs->file);
1484 bs->file = child;
1487 bdrv_apply_subtree_drain(child, bs);
1490 static void bdrv_child_cb_detach(BdrvChild *child)
1492 BlockDriverState *bs = child->opaque;
1494 if (child->role & BDRV_CHILD_COW) {
1495 bdrv_backing_detach(child);
1498 bdrv_unapply_subtree_drain(child, bs);
1500 assert_bdrv_graph_writable(bs);
1501 QLIST_REMOVE(child, next);
1502 if (child == bs->backing) {
1503 assert(child != bs->file);
1504 bs->backing = NULL;
1505 } else if (child == bs->file) {
1506 bs->file = NULL;
1510 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1511 const char *filename, Error **errp)
1513 if (c->role & BDRV_CHILD_COW) {
1514 return bdrv_backing_update_filename(c, base, filename, errp);
1516 return 0;
1519 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1521 BlockDriverState *bs = c->opaque;
1522 IO_CODE();
1524 return bdrv_get_aio_context(bs);
1527 const BdrvChildClass child_of_bds = {
1528 .parent_is_bds = true,
1529 .get_parent_desc = bdrv_child_get_parent_desc,
1530 .inherit_options = bdrv_inherited_options,
1531 .drained_begin = bdrv_child_cb_drained_begin,
1532 .drained_poll = bdrv_child_cb_drained_poll,
1533 .drained_end = bdrv_child_cb_drained_end,
1534 .attach = bdrv_child_cb_attach,
1535 .detach = bdrv_child_cb_detach,
1536 .inactivate = bdrv_child_cb_inactivate,
1537 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
1538 .update_filename = bdrv_child_cb_update_filename,
1539 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1542 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1544 IO_CODE();
1545 return c->klass->get_parent_aio_context(c);
1548 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1550 int open_flags = flags;
1551 GLOBAL_STATE_CODE();
1554 * Clear flags that are internal to the block layer before opening the
1555 * image.
1557 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1559 return open_flags;
1562 static void update_flags_from_options(int *flags, QemuOpts *opts)
1564 GLOBAL_STATE_CODE();
1566 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1568 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1569 *flags |= BDRV_O_NO_FLUSH;
1572 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1573 *flags |= BDRV_O_NOCACHE;
1576 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1577 *flags |= BDRV_O_RDWR;
1580 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1581 *flags |= BDRV_O_AUTO_RDONLY;
1585 static void update_options_from_flags(QDict *options, int flags)
1587 GLOBAL_STATE_CODE();
1588 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1589 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1591 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1592 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1593 flags & BDRV_O_NO_FLUSH);
1595 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1596 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1598 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1599 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1600 flags & BDRV_O_AUTO_RDONLY);
1604 static void bdrv_assign_node_name(BlockDriverState *bs,
1605 const char *node_name,
1606 Error **errp)
1608 char *gen_node_name = NULL;
1609 GLOBAL_STATE_CODE();
1611 if (!node_name) {
1612 node_name = gen_node_name = id_generate(ID_BLOCK);
1613 } else if (!id_wellformed(node_name)) {
1615 * Check for empty string or invalid characters, but not if it is
1616 * generated (generated names use characters not available to the user)
1618 error_setg(errp, "Invalid node-name: '%s'", node_name);
1619 return;
1622 /* takes care of avoiding namespaces collisions */
1623 if (blk_by_name(node_name)) {
1624 error_setg(errp, "node-name=%s is conflicting with a device id",
1625 node_name);
1626 goto out;
1629 /* takes care of avoiding duplicates node names */
1630 if (bdrv_find_node(node_name)) {
1631 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1632 goto out;
1635 /* Make sure that the node name isn't truncated */
1636 if (strlen(node_name) >= sizeof(bs->node_name)) {
1637 error_setg(errp, "Node name too long");
1638 goto out;
1641 /* copy node name into the bs and insert it into the graph list */
1642 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1643 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1644 out:
1645 g_free(gen_node_name);
1648 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1649 const char *node_name, QDict *options,
1650 int open_flags, Error **errp)
1652 Error *local_err = NULL;
1653 int i, ret;
1654 GLOBAL_STATE_CODE();
1656 bdrv_assign_node_name(bs, node_name, &local_err);
1657 if (local_err) {
1658 error_propagate(errp, local_err);
1659 return -EINVAL;
1662 bs->drv = drv;
1663 bs->opaque = g_malloc0(drv->instance_size);
1665 if (drv->bdrv_file_open) {
1666 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1667 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1668 } else if (drv->bdrv_open) {
1669 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1670 } else {
1671 ret = 0;
1674 if (ret < 0) {
1675 if (local_err) {
1676 error_propagate(errp, local_err);
1677 } else if (bs->filename[0]) {
1678 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1679 } else {
1680 error_setg_errno(errp, -ret, "Could not open image");
1682 goto open_failed;
1685 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1686 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1689 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1690 * drivers that pass read/write requests through to a child the trouble of
1691 * declaring support explicitly.
1693 * Drivers must not propagate this flag accidentally when they initiate I/O
1694 * to a bounce buffer. That case should be rare though.
1696 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1697 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1699 ret = refresh_total_sectors(bs, bs->total_sectors);
1700 if (ret < 0) {
1701 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1702 return ret;
1705 bdrv_refresh_limits(bs, NULL, &local_err);
1706 if (local_err) {
1707 error_propagate(errp, local_err);
1708 return -EINVAL;
1711 assert(bdrv_opt_mem_align(bs) != 0);
1712 assert(bdrv_min_mem_align(bs) != 0);
1713 assert(is_power_of_2(bs->bl.request_alignment));
1715 for (i = 0; i < bs->quiesce_counter; i++) {
1716 if (drv->bdrv_co_drain_begin) {
1717 drv->bdrv_co_drain_begin(bs);
1721 return 0;
1722 open_failed:
1723 bs->drv = NULL;
1724 if (bs->file != NULL) {
1725 bdrv_unref_child(bs, bs->file);
1726 assert(!bs->file);
1728 g_free(bs->opaque);
1729 bs->opaque = NULL;
1730 return ret;
1734 * Create and open a block node.
1736 * @options is a QDict of options to pass to the block drivers, or NULL for an
1737 * empty set of options. The reference to the QDict belongs to the block layer
1738 * after the call (even on failure), so if the caller intends to reuse the
1739 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1741 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1742 const char *node_name,
1743 QDict *options, int flags,
1744 Error **errp)
1746 BlockDriverState *bs;
1747 int ret;
1749 GLOBAL_STATE_CODE();
1751 bs = bdrv_new();
1752 bs->open_flags = flags;
1753 bs->options = options ?: qdict_new();
1754 bs->explicit_options = qdict_clone_shallow(bs->options);
1755 bs->opaque = NULL;
1757 update_options_from_flags(bs->options, flags);
1759 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1760 if (ret < 0) {
1761 qobject_unref(bs->explicit_options);
1762 bs->explicit_options = NULL;
1763 qobject_unref(bs->options);
1764 bs->options = NULL;
1765 bdrv_unref(bs);
1766 return NULL;
1769 return bs;
1772 /* Create and open a block node. */
1773 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1774 int flags, Error **errp)
1776 GLOBAL_STATE_CODE();
1777 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1780 QemuOptsList bdrv_runtime_opts = {
1781 .name = "bdrv_common",
1782 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1783 .desc = {
1785 .name = "node-name",
1786 .type = QEMU_OPT_STRING,
1787 .help = "Node name of the block device node",
1790 .name = "driver",
1791 .type = QEMU_OPT_STRING,
1792 .help = "Block driver to use for the node",
1795 .name = BDRV_OPT_CACHE_DIRECT,
1796 .type = QEMU_OPT_BOOL,
1797 .help = "Bypass software writeback cache on the host",
1800 .name = BDRV_OPT_CACHE_NO_FLUSH,
1801 .type = QEMU_OPT_BOOL,
1802 .help = "Ignore flush requests",
1805 .name = BDRV_OPT_READ_ONLY,
1806 .type = QEMU_OPT_BOOL,
1807 .help = "Node is opened in read-only mode",
1810 .name = BDRV_OPT_AUTO_READ_ONLY,
1811 .type = QEMU_OPT_BOOL,
1812 .help = "Node can become read-only if opening read-write fails",
1815 .name = "detect-zeroes",
1816 .type = QEMU_OPT_STRING,
1817 .help = "try to optimize zero writes (off, on, unmap)",
1820 .name = BDRV_OPT_DISCARD,
1821 .type = QEMU_OPT_STRING,
1822 .help = "discard operation (ignore/off, unmap/on)",
1825 .name = BDRV_OPT_FORCE_SHARE,
1826 .type = QEMU_OPT_BOOL,
1827 .help = "always accept other writers (default: off)",
1829 { /* end of list */ }
1833 QemuOptsList bdrv_create_opts_simple = {
1834 .name = "simple-create-opts",
1835 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1836 .desc = {
1838 .name = BLOCK_OPT_SIZE,
1839 .type = QEMU_OPT_SIZE,
1840 .help = "Virtual disk size"
1843 .name = BLOCK_OPT_PREALLOC,
1844 .type = QEMU_OPT_STRING,
1845 .help = "Preallocation mode (allowed values: off)"
1847 { /* end of list */ }
1852 * Common part for opening disk images and files
1854 * Removes all processed options from *options.
1856 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1857 QDict *options, Error **errp)
1859 int ret, open_flags;
1860 const char *filename;
1861 const char *driver_name = NULL;
1862 const char *node_name = NULL;
1863 const char *discard;
1864 QemuOpts *opts;
1865 BlockDriver *drv;
1866 Error *local_err = NULL;
1867 bool ro;
1869 assert(bs->file == NULL);
1870 assert(options != NULL && bs->options != options);
1871 GLOBAL_STATE_CODE();
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_refresh_filename(blk_bs(file));
1897 filename = blk_bs(file)->filename;
1898 } else {
1900 * Caution: while qdict_get_try_str() is fine, getting
1901 * non-string types would require more care. When @options
1902 * come from -blockdev or blockdev_add, its members are typed
1903 * according to the QAPI schema, but when they come from
1904 * -drive, they're all QString.
1906 filename = qdict_get_try_str(options, "filename");
1909 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1910 error_setg(errp, "The '%s' block driver requires a file name",
1911 drv->format_name);
1912 ret = -EINVAL;
1913 goto fail_opts;
1916 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1917 drv->format_name);
1919 ro = bdrv_is_read_only(bs);
1921 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1922 if (!ro && bdrv_is_whitelisted(drv, true)) {
1923 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1924 } else {
1925 ret = -ENOTSUP;
1927 if (ret < 0) {
1928 error_setg(errp,
1929 !ro && bdrv_is_whitelisted(drv, true)
1930 ? "Driver '%s' can only be used for read-only devices"
1931 : "Driver '%s' is not whitelisted",
1932 drv->format_name);
1933 goto fail_opts;
1937 /* bdrv_new() and bdrv_close() make it so */
1938 assert(qatomic_read(&bs->copy_on_read) == 0);
1940 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1941 if (!ro) {
1942 bdrv_enable_copy_on_read(bs);
1943 } else {
1944 error_setg(errp, "Can't use copy-on-read on read-only device");
1945 ret = -EINVAL;
1946 goto fail_opts;
1950 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1951 if (discard != NULL) {
1952 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1953 error_setg(errp, "Invalid discard option");
1954 ret = -EINVAL;
1955 goto fail_opts;
1959 bs->detect_zeroes =
1960 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1961 if (local_err) {
1962 error_propagate(errp, local_err);
1963 ret = -EINVAL;
1964 goto fail_opts;
1967 if (filename != NULL) {
1968 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1969 } else {
1970 bs->filename[0] = '\0';
1972 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1974 /* Open the image, either directly or using a protocol */
1975 open_flags = bdrv_open_flags(bs, bs->open_flags);
1976 node_name = qemu_opt_get(opts, "node-name");
1978 assert(!drv->bdrv_file_open || file == NULL);
1979 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1980 if (ret < 0) {
1981 goto fail_opts;
1984 qemu_opts_del(opts);
1985 return 0;
1987 fail_opts:
1988 qemu_opts_del(opts);
1989 return ret;
1992 static QDict *parse_json_filename(const char *filename, Error **errp)
1994 QObject *options_obj;
1995 QDict *options;
1996 int ret;
1997 GLOBAL_STATE_CODE();
1999 ret = strstart(filename, "json:", &filename);
2000 assert(ret);
2002 options_obj = qobject_from_json(filename, errp);
2003 if (!options_obj) {
2004 error_prepend(errp, "Could not parse the JSON options: ");
2005 return NULL;
2008 options = qobject_to(QDict, options_obj);
2009 if (!options) {
2010 qobject_unref(options_obj);
2011 error_setg(errp, "Invalid JSON object given");
2012 return NULL;
2015 qdict_flatten(options);
2017 return options;
2020 static void parse_json_protocol(QDict *options, const char **pfilename,
2021 Error **errp)
2023 QDict *json_options;
2024 Error *local_err = NULL;
2025 GLOBAL_STATE_CODE();
2027 /* Parse json: pseudo-protocol */
2028 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2029 return;
2032 json_options = parse_json_filename(*pfilename, &local_err);
2033 if (local_err) {
2034 error_propagate(errp, local_err);
2035 return;
2038 /* Options given in the filename have lower priority than options
2039 * specified directly */
2040 qdict_join(options, json_options, false);
2041 qobject_unref(json_options);
2042 *pfilename = NULL;
2046 * Fills in default options for opening images and converts the legacy
2047 * filename/flags pair to option QDict entries.
2048 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2049 * block driver has been specified explicitly.
2051 static int bdrv_fill_options(QDict **options, const char *filename,
2052 int *flags, Error **errp)
2054 const char *drvname;
2055 bool protocol = *flags & BDRV_O_PROTOCOL;
2056 bool parse_filename = false;
2057 BlockDriver *drv = NULL;
2058 Error *local_err = NULL;
2060 GLOBAL_STATE_CODE();
2063 * Caution: while qdict_get_try_str() is fine, getting non-string
2064 * types would require more care. When @options come from
2065 * -blockdev or blockdev_add, its members are typed according to
2066 * the QAPI schema, but when they come from -drive, they're all
2067 * QString.
2069 drvname = qdict_get_try_str(*options, "driver");
2070 if (drvname) {
2071 drv = bdrv_find_format(drvname);
2072 if (!drv) {
2073 error_setg(errp, "Unknown driver '%s'", drvname);
2074 return -ENOENT;
2076 /* If the user has explicitly specified the driver, this choice should
2077 * override the BDRV_O_PROTOCOL flag */
2078 protocol = drv->bdrv_file_open;
2081 if (protocol) {
2082 *flags |= BDRV_O_PROTOCOL;
2083 } else {
2084 *flags &= ~BDRV_O_PROTOCOL;
2087 /* Translate cache options from flags into options */
2088 update_options_from_flags(*options, *flags);
2090 /* Fetch the file name from the options QDict if necessary */
2091 if (protocol && filename) {
2092 if (!qdict_haskey(*options, "filename")) {
2093 qdict_put_str(*options, "filename", filename);
2094 parse_filename = true;
2095 } else {
2096 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2097 "the same time");
2098 return -EINVAL;
2102 /* Find the right block driver */
2103 /* See cautionary note on accessing @options above */
2104 filename = qdict_get_try_str(*options, "filename");
2106 if (!drvname && protocol) {
2107 if (filename) {
2108 drv = bdrv_find_protocol(filename, parse_filename, errp);
2109 if (!drv) {
2110 return -EINVAL;
2113 drvname = drv->format_name;
2114 qdict_put_str(*options, "driver", drvname);
2115 } else {
2116 error_setg(errp, "Must specify either driver or file");
2117 return -EINVAL;
2121 assert(drv || !protocol);
2123 /* Driver-specific filename parsing */
2124 if (drv && drv->bdrv_parse_filename && parse_filename) {
2125 drv->bdrv_parse_filename(filename, *options, &local_err);
2126 if (local_err) {
2127 error_propagate(errp, local_err);
2128 return -EINVAL;
2131 if (!drv->bdrv_needs_filename) {
2132 qdict_del(*options, "filename");
2136 return 0;
2139 typedef struct BlockReopenQueueEntry {
2140 bool prepared;
2141 bool perms_checked;
2142 BDRVReopenState state;
2143 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2144 } BlockReopenQueueEntry;
2147 * Return the flags that @bs will have after the reopens in @q have
2148 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2149 * return the current flags.
2151 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2153 BlockReopenQueueEntry *entry;
2155 if (q != NULL) {
2156 QTAILQ_FOREACH(entry, q, entry) {
2157 if (entry->state.bs == bs) {
2158 return entry->state.flags;
2163 return bs->open_flags;
2166 /* Returns whether the image file can be written to after the reopen queue @q
2167 * has been successfully applied, or right now if @q is NULL. */
2168 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2169 BlockReopenQueue *q)
2171 int flags = bdrv_reopen_get_flags(q, bs);
2173 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2177 * Return whether the BDS can be written to. This is not necessarily
2178 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2179 * be written to but do not count as read-only images.
2181 bool bdrv_is_writable(BlockDriverState *bs)
2183 IO_CODE();
2184 return bdrv_is_writable_after_reopen(bs, NULL);
2187 static char *bdrv_child_user_desc(BdrvChild *c)
2189 GLOBAL_STATE_CODE();
2190 return c->klass->get_parent_desc(c);
2194 * Check that @a allows everything that @b needs. @a and @b must reference same
2195 * child node.
2197 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2199 const char *child_bs_name;
2200 g_autofree char *a_user = NULL;
2201 g_autofree char *b_user = NULL;
2202 g_autofree char *perms = NULL;
2204 assert(a->bs);
2205 assert(a->bs == b->bs);
2206 GLOBAL_STATE_CODE();
2208 if ((b->perm & a->shared_perm) == b->perm) {
2209 return true;
2212 child_bs_name = bdrv_get_node_name(b->bs);
2213 a_user = bdrv_child_user_desc(a);
2214 b_user = bdrv_child_user_desc(b);
2215 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2217 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2218 "both required by %s (uses node '%s' as '%s' child) and "
2219 "unshared by %s (uses node '%s' as '%s' child).",
2220 child_bs_name, perms,
2221 b_user, child_bs_name, b->name,
2222 a_user, child_bs_name, a->name);
2224 return false;
2227 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2229 BdrvChild *a, *b;
2230 GLOBAL_STATE_CODE();
2233 * During the loop we'll look at each pair twice. That's correct because
2234 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2235 * directions.
2237 QLIST_FOREACH(a, &bs->parents, next_parent) {
2238 QLIST_FOREACH(b, &bs->parents, next_parent) {
2239 if (a == b) {
2240 continue;
2243 if (!bdrv_a_allow_b(a, b, errp)) {
2244 return true;
2249 return false;
2252 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2253 BdrvChild *c, BdrvChildRole role,
2254 BlockReopenQueue *reopen_queue,
2255 uint64_t parent_perm, uint64_t parent_shared,
2256 uint64_t *nperm, uint64_t *nshared)
2258 assert(bs->drv && bs->drv->bdrv_child_perm);
2259 GLOBAL_STATE_CODE();
2260 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2261 parent_perm, parent_shared,
2262 nperm, nshared);
2263 /* TODO Take force_share from reopen_queue */
2264 if (child_bs && child_bs->force_share) {
2265 *nshared = BLK_PERM_ALL;
2270 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2271 * nodes that are already in the @list, of course) so that final list is
2272 * topologically sorted. Return the result (GSList @list object is updated, so
2273 * don't use old reference after function call).
2275 * On function start @list must be already topologically sorted and for any node
2276 * in the @list the whole subtree of the node must be in the @list as well. The
2277 * simplest way to satisfy this criteria: use only result of
2278 * bdrv_topological_dfs() or NULL as @list parameter.
2280 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2281 BlockDriverState *bs)
2283 BdrvChild *child;
2284 g_autoptr(GHashTable) local_found = NULL;
2286 GLOBAL_STATE_CODE();
2288 if (!found) {
2289 assert(!list);
2290 found = local_found = g_hash_table_new(NULL, NULL);
2293 if (g_hash_table_contains(found, bs)) {
2294 return list;
2296 g_hash_table_add(found, bs);
2298 QLIST_FOREACH(child, &bs->children, next) {
2299 list = bdrv_topological_dfs(list, found, child->bs);
2302 return g_slist_prepend(list, bs);
2305 typedef struct BdrvChildSetPermState {
2306 BdrvChild *child;
2307 uint64_t old_perm;
2308 uint64_t old_shared_perm;
2309 } BdrvChildSetPermState;
2311 static void bdrv_child_set_perm_abort(void *opaque)
2313 BdrvChildSetPermState *s = opaque;
2315 GLOBAL_STATE_CODE();
2317 s->child->perm = s->old_perm;
2318 s->child->shared_perm = s->old_shared_perm;
2321 static TransactionActionDrv bdrv_child_set_pem_drv = {
2322 .abort = bdrv_child_set_perm_abort,
2323 .clean = g_free,
2326 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2327 uint64_t shared, Transaction *tran)
2329 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2330 GLOBAL_STATE_CODE();
2332 *s = (BdrvChildSetPermState) {
2333 .child = c,
2334 .old_perm = c->perm,
2335 .old_shared_perm = c->shared_perm,
2338 c->perm = perm;
2339 c->shared_perm = shared;
2341 tran_add(tran, &bdrv_child_set_pem_drv, s);
2344 static void bdrv_drv_set_perm_commit(void *opaque)
2346 BlockDriverState *bs = opaque;
2347 uint64_t cumulative_perms, cumulative_shared_perms;
2348 GLOBAL_STATE_CODE();
2350 if (bs->drv->bdrv_set_perm) {
2351 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2352 &cumulative_shared_perms);
2353 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2357 static void bdrv_drv_set_perm_abort(void *opaque)
2359 BlockDriverState *bs = opaque;
2360 GLOBAL_STATE_CODE();
2362 if (bs->drv->bdrv_abort_perm_update) {
2363 bs->drv->bdrv_abort_perm_update(bs);
2367 TransactionActionDrv bdrv_drv_set_perm_drv = {
2368 .abort = bdrv_drv_set_perm_abort,
2369 .commit = bdrv_drv_set_perm_commit,
2372 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2373 uint64_t shared_perm, Transaction *tran,
2374 Error **errp)
2376 GLOBAL_STATE_CODE();
2377 if (!bs->drv) {
2378 return 0;
2381 if (bs->drv->bdrv_check_perm) {
2382 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2383 if (ret < 0) {
2384 return ret;
2388 if (tran) {
2389 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2392 return 0;
2395 typedef struct BdrvReplaceChildState {
2396 BdrvChild *child;
2397 BlockDriverState *old_bs;
2398 } BdrvReplaceChildState;
2400 static void bdrv_replace_child_commit(void *opaque)
2402 BdrvReplaceChildState *s = opaque;
2403 GLOBAL_STATE_CODE();
2405 bdrv_unref(s->old_bs);
2408 static void bdrv_replace_child_abort(void *opaque)
2410 BdrvReplaceChildState *s = opaque;
2411 BlockDriverState *new_bs = s->child->bs;
2413 GLOBAL_STATE_CODE();
2414 /* old_bs reference is transparently moved from @s to @s->child */
2415 bdrv_replace_child_noperm(s->child, s->old_bs);
2416 bdrv_unref(new_bs);
2419 static TransactionActionDrv bdrv_replace_child_drv = {
2420 .commit = bdrv_replace_child_commit,
2421 .abort = bdrv_replace_child_abort,
2422 .clean = g_free,
2426 * bdrv_replace_child_tran
2428 * Note: real unref of old_bs is done only on commit.
2430 * The function doesn't update permissions, caller is responsible for this.
2432 static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2433 Transaction *tran)
2435 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2436 *s = (BdrvReplaceChildState) {
2437 .child = child,
2438 .old_bs = child->bs,
2440 tran_add(tran, &bdrv_replace_child_drv, s);
2442 if (new_bs) {
2443 bdrv_ref(new_bs);
2445 bdrv_replace_child_noperm(child, new_bs);
2446 /* old_bs reference is transparently moved from @child to @s */
2450 * Refresh permissions in @bs subtree. The function is intended to be called
2451 * after some graph modification that was done without permission update.
2453 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2454 Transaction *tran, Error **errp)
2456 BlockDriver *drv = bs->drv;
2457 BdrvChild *c;
2458 int ret;
2459 uint64_t cumulative_perms, cumulative_shared_perms;
2460 GLOBAL_STATE_CODE();
2462 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2464 /* Write permissions never work with read-only images */
2465 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2466 !bdrv_is_writable_after_reopen(bs, q))
2468 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2469 error_setg(errp, "Block node is read-only");
2470 } else {
2471 error_setg(errp, "Read-only block node '%s' cannot support "
2472 "read-write users", bdrv_get_node_name(bs));
2475 return -EPERM;
2479 * Unaligned requests will automatically be aligned to bl.request_alignment
2480 * and without RESIZE we can't extend requests to write to space beyond the
2481 * end of the image, so it's required that the image size is aligned.
2483 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2484 !(cumulative_perms & BLK_PERM_RESIZE))
2486 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2487 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2488 "Image size is not a multiple of request "
2489 "alignment");
2490 return -EPERM;
2494 /* Check this node */
2495 if (!drv) {
2496 return 0;
2499 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2500 errp);
2501 if (ret < 0) {
2502 return ret;
2505 /* Drivers that never have children can omit .bdrv_child_perm() */
2506 if (!drv->bdrv_child_perm) {
2507 assert(QLIST_EMPTY(&bs->children));
2508 return 0;
2511 /* Check all children */
2512 QLIST_FOREACH(c, &bs->children, next) {
2513 uint64_t cur_perm, cur_shared;
2515 bdrv_child_perm(bs, c->bs, c, c->role, q,
2516 cumulative_perms, cumulative_shared_perms,
2517 &cur_perm, &cur_shared);
2518 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2521 return 0;
2525 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2526 * a topologically sorted subgraph.
2528 static int bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q,
2529 Transaction *tran, Error **errp)
2531 int ret;
2532 BlockDriverState *bs;
2533 GLOBAL_STATE_CODE();
2535 for ( ; list; list = list->next) {
2536 bs = list->data;
2538 if (bdrv_parent_perms_conflict(bs, errp)) {
2539 return -EINVAL;
2542 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2543 if (ret < 0) {
2544 return ret;
2548 return 0;
2552 * @list is any list of nodes. List is completed by all subtrees and
2553 * topologically sorted. It's not a problem if some node occurs in the @list
2554 * several times.
2556 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2557 Transaction *tran, Error **errp)
2559 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2560 g_autoptr(GSList) refresh_list = NULL;
2562 for ( ; list; list = list->next) {
2563 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2566 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2569 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2570 uint64_t *shared_perm)
2572 BdrvChild *c;
2573 uint64_t cumulative_perms = 0;
2574 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2576 GLOBAL_STATE_CODE();
2578 QLIST_FOREACH(c, &bs->parents, next_parent) {
2579 cumulative_perms |= c->perm;
2580 cumulative_shared_perms &= c->shared_perm;
2583 *perm = cumulative_perms;
2584 *shared_perm = cumulative_shared_perms;
2587 char *bdrv_perm_names(uint64_t perm)
2589 struct perm_name {
2590 uint64_t perm;
2591 const char *name;
2592 } permissions[] = {
2593 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2594 { BLK_PERM_WRITE, "write" },
2595 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2596 { BLK_PERM_RESIZE, "resize" },
2597 { 0, NULL }
2600 GString *result = g_string_sized_new(30);
2601 struct perm_name *p;
2603 for (p = permissions; p->name; p++) {
2604 if (perm & p->perm) {
2605 if (result->len > 0) {
2606 g_string_append(result, ", ");
2608 g_string_append(result, p->name);
2612 return g_string_free(result, FALSE);
2616 /* @tran is allowed to be NULL. In this case no rollback is possible */
2617 static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2618 Error **errp)
2620 int ret;
2621 Transaction *local_tran = NULL;
2622 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2623 GLOBAL_STATE_CODE();
2625 if (!tran) {
2626 tran = local_tran = tran_new();
2629 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2631 if (local_tran) {
2632 tran_finalize(local_tran, ret);
2635 return ret;
2638 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2639 Error **errp)
2641 Error *local_err = NULL;
2642 Transaction *tran = tran_new();
2643 int ret;
2645 GLOBAL_STATE_CODE();
2647 bdrv_child_set_perm(c, perm, shared, tran);
2649 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2651 tran_finalize(tran, ret);
2653 if (ret < 0) {
2654 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2655 /* tighten permissions */
2656 error_propagate(errp, local_err);
2657 } else {
2659 * Our caller may intend to only loosen restrictions and
2660 * does not expect this function to fail. Errors are not
2661 * fatal in such a case, so we can just hide them from our
2662 * caller.
2664 error_free(local_err);
2665 ret = 0;
2669 return ret;
2672 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2674 uint64_t parent_perms, parent_shared;
2675 uint64_t perms, shared;
2677 GLOBAL_STATE_CODE();
2679 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2680 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2681 parent_perms, parent_shared, &perms, &shared);
2683 return bdrv_child_try_set_perm(c, perms, shared, errp);
2687 * Default implementation for .bdrv_child_perm() for block filters:
2688 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2689 * filtered child.
2691 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2692 BdrvChildRole role,
2693 BlockReopenQueue *reopen_queue,
2694 uint64_t perm, uint64_t shared,
2695 uint64_t *nperm, uint64_t *nshared)
2697 GLOBAL_STATE_CODE();
2698 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2699 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2702 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2703 BdrvChildRole role,
2704 BlockReopenQueue *reopen_queue,
2705 uint64_t perm, uint64_t shared,
2706 uint64_t *nperm, uint64_t *nshared)
2708 assert(role & BDRV_CHILD_COW);
2709 GLOBAL_STATE_CODE();
2712 * We want consistent read from backing files if the parent needs it.
2713 * No other operations are performed on backing files.
2715 perm &= BLK_PERM_CONSISTENT_READ;
2718 * If the parent can deal with changing data, we're okay with a
2719 * writable and resizable backing file.
2720 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2722 if (shared & BLK_PERM_WRITE) {
2723 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2724 } else {
2725 shared = 0;
2728 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2730 if (bs->open_flags & BDRV_O_INACTIVE) {
2731 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2734 *nperm = perm;
2735 *nshared = shared;
2738 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2739 BdrvChildRole role,
2740 BlockReopenQueue *reopen_queue,
2741 uint64_t perm, uint64_t shared,
2742 uint64_t *nperm, uint64_t *nshared)
2744 int flags;
2746 GLOBAL_STATE_CODE();
2747 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2749 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2752 * Apart from the modifications below, the same permissions are
2753 * forwarded and left alone as for filters
2755 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2756 perm, shared, &perm, &shared);
2758 if (role & BDRV_CHILD_METADATA) {
2759 /* Format drivers may touch metadata even if the guest doesn't write */
2760 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2761 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2765 * bs->file always needs to be consistent because of the
2766 * metadata. We can never allow other users to resize or write
2767 * to it.
2769 if (!(flags & BDRV_O_NO_IO)) {
2770 perm |= BLK_PERM_CONSISTENT_READ;
2772 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2775 if (role & BDRV_CHILD_DATA) {
2777 * Technically, everything in this block is a subset of the
2778 * BDRV_CHILD_METADATA path taken above, and so this could
2779 * be an "else if" branch. However, that is not obvious, and
2780 * this function is not performance critical, therefore we let
2781 * this be an independent "if".
2785 * We cannot allow other users to resize the file because the
2786 * format driver might have some assumptions about the size
2787 * (e.g. because it is stored in metadata, or because the file
2788 * is split into fixed-size data files).
2790 shared &= ~BLK_PERM_RESIZE;
2793 * WRITE_UNCHANGED often cannot be performed as such on the
2794 * data file. For example, the qcow2 driver may still need to
2795 * write copied clusters on copy-on-read.
2797 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2798 perm |= BLK_PERM_WRITE;
2802 * If the data file is written to, the format driver may
2803 * expect to be able to resize it by writing beyond the EOF.
2805 if (perm & BLK_PERM_WRITE) {
2806 perm |= BLK_PERM_RESIZE;
2810 if (bs->open_flags & BDRV_O_INACTIVE) {
2811 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2814 *nperm = perm;
2815 *nshared = shared;
2818 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2819 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2820 uint64_t perm, uint64_t shared,
2821 uint64_t *nperm, uint64_t *nshared)
2823 GLOBAL_STATE_CODE();
2824 if (role & BDRV_CHILD_FILTERED) {
2825 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2826 BDRV_CHILD_COW)));
2827 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2828 perm, shared, nperm, nshared);
2829 } else if (role & BDRV_CHILD_COW) {
2830 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2831 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2832 perm, shared, nperm, nshared);
2833 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2834 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2835 perm, shared, nperm, nshared);
2836 } else {
2837 g_assert_not_reached();
2841 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2843 static const uint64_t permissions[] = {
2844 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2845 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2846 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2847 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2850 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2851 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2853 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2855 return permissions[qapi_perm];
2858 static void bdrv_replace_child_noperm(BdrvChild *child,
2859 BlockDriverState *new_bs)
2861 BlockDriverState *old_bs = child->bs;
2862 int new_bs_quiesce_counter;
2863 int drain_saldo;
2865 assert(!child->frozen);
2866 assert(old_bs != new_bs);
2867 GLOBAL_STATE_CODE();
2869 if (old_bs && new_bs) {
2870 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2873 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2874 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2877 * If the new child node is drained but the old one was not, flush
2878 * all outstanding requests to the old child node.
2880 while (drain_saldo > 0 && child->klass->drained_begin) {
2881 bdrv_parent_drained_begin_single(child, true);
2882 drain_saldo--;
2885 if (old_bs) {
2886 /* Detach first so that the recursive drain sections coming from @child
2887 * are already gone and we only end the drain sections that came from
2888 * elsewhere. */
2889 if (child->klass->detach) {
2890 child->klass->detach(child);
2892 assert_bdrv_graph_writable(old_bs);
2893 QLIST_REMOVE(child, next_parent);
2896 child->bs = new_bs;
2898 if (new_bs) {
2899 assert_bdrv_graph_writable(new_bs);
2900 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2903 * Detaching the old node may have led to the new node's
2904 * quiesce_counter having been decreased. Not a problem, we
2905 * just need to recognize this here and then invoke
2906 * drained_end appropriately more often.
2908 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2909 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2911 /* Attach only after starting new drained sections, so that recursive
2912 * drain sections coming from @child don't get an extra .drained_begin
2913 * callback. */
2914 if (child->klass->attach) {
2915 child->klass->attach(child);
2920 * If the old child node was drained but the new one is not, allow
2921 * requests to come in only after the new node has been attached.
2923 while (drain_saldo < 0 && child->klass->drained_end) {
2924 bdrv_parent_drained_end_single(child);
2925 drain_saldo++;
2930 * Free the given @child.
2932 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2933 * unused (i.e. not in a children list).
2935 static void bdrv_child_free(BdrvChild *child)
2937 assert(!child->bs);
2938 GLOBAL_STATE_CODE();
2939 assert(!child->next.le_prev); /* not in children list */
2941 g_free(child->name);
2942 g_free(child);
2945 typedef struct BdrvAttachChildCommonState {
2946 BdrvChild *child;
2947 AioContext *old_parent_ctx;
2948 AioContext *old_child_ctx;
2949 } BdrvAttachChildCommonState;
2951 static void bdrv_attach_child_common_abort(void *opaque)
2953 BdrvAttachChildCommonState *s = opaque;
2954 BlockDriverState *bs = s->child->bs;
2956 GLOBAL_STATE_CODE();
2957 bdrv_replace_child_noperm(s->child, NULL);
2959 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2960 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
2963 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
2964 Transaction *tran;
2965 GHashTable *visited;
2966 bool ret;
2968 tran = tran_new();
2970 /* No need to visit `child`, because it has been detached already */
2971 visited = g_hash_table_new(NULL, NULL);
2972 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2973 visited, tran, &error_abort);
2974 g_hash_table_destroy(visited);
2976 /* transaction is supposed to always succeed */
2977 assert(ret == true);
2978 tran_commit(tran);
2981 bdrv_unref(bs);
2982 bdrv_child_free(s->child);
2985 static TransactionActionDrv bdrv_attach_child_common_drv = {
2986 .abort = bdrv_attach_child_common_abort,
2987 .clean = g_free,
2991 * Common part of attaching bdrv child to bs or to blk or to job
2993 * Function doesn't update permissions, caller is responsible for this.
2995 * Returns new created child.
2997 static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2998 const char *child_name,
2999 const BdrvChildClass *child_class,
3000 BdrvChildRole child_role,
3001 uint64_t perm, uint64_t shared_perm,
3002 void *opaque,
3003 Transaction *tran, Error **errp)
3005 BdrvChild *new_child;
3006 AioContext *parent_ctx;
3007 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3009 assert(child_class->get_parent_desc);
3010 GLOBAL_STATE_CODE();
3012 new_child = g_new(BdrvChild, 1);
3013 *new_child = (BdrvChild) {
3014 .bs = NULL,
3015 .name = g_strdup(child_name),
3016 .klass = child_class,
3017 .role = child_role,
3018 .perm = perm,
3019 .shared_perm = shared_perm,
3020 .opaque = opaque,
3024 * If the AioContexts don't match, first try to move the subtree of
3025 * child_bs into the AioContext of the new parent. If this doesn't work,
3026 * try moving the parent into the AioContext of child_bs instead.
3028 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3029 if (child_ctx != parent_ctx) {
3030 Error *local_err = NULL;
3031 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3032 &local_err);
3034 if (ret < 0 && child_class->change_aio_ctx) {
3035 Transaction *tran = tran_new();
3036 GHashTable *visited = g_hash_table_new(NULL, NULL);
3037 bool ret_child;
3039 g_hash_table_add(visited, new_child);
3040 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3041 visited, tran, NULL);
3042 if (ret_child == true) {
3043 error_free(local_err);
3044 ret = 0;
3046 tran_finalize(tran, ret_child == true ? 0 : -1);
3047 g_hash_table_destroy(visited);
3050 if (ret < 0) {
3051 error_propagate(errp, local_err);
3052 bdrv_child_free(new_child);
3053 return NULL;
3057 bdrv_ref(child_bs);
3058 bdrv_replace_child_noperm(new_child, child_bs);
3060 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3061 *s = (BdrvAttachChildCommonState) {
3062 .child = new_child,
3063 .old_parent_ctx = parent_ctx,
3064 .old_child_ctx = child_ctx,
3066 tran_add(tran, &bdrv_attach_child_common_drv, s);
3068 return new_child;
3072 * Function doesn't update permissions, caller is responsible for this.
3074 static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3075 BlockDriverState *child_bs,
3076 const char *child_name,
3077 const BdrvChildClass *child_class,
3078 BdrvChildRole child_role,
3079 Transaction *tran,
3080 Error **errp)
3082 uint64_t perm, shared_perm;
3084 assert(parent_bs->drv);
3085 GLOBAL_STATE_CODE();
3087 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3088 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3089 child_bs->node_name, child_name, parent_bs->node_name);
3090 return NULL;
3093 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3094 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3095 perm, shared_perm, &perm, &shared_perm);
3097 return bdrv_attach_child_common(child_bs, child_name, child_class,
3098 child_role, perm, shared_perm, parent_bs,
3099 tran, errp);
3103 * This function steals the reference to child_bs from the caller.
3104 * That reference is later dropped by bdrv_root_unref_child().
3106 * On failure NULL is returned, errp is set and the reference to
3107 * child_bs is also dropped.
3109 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3110 * (unless @child_bs is already in @ctx).
3112 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3113 const char *child_name,
3114 const BdrvChildClass *child_class,
3115 BdrvChildRole child_role,
3116 uint64_t perm, uint64_t shared_perm,
3117 void *opaque, Error **errp)
3119 int ret;
3120 BdrvChild *child;
3121 Transaction *tran = tran_new();
3123 GLOBAL_STATE_CODE();
3125 child = bdrv_attach_child_common(child_bs, child_name, child_class,
3126 child_role, perm, shared_perm, opaque,
3127 tran, errp);
3128 if (!child) {
3129 ret = -EINVAL;
3130 goto out;
3133 ret = bdrv_refresh_perms(child_bs, tran, errp);
3135 out:
3136 tran_finalize(tran, ret);
3138 bdrv_unref(child_bs);
3140 return ret < 0 ? NULL : child;
3144 * This function transfers the reference to child_bs from the caller
3145 * to parent_bs. That reference is later dropped by parent_bs on
3146 * bdrv_close() or if someone calls bdrv_unref_child().
3148 * On failure NULL is returned, errp is set and the reference to
3149 * child_bs is also dropped.
3151 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3152 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3154 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3155 BlockDriverState *child_bs,
3156 const char *child_name,
3157 const BdrvChildClass *child_class,
3158 BdrvChildRole child_role,
3159 Error **errp)
3161 int ret;
3162 BdrvChild *child;
3163 Transaction *tran = tran_new();
3165 GLOBAL_STATE_CODE();
3167 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3168 child_class, child_role, tran, errp);
3169 if (!child) {
3170 ret = -EINVAL;
3171 goto out;
3174 ret = bdrv_refresh_perms(parent_bs, tran, errp);
3175 if (ret < 0) {
3176 goto out;
3179 out:
3180 tran_finalize(tran, ret);
3182 bdrv_unref(child_bs);
3184 return ret < 0 ? NULL : child;
3187 /* Callers must ensure that child->frozen is false. */
3188 void bdrv_root_unref_child(BdrvChild *child)
3190 BlockDriverState *child_bs = child->bs;
3192 GLOBAL_STATE_CODE();
3193 bdrv_replace_child_noperm(child, NULL);
3194 bdrv_child_free(child);
3196 if (child_bs) {
3198 * Update permissions for old node. We're just taking a parent away, so
3199 * we're loosening restrictions. Errors of permission update are not
3200 * fatal in this case, ignore them.
3202 bdrv_refresh_perms(child_bs, NULL, NULL);
3205 * When the parent requiring a non-default AioContext is removed, the
3206 * node moves back to the main AioContext
3208 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3209 NULL);
3212 bdrv_unref(child_bs);
3215 typedef struct BdrvSetInheritsFrom {
3216 BlockDriverState *bs;
3217 BlockDriverState *old_inherits_from;
3218 } BdrvSetInheritsFrom;
3220 static void bdrv_set_inherits_from_abort(void *opaque)
3222 BdrvSetInheritsFrom *s = opaque;
3224 s->bs->inherits_from = s->old_inherits_from;
3227 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3228 .abort = bdrv_set_inherits_from_abort,
3229 .clean = g_free,
3232 /* @tran is allowed to be NULL. In this case no rollback is possible */
3233 static void bdrv_set_inherits_from(BlockDriverState *bs,
3234 BlockDriverState *new_inherits_from,
3235 Transaction *tran)
3237 if (tran) {
3238 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3240 *s = (BdrvSetInheritsFrom) {
3241 .bs = bs,
3242 .old_inherits_from = bs->inherits_from,
3245 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3248 bs->inherits_from = new_inherits_from;
3252 * Clear all inherits_from pointers from children and grandchildren of
3253 * @root that point to @root, where necessary.
3254 * @tran is allowed to be NULL. In this case no rollback is possible
3256 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3257 Transaction *tran)
3259 BdrvChild *c;
3261 if (child->bs->inherits_from == root) {
3263 * Remove inherits_from only when the last reference between root and
3264 * child->bs goes away.
3266 QLIST_FOREACH(c, &root->children, next) {
3267 if (c != child && c->bs == child->bs) {
3268 break;
3271 if (c == NULL) {
3272 bdrv_set_inherits_from(child->bs, NULL, tran);
3276 QLIST_FOREACH(c, &child->bs->children, next) {
3277 bdrv_unset_inherits_from(root, c, tran);
3281 /* Callers must ensure that child->frozen is false. */
3282 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3284 GLOBAL_STATE_CODE();
3285 if (child == NULL) {
3286 return;
3289 bdrv_unset_inherits_from(parent, child, NULL);
3290 bdrv_root_unref_child(child);
3294 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3296 BdrvChild *c;
3297 GLOBAL_STATE_CODE();
3298 QLIST_FOREACH(c, &bs->parents, next_parent) {
3299 if (c->klass->change_media) {
3300 c->klass->change_media(c, load);
3305 /* Return true if you can reach parent going through child->inherits_from
3306 * recursively. If parent or child are NULL, return false */
3307 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3308 BlockDriverState *parent)
3310 while (child && child != parent) {
3311 child = child->inherits_from;
3314 return child != NULL;
3318 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3319 * mostly used for COW backing children (role = COW), but also for
3320 * filtered children (role = FILTERED | PRIMARY).
3322 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3324 if (bs->drv && bs->drv->is_filter) {
3325 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3326 } else {
3327 return BDRV_CHILD_COW;
3332 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3333 * callers which don't need their own reference any more must call bdrv_unref().
3335 * Function doesn't update permissions, caller is responsible for this.
3337 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3338 BlockDriverState *child_bs,
3339 bool is_backing,
3340 Transaction *tran, Error **errp)
3342 bool update_inherits_from =
3343 bdrv_inherits_from_recursive(child_bs, parent_bs);
3344 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3345 BdrvChildRole role;
3347 GLOBAL_STATE_CODE();
3349 if (!parent_bs->drv) {
3351 * Node without drv is an object without a class :/. TODO: finally fix
3352 * qcow2 driver to never clear bs->drv and implement format corruption
3353 * handling in other way.
3355 error_setg(errp, "Node corrupted");
3356 return -EINVAL;
3359 if (child && child->frozen) {
3360 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3361 child->name, parent_bs->node_name, child->bs->node_name);
3362 return -EPERM;
3365 if (is_backing && !parent_bs->drv->is_filter &&
3366 !parent_bs->drv->supports_backing)
3368 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3369 "files", parent_bs->drv->format_name, parent_bs->node_name);
3370 return -EINVAL;
3373 if (parent_bs->drv->is_filter) {
3374 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3375 } else if (is_backing) {
3376 role = BDRV_CHILD_COW;
3377 } else {
3379 * We only can use same role as it is in existing child. We don't have
3380 * infrastructure to determine role of file child in generic way
3382 if (!child) {
3383 error_setg(errp, "Cannot set file child to format node without "
3384 "file child");
3385 return -EINVAL;
3387 role = child->role;
3390 if (child) {
3391 bdrv_unset_inherits_from(parent_bs, child, tran);
3392 bdrv_remove_child(child, tran);
3395 if (!child_bs) {
3396 goto out;
3399 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3400 is_backing ? "backing" : "file",
3401 &child_of_bds, role,
3402 tran, errp);
3403 if (!child) {
3404 return -EINVAL;
3409 * If inherits_from pointed recursively to bs then let's update it to
3410 * point directly to bs (else it will become NULL).
3412 if (update_inherits_from) {
3413 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3416 out:
3417 bdrv_refresh_limits(parent_bs, tran, NULL);
3419 return 0;
3422 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3423 BlockDriverState *backing_hd,
3424 Transaction *tran, Error **errp)
3426 GLOBAL_STATE_CODE();
3427 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3430 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3431 Error **errp)
3433 int ret;
3434 Transaction *tran = tran_new();
3436 GLOBAL_STATE_CODE();
3437 bdrv_drained_begin(bs);
3439 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3440 if (ret < 0) {
3441 goto out;
3444 ret = bdrv_refresh_perms(bs, tran, errp);
3445 out:
3446 tran_finalize(tran, ret);
3448 bdrv_drained_end(bs);
3450 return ret;
3454 * Opens the backing file for a BlockDriverState if not yet open
3456 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3457 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3458 * itself, all options starting with "${bdref_key}." are considered part of the
3459 * BlockdevRef.
3461 * TODO Can this be unified with bdrv_open_image()?
3463 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3464 const char *bdref_key, Error **errp)
3466 char *backing_filename = NULL;
3467 char *bdref_key_dot;
3468 const char *reference = NULL;
3469 int ret = 0;
3470 bool implicit_backing = false;
3471 BlockDriverState *backing_hd;
3472 QDict *options;
3473 QDict *tmp_parent_options = NULL;
3474 Error *local_err = NULL;
3476 GLOBAL_STATE_CODE();
3478 if (bs->backing != NULL) {
3479 goto free_exit;
3482 /* NULL means an empty set of options */
3483 if (parent_options == NULL) {
3484 tmp_parent_options = qdict_new();
3485 parent_options = tmp_parent_options;
3488 bs->open_flags &= ~BDRV_O_NO_BACKING;
3490 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3491 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3492 g_free(bdref_key_dot);
3495 * Caution: while qdict_get_try_str() is fine, getting non-string
3496 * types would require more care. When @parent_options come from
3497 * -blockdev or blockdev_add, its members are typed according to
3498 * the QAPI schema, but when they come from -drive, they're all
3499 * QString.
3501 reference = qdict_get_try_str(parent_options, bdref_key);
3502 if (reference || qdict_haskey(options, "file.filename")) {
3503 /* keep backing_filename NULL */
3504 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3505 qobject_unref(options);
3506 goto free_exit;
3507 } else {
3508 if (qdict_size(options) == 0) {
3509 /* If the user specifies options that do not modify the
3510 * backing file's behavior, we might still consider it the
3511 * implicit backing file. But it's easier this way, and
3512 * just specifying some of the backing BDS's options is
3513 * only possible with -drive anyway (otherwise the QAPI
3514 * schema forces the user to specify everything). */
3515 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3518 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3519 if (local_err) {
3520 ret = -EINVAL;
3521 error_propagate(errp, local_err);
3522 qobject_unref(options);
3523 goto free_exit;
3527 if (!bs->drv || !bs->drv->supports_backing) {
3528 ret = -EINVAL;
3529 error_setg(errp, "Driver doesn't support backing files");
3530 qobject_unref(options);
3531 goto free_exit;
3534 if (!reference &&
3535 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3536 qdict_put_str(options, "driver", bs->backing_format);
3539 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3540 &child_of_bds, bdrv_backing_role(bs), errp);
3541 if (!backing_hd) {
3542 bs->open_flags |= BDRV_O_NO_BACKING;
3543 error_prepend(errp, "Could not open backing file: ");
3544 ret = -EINVAL;
3545 goto free_exit;
3548 if (implicit_backing) {
3549 bdrv_refresh_filename(backing_hd);
3550 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3551 backing_hd->filename);
3554 /* Hook up the backing file link; drop our reference, bs owns the
3555 * backing_hd reference now */
3556 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3557 bdrv_unref(backing_hd);
3558 if (ret < 0) {
3559 goto free_exit;
3562 qdict_del(parent_options, bdref_key);
3564 free_exit:
3565 g_free(backing_filename);
3566 qobject_unref(tmp_parent_options);
3567 return ret;
3570 static BlockDriverState *
3571 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3572 BlockDriverState *parent, const BdrvChildClass *child_class,
3573 BdrvChildRole child_role, bool allow_none, Error **errp)
3575 BlockDriverState *bs = NULL;
3576 QDict *image_options;
3577 char *bdref_key_dot;
3578 const char *reference;
3580 assert(child_class != NULL);
3582 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3583 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3584 g_free(bdref_key_dot);
3587 * Caution: while qdict_get_try_str() is fine, getting non-string
3588 * types would require more care. When @options come from
3589 * -blockdev or blockdev_add, its members are typed according to
3590 * the QAPI schema, but when they come from -drive, they're all
3591 * QString.
3593 reference = qdict_get_try_str(options, bdref_key);
3594 if (!filename && !reference && !qdict_size(image_options)) {
3595 if (!allow_none) {
3596 error_setg(errp, "A block device must be specified for \"%s\"",
3597 bdref_key);
3599 qobject_unref(image_options);
3600 goto done;
3603 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3604 parent, child_class, child_role, errp);
3605 if (!bs) {
3606 goto done;
3609 done:
3610 qdict_del(options, bdref_key);
3611 return bs;
3615 * Opens a disk image whose options are given as BlockdevRef in another block
3616 * device's options.
3618 * If allow_none is true, no image will be opened if filename is false and no
3619 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3621 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3622 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3623 * itself, all options starting with "${bdref_key}." are considered part of the
3624 * BlockdevRef.
3626 * The BlockdevRef will be removed from the options QDict.
3628 BdrvChild *bdrv_open_child(const char *filename,
3629 QDict *options, const char *bdref_key,
3630 BlockDriverState *parent,
3631 const BdrvChildClass *child_class,
3632 BdrvChildRole child_role,
3633 bool allow_none, Error **errp)
3635 BlockDriverState *bs;
3637 GLOBAL_STATE_CODE();
3639 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3640 child_role, allow_none, errp);
3641 if (bs == NULL) {
3642 return NULL;
3645 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3646 errp);
3650 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3652 int bdrv_open_file_child(const char *filename,
3653 QDict *options, const char *bdref_key,
3654 BlockDriverState *parent, Error **errp)
3656 BdrvChildRole role;
3658 /* commit_top and mirror_top don't use this function */
3659 assert(!parent->drv->filtered_child_is_backing);
3660 role = parent->drv->is_filter ?
3661 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3663 if (!bdrv_open_child(filename, options, bdref_key, parent,
3664 &child_of_bds, role, false, errp))
3666 return -EINVAL;
3669 return 0;
3673 * TODO Future callers may need to specify parent/child_class in order for
3674 * option inheritance to work. Existing callers use it for the root node.
3676 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3678 BlockDriverState *bs = NULL;
3679 QObject *obj = NULL;
3680 QDict *qdict = NULL;
3681 const char *reference = NULL;
3682 Visitor *v = NULL;
3684 GLOBAL_STATE_CODE();
3686 if (ref->type == QTYPE_QSTRING) {
3687 reference = ref->u.reference;
3688 } else {
3689 BlockdevOptions *options = &ref->u.definition;
3690 assert(ref->type == QTYPE_QDICT);
3692 v = qobject_output_visitor_new(&obj);
3693 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3694 visit_complete(v, &obj);
3696 qdict = qobject_to(QDict, obj);
3697 qdict_flatten(qdict);
3699 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3700 * compatibility with other callers) rather than what we want as the
3701 * real defaults. Apply the defaults here instead. */
3702 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3703 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3704 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3705 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3709 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3710 obj = NULL;
3711 qobject_unref(obj);
3712 visit_free(v);
3713 return bs;
3716 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3717 int flags,
3718 QDict *snapshot_options,
3719 Error **errp)
3721 g_autofree char *tmp_filename = NULL;
3722 int64_t total_size;
3723 QemuOpts *opts = NULL;
3724 BlockDriverState *bs_snapshot = NULL;
3725 int ret;
3727 GLOBAL_STATE_CODE();
3729 /* if snapshot, we create a temporary backing file and open it
3730 instead of opening 'filename' directly */
3732 /* Get the required size from the image */
3733 total_size = bdrv_getlength(bs);
3734 if (total_size < 0) {
3735 error_setg_errno(errp, -total_size, "Could not get image size");
3736 goto out;
3739 /* Create the temporary image */
3740 tmp_filename = create_tmp_file(errp);
3741 if (!tmp_filename) {
3742 goto out;
3745 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3746 &error_abort);
3747 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3748 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3749 qemu_opts_del(opts);
3750 if (ret < 0) {
3751 error_prepend(errp, "Could not create temporary overlay '%s': ",
3752 tmp_filename);
3753 goto out;
3756 /* Prepare options QDict for the temporary file */
3757 qdict_put_str(snapshot_options, "file.driver", "file");
3758 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3759 qdict_put_str(snapshot_options, "driver", "qcow2");
3761 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3762 snapshot_options = NULL;
3763 if (!bs_snapshot) {
3764 goto out;
3767 ret = bdrv_append(bs_snapshot, bs, errp);
3768 if (ret < 0) {
3769 bs_snapshot = NULL;
3770 goto out;
3773 out:
3774 qobject_unref(snapshot_options);
3775 return bs_snapshot;
3779 * Opens a disk image (raw, qcow2, vmdk, ...)
3781 * options is a QDict of options to pass to the block drivers, or NULL for an
3782 * empty set of options. The reference to the QDict belongs to the block layer
3783 * after the call (even on failure), so if the caller intends to reuse the
3784 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3786 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3787 * If it is not NULL, the referenced BDS will be reused.
3789 * The reference parameter may be used to specify an existing block device which
3790 * should be opened. If specified, neither options nor a filename may be given,
3791 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3793 static BlockDriverState *bdrv_open_inherit(const char *filename,
3794 const char *reference,
3795 QDict *options, int flags,
3796 BlockDriverState *parent,
3797 const BdrvChildClass *child_class,
3798 BdrvChildRole child_role,
3799 Error **errp)
3801 int ret;
3802 BlockBackend *file = NULL;
3803 BlockDriverState *bs;
3804 BlockDriver *drv = NULL;
3805 BdrvChild *child;
3806 const char *drvname;
3807 const char *backing;
3808 Error *local_err = NULL;
3809 QDict *snapshot_options = NULL;
3810 int snapshot_flags = 0;
3812 assert(!child_class || !flags);
3813 assert(!child_class == !parent);
3814 GLOBAL_STATE_CODE();
3816 if (reference) {
3817 bool options_non_empty = options ? qdict_size(options) : false;
3818 qobject_unref(options);
3820 if (filename || options_non_empty) {
3821 error_setg(errp, "Cannot reference an existing block device with "
3822 "additional options or a new filename");
3823 return NULL;
3826 bs = bdrv_lookup_bs(reference, reference, errp);
3827 if (!bs) {
3828 return NULL;
3831 bdrv_ref(bs);
3832 return bs;
3835 bs = bdrv_new();
3837 /* NULL means an empty set of options */
3838 if (options == NULL) {
3839 options = qdict_new();
3842 /* json: syntax counts as explicit options, as if in the QDict */
3843 parse_json_protocol(options, &filename, &local_err);
3844 if (local_err) {
3845 goto fail;
3848 bs->explicit_options = qdict_clone_shallow(options);
3850 if (child_class) {
3851 bool parent_is_format;
3853 if (parent->drv) {
3854 parent_is_format = parent->drv->is_format;
3855 } else {
3857 * parent->drv is not set yet because this node is opened for
3858 * (potential) format probing. That means that @parent is going
3859 * to be a format node.
3861 parent_is_format = true;
3864 bs->inherits_from = parent;
3865 child_class->inherit_options(child_role, parent_is_format,
3866 &flags, options,
3867 parent->open_flags, parent->options);
3870 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3871 if (ret < 0) {
3872 goto fail;
3876 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3877 * Caution: getting a boolean member of @options requires care.
3878 * When @options come from -blockdev or blockdev_add, members are
3879 * typed according to the QAPI schema, but when they come from
3880 * -drive, they're all QString.
3882 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3883 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3884 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3885 } else {
3886 flags &= ~BDRV_O_RDWR;
3889 if (flags & BDRV_O_SNAPSHOT) {
3890 snapshot_options = qdict_new();
3891 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3892 flags, options);
3893 /* Let bdrv_backing_options() override "read-only" */
3894 qdict_del(options, BDRV_OPT_READ_ONLY);
3895 bdrv_inherited_options(BDRV_CHILD_COW, true,
3896 &flags, options, flags, options);
3899 bs->open_flags = flags;
3900 bs->options = options;
3901 options = qdict_clone_shallow(options);
3903 /* Find the right image format driver */
3904 /* See cautionary note on accessing @options above */
3905 drvname = qdict_get_try_str(options, "driver");
3906 if (drvname) {
3907 drv = bdrv_find_format(drvname);
3908 if (!drv) {
3909 error_setg(errp, "Unknown driver: '%s'", drvname);
3910 goto fail;
3914 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3916 /* See cautionary note on accessing @options above */
3917 backing = qdict_get_try_str(options, "backing");
3918 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3919 (backing && *backing == '\0'))
3921 if (backing) {
3922 warn_report("Use of \"backing\": \"\" is deprecated; "
3923 "use \"backing\": null instead");
3925 flags |= BDRV_O_NO_BACKING;
3926 qdict_del(bs->explicit_options, "backing");
3927 qdict_del(bs->options, "backing");
3928 qdict_del(options, "backing");
3931 /* Open image file without format layer. This BlockBackend is only used for
3932 * probing, the block drivers will do their own bdrv_open_child() for the
3933 * same BDS, which is why we put the node name back into options. */
3934 if ((flags & BDRV_O_PROTOCOL) == 0) {
3935 BlockDriverState *file_bs;
3937 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3938 &child_of_bds, BDRV_CHILD_IMAGE,
3939 true, &local_err);
3940 if (local_err) {
3941 goto fail;
3943 if (file_bs != NULL) {
3944 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3945 * looking at the header to guess the image format. This works even
3946 * in cases where a guest would not see a consistent state. */
3947 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3948 blk_insert_bs(file, file_bs, &local_err);
3949 bdrv_unref(file_bs);
3950 if (local_err) {
3951 goto fail;
3954 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3958 /* Image format probing */
3959 bs->probed = !drv;
3960 if (!drv && file) {
3961 ret = find_image_format(file, filename, &drv, &local_err);
3962 if (ret < 0) {
3963 goto fail;
3966 * This option update would logically belong in bdrv_fill_options(),
3967 * but we first need to open bs->file for the probing to work, while
3968 * opening bs->file already requires the (mostly) final set of options
3969 * so that cache mode etc. can be inherited.
3971 * Adding the driver later is somewhat ugly, but it's not an option
3972 * that would ever be inherited, so it's correct. We just need to make
3973 * sure to update both bs->options (which has the full effective
3974 * options for bs) and options (which has file.* already removed).
3976 qdict_put_str(bs->options, "driver", drv->format_name);
3977 qdict_put_str(options, "driver", drv->format_name);
3978 } else if (!drv) {
3979 error_setg(errp, "Must specify either driver or file");
3980 goto fail;
3983 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3984 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3985 /* file must be NULL if a protocol BDS is about to be created
3986 * (the inverse results in an error message from bdrv_open_common()) */
3987 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3989 /* Open the image */
3990 ret = bdrv_open_common(bs, file, options, &local_err);
3991 if (ret < 0) {
3992 goto fail;
3995 if (file) {
3996 blk_unref(file);
3997 file = NULL;
4000 /* If there is a backing file, use it */
4001 if ((flags & BDRV_O_NO_BACKING) == 0) {
4002 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4003 if (ret < 0) {
4004 goto close_and_fail;
4008 /* Remove all children options and references
4009 * from bs->options and bs->explicit_options */
4010 QLIST_FOREACH(child, &bs->children, next) {
4011 char *child_key_dot;
4012 child_key_dot = g_strdup_printf("%s.", child->name);
4013 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4014 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4015 qdict_del(bs->explicit_options, child->name);
4016 qdict_del(bs->options, child->name);
4017 g_free(child_key_dot);
4020 /* Check if any unknown options were used */
4021 if (qdict_size(options) != 0) {
4022 const QDictEntry *entry = qdict_first(options);
4023 if (flags & BDRV_O_PROTOCOL) {
4024 error_setg(errp, "Block protocol '%s' doesn't support the option "
4025 "'%s'", drv->format_name, entry->key);
4026 } else {
4027 error_setg(errp,
4028 "Block format '%s' does not support the option '%s'",
4029 drv->format_name, entry->key);
4032 goto close_and_fail;
4035 bdrv_parent_cb_change_media(bs, true);
4037 qobject_unref(options);
4038 options = NULL;
4040 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4041 * temporary snapshot afterwards. */
4042 if (snapshot_flags) {
4043 BlockDriverState *snapshot_bs;
4044 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4045 snapshot_options, &local_err);
4046 snapshot_options = NULL;
4047 if (local_err) {
4048 goto close_and_fail;
4050 /* We are not going to return bs but the overlay on top of it
4051 * (snapshot_bs); thus, we have to drop the strong reference to bs
4052 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4053 * though, because the overlay still has a reference to it. */
4054 bdrv_unref(bs);
4055 bs = snapshot_bs;
4058 return bs;
4060 fail:
4061 blk_unref(file);
4062 qobject_unref(snapshot_options);
4063 qobject_unref(bs->explicit_options);
4064 qobject_unref(bs->options);
4065 qobject_unref(options);
4066 bs->options = NULL;
4067 bs->explicit_options = NULL;
4068 bdrv_unref(bs);
4069 error_propagate(errp, local_err);
4070 return NULL;
4072 close_and_fail:
4073 bdrv_unref(bs);
4074 qobject_unref(snapshot_options);
4075 qobject_unref(options);
4076 error_propagate(errp, local_err);
4077 return NULL;
4080 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4081 QDict *options, int flags, Error **errp)
4083 GLOBAL_STATE_CODE();
4085 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4086 NULL, 0, errp);
4089 /* Return true if the NULL-terminated @list contains @str */
4090 static bool is_str_in_list(const char *str, const char *const *list)
4092 if (str && list) {
4093 int i;
4094 for (i = 0; list[i] != NULL; i++) {
4095 if (!strcmp(str, list[i])) {
4096 return true;
4100 return false;
4104 * Check that every option set in @bs->options is also set in
4105 * @new_opts.
4107 * Options listed in the common_options list and in
4108 * @bs->drv->mutable_opts are skipped.
4110 * Return 0 on success, otherwise return -EINVAL and set @errp.
4112 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4113 const QDict *new_opts, Error **errp)
4115 const QDictEntry *e;
4116 /* These options are common to all block drivers and are handled
4117 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4118 const char *const common_options[] = {
4119 "node-name", "discard", "cache.direct", "cache.no-flush",
4120 "read-only", "auto-read-only", "detect-zeroes", NULL
4123 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4124 if (!qdict_haskey(new_opts, e->key) &&
4125 !is_str_in_list(e->key, common_options) &&
4126 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4127 error_setg(errp, "Option '%s' cannot be reset "
4128 "to its default value", e->key);
4129 return -EINVAL;
4133 return 0;
4137 * Returns true if @child can be reached recursively from @bs
4139 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4140 BlockDriverState *child)
4142 BdrvChild *c;
4144 if (bs == child) {
4145 return true;
4148 QLIST_FOREACH(c, &bs->children, next) {
4149 if (bdrv_recurse_has_child(c->bs, child)) {
4150 return true;
4154 return false;
4158 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4159 * reopen of multiple devices.
4161 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4162 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4163 * be created and initialized. This newly created BlockReopenQueue should be
4164 * passed back in for subsequent calls that are intended to be of the same
4165 * atomic 'set'.
4167 * bs is the BlockDriverState to add to the reopen queue.
4169 * options contains the changed options for the associated bs
4170 * (the BlockReopenQueue takes ownership)
4172 * flags contains the open flags for the associated bs
4174 * returns a pointer to bs_queue, which is either the newly allocated
4175 * bs_queue, or the existing bs_queue being used.
4177 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4179 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4180 BlockDriverState *bs,
4181 QDict *options,
4182 const BdrvChildClass *klass,
4183 BdrvChildRole role,
4184 bool parent_is_format,
4185 QDict *parent_options,
4186 int parent_flags,
4187 bool keep_old_opts)
4189 assert(bs != NULL);
4191 BlockReopenQueueEntry *bs_entry;
4192 BdrvChild *child;
4193 QDict *old_options, *explicit_options, *options_copy;
4194 int flags;
4195 QemuOpts *opts;
4197 /* Make sure that the caller remembered to use a drained section. This is
4198 * important to avoid graph changes between the recursive queuing here and
4199 * bdrv_reopen_multiple(). */
4200 assert(bs->quiesce_counter > 0);
4201 GLOBAL_STATE_CODE();
4203 if (bs_queue == NULL) {
4204 bs_queue = g_new0(BlockReopenQueue, 1);
4205 QTAILQ_INIT(bs_queue);
4208 if (!options) {
4209 options = qdict_new();
4212 /* Check if this BlockDriverState is already in the queue */
4213 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4214 if (bs == bs_entry->state.bs) {
4215 break;
4220 * Precedence of options:
4221 * 1. Explicitly passed in options (highest)
4222 * 2. Retained from explicitly set options of bs
4223 * 3. Inherited from parent node
4224 * 4. Retained from effective options of bs
4227 /* Old explicitly set values (don't overwrite by inherited value) */
4228 if (bs_entry || keep_old_opts) {
4229 old_options = qdict_clone_shallow(bs_entry ?
4230 bs_entry->state.explicit_options :
4231 bs->explicit_options);
4232 bdrv_join_options(bs, options, old_options);
4233 qobject_unref(old_options);
4236 explicit_options = qdict_clone_shallow(options);
4238 /* Inherit from parent node */
4239 if (parent_options) {
4240 flags = 0;
4241 klass->inherit_options(role, parent_is_format, &flags, options,
4242 parent_flags, parent_options);
4243 } else {
4244 flags = bdrv_get_flags(bs);
4247 if (keep_old_opts) {
4248 /* Old values are used for options that aren't set yet */
4249 old_options = qdict_clone_shallow(bs->options);
4250 bdrv_join_options(bs, options, old_options);
4251 qobject_unref(old_options);
4254 /* We have the final set of options so let's update the flags */
4255 options_copy = qdict_clone_shallow(options);
4256 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4257 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4258 update_flags_from_options(&flags, opts);
4259 qemu_opts_del(opts);
4260 qobject_unref(options_copy);
4262 /* bdrv_open_inherit() sets and clears some additional flags internally */
4263 flags &= ~BDRV_O_PROTOCOL;
4264 if (flags & BDRV_O_RDWR) {
4265 flags |= BDRV_O_ALLOW_RDWR;
4268 if (!bs_entry) {
4269 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4270 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4271 } else {
4272 qobject_unref(bs_entry->state.options);
4273 qobject_unref(bs_entry->state.explicit_options);
4276 bs_entry->state.bs = bs;
4277 bs_entry->state.options = options;
4278 bs_entry->state.explicit_options = explicit_options;
4279 bs_entry->state.flags = flags;
4282 * If keep_old_opts is false then it means that unspecified
4283 * options must be reset to their original value. We don't allow
4284 * resetting 'backing' but we need to know if the option is
4285 * missing in order to decide if we have to return an error.
4287 if (!keep_old_opts) {
4288 bs_entry->state.backing_missing =
4289 !qdict_haskey(options, "backing") &&
4290 !qdict_haskey(options, "backing.driver");
4293 QLIST_FOREACH(child, &bs->children, next) {
4294 QDict *new_child_options = NULL;
4295 bool child_keep_old = keep_old_opts;
4297 /* reopen can only change the options of block devices that were
4298 * implicitly created and inherited options. For other (referenced)
4299 * block devices, a syntax like "backing.foo" results in an error. */
4300 if (child->bs->inherits_from != bs) {
4301 continue;
4304 /* Check if the options contain a child reference */
4305 if (qdict_haskey(options, child->name)) {
4306 const char *childref = qdict_get_try_str(options, child->name);
4308 * The current child must not be reopened if the child
4309 * reference is null or points to a different node.
4311 if (g_strcmp0(childref, child->bs->node_name)) {
4312 continue;
4315 * If the child reference points to the current child then
4316 * reopen it with its existing set of options (note that
4317 * it can still inherit new options from the parent).
4319 child_keep_old = true;
4320 } else {
4321 /* Extract child options ("child-name.*") */
4322 char *child_key_dot = g_strdup_printf("%s.", child->name);
4323 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4324 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4325 g_free(child_key_dot);
4328 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4329 child->klass, child->role, bs->drv->is_format,
4330 options, flags, child_keep_old);
4333 return bs_queue;
4336 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4337 BlockDriverState *bs,
4338 QDict *options, bool keep_old_opts)
4340 GLOBAL_STATE_CODE();
4342 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4343 NULL, 0, keep_old_opts);
4346 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4348 GLOBAL_STATE_CODE();
4349 if (bs_queue) {
4350 BlockReopenQueueEntry *bs_entry, *next;
4351 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4352 qobject_unref(bs_entry->state.explicit_options);
4353 qobject_unref(bs_entry->state.options);
4354 g_free(bs_entry);
4356 g_free(bs_queue);
4361 * Reopen multiple BlockDriverStates atomically & transactionally.
4363 * The queue passed in (bs_queue) must have been built up previous
4364 * via bdrv_reopen_queue().
4366 * Reopens all BDS specified in the queue, with the appropriate
4367 * flags. All devices are prepared for reopen, and failure of any
4368 * device will cause all device changes to be abandoned, and intermediate
4369 * data cleaned up.
4371 * If all devices prepare successfully, then the changes are committed
4372 * to all devices.
4374 * All affected nodes must be drained between bdrv_reopen_queue() and
4375 * bdrv_reopen_multiple().
4377 * To be called from the main thread, with all other AioContexts unlocked.
4379 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4381 int ret = -1;
4382 BlockReopenQueueEntry *bs_entry, *next;
4383 AioContext *ctx;
4384 Transaction *tran = tran_new();
4385 g_autoptr(GSList) refresh_list = NULL;
4387 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4388 assert(bs_queue != NULL);
4389 GLOBAL_STATE_CODE();
4391 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4392 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4393 aio_context_acquire(ctx);
4394 ret = bdrv_flush(bs_entry->state.bs);
4395 aio_context_release(ctx);
4396 if (ret < 0) {
4397 error_setg_errno(errp, -ret, "Error flushing drive");
4398 goto abort;
4402 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4403 assert(bs_entry->state.bs->quiesce_counter > 0);
4404 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4405 aio_context_acquire(ctx);
4406 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4407 aio_context_release(ctx);
4408 if (ret < 0) {
4409 goto abort;
4411 bs_entry->prepared = true;
4414 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4415 BDRVReopenState *state = &bs_entry->state;
4417 refresh_list = g_slist_prepend(refresh_list, state->bs);
4418 if (state->old_backing_bs) {
4419 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4421 if (state->old_file_bs) {
4422 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4427 * Note that file-posix driver rely on permission update done during reopen
4428 * (even if no permission changed), because it wants "new" permissions for
4429 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4430 * in raw_reopen_prepare() which is called with "old" permissions.
4432 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4433 if (ret < 0) {
4434 goto abort;
4438 * If we reach this point, we have success and just need to apply the
4439 * changes.
4441 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4442 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4443 * children are usually goes after parents in reopen-queue, so go from last
4444 * to first element.
4446 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4447 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4448 aio_context_acquire(ctx);
4449 bdrv_reopen_commit(&bs_entry->state);
4450 aio_context_release(ctx);
4453 tran_commit(tran);
4455 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4456 BlockDriverState *bs = bs_entry->state.bs;
4458 if (bs->drv->bdrv_reopen_commit_post) {
4459 ctx = bdrv_get_aio_context(bs);
4460 aio_context_acquire(ctx);
4461 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4462 aio_context_release(ctx);
4466 ret = 0;
4467 goto cleanup;
4469 abort:
4470 tran_abort(tran);
4471 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4472 if (bs_entry->prepared) {
4473 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4474 aio_context_acquire(ctx);
4475 bdrv_reopen_abort(&bs_entry->state);
4476 aio_context_release(ctx);
4480 cleanup:
4481 bdrv_reopen_queue_free(bs_queue);
4483 return ret;
4486 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4487 Error **errp)
4489 AioContext *ctx = bdrv_get_aio_context(bs);
4490 BlockReopenQueue *queue;
4491 int ret;
4493 GLOBAL_STATE_CODE();
4495 bdrv_subtree_drained_begin(bs);
4496 if (ctx != qemu_get_aio_context()) {
4497 aio_context_release(ctx);
4500 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4501 ret = bdrv_reopen_multiple(queue, errp);
4503 if (ctx != qemu_get_aio_context()) {
4504 aio_context_acquire(ctx);
4506 bdrv_subtree_drained_end(bs);
4508 return ret;
4511 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4512 Error **errp)
4514 QDict *opts = qdict_new();
4516 GLOBAL_STATE_CODE();
4518 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4520 return bdrv_reopen(bs, opts, true, errp);
4524 * Take a BDRVReopenState and check if the value of 'backing' in the
4525 * reopen_state->options QDict is valid or not.
4527 * If 'backing' is missing from the QDict then return 0.
4529 * If 'backing' contains the node name of the backing file of
4530 * reopen_state->bs then return 0.
4532 * If 'backing' contains a different node name (or is null) then check
4533 * whether the current backing file can be replaced with the new one.
4534 * If that's the case then reopen_state->replace_backing_bs is set to
4535 * true and reopen_state->new_backing_bs contains a pointer to the new
4536 * backing BlockDriverState (or NULL).
4538 * Return 0 on success, otherwise return < 0 and set @errp.
4540 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4541 bool is_backing, Transaction *tran,
4542 Error **errp)
4544 BlockDriverState *bs = reopen_state->bs;
4545 BlockDriverState *new_child_bs;
4546 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4547 child_bs(bs->file);
4548 const char *child_name = is_backing ? "backing" : "file";
4549 QObject *value;
4550 const char *str;
4552 GLOBAL_STATE_CODE();
4554 value = qdict_get(reopen_state->options, child_name);
4555 if (value == NULL) {
4556 return 0;
4559 switch (qobject_type(value)) {
4560 case QTYPE_QNULL:
4561 assert(is_backing); /* The 'file' option does not allow a null value */
4562 new_child_bs = NULL;
4563 break;
4564 case QTYPE_QSTRING:
4565 str = qstring_get_str(qobject_to(QString, value));
4566 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4567 if (new_child_bs == NULL) {
4568 return -EINVAL;
4569 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4570 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4571 "cycle", str, child_name, bs->node_name);
4572 return -EINVAL;
4574 break;
4575 default:
4577 * The options QDict has been flattened, so 'backing' and 'file'
4578 * do not allow any other data type here.
4580 g_assert_not_reached();
4583 if (old_child_bs == new_child_bs) {
4584 return 0;
4587 if (old_child_bs) {
4588 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4589 return 0;
4592 if (old_child_bs->implicit) {
4593 error_setg(errp, "Cannot replace implicit %s child of %s",
4594 child_name, bs->node_name);
4595 return -EPERM;
4599 if (bs->drv->is_filter && !old_child_bs) {
4601 * Filters always have a file or a backing child, so we are trying to
4602 * change wrong child
4604 error_setg(errp, "'%s' is a %s filter node that does not support a "
4605 "%s child", bs->node_name, bs->drv->format_name, child_name);
4606 return -EINVAL;
4609 if (is_backing) {
4610 reopen_state->old_backing_bs = old_child_bs;
4611 } else {
4612 reopen_state->old_file_bs = old_child_bs;
4615 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4616 tran, errp);
4620 * Prepares a BlockDriverState for reopen. All changes are staged in the
4621 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4622 * the block driver layer .bdrv_reopen_prepare()
4624 * bs is the BlockDriverState to reopen
4625 * flags are the new open flags
4626 * queue is the reopen queue
4628 * Returns 0 on success, non-zero on error. On error errp will be set
4629 * as well.
4631 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4632 * It is the responsibility of the caller to then call the abort() or
4633 * commit() for any other BDS that have been left in a prepare() state
4636 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4637 BlockReopenQueue *queue,
4638 Transaction *change_child_tran, Error **errp)
4640 int ret = -1;
4641 int old_flags;
4642 Error *local_err = NULL;
4643 BlockDriver *drv;
4644 QemuOpts *opts;
4645 QDict *orig_reopen_opts;
4646 char *discard = NULL;
4647 bool read_only;
4648 bool drv_prepared = false;
4650 assert(reopen_state != NULL);
4651 assert(reopen_state->bs->drv != NULL);
4652 GLOBAL_STATE_CODE();
4653 drv = reopen_state->bs->drv;
4655 /* This function and each driver's bdrv_reopen_prepare() remove
4656 * entries from reopen_state->options as they are processed, so
4657 * we need to make a copy of the original QDict. */
4658 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4660 /* Process generic block layer options */
4661 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4662 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4663 ret = -EINVAL;
4664 goto error;
4667 /* This was already called in bdrv_reopen_queue_child() so the flags
4668 * are up-to-date. This time we simply want to remove the options from
4669 * QemuOpts in order to indicate that they have been processed. */
4670 old_flags = reopen_state->flags;
4671 update_flags_from_options(&reopen_state->flags, opts);
4672 assert(old_flags == reopen_state->flags);
4674 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4675 if (discard != NULL) {
4676 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4677 error_setg(errp, "Invalid discard option");
4678 ret = -EINVAL;
4679 goto error;
4683 reopen_state->detect_zeroes =
4684 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4685 if (local_err) {
4686 error_propagate(errp, local_err);
4687 ret = -EINVAL;
4688 goto error;
4691 /* All other options (including node-name and driver) must be unchanged.
4692 * Put them back into the QDict, so that they are checked at the end
4693 * of this function. */
4694 qemu_opts_to_qdict(opts, reopen_state->options);
4696 /* If we are to stay read-only, do not allow permission change
4697 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4698 * not set, or if the BDS still has copy_on_read enabled */
4699 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4700 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4701 if (local_err) {
4702 error_propagate(errp, local_err);
4703 goto error;
4706 if (drv->bdrv_reopen_prepare) {
4708 * If a driver-specific option is missing, it means that we
4709 * should reset it to its default value.
4710 * But not all options allow that, so we need to check it first.
4712 ret = bdrv_reset_options_allowed(reopen_state->bs,
4713 reopen_state->options, errp);
4714 if (ret) {
4715 goto error;
4718 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4719 if (ret) {
4720 if (local_err != NULL) {
4721 error_propagate(errp, local_err);
4722 } else {
4723 bdrv_refresh_filename(reopen_state->bs);
4724 error_setg(errp, "failed while preparing to reopen image '%s'",
4725 reopen_state->bs->filename);
4727 goto error;
4729 } else {
4730 /* It is currently mandatory to have a bdrv_reopen_prepare()
4731 * handler for each supported drv. */
4732 error_setg(errp, "Block format '%s' used by node '%s' "
4733 "does not support reopening files", drv->format_name,
4734 bdrv_get_device_or_node_name(reopen_state->bs));
4735 ret = -1;
4736 goto error;
4739 drv_prepared = true;
4742 * We must provide the 'backing' option if the BDS has a backing
4743 * file or if the image file has a backing file name as part of
4744 * its metadata. Otherwise the 'backing' option can be omitted.
4746 if (drv->supports_backing && reopen_state->backing_missing &&
4747 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4748 error_setg(errp, "backing is missing for '%s'",
4749 reopen_state->bs->node_name);
4750 ret = -EINVAL;
4751 goto error;
4755 * Allow changing the 'backing' option. The new value can be
4756 * either a reference to an existing node (using its node name)
4757 * or NULL to simply detach the current backing file.
4759 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4760 change_child_tran, errp);
4761 if (ret < 0) {
4762 goto error;
4764 qdict_del(reopen_state->options, "backing");
4766 /* Allow changing the 'file' option. In this case NULL is not allowed */
4767 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4768 change_child_tran, errp);
4769 if (ret < 0) {
4770 goto error;
4772 qdict_del(reopen_state->options, "file");
4774 /* Options that are not handled are only okay if they are unchanged
4775 * compared to the old state. It is expected that some options are only
4776 * used for the initial open, but not reopen (e.g. filename) */
4777 if (qdict_size(reopen_state->options)) {
4778 const QDictEntry *entry = qdict_first(reopen_state->options);
4780 do {
4781 QObject *new = entry->value;
4782 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4784 /* Allow child references (child_name=node_name) as long as they
4785 * point to the current child (i.e. everything stays the same). */
4786 if (qobject_type(new) == QTYPE_QSTRING) {
4787 BdrvChild *child;
4788 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4789 if (!strcmp(child->name, entry->key)) {
4790 break;
4794 if (child) {
4795 if (!strcmp(child->bs->node_name,
4796 qstring_get_str(qobject_to(QString, new)))) {
4797 continue; /* Found child with this name, skip option */
4803 * TODO: When using -drive to specify blockdev options, all values
4804 * will be strings; however, when using -blockdev, blockdev-add or
4805 * filenames using the json:{} pseudo-protocol, they will be
4806 * correctly typed.
4807 * In contrast, reopening options are (currently) always strings
4808 * (because you can only specify them through qemu-io; all other
4809 * callers do not specify any options).
4810 * Therefore, when using anything other than -drive to create a BDS,
4811 * this cannot detect non-string options as unchanged, because
4812 * qobject_is_equal() always returns false for objects of different
4813 * type. In the future, this should be remedied by correctly typing
4814 * all options. For now, this is not too big of an issue because
4815 * the user can simply omit options which cannot be changed anyway,
4816 * so they will stay unchanged.
4818 if (!qobject_is_equal(new, old)) {
4819 error_setg(errp, "Cannot change the option '%s'", entry->key);
4820 ret = -EINVAL;
4821 goto error;
4823 } while ((entry = qdict_next(reopen_state->options, entry)));
4826 ret = 0;
4828 /* Restore the original reopen_state->options QDict */
4829 qobject_unref(reopen_state->options);
4830 reopen_state->options = qobject_ref(orig_reopen_opts);
4832 error:
4833 if (ret < 0 && drv_prepared) {
4834 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4835 * call drv->bdrv_reopen_abort() before signaling an error
4836 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4837 * when the respective bdrv_reopen_prepare() has failed) */
4838 if (drv->bdrv_reopen_abort) {
4839 drv->bdrv_reopen_abort(reopen_state);
4842 qemu_opts_del(opts);
4843 qobject_unref(orig_reopen_opts);
4844 g_free(discard);
4845 return ret;
4849 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4850 * makes them final by swapping the staging BlockDriverState contents into
4851 * the active BlockDriverState contents.
4853 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4855 BlockDriver *drv;
4856 BlockDriverState *bs;
4857 BdrvChild *child;
4859 assert(reopen_state != NULL);
4860 bs = reopen_state->bs;
4861 drv = bs->drv;
4862 assert(drv != NULL);
4863 GLOBAL_STATE_CODE();
4865 /* If there are any driver level actions to take */
4866 if (drv->bdrv_reopen_commit) {
4867 drv->bdrv_reopen_commit(reopen_state);
4870 /* set BDS specific flags now */
4871 qobject_unref(bs->explicit_options);
4872 qobject_unref(bs->options);
4873 qobject_ref(reopen_state->explicit_options);
4874 qobject_ref(reopen_state->options);
4876 bs->explicit_options = reopen_state->explicit_options;
4877 bs->options = reopen_state->options;
4878 bs->open_flags = reopen_state->flags;
4879 bs->detect_zeroes = reopen_state->detect_zeroes;
4881 /* Remove child references from bs->options and bs->explicit_options.
4882 * Child options were already removed in bdrv_reopen_queue_child() */
4883 QLIST_FOREACH(child, &bs->children, next) {
4884 qdict_del(bs->explicit_options, child->name);
4885 qdict_del(bs->options, child->name);
4887 /* backing is probably removed, so it's not handled by previous loop */
4888 qdict_del(bs->explicit_options, "backing");
4889 qdict_del(bs->options, "backing");
4891 bdrv_refresh_limits(bs, NULL, NULL);
4895 * Abort the reopen, and delete and free the staged changes in
4896 * reopen_state
4898 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4900 BlockDriver *drv;
4902 assert(reopen_state != NULL);
4903 drv = reopen_state->bs->drv;
4904 assert(drv != NULL);
4905 GLOBAL_STATE_CODE();
4907 if (drv->bdrv_reopen_abort) {
4908 drv->bdrv_reopen_abort(reopen_state);
4913 static void bdrv_close(BlockDriverState *bs)
4915 BdrvAioNotifier *ban, *ban_next;
4916 BdrvChild *child, *next;
4918 GLOBAL_STATE_CODE();
4919 assert(!bs->refcnt);
4921 bdrv_drained_begin(bs); /* complete I/O */
4922 bdrv_flush(bs);
4923 bdrv_drain(bs); /* in case flush left pending I/O */
4925 if (bs->drv) {
4926 if (bs->drv->bdrv_close) {
4927 /* Must unfreeze all children, so bdrv_unref_child() works */
4928 bs->drv->bdrv_close(bs);
4930 bs->drv = NULL;
4933 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4934 bdrv_unref_child(bs, child);
4937 assert(!bs->backing);
4938 assert(!bs->file);
4939 g_free(bs->opaque);
4940 bs->opaque = NULL;
4941 qatomic_set(&bs->copy_on_read, 0);
4942 bs->backing_file[0] = '\0';
4943 bs->backing_format[0] = '\0';
4944 bs->total_sectors = 0;
4945 bs->encrypted = false;
4946 bs->sg = false;
4947 qobject_unref(bs->options);
4948 qobject_unref(bs->explicit_options);
4949 bs->options = NULL;
4950 bs->explicit_options = NULL;
4951 qobject_unref(bs->full_open_options);
4952 bs->full_open_options = NULL;
4953 g_free(bs->block_status_cache);
4954 bs->block_status_cache = NULL;
4956 bdrv_release_named_dirty_bitmaps(bs);
4957 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4959 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4960 g_free(ban);
4962 QLIST_INIT(&bs->aio_notifiers);
4963 bdrv_drained_end(bs);
4966 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4967 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4968 * gets called.
4970 if (bs->quiesce_counter) {
4971 bdrv_drain_all_end_quiesce(bs);
4975 void bdrv_close_all(void)
4977 GLOBAL_STATE_CODE();
4978 assert(job_next(NULL) == NULL);
4980 /* Drop references from requests still in flight, such as canceled block
4981 * jobs whose AIO context has not been polled yet */
4982 bdrv_drain_all();
4984 blk_remove_all_bs();
4985 blockdev_close_all_bdrv_states();
4987 assert(QTAILQ_EMPTY(&all_bdrv_states));
4990 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4992 GQueue *queue;
4993 GHashTable *found;
4994 bool ret;
4996 if (c->klass->stay_at_node) {
4997 return false;
5000 /* If the child @c belongs to the BDS @to, replacing the current
5001 * c->bs by @to would mean to create a loop.
5003 * Such a case occurs when appending a BDS to a backing chain.
5004 * For instance, imagine the following chain:
5006 * guest device -> node A -> further backing chain...
5008 * Now we create a new BDS B which we want to put on top of this
5009 * chain, so we first attach A as its backing node:
5011 * node B
5014 * guest device -> node A -> further backing chain...
5016 * Finally we want to replace A by B. When doing that, we want to
5017 * replace all pointers to A by pointers to B -- except for the
5018 * pointer from B because (1) that would create a loop, and (2)
5019 * that pointer should simply stay intact:
5021 * guest device -> node B
5024 * node A -> further backing chain...
5026 * In general, when replacing a node A (c->bs) by a node B (@to),
5027 * if A is a child of B, that means we cannot replace A by B there
5028 * because that would create a loop. Silently detaching A from B
5029 * is also not really an option. So overall just leaving A in
5030 * place there is the most sensible choice.
5032 * We would also create a loop in any cases where @c is only
5033 * indirectly referenced by @to. Prevent this by returning false
5034 * if @c is found (by breadth-first search) anywhere in the whole
5035 * subtree of @to.
5038 ret = true;
5039 found = g_hash_table_new(NULL, NULL);
5040 g_hash_table_add(found, to);
5041 queue = g_queue_new();
5042 g_queue_push_tail(queue, to);
5044 while (!g_queue_is_empty(queue)) {
5045 BlockDriverState *v = g_queue_pop_head(queue);
5046 BdrvChild *c2;
5048 QLIST_FOREACH(c2, &v->children, next) {
5049 if (c2 == c) {
5050 ret = false;
5051 break;
5054 if (g_hash_table_contains(found, c2->bs)) {
5055 continue;
5058 g_queue_push_tail(queue, c2->bs);
5059 g_hash_table_add(found, c2->bs);
5063 g_queue_free(queue);
5064 g_hash_table_destroy(found);
5066 return ret;
5069 static void bdrv_remove_child_commit(void *opaque)
5071 GLOBAL_STATE_CODE();
5072 bdrv_child_free(opaque);
5075 static TransactionActionDrv bdrv_remove_child_drv = {
5076 .commit = bdrv_remove_child_commit,
5079 /* Function doesn't update permissions, caller is responsible for this. */
5080 static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
5082 if (!child) {
5083 return;
5086 if (child->bs) {
5087 bdrv_replace_child_tran(child, NULL, tran);
5090 tran_add(tran, &bdrv_remove_child_drv, child);
5093 static int bdrv_replace_node_noperm(BlockDriverState *from,
5094 BlockDriverState *to,
5095 bool auto_skip, Transaction *tran,
5096 Error **errp)
5098 BdrvChild *c, *next;
5100 GLOBAL_STATE_CODE();
5102 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5103 assert(c->bs == from);
5104 if (!should_update_child(c, to)) {
5105 if (auto_skip) {
5106 continue;
5108 error_setg(errp, "Should not change '%s' link to '%s'",
5109 c->name, from->node_name);
5110 return -EINVAL;
5112 if (c->frozen) {
5113 error_setg(errp, "Cannot change '%s' link to '%s'",
5114 c->name, from->node_name);
5115 return -EPERM;
5117 bdrv_replace_child_tran(c, to, tran);
5120 return 0;
5124 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5125 * if it creates a parent-child relation loop or if parent is block-job.
5127 * With auto_skip=false the error is returned if from has a parent which should
5128 * not be updated.
5130 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5131 * case backing link of the cow-parent of @to is removed.
5133 static int bdrv_replace_node_common(BlockDriverState *from,
5134 BlockDriverState *to,
5135 bool auto_skip, bool detach_subchain,
5136 Error **errp)
5138 Transaction *tran = tran_new();
5139 g_autoptr(GSList) refresh_list = NULL;
5140 BlockDriverState *to_cow_parent = NULL;
5141 int ret;
5143 GLOBAL_STATE_CODE();
5145 if (detach_subchain) {
5146 assert(bdrv_chain_contains(from, to));
5147 assert(from != to);
5148 for (to_cow_parent = from;
5149 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5150 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5156 /* Make sure that @from doesn't go away until we have successfully attached
5157 * all of its parents to @to. */
5158 bdrv_ref(from);
5160 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5161 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5162 bdrv_drained_begin(from);
5165 * Do the replacement without permission update.
5166 * Replacement may influence the permissions, we should calculate new
5167 * permissions based on new graph. If we fail, we'll roll-back the
5168 * replacement.
5170 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5171 if (ret < 0) {
5172 goto out;
5175 if (detach_subchain) {
5176 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5179 refresh_list = g_slist_prepend(refresh_list, to);
5180 refresh_list = g_slist_prepend(refresh_list, from);
5182 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5183 if (ret < 0) {
5184 goto out;
5187 ret = 0;
5189 out:
5190 tran_finalize(tran, ret);
5192 bdrv_drained_end(from);
5193 bdrv_unref(from);
5195 return ret;
5198 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5199 Error **errp)
5201 GLOBAL_STATE_CODE();
5203 return bdrv_replace_node_common(from, to, true, false, errp);
5206 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5208 GLOBAL_STATE_CODE();
5210 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5211 errp);
5215 * Add new bs contents at the top of an image chain while the chain is
5216 * live, while keeping required fields on the top layer.
5218 * This will modify the BlockDriverState fields, and swap contents
5219 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5221 * bs_new must not be attached to a BlockBackend and must not have backing
5222 * child.
5224 * This function does not create any image files.
5226 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5227 Error **errp)
5229 int ret;
5230 BdrvChild *child;
5231 Transaction *tran = tran_new();
5233 GLOBAL_STATE_CODE();
5235 assert(!bs_new->backing);
5237 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5238 &child_of_bds, bdrv_backing_role(bs_new),
5239 tran, errp);
5240 if (!child) {
5241 ret = -EINVAL;
5242 goto out;
5245 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5246 if (ret < 0) {
5247 goto out;
5250 ret = bdrv_refresh_perms(bs_new, tran, errp);
5251 out:
5252 tran_finalize(tran, ret);
5254 bdrv_refresh_limits(bs_top, NULL, NULL);
5256 return ret;
5259 /* Not for empty child */
5260 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5261 Error **errp)
5263 int ret;
5264 Transaction *tran = tran_new();
5265 g_autoptr(GSList) refresh_list = NULL;
5266 BlockDriverState *old_bs = child->bs;
5268 GLOBAL_STATE_CODE();
5270 bdrv_ref(old_bs);
5271 bdrv_drained_begin(old_bs);
5272 bdrv_drained_begin(new_bs);
5274 bdrv_replace_child_tran(child, new_bs, tran);
5276 refresh_list = g_slist_prepend(refresh_list, old_bs);
5277 refresh_list = g_slist_prepend(refresh_list, new_bs);
5279 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5281 tran_finalize(tran, ret);
5283 bdrv_drained_end(old_bs);
5284 bdrv_drained_end(new_bs);
5285 bdrv_unref(old_bs);
5287 return ret;
5290 static void bdrv_delete(BlockDriverState *bs)
5292 assert(bdrv_op_blocker_is_empty(bs));
5293 assert(!bs->refcnt);
5294 GLOBAL_STATE_CODE();
5296 /* remove from list, if necessary */
5297 if (bs->node_name[0] != '\0') {
5298 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5300 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5302 bdrv_close(bs);
5304 g_free(bs);
5309 * Replace @bs by newly created block node.
5311 * @options is a QDict of options to pass to the block drivers, or NULL for an
5312 * empty set of options. The reference to the QDict belongs to the block layer
5313 * after the call (even on failure), so if the caller intends to reuse the
5314 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5316 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5317 int flags, Error **errp)
5319 ERRP_GUARD();
5320 int ret;
5321 BlockDriverState *new_node_bs = NULL;
5322 const char *drvname, *node_name;
5323 BlockDriver *drv;
5325 drvname = qdict_get_try_str(options, "driver");
5326 if (!drvname) {
5327 error_setg(errp, "driver is not specified");
5328 goto fail;
5331 drv = bdrv_find_format(drvname);
5332 if (!drv) {
5333 error_setg(errp, "Unknown driver: '%s'", drvname);
5334 goto fail;
5337 node_name = qdict_get_try_str(options, "node-name");
5339 GLOBAL_STATE_CODE();
5341 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5342 errp);
5343 options = NULL; /* bdrv_new_open_driver() eats options */
5344 if (!new_node_bs) {
5345 error_prepend(errp, "Could not create node: ");
5346 goto fail;
5349 bdrv_drained_begin(bs);
5350 ret = bdrv_replace_node(bs, new_node_bs, errp);
5351 bdrv_drained_end(bs);
5353 if (ret < 0) {
5354 error_prepend(errp, "Could not replace node: ");
5355 goto fail;
5358 return new_node_bs;
5360 fail:
5361 qobject_unref(options);
5362 bdrv_unref(new_node_bs);
5363 return NULL;
5367 * Run consistency checks on an image
5369 * Returns 0 if the check could be completed (it doesn't mean that the image is
5370 * free of errors) or -errno when an internal error occurred. The results of the
5371 * check are stored in res.
5373 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5374 BdrvCheckResult *res, BdrvCheckMode fix)
5376 IO_CODE();
5377 if (bs->drv == NULL) {
5378 return -ENOMEDIUM;
5380 if (bs->drv->bdrv_co_check == NULL) {
5381 return -ENOTSUP;
5384 memset(res, 0, sizeof(*res));
5385 return bs->drv->bdrv_co_check(bs, res, fix);
5389 * Return values:
5390 * 0 - success
5391 * -EINVAL - backing format specified, but no file
5392 * -ENOSPC - can't update the backing file because no space is left in the
5393 * image file header
5394 * -ENOTSUP - format driver doesn't support changing the backing file
5396 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5397 const char *backing_fmt, bool require)
5399 BlockDriver *drv = bs->drv;
5400 int ret;
5402 GLOBAL_STATE_CODE();
5404 if (!drv) {
5405 return -ENOMEDIUM;
5408 /* Backing file format doesn't make sense without a backing file */
5409 if (backing_fmt && !backing_file) {
5410 return -EINVAL;
5413 if (require && backing_file && !backing_fmt) {
5414 return -EINVAL;
5417 if (drv->bdrv_change_backing_file != NULL) {
5418 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5419 } else {
5420 ret = -ENOTSUP;
5423 if (ret == 0) {
5424 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5425 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5426 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5427 backing_file ?: "");
5429 return ret;
5433 * Finds the first non-filter node above bs in the chain between
5434 * active and bs. The returned node is either an immediate parent of
5435 * bs, or there are only filter nodes between the two.
5437 * Returns NULL if bs is not found in active's image chain,
5438 * or if active == bs.
5440 * Returns the bottommost base image if bs == NULL.
5442 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5443 BlockDriverState *bs)
5446 GLOBAL_STATE_CODE();
5448 bs = bdrv_skip_filters(bs);
5449 active = bdrv_skip_filters(active);
5451 while (active) {
5452 BlockDriverState *next = bdrv_backing_chain_next(active);
5453 if (bs == next) {
5454 return active;
5456 active = next;
5459 return NULL;
5462 /* Given a BDS, searches for the base layer. */
5463 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5465 GLOBAL_STATE_CODE();
5467 return bdrv_find_overlay(bs, NULL);
5471 * Return true if at least one of the COW (backing) and filter links
5472 * between @bs and @base is frozen. @errp is set if that's the case.
5473 * @base must be reachable from @bs, or NULL.
5475 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5476 Error **errp)
5478 BlockDriverState *i;
5479 BdrvChild *child;
5481 GLOBAL_STATE_CODE();
5483 for (i = bs; i != base; i = child_bs(child)) {
5484 child = bdrv_filter_or_cow_child(i);
5486 if (child && child->frozen) {
5487 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5488 child->name, i->node_name, child->bs->node_name);
5489 return true;
5493 return false;
5497 * Freeze all COW (backing) and filter links between @bs and @base.
5498 * If any of the links is already frozen the operation is aborted and
5499 * none of the links are modified.
5500 * @base must be reachable from @bs, or NULL.
5501 * Returns 0 on success. On failure returns < 0 and sets @errp.
5503 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5504 Error **errp)
5506 BlockDriverState *i;
5507 BdrvChild *child;
5509 GLOBAL_STATE_CODE();
5511 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5512 return -EPERM;
5515 for (i = bs; i != base; i = child_bs(child)) {
5516 child = bdrv_filter_or_cow_child(i);
5517 if (child && child->bs->never_freeze) {
5518 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5519 child->name, child->bs->node_name);
5520 return -EPERM;
5524 for (i = bs; i != base; i = child_bs(child)) {
5525 child = bdrv_filter_or_cow_child(i);
5526 if (child) {
5527 child->frozen = true;
5531 return 0;
5535 * Unfreeze all COW (backing) and filter links between @bs and @base.
5536 * The caller must ensure that all links are frozen before using this
5537 * function.
5538 * @base must be reachable from @bs, or NULL.
5540 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5542 BlockDriverState *i;
5543 BdrvChild *child;
5545 GLOBAL_STATE_CODE();
5547 for (i = bs; i != base; i = child_bs(child)) {
5548 child = bdrv_filter_or_cow_child(i);
5549 if (child) {
5550 assert(child->frozen);
5551 child->frozen = false;
5557 * Drops images above 'base' up to and including 'top', and sets the image
5558 * above 'top' to have base as its backing file.
5560 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5561 * information in 'bs' can be properly updated.
5563 * E.g., this will convert the following chain:
5564 * bottom <- base <- intermediate <- top <- active
5566 * to
5568 * bottom <- base <- active
5570 * It is allowed for bottom==base, in which case it converts:
5572 * base <- intermediate <- top <- active
5574 * to
5576 * base <- active
5578 * If backing_file_str is non-NULL, it will be used when modifying top's
5579 * overlay image metadata.
5581 * Error conditions:
5582 * if active == top, that is considered an error
5585 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5586 const char *backing_file_str)
5588 BlockDriverState *explicit_top = top;
5589 bool update_inherits_from;
5590 BdrvChild *c;
5591 Error *local_err = NULL;
5592 int ret = -EIO;
5593 g_autoptr(GSList) updated_children = NULL;
5594 GSList *p;
5596 GLOBAL_STATE_CODE();
5598 bdrv_ref(top);
5599 bdrv_subtree_drained_begin(top);
5601 if (!top->drv || !base->drv) {
5602 goto exit;
5605 /* Make sure that base is in the backing chain of top */
5606 if (!bdrv_chain_contains(top, base)) {
5607 goto exit;
5610 /* If 'base' recursively inherits from 'top' then we should set
5611 * base->inherits_from to top->inherits_from after 'top' and all
5612 * other intermediate nodes have been dropped.
5613 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5614 * it because no one inherits from it. We use explicit_top for that. */
5615 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5616 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5618 /* success - we can delete the intermediate states, and link top->base */
5619 if (!backing_file_str) {
5620 bdrv_refresh_filename(base);
5621 backing_file_str = base->filename;
5624 QLIST_FOREACH(c, &top->parents, next_parent) {
5625 updated_children = g_slist_prepend(updated_children, c);
5629 * It seems correct to pass detach_subchain=true here, but it triggers
5630 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5631 * another drained section, which modify the graph (for example, removing
5632 * the child, which we keep in updated_children list). So, it's a TODO.
5634 * Note, bug triggered if pass detach_subchain=true here and run
5635 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5636 * That's a FIXME.
5638 bdrv_replace_node_common(top, base, false, false, &local_err);
5639 if (local_err) {
5640 error_report_err(local_err);
5641 goto exit;
5644 for (p = updated_children; p; p = p->next) {
5645 c = p->data;
5647 if (c->klass->update_filename) {
5648 ret = c->klass->update_filename(c, base, backing_file_str,
5649 &local_err);
5650 if (ret < 0) {
5652 * TODO: Actually, we want to rollback all previous iterations
5653 * of this loop, and (which is almost impossible) previous
5654 * bdrv_replace_node()...
5656 * Note, that c->klass->update_filename may lead to permission
5657 * update, so it's a bad idea to call it inside permission
5658 * update transaction of bdrv_replace_node.
5660 error_report_err(local_err);
5661 goto exit;
5666 if (update_inherits_from) {
5667 base->inherits_from = explicit_top->inherits_from;
5670 ret = 0;
5671 exit:
5672 bdrv_subtree_drained_end(top);
5673 bdrv_unref(top);
5674 return ret;
5678 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5679 * sums the size of all data-bearing children. (This excludes backing
5680 * children.)
5682 static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5684 BdrvChild *child;
5685 int64_t child_size, sum = 0;
5687 QLIST_FOREACH(child, &bs->children, next) {
5688 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5689 BDRV_CHILD_FILTERED))
5691 child_size = bdrv_get_allocated_file_size(child->bs);
5692 if (child_size < 0) {
5693 return child_size;
5695 sum += child_size;
5699 return sum;
5703 * Length of a allocated file in bytes. Sparse files are counted by actual
5704 * allocated space. Return < 0 if error or unknown.
5706 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5708 BlockDriver *drv = bs->drv;
5709 IO_CODE();
5711 if (!drv) {
5712 return -ENOMEDIUM;
5714 if (drv->bdrv_get_allocated_file_size) {
5715 return drv->bdrv_get_allocated_file_size(bs);
5718 if (drv->bdrv_file_open) {
5720 * Protocol drivers default to -ENOTSUP (most of their data is
5721 * not stored in any of their children (if they even have any),
5722 * so there is no generic way to figure it out).
5724 return -ENOTSUP;
5725 } else if (drv->is_filter) {
5726 /* Filter drivers default to the size of their filtered child */
5727 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5728 } else {
5729 /* Other drivers default to summing their children's sizes */
5730 return bdrv_sum_allocated_file_size(bs);
5735 * bdrv_measure:
5736 * @drv: Format driver
5737 * @opts: Creation options for new image
5738 * @in_bs: Existing image containing data for new image (may be NULL)
5739 * @errp: Error object
5740 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5741 * or NULL on error
5743 * Calculate file size required to create a new image.
5745 * If @in_bs is given then space for allocated clusters and zero clusters
5746 * from that image are included in the calculation. If @opts contains a
5747 * backing file that is shared by @in_bs then backing clusters may be omitted
5748 * from the calculation.
5750 * If @in_bs is NULL then the calculation includes no allocated clusters
5751 * unless a preallocation option is given in @opts.
5753 * Note that @in_bs may use a different BlockDriver from @drv.
5755 * If an error occurs the @errp pointer is set.
5757 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5758 BlockDriverState *in_bs, Error **errp)
5760 IO_CODE();
5761 if (!drv->bdrv_measure) {
5762 error_setg(errp, "Block driver '%s' does not support size measurement",
5763 drv->format_name);
5764 return NULL;
5767 return drv->bdrv_measure(opts, in_bs, errp);
5771 * Return number of sectors on success, -errno on error.
5773 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5775 BlockDriver *drv = bs->drv;
5776 IO_CODE();
5778 if (!drv)
5779 return -ENOMEDIUM;
5781 if (drv->has_variable_length) {
5782 int ret = refresh_total_sectors(bs, bs->total_sectors);
5783 if (ret < 0) {
5784 return ret;
5787 return bs->total_sectors;
5791 * Return length in bytes on success, -errno on error.
5792 * The length is always a multiple of BDRV_SECTOR_SIZE.
5794 int64_t bdrv_getlength(BlockDriverState *bs)
5796 int64_t ret = bdrv_nb_sectors(bs);
5797 IO_CODE();
5799 if (ret < 0) {
5800 return ret;
5802 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5803 return -EFBIG;
5805 return ret * BDRV_SECTOR_SIZE;
5808 /* return 0 as number of sectors if no device present or error */
5809 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5811 int64_t nb_sectors = bdrv_nb_sectors(bs);
5812 IO_CODE();
5814 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5817 bool bdrv_is_sg(BlockDriverState *bs)
5819 IO_CODE();
5820 return bs->sg;
5824 * Return whether the given node supports compressed writes.
5826 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5828 BlockDriverState *filtered;
5829 IO_CODE();
5831 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5832 return false;
5835 filtered = bdrv_filter_bs(bs);
5836 if (filtered) {
5838 * Filters can only forward compressed writes, so we have to
5839 * check the child.
5841 return bdrv_supports_compressed_writes(filtered);
5844 return true;
5847 const char *bdrv_get_format_name(BlockDriverState *bs)
5849 IO_CODE();
5850 return bs->drv ? bs->drv->format_name : NULL;
5853 static int qsort_strcmp(const void *a, const void *b)
5855 return strcmp(*(char *const *)a, *(char *const *)b);
5858 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5859 void *opaque, bool read_only)
5861 BlockDriver *drv;
5862 int count = 0;
5863 int i;
5864 const char **formats = NULL;
5866 GLOBAL_STATE_CODE();
5868 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5869 if (drv->format_name) {
5870 bool found = false;
5871 int i = count;
5873 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5874 continue;
5877 while (formats && i && !found) {
5878 found = !strcmp(formats[--i], drv->format_name);
5881 if (!found) {
5882 formats = g_renew(const char *, formats, count + 1);
5883 formats[count++] = drv->format_name;
5888 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5889 const char *format_name = block_driver_modules[i].format_name;
5891 if (format_name) {
5892 bool found = false;
5893 int j = count;
5895 if (use_bdrv_whitelist &&
5896 !bdrv_format_is_whitelisted(format_name, read_only)) {
5897 continue;
5900 while (formats && j && !found) {
5901 found = !strcmp(formats[--j], format_name);
5904 if (!found) {
5905 formats = g_renew(const char *, formats, count + 1);
5906 formats[count++] = format_name;
5911 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5913 for (i = 0; i < count; i++) {
5914 it(opaque, formats[i]);
5917 g_free(formats);
5920 /* This function is to find a node in the bs graph */
5921 BlockDriverState *bdrv_find_node(const char *node_name)
5923 BlockDriverState *bs;
5925 assert(node_name);
5926 GLOBAL_STATE_CODE();
5928 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5929 if (!strcmp(node_name, bs->node_name)) {
5930 return bs;
5933 return NULL;
5936 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5937 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5938 Error **errp)
5940 BlockDeviceInfoList *list;
5941 BlockDriverState *bs;
5943 GLOBAL_STATE_CODE();
5945 list = NULL;
5946 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5947 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5948 if (!info) {
5949 qapi_free_BlockDeviceInfoList(list);
5950 return NULL;
5952 QAPI_LIST_PREPEND(list, info);
5955 return list;
5958 typedef struct XDbgBlockGraphConstructor {
5959 XDbgBlockGraph *graph;
5960 GHashTable *graph_nodes;
5961 } XDbgBlockGraphConstructor;
5963 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5965 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5967 gr->graph = g_new0(XDbgBlockGraph, 1);
5968 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5970 return gr;
5973 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5975 XDbgBlockGraph *graph = gr->graph;
5977 g_hash_table_destroy(gr->graph_nodes);
5978 g_free(gr);
5980 return graph;
5983 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5985 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5987 if (ret != 0) {
5988 return ret;
5992 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5993 * answer of g_hash_table_lookup.
5995 ret = g_hash_table_size(gr->graph_nodes) + 1;
5996 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5998 return ret;
6001 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6002 XDbgBlockGraphNodeType type, const char *name)
6004 XDbgBlockGraphNode *n;
6006 n = g_new0(XDbgBlockGraphNode, 1);
6008 n->id = xdbg_graph_node_num(gr, node);
6009 n->type = type;
6010 n->name = g_strdup(name);
6012 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6015 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6016 const BdrvChild *child)
6018 BlockPermission qapi_perm;
6019 XDbgBlockGraphEdge *edge;
6020 GLOBAL_STATE_CODE();
6022 edge = g_new0(XDbgBlockGraphEdge, 1);
6024 edge->parent = xdbg_graph_node_num(gr, parent);
6025 edge->child = xdbg_graph_node_num(gr, child->bs);
6026 edge->name = g_strdup(child->name);
6028 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6029 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6031 if (flag & child->perm) {
6032 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6034 if (flag & child->shared_perm) {
6035 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6039 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6043 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6045 BlockBackend *blk;
6046 BlockJob *job;
6047 BlockDriverState *bs;
6048 BdrvChild *child;
6049 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6051 GLOBAL_STATE_CODE();
6053 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6054 char *allocated_name = NULL;
6055 const char *name = blk_name(blk);
6057 if (!*name) {
6058 name = allocated_name = blk_get_attached_dev_id(blk);
6060 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6061 name);
6062 g_free(allocated_name);
6063 if (blk_root(blk)) {
6064 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6068 WITH_JOB_LOCK_GUARD() {
6069 for (job = block_job_next_locked(NULL); job;
6070 job = block_job_next_locked(job)) {
6071 GSList *el;
6073 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6074 job->job.id);
6075 for (el = job->nodes; el; el = el->next) {
6076 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6081 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6082 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6083 bs->node_name);
6084 QLIST_FOREACH(child, &bs->children, next) {
6085 xdbg_graph_add_edge(gr, bs, child);
6089 return xdbg_graph_finalize(gr);
6092 BlockDriverState *bdrv_lookup_bs(const char *device,
6093 const char *node_name,
6094 Error **errp)
6096 BlockBackend *blk;
6097 BlockDriverState *bs;
6099 GLOBAL_STATE_CODE();
6101 if (device) {
6102 blk = blk_by_name(device);
6104 if (blk) {
6105 bs = blk_bs(blk);
6106 if (!bs) {
6107 error_setg(errp, "Device '%s' has no medium", device);
6110 return bs;
6114 if (node_name) {
6115 bs = bdrv_find_node(node_name);
6117 if (bs) {
6118 return bs;
6122 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6123 device ? device : "",
6124 node_name ? node_name : "");
6125 return NULL;
6128 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6129 * return false. If either argument is NULL, return false. */
6130 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6133 GLOBAL_STATE_CODE();
6135 while (top && top != base) {
6136 top = bdrv_filter_or_cow_bs(top);
6139 return top != NULL;
6142 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6144 GLOBAL_STATE_CODE();
6145 if (!bs) {
6146 return QTAILQ_FIRST(&graph_bdrv_states);
6148 return QTAILQ_NEXT(bs, node_list);
6151 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6153 GLOBAL_STATE_CODE();
6154 if (!bs) {
6155 return QTAILQ_FIRST(&all_bdrv_states);
6157 return QTAILQ_NEXT(bs, bs_list);
6160 const char *bdrv_get_node_name(const BlockDriverState *bs)
6162 IO_CODE();
6163 return bs->node_name;
6166 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6168 BdrvChild *c;
6169 const char *name;
6170 IO_CODE();
6172 /* If multiple parents have a name, just pick the first one. */
6173 QLIST_FOREACH(c, &bs->parents, next_parent) {
6174 if (c->klass->get_name) {
6175 name = c->klass->get_name(c);
6176 if (name && *name) {
6177 return name;
6182 return NULL;
6185 /* TODO check what callers really want: bs->node_name or blk_name() */
6186 const char *bdrv_get_device_name(const BlockDriverState *bs)
6188 IO_CODE();
6189 return bdrv_get_parent_name(bs) ?: "";
6192 /* This can be used to identify nodes that might not have a device
6193 * name associated. Since node and device names live in the same
6194 * namespace, the result is unambiguous. The exception is if both are
6195 * absent, then this returns an empty (non-null) string. */
6196 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6198 IO_CODE();
6199 return bdrv_get_parent_name(bs) ?: bs->node_name;
6202 int bdrv_get_flags(BlockDriverState *bs)
6204 IO_CODE();
6205 return bs->open_flags;
6208 int bdrv_has_zero_init_1(BlockDriverState *bs)
6210 GLOBAL_STATE_CODE();
6211 return 1;
6214 int bdrv_has_zero_init(BlockDriverState *bs)
6216 BlockDriverState *filtered;
6217 GLOBAL_STATE_CODE();
6219 if (!bs->drv) {
6220 return 0;
6223 /* If BS is a copy on write image, it is initialized to
6224 the contents of the base image, which may not be zeroes. */
6225 if (bdrv_cow_child(bs)) {
6226 return 0;
6228 if (bs->drv->bdrv_has_zero_init) {
6229 return bs->drv->bdrv_has_zero_init(bs);
6232 filtered = bdrv_filter_bs(bs);
6233 if (filtered) {
6234 return bdrv_has_zero_init(filtered);
6237 /* safe default */
6238 return 0;
6241 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6243 IO_CODE();
6244 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6245 return false;
6248 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6251 void bdrv_get_backing_filename(BlockDriverState *bs,
6252 char *filename, int filename_size)
6254 IO_CODE();
6255 pstrcpy(filename, filename_size, bs->backing_file);
6258 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6260 int ret;
6261 BlockDriver *drv = bs->drv;
6262 IO_CODE();
6263 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6264 if (!drv) {
6265 return -ENOMEDIUM;
6267 if (!drv->bdrv_get_info) {
6268 BlockDriverState *filtered = bdrv_filter_bs(bs);
6269 if (filtered) {
6270 return bdrv_get_info(filtered, bdi);
6272 return -ENOTSUP;
6274 memset(bdi, 0, sizeof(*bdi));
6275 ret = drv->bdrv_get_info(bs, bdi);
6276 if (ret < 0) {
6277 return ret;
6280 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6281 return -EINVAL;
6284 return 0;
6287 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6288 Error **errp)
6290 BlockDriver *drv = bs->drv;
6291 IO_CODE();
6292 if (drv && drv->bdrv_get_specific_info) {
6293 return drv->bdrv_get_specific_info(bs, errp);
6295 return NULL;
6298 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6300 BlockDriver *drv = bs->drv;
6301 IO_CODE();
6302 if (!drv || !drv->bdrv_get_specific_stats) {
6303 return NULL;
6305 return drv->bdrv_get_specific_stats(bs);
6308 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6310 IO_CODE();
6311 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6312 return;
6315 bs->drv->bdrv_debug_event(bs, event);
6318 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
6320 GLOBAL_STATE_CODE();
6321 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6322 bs = bdrv_primary_bs(bs);
6325 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6326 assert(bs->drv->bdrv_debug_remove_breakpoint);
6327 return bs;
6330 return NULL;
6333 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6334 const char *tag)
6336 GLOBAL_STATE_CODE();
6337 bs = bdrv_find_debug_node(bs);
6338 if (bs) {
6339 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6342 return -ENOTSUP;
6345 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6347 GLOBAL_STATE_CODE();
6348 bs = bdrv_find_debug_node(bs);
6349 if (bs) {
6350 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6353 return -ENOTSUP;
6356 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6358 GLOBAL_STATE_CODE();
6359 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6360 bs = bdrv_primary_bs(bs);
6363 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6364 return bs->drv->bdrv_debug_resume(bs, tag);
6367 return -ENOTSUP;
6370 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6372 GLOBAL_STATE_CODE();
6373 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6374 bs = bdrv_primary_bs(bs);
6377 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6378 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6381 return false;
6384 /* backing_file can either be relative, or absolute, or a protocol. If it is
6385 * relative, it must be relative to the chain. So, passing in bs->filename
6386 * from a BDS as backing_file should not be done, as that may be relative to
6387 * the CWD rather than the chain. */
6388 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6389 const char *backing_file)
6391 char *filename_full = NULL;
6392 char *backing_file_full = NULL;
6393 char *filename_tmp = NULL;
6394 int is_protocol = 0;
6395 bool filenames_refreshed = false;
6396 BlockDriverState *curr_bs = NULL;
6397 BlockDriverState *retval = NULL;
6398 BlockDriverState *bs_below;
6400 GLOBAL_STATE_CODE();
6402 if (!bs || !bs->drv || !backing_file) {
6403 return NULL;
6406 filename_full = g_malloc(PATH_MAX);
6407 backing_file_full = g_malloc(PATH_MAX);
6409 is_protocol = path_has_protocol(backing_file);
6412 * Being largely a legacy function, skip any filters here
6413 * (because filters do not have normal filenames, so they cannot
6414 * match anyway; and allowing json:{} filenames is a bit out of
6415 * scope).
6417 for (curr_bs = bdrv_skip_filters(bs);
6418 bdrv_cow_child(curr_bs) != NULL;
6419 curr_bs = bs_below)
6421 bs_below = bdrv_backing_chain_next(curr_bs);
6423 if (bdrv_backing_overridden(curr_bs)) {
6425 * If the backing file was overridden, we can only compare
6426 * directly against the backing node's filename.
6429 if (!filenames_refreshed) {
6431 * This will automatically refresh all of the
6432 * filenames in the rest of the backing chain, so we
6433 * only need to do this once.
6435 bdrv_refresh_filename(bs_below);
6436 filenames_refreshed = true;
6439 if (strcmp(backing_file, bs_below->filename) == 0) {
6440 retval = bs_below;
6441 break;
6443 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6445 * If either of the filename paths is actually a protocol, then
6446 * compare unmodified paths; otherwise make paths relative.
6448 char *backing_file_full_ret;
6450 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6451 retval = bs_below;
6452 break;
6454 /* Also check against the full backing filename for the image */
6455 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6456 NULL);
6457 if (backing_file_full_ret) {
6458 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6459 g_free(backing_file_full_ret);
6460 if (equal) {
6461 retval = bs_below;
6462 break;
6465 } else {
6466 /* If not an absolute filename path, make it relative to the current
6467 * image's filename path */
6468 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6469 NULL);
6470 /* We are going to compare canonicalized absolute pathnames */
6471 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6472 g_free(filename_tmp);
6473 continue;
6475 g_free(filename_tmp);
6477 /* We need to make sure the backing filename we are comparing against
6478 * is relative to the current image filename (or absolute) */
6479 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6480 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6481 g_free(filename_tmp);
6482 continue;
6484 g_free(filename_tmp);
6486 if (strcmp(backing_file_full, filename_full) == 0) {
6487 retval = bs_below;
6488 break;
6493 g_free(filename_full);
6494 g_free(backing_file_full);
6495 return retval;
6498 void bdrv_init(void)
6500 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6501 use_bdrv_whitelist = 1;
6502 #endif
6503 module_call_init(MODULE_INIT_BLOCK);
6506 void bdrv_init_with_whitelist(void)
6508 use_bdrv_whitelist = 1;
6509 bdrv_init();
6512 int bdrv_activate(BlockDriverState *bs, Error **errp)
6514 BdrvChild *child, *parent;
6515 Error *local_err = NULL;
6516 int ret;
6517 BdrvDirtyBitmap *bm;
6519 GLOBAL_STATE_CODE();
6521 if (!bs->drv) {
6522 return -ENOMEDIUM;
6525 QLIST_FOREACH(child, &bs->children, next) {
6526 bdrv_activate(child->bs, &local_err);
6527 if (local_err) {
6528 error_propagate(errp, local_err);
6529 return -EINVAL;
6534 * Update permissions, they may differ for inactive nodes.
6536 * Note that the required permissions of inactive images are always a
6537 * subset of the permissions required after activating the image. This
6538 * allows us to just get the permissions upfront without restricting
6539 * bdrv_co_invalidate_cache().
6541 * It also means that in error cases, we don't have to try and revert to
6542 * the old permissions (which is an operation that could fail, too). We can
6543 * just keep the extended permissions for the next time that an activation
6544 * of the image is tried.
6546 if (bs->open_flags & BDRV_O_INACTIVE) {
6547 bs->open_flags &= ~BDRV_O_INACTIVE;
6548 ret = bdrv_refresh_perms(bs, NULL, errp);
6549 if (ret < 0) {
6550 bs->open_flags |= BDRV_O_INACTIVE;
6551 return ret;
6554 ret = bdrv_invalidate_cache(bs, errp);
6555 if (ret < 0) {
6556 bs->open_flags |= BDRV_O_INACTIVE;
6557 return ret;
6560 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6561 bdrv_dirty_bitmap_skip_store(bm, false);
6564 ret = refresh_total_sectors(bs, bs->total_sectors);
6565 if (ret < 0) {
6566 bs->open_flags |= BDRV_O_INACTIVE;
6567 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6568 return ret;
6572 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6573 if (parent->klass->activate) {
6574 parent->klass->activate(parent, &local_err);
6575 if (local_err) {
6576 bs->open_flags |= BDRV_O_INACTIVE;
6577 error_propagate(errp, local_err);
6578 return -EINVAL;
6583 return 0;
6586 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6588 Error *local_err = NULL;
6589 IO_CODE();
6591 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6593 if (bs->drv->bdrv_co_invalidate_cache) {
6594 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6595 if (local_err) {
6596 error_propagate(errp, local_err);
6597 return -EINVAL;
6601 return 0;
6604 void bdrv_activate_all(Error **errp)
6606 BlockDriverState *bs;
6607 BdrvNextIterator it;
6609 GLOBAL_STATE_CODE();
6611 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6612 AioContext *aio_context = bdrv_get_aio_context(bs);
6613 int ret;
6615 aio_context_acquire(aio_context);
6616 ret = bdrv_activate(bs, errp);
6617 aio_context_release(aio_context);
6618 if (ret < 0) {
6619 bdrv_next_cleanup(&it);
6620 return;
6625 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6627 BdrvChild *parent;
6628 GLOBAL_STATE_CODE();
6630 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6631 if (parent->klass->parent_is_bds) {
6632 BlockDriverState *parent_bs = parent->opaque;
6633 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6634 return true;
6639 return false;
6642 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6644 BdrvChild *child, *parent;
6645 int ret;
6646 uint64_t cumulative_perms, cumulative_shared_perms;
6648 GLOBAL_STATE_CODE();
6650 if (!bs->drv) {
6651 return -ENOMEDIUM;
6654 /* Make sure that we don't inactivate a child before its parent.
6655 * It will be covered by recursion from the yet active parent. */
6656 if (bdrv_has_bds_parent(bs, true)) {
6657 return 0;
6660 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6662 /* Inactivate this node */
6663 if (bs->drv->bdrv_inactivate) {
6664 ret = bs->drv->bdrv_inactivate(bs);
6665 if (ret < 0) {
6666 return ret;
6670 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6671 if (parent->klass->inactivate) {
6672 ret = parent->klass->inactivate(parent);
6673 if (ret < 0) {
6674 return ret;
6679 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6680 &cumulative_shared_perms);
6681 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6682 /* Our inactive parents still need write access. Inactivation failed. */
6683 return -EPERM;
6686 bs->open_flags |= BDRV_O_INACTIVE;
6689 * Update permissions, they may differ for inactive nodes.
6690 * We only tried to loosen restrictions, so errors are not fatal, ignore
6691 * them.
6693 bdrv_refresh_perms(bs, NULL, NULL);
6695 /* Recursively inactivate children */
6696 QLIST_FOREACH(child, &bs->children, next) {
6697 ret = bdrv_inactivate_recurse(child->bs);
6698 if (ret < 0) {
6699 return ret;
6703 return 0;
6706 int bdrv_inactivate_all(void)
6708 BlockDriverState *bs = NULL;
6709 BdrvNextIterator it;
6710 int ret = 0;
6711 GSList *aio_ctxs = NULL, *ctx;
6713 GLOBAL_STATE_CODE();
6715 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6716 AioContext *aio_context = bdrv_get_aio_context(bs);
6718 if (!g_slist_find(aio_ctxs, aio_context)) {
6719 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6720 aio_context_acquire(aio_context);
6724 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6725 /* Nodes with BDS parents are covered by recursion from the last
6726 * parent that gets inactivated. Don't inactivate them a second
6727 * time if that has already happened. */
6728 if (bdrv_has_bds_parent(bs, false)) {
6729 continue;
6731 ret = bdrv_inactivate_recurse(bs);
6732 if (ret < 0) {
6733 bdrv_next_cleanup(&it);
6734 goto out;
6738 out:
6739 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6740 AioContext *aio_context = ctx->data;
6741 aio_context_release(aio_context);
6743 g_slist_free(aio_ctxs);
6745 return ret;
6748 /**************************************************************/
6749 /* removable device support */
6752 * Return TRUE if the media is present
6754 bool bdrv_is_inserted(BlockDriverState *bs)
6756 BlockDriver *drv = bs->drv;
6757 BdrvChild *child;
6758 IO_CODE();
6760 if (!drv) {
6761 return false;
6763 if (drv->bdrv_is_inserted) {
6764 return drv->bdrv_is_inserted(bs);
6766 QLIST_FOREACH(child, &bs->children, next) {
6767 if (!bdrv_is_inserted(child->bs)) {
6768 return false;
6771 return true;
6775 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6777 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6779 BlockDriver *drv = bs->drv;
6780 IO_CODE();
6782 if (drv && drv->bdrv_eject) {
6783 drv->bdrv_eject(bs, eject_flag);
6788 * Lock or unlock the media (if it is locked, the user won't be able
6789 * to eject it manually).
6791 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6793 BlockDriver *drv = bs->drv;
6794 IO_CODE();
6795 trace_bdrv_lock_medium(bs, locked);
6797 if (drv && drv->bdrv_lock_medium) {
6798 drv->bdrv_lock_medium(bs, locked);
6802 /* Get a reference to bs */
6803 void bdrv_ref(BlockDriverState *bs)
6805 GLOBAL_STATE_CODE();
6806 bs->refcnt++;
6809 /* Release a previously grabbed reference to bs.
6810 * If after releasing, reference count is zero, the BlockDriverState is
6811 * deleted. */
6812 void bdrv_unref(BlockDriverState *bs)
6814 GLOBAL_STATE_CODE();
6815 if (!bs) {
6816 return;
6818 assert(bs->refcnt > 0);
6819 if (--bs->refcnt == 0) {
6820 bdrv_delete(bs);
6824 struct BdrvOpBlocker {
6825 Error *reason;
6826 QLIST_ENTRY(BdrvOpBlocker) list;
6829 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6831 BdrvOpBlocker *blocker;
6832 GLOBAL_STATE_CODE();
6833 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6834 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6835 blocker = QLIST_FIRST(&bs->op_blockers[op]);
6836 error_propagate_prepend(errp, error_copy(blocker->reason),
6837 "Node '%s' is busy: ",
6838 bdrv_get_device_or_node_name(bs));
6839 return true;
6841 return false;
6844 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6846 BdrvOpBlocker *blocker;
6847 GLOBAL_STATE_CODE();
6848 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6850 blocker = g_new0(BdrvOpBlocker, 1);
6851 blocker->reason = reason;
6852 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6855 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6857 BdrvOpBlocker *blocker, *next;
6858 GLOBAL_STATE_CODE();
6859 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6860 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6861 if (blocker->reason == reason) {
6862 QLIST_REMOVE(blocker, list);
6863 g_free(blocker);
6868 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6870 int i;
6871 GLOBAL_STATE_CODE();
6872 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6873 bdrv_op_block(bs, i, reason);
6877 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6879 int i;
6880 GLOBAL_STATE_CODE();
6881 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6882 bdrv_op_unblock(bs, i, reason);
6886 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6888 int i;
6889 GLOBAL_STATE_CODE();
6890 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6891 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6892 return false;
6895 return true;
6898 void bdrv_img_create(const char *filename, const char *fmt,
6899 const char *base_filename, const char *base_fmt,
6900 char *options, uint64_t img_size, int flags, bool quiet,
6901 Error **errp)
6903 QemuOptsList *create_opts = NULL;
6904 QemuOpts *opts = NULL;
6905 const char *backing_fmt, *backing_file;
6906 int64_t size;
6907 BlockDriver *drv, *proto_drv;
6908 Error *local_err = NULL;
6909 int ret = 0;
6911 GLOBAL_STATE_CODE();
6913 /* Find driver and parse its options */
6914 drv = bdrv_find_format(fmt);
6915 if (!drv) {
6916 error_setg(errp, "Unknown file format '%s'", fmt);
6917 return;
6920 proto_drv = bdrv_find_protocol(filename, true, errp);
6921 if (!proto_drv) {
6922 return;
6925 if (!drv->create_opts) {
6926 error_setg(errp, "Format driver '%s' does not support image creation",
6927 drv->format_name);
6928 return;
6931 if (!proto_drv->create_opts) {
6932 error_setg(errp, "Protocol driver '%s' does not support image creation",
6933 proto_drv->format_name);
6934 return;
6937 /* Create parameter list */
6938 create_opts = qemu_opts_append(create_opts, drv->create_opts);
6939 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6941 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6943 /* Parse -o options */
6944 if (options) {
6945 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
6946 goto out;
6950 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6951 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6952 } else if (img_size != UINT64_C(-1)) {
6953 error_setg(errp, "The image size must be specified only once");
6954 goto out;
6957 if (base_filename) {
6958 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
6959 NULL)) {
6960 error_setg(errp, "Backing file not supported for file format '%s'",
6961 fmt);
6962 goto out;
6966 if (base_fmt) {
6967 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
6968 error_setg(errp, "Backing file format not supported for file "
6969 "format '%s'", fmt);
6970 goto out;
6974 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6975 if (backing_file) {
6976 if (!strcmp(filename, backing_file)) {
6977 error_setg(errp, "Error: Trying to create an image with the "
6978 "same filename as the backing file");
6979 goto out;
6981 if (backing_file[0] == '\0') {
6982 error_setg(errp, "Expected backing file name, got empty string");
6983 goto out;
6987 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6989 /* The size for the image must always be specified, unless we have a backing
6990 * file and we have not been forbidden from opening it. */
6991 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6992 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6993 BlockDriverState *bs;
6994 char *full_backing;
6995 int back_flags;
6996 QDict *backing_options = NULL;
6998 full_backing =
6999 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7000 &local_err);
7001 if (local_err) {
7002 goto out;
7004 assert(full_backing);
7007 * No need to do I/O here, which allows us to open encrypted
7008 * backing images without needing the secret
7010 back_flags = flags;
7011 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7012 back_flags |= BDRV_O_NO_IO;
7014 backing_options = qdict_new();
7015 if (backing_fmt) {
7016 qdict_put_str(backing_options, "driver", backing_fmt);
7018 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7020 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7021 &local_err);
7022 g_free(full_backing);
7023 if (!bs) {
7024 error_append_hint(&local_err, "Could not open backing image.\n");
7025 goto out;
7026 } else {
7027 if (!backing_fmt) {
7028 error_setg(&local_err,
7029 "Backing file specified without backing format");
7030 error_append_hint(&local_err, "Detected format of %s.",
7031 bs->drv->format_name);
7032 goto out;
7034 if (size == -1) {
7035 /* Opened BS, have no size */
7036 size = bdrv_getlength(bs);
7037 if (size < 0) {
7038 error_setg_errno(errp, -size, "Could not get size of '%s'",
7039 backing_file);
7040 bdrv_unref(bs);
7041 goto out;
7043 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7045 bdrv_unref(bs);
7047 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7048 } else if (backing_file && !backing_fmt) {
7049 error_setg(&local_err,
7050 "Backing file specified without backing format");
7051 goto out;
7054 if (size == -1) {
7055 error_setg(errp, "Image creation needs a size parameter");
7056 goto out;
7059 if (!quiet) {
7060 printf("Formatting '%s', fmt=%s ", filename, fmt);
7061 qemu_opts_print(opts, " ");
7062 puts("");
7063 fflush(stdout);
7066 ret = bdrv_create(drv, filename, opts, &local_err);
7068 if (ret == -EFBIG) {
7069 /* This is generally a better message than whatever the driver would
7070 * deliver (especially because of the cluster_size_hint), since that
7071 * is most probably not much different from "image too large". */
7072 const char *cluster_size_hint = "";
7073 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7074 cluster_size_hint = " (try using a larger cluster size)";
7076 error_setg(errp, "The image size is too large for file format '%s'"
7077 "%s", fmt, cluster_size_hint);
7078 error_free(local_err);
7079 local_err = NULL;
7082 out:
7083 qemu_opts_del(opts);
7084 qemu_opts_free(create_opts);
7085 error_propagate(errp, local_err);
7088 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7090 IO_CODE();
7091 return bs ? bs->aio_context : qemu_get_aio_context();
7094 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7096 Coroutine *self = qemu_coroutine_self();
7097 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7098 AioContext *new_ctx;
7099 IO_CODE();
7102 * Increase bs->in_flight to ensure that this operation is completed before
7103 * moving the node to a different AioContext. Read new_ctx only afterwards.
7105 bdrv_inc_in_flight(bs);
7107 new_ctx = bdrv_get_aio_context(bs);
7108 aio_co_reschedule_self(new_ctx);
7109 return old_ctx;
7112 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7114 IO_CODE();
7115 aio_co_reschedule_self(old_ctx);
7116 bdrv_dec_in_flight(bs);
7119 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7121 AioContext *ctx = bdrv_get_aio_context(bs);
7123 /* In the main thread, bs->aio_context won't change concurrently */
7124 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7127 * We're in coroutine context, so we already hold the lock of the main
7128 * loop AioContext. Don't lock it twice to avoid deadlocks.
7130 assert(qemu_in_coroutine());
7131 if (ctx != qemu_get_aio_context()) {
7132 aio_context_acquire(ctx);
7136 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7138 AioContext *ctx = bdrv_get_aio_context(bs);
7140 assert(qemu_in_coroutine());
7141 if (ctx != qemu_get_aio_context()) {
7142 aio_context_release(ctx);
7146 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7148 IO_CODE();
7149 aio_co_enter(bdrv_get_aio_context(bs), co);
7152 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7154 GLOBAL_STATE_CODE();
7155 QLIST_REMOVE(ban, list);
7156 g_free(ban);
7159 static void bdrv_detach_aio_context(BlockDriverState *bs)
7161 BdrvAioNotifier *baf, *baf_tmp;
7163 assert(!bs->walking_aio_notifiers);
7164 GLOBAL_STATE_CODE();
7165 bs->walking_aio_notifiers = true;
7166 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7167 if (baf->deleted) {
7168 bdrv_do_remove_aio_context_notifier(baf);
7169 } else {
7170 baf->detach_aio_context(baf->opaque);
7173 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7174 * remove remaining aio notifiers if we aren't called again.
7176 bs->walking_aio_notifiers = false;
7178 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7179 bs->drv->bdrv_detach_aio_context(bs);
7182 if (bs->quiesce_counter) {
7183 aio_enable_external(bs->aio_context);
7185 assert_bdrv_graph_writable(bs);
7186 bs->aio_context = NULL;
7189 static void bdrv_attach_aio_context(BlockDriverState *bs,
7190 AioContext *new_context)
7192 BdrvAioNotifier *ban, *ban_tmp;
7193 GLOBAL_STATE_CODE();
7195 if (bs->quiesce_counter) {
7196 aio_disable_external(new_context);
7199 assert_bdrv_graph_writable(bs);
7200 bs->aio_context = new_context;
7202 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7203 bs->drv->bdrv_attach_aio_context(bs, new_context);
7206 assert(!bs->walking_aio_notifiers);
7207 bs->walking_aio_notifiers = true;
7208 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7209 if (ban->deleted) {
7210 bdrv_do_remove_aio_context_notifier(ban);
7211 } else {
7212 ban->attached_aio_context(new_context, ban->opaque);
7215 bs->walking_aio_notifiers = false;
7218 typedef struct BdrvStateSetAioContext {
7219 AioContext *new_ctx;
7220 BlockDriverState *bs;
7221 } BdrvStateSetAioContext;
7223 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7224 GHashTable *visited,
7225 Transaction *tran,
7226 Error **errp)
7228 GLOBAL_STATE_CODE();
7229 if (g_hash_table_contains(visited, c)) {
7230 return true;
7232 g_hash_table_add(visited, c);
7235 * A BdrvChildClass that doesn't handle AioContext changes cannot
7236 * tolerate any AioContext changes
7238 if (!c->klass->change_aio_ctx) {
7239 char *user = bdrv_child_user_desc(c);
7240 error_setg(errp, "Changing iothreads is not supported by %s", user);
7241 g_free(user);
7242 return false;
7244 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7245 assert(!errp || *errp);
7246 return false;
7248 return true;
7251 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7252 GHashTable *visited, Transaction *tran,
7253 Error **errp)
7255 GLOBAL_STATE_CODE();
7256 if (g_hash_table_contains(visited, c)) {
7257 return true;
7259 g_hash_table_add(visited, c);
7260 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7263 static void bdrv_set_aio_context_clean(void *opaque)
7265 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7266 BlockDriverState *bs = (BlockDriverState *) state->bs;
7268 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7269 bdrv_drained_end(bs);
7271 g_free(state);
7274 static void bdrv_set_aio_context_commit(void *opaque)
7276 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7277 BlockDriverState *bs = (BlockDriverState *) state->bs;
7278 AioContext *new_context = state->new_ctx;
7279 AioContext *old_context = bdrv_get_aio_context(bs);
7280 assert_bdrv_graph_writable(bs);
7283 * Take the old AioContex when detaching it from bs.
7284 * At this point, new_context lock is already acquired, and we are now
7285 * also taking old_context. This is safe as long as bdrv_detach_aio_context
7286 * does not call AIO_POLL_WHILE().
7288 if (old_context != qemu_get_aio_context()) {
7289 aio_context_acquire(old_context);
7291 bdrv_detach_aio_context(bs);
7292 if (old_context != qemu_get_aio_context()) {
7293 aio_context_release(old_context);
7295 bdrv_attach_aio_context(bs, new_context);
7298 static TransactionActionDrv set_aio_context = {
7299 .commit = bdrv_set_aio_context_commit,
7300 .clean = bdrv_set_aio_context_clean,
7304 * Changes the AioContext used for fd handlers, timers, and BHs by this
7305 * BlockDriverState and all its children and parents.
7307 * Must be called from the main AioContext.
7309 * The caller must own the AioContext lock for the old AioContext of bs, but it
7310 * must not own the AioContext lock for new_context (unless new_context is the
7311 * same as the current context of bs).
7313 * @visited will accumulate all visited BdrvChild objects. The caller is
7314 * responsible for freeing the list afterwards.
7316 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7317 GHashTable *visited, Transaction *tran,
7318 Error **errp)
7320 BdrvChild *c;
7321 BdrvStateSetAioContext *state;
7323 GLOBAL_STATE_CODE();
7325 if (bdrv_get_aio_context(bs) == ctx) {
7326 return true;
7329 QLIST_FOREACH(c, &bs->parents, next_parent) {
7330 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7331 return false;
7335 QLIST_FOREACH(c, &bs->children, next) {
7336 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7337 return false;
7341 state = g_new(BdrvStateSetAioContext, 1);
7342 *state = (BdrvStateSetAioContext) {
7343 .new_ctx = ctx,
7344 .bs = bs,
7347 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7348 bdrv_drained_begin(bs);
7350 tran_add(tran, &set_aio_context, state);
7352 return true;
7356 * Change bs's and recursively all of its parents' and children's AioContext
7357 * to the given new context, returning an error if that isn't possible.
7359 * If ignore_child is not NULL, that child (and its subgraph) will not
7360 * be touched.
7362 * This function still requires the caller to take the bs current
7363 * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7364 * assumes the lock is always held if bs is in another AioContext.
7365 * For the same reason, it temporarily also holds the new AioContext, since
7366 * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7367 * Therefore the new AioContext lock must not be taken by the caller.
7369 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7370 BdrvChild *ignore_child, Error **errp)
7372 Transaction *tran;
7373 GHashTable *visited;
7374 int ret;
7375 AioContext *old_context = bdrv_get_aio_context(bs);
7376 GLOBAL_STATE_CODE();
7379 * Recursion phase: go through all nodes of the graph.
7380 * Take care of checking that all nodes support changing AioContext
7381 * and drain them, builing a linear list of callbacks to run if everything
7382 * is successful (the transaction itself).
7384 tran = tran_new();
7385 visited = g_hash_table_new(NULL, NULL);
7386 if (ignore_child) {
7387 g_hash_table_add(visited, ignore_child);
7389 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7390 g_hash_table_destroy(visited);
7393 * Linear phase: go through all callbacks collected in the transaction.
7394 * Run all callbacks collected in the recursion to switch all nodes
7395 * AioContext lock (transaction commit), or undo all changes done in the
7396 * recursion (transaction abort).
7399 if (!ret) {
7400 /* Just run clean() callbacks. No AioContext changed. */
7401 tran_abort(tran);
7402 return -EPERM;
7406 * Release old AioContext, it won't be needed anymore, as all
7407 * bdrv_drained_begin() have been called already.
7409 if (qemu_get_aio_context() != old_context) {
7410 aio_context_release(old_context);
7414 * Acquire new AioContext since bdrv_drained_end() is going to be called
7415 * after we switched all nodes in the new AioContext, and the function
7416 * assumes that the lock of the bs is always taken.
7418 if (qemu_get_aio_context() != ctx) {
7419 aio_context_acquire(ctx);
7422 tran_commit(tran);
7424 if (qemu_get_aio_context() != ctx) {
7425 aio_context_release(ctx);
7428 /* Re-acquire the old AioContext, since the caller takes and releases it. */
7429 if (qemu_get_aio_context() != old_context) {
7430 aio_context_acquire(old_context);
7433 return 0;
7436 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7437 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7438 void (*detach_aio_context)(void *opaque), void *opaque)
7440 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7441 *ban = (BdrvAioNotifier){
7442 .attached_aio_context = attached_aio_context,
7443 .detach_aio_context = detach_aio_context,
7444 .opaque = opaque
7446 GLOBAL_STATE_CODE();
7448 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7451 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7452 void (*attached_aio_context)(AioContext *,
7453 void *),
7454 void (*detach_aio_context)(void *),
7455 void *opaque)
7457 BdrvAioNotifier *ban, *ban_next;
7458 GLOBAL_STATE_CODE();
7460 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7461 if (ban->attached_aio_context == attached_aio_context &&
7462 ban->detach_aio_context == detach_aio_context &&
7463 ban->opaque == opaque &&
7464 ban->deleted == false)
7466 if (bs->walking_aio_notifiers) {
7467 ban->deleted = true;
7468 } else {
7469 bdrv_do_remove_aio_context_notifier(ban);
7471 return;
7475 abort();
7478 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7479 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7480 bool force,
7481 Error **errp)
7483 GLOBAL_STATE_CODE();
7484 if (!bs->drv) {
7485 error_setg(errp, "Node is ejected");
7486 return -ENOMEDIUM;
7488 if (!bs->drv->bdrv_amend_options) {
7489 error_setg(errp, "Block driver '%s' does not support option amendment",
7490 bs->drv->format_name);
7491 return -ENOTSUP;
7493 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7494 cb_opaque, force, errp);
7498 * This function checks whether the given @to_replace is allowed to be
7499 * replaced by a node that always shows the same data as @bs. This is
7500 * used for example to verify whether the mirror job can replace
7501 * @to_replace by the target mirrored from @bs.
7502 * To be replaceable, @bs and @to_replace may either be guaranteed to
7503 * always show the same data (because they are only connected through
7504 * filters), or some driver may allow replacing one of its children
7505 * because it can guarantee that this child's data is not visible at
7506 * all (for example, for dissenting quorum children that have no other
7507 * parents).
7509 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7510 BlockDriverState *to_replace)
7512 BlockDriverState *filtered;
7514 GLOBAL_STATE_CODE();
7516 if (!bs || !bs->drv) {
7517 return false;
7520 if (bs == to_replace) {
7521 return true;
7524 /* See what the driver can do */
7525 if (bs->drv->bdrv_recurse_can_replace) {
7526 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7529 /* For filters without an own implementation, we can recurse on our own */
7530 filtered = bdrv_filter_bs(bs);
7531 if (filtered) {
7532 return bdrv_recurse_can_replace(filtered, to_replace);
7535 /* Safe default */
7536 return false;
7540 * Check whether the given @node_name can be replaced by a node that
7541 * has the same data as @parent_bs. If so, return @node_name's BDS;
7542 * NULL otherwise.
7544 * @node_name must be a (recursive) *child of @parent_bs (or this
7545 * function will return NULL).
7547 * The result (whether the node can be replaced or not) is only valid
7548 * for as long as no graph or permission changes occur.
7550 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7551 const char *node_name, Error **errp)
7553 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7554 AioContext *aio_context;
7556 GLOBAL_STATE_CODE();
7558 if (!to_replace_bs) {
7559 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7560 return NULL;
7563 aio_context = bdrv_get_aio_context(to_replace_bs);
7564 aio_context_acquire(aio_context);
7566 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7567 to_replace_bs = NULL;
7568 goto out;
7571 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7572 * most non filter in order to prevent data corruption.
7573 * Another benefit is that this tests exclude backing files which are
7574 * blocked by the backing blockers.
7576 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7577 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7578 "because it cannot be guaranteed that doing so would not "
7579 "lead to an abrupt change of visible data",
7580 node_name, parent_bs->node_name);
7581 to_replace_bs = NULL;
7582 goto out;
7585 out:
7586 aio_context_release(aio_context);
7587 return to_replace_bs;
7591 * Iterates through the list of runtime option keys that are said to
7592 * be "strong" for a BDS. An option is called "strong" if it changes
7593 * a BDS's data. For example, the null block driver's "size" and
7594 * "read-zeroes" options are strong, but its "latency-ns" option is
7595 * not.
7597 * If a key returned by this function ends with a dot, all options
7598 * starting with that prefix are strong.
7600 static const char *const *strong_options(BlockDriverState *bs,
7601 const char *const *curopt)
7603 static const char *const global_options[] = {
7604 "driver", "filename", NULL
7607 if (!curopt) {
7608 return &global_options[0];
7611 curopt++;
7612 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7613 curopt = bs->drv->strong_runtime_opts;
7616 return (curopt && *curopt) ? curopt : NULL;
7620 * Copies all strong runtime options from bs->options to the given
7621 * QDict. The set of strong option keys is determined by invoking
7622 * strong_options().
7624 * Returns true iff any strong option was present in bs->options (and
7625 * thus copied to the target QDict) with the exception of "filename"
7626 * and "driver". The caller is expected to use this value to decide
7627 * whether the existence of strong options prevents the generation of
7628 * a plain filename.
7630 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7632 bool found_any = false;
7633 const char *const *option_name = NULL;
7635 if (!bs->drv) {
7636 return false;
7639 while ((option_name = strong_options(bs, option_name))) {
7640 bool option_given = false;
7642 assert(strlen(*option_name) > 0);
7643 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7644 QObject *entry = qdict_get(bs->options, *option_name);
7645 if (!entry) {
7646 continue;
7649 qdict_put_obj(d, *option_name, qobject_ref(entry));
7650 option_given = true;
7651 } else {
7652 const QDictEntry *entry;
7653 for (entry = qdict_first(bs->options); entry;
7654 entry = qdict_next(bs->options, entry))
7656 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7657 qdict_put_obj(d, qdict_entry_key(entry),
7658 qobject_ref(qdict_entry_value(entry)));
7659 option_given = true;
7664 /* While "driver" and "filename" need to be included in a JSON filename,
7665 * their existence does not prohibit generation of a plain filename. */
7666 if (!found_any && option_given &&
7667 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7669 found_any = true;
7673 if (!qdict_haskey(d, "driver")) {
7674 /* Drivers created with bdrv_new_open_driver() may not have a
7675 * @driver option. Add it here. */
7676 qdict_put_str(d, "driver", bs->drv->format_name);
7679 return found_any;
7682 /* Note: This function may return false positives; it may return true
7683 * even if opening the backing file specified by bs's image header
7684 * would result in exactly bs->backing. */
7685 static bool bdrv_backing_overridden(BlockDriverState *bs)
7687 GLOBAL_STATE_CODE();
7688 if (bs->backing) {
7689 return strcmp(bs->auto_backing_file,
7690 bs->backing->bs->filename);
7691 } else {
7692 /* No backing BDS, so if the image header reports any backing
7693 * file, it must have been suppressed */
7694 return bs->auto_backing_file[0] != '\0';
7698 /* Updates the following BDS fields:
7699 * - exact_filename: A filename which may be used for opening a block device
7700 * which (mostly) equals the given BDS (even without any
7701 * other options; so reading and writing must return the same
7702 * results, but caching etc. may be different)
7703 * - full_open_options: Options which, when given when opening a block device
7704 * (without a filename), result in a BDS (mostly)
7705 * equalling the given one
7706 * - filename: If exact_filename is set, it is copied here. Otherwise,
7707 * full_open_options is converted to a JSON object, prefixed with
7708 * "json:" (for use through the JSON pseudo protocol) and put here.
7710 void bdrv_refresh_filename(BlockDriverState *bs)
7712 BlockDriver *drv = bs->drv;
7713 BdrvChild *child;
7714 BlockDriverState *primary_child_bs;
7715 QDict *opts;
7716 bool backing_overridden;
7717 bool generate_json_filename; /* Whether our default implementation should
7718 fill exact_filename (false) or not (true) */
7720 GLOBAL_STATE_CODE();
7722 if (!drv) {
7723 return;
7726 /* This BDS's file name may depend on any of its children's file names, so
7727 * refresh those first */
7728 QLIST_FOREACH(child, &bs->children, next) {
7729 bdrv_refresh_filename(child->bs);
7732 if (bs->implicit) {
7733 /* For implicit nodes, just copy everything from the single child */
7734 child = QLIST_FIRST(&bs->children);
7735 assert(QLIST_NEXT(child, next) == NULL);
7737 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7738 child->bs->exact_filename);
7739 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7741 qobject_unref(bs->full_open_options);
7742 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7744 return;
7747 backing_overridden = bdrv_backing_overridden(bs);
7749 if (bs->open_flags & BDRV_O_NO_IO) {
7750 /* Without I/O, the backing file does not change anything.
7751 * Therefore, in such a case (primarily qemu-img), we can
7752 * pretend the backing file has not been overridden even if
7753 * it technically has been. */
7754 backing_overridden = false;
7757 /* Gather the options QDict */
7758 opts = qdict_new();
7759 generate_json_filename = append_strong_runtime_options(opts, bs);
7760 generate_json_filename |= backing_overridden;
7762 if (drv->bdrv_gather_child_options) {
7763 /* Some block drivers may not want to present all of their children's
7764 * options, or name them differently from BdrvChild.name */
7765 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7766 } else {
7767 QLIST_FOREACH(child, &bs->children, next) {
7768 if (child == bs->backing && !backing_overridden) {
7769 /* We can skip the backing BDS if it has not been overridden */
7770 continue;
7773 qdict_put(opts, child->name,
7774 qobject_ref(child->bs->full_open_options));
7777 if (backing_overridden && !bs->backing) {
7778 /* Force no backing file */
7779 qdict_put_null(opts, "backing");
7783 qobject_unref(bs->full_open_options);
7784 bs->full_open_options = opts;
7786 primary_child_bs = bdrv_primary_bs(bs);
7788 if (drv->bdrv_refresh_filename) {
7789 /* Obsolete information is of no use here, so drop the old file name
7790 * information before refreshing it */
7791 bs->exact_filename[0] = '\0';
7793 drv->bdrv_refresh_filename(bs);
7794 } else if (primary_child_bs) {
7796 * Try to reconstruct valid information from the underlying
7797 * file -- this only works for format nodes (filter nodes
7798 * cannot be probed and as such must be selected by the user
7799 * either through an options dict, or through a special
7800 * filename which the filter driver must construct in its
7801 * .bdrv_refresh_filename() implementation).
7804 bs->exact_filename[0] = '\0';
7807 * We can use the underlying file's filename if:
7808 * - it has a filename,
7809 * - the current BDS is not a filter,
7810 * - the file is a protocol BDS, and
7811 * - opening that file (as this BDS's format) will automatically create
7812 * the BDS tree we have right now, that is:
7813 * - the user did not significantly change this BDS's behavior with
7814 * some explicit (strong) options
7815 * - no non-file child of this BDS has been overridden by the user
7816 * Both of these conditions are represented by generate_json_filename.
7818 if (primary_child_bs->exact_filename[0] &&
7819 primary_child_bs->drv->bdrv_file_open &&
7820 !drv->is_filter && !generate_json_filename)
7822 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
7826 if (bs->exact_filename[0]) {
7827 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
7828 } else {
7829 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
7830 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
7831 json->str) >= sizeof(bs->filename)) {
7832 /* Give user a hint if we truncated things. */
7833 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7835 g_string_free(json, true);
7839 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7841 BlockDriver *drv = bs->drv;
7842 BlockDriverState *child_bs;
7844 GLOBAL_STATE_CODE();
7846 if (!drv) {
7847 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7848 return NULL;
7851 if (drv->bdrv_dirname) {
7852 return drv->bdrv_dirname(bs, errp);
7855 child_bs = bdrv_primary_bs(bs);
7856 if (child_bs) {
7857 return bdrv_dirname(child_bs, errp);
7860 bdrv_refresh_filename(bs);
7861 if (bs->exact_filename[0] != '\0') {
7862 return path_combine(bs->exact_filename, "");
7865 error_setg(errp, "Cannot generate a base directory for %s nodes",
7866 drv->format_name);
7867 return NULL;
7871 * Hot add/remove a BDS's child. So the user can take a child offline when
7872 * it is broken and take a new child online
7874 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7875 Error **errp)
7877 GLOBAL_STATE_CODE();
7878 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7879 error_setg(errp, "The node %s does not support adding a child",
7880 bdrv_get_device_or_node_name(parent_bs));
7881 return;
7884 if (!QLIST_EMPTY(&child_bs->parents)) {
7885 error_setg(errp, "The node %s already has a parent",
7886 child_bs->node_name);
7887 return;
7890 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7893 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7895 BdrvChild *tmp;
7897 GLOBAL_STATE_CODE();
7898 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7899 error_setg(errp, "The node %s does not support removing a child",
7900 bdrv_get_device_or_node_name(parent_bs));
7901 return;
7904 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7905 if (tmp == child) {
7906 break;
7910 if (!tmp) {
7911 error_setg(errp, "The node %s does not have a child named %s",
7912 bdrv_get_device_or_node_name(parent_bs),
7913 bdrv_get_device_or_node_name(child->bs));
7914 return;
7917 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7920 int bdrv_make_empty(BdrvChild *c, Error **errp)
7922 BlockDriver *drv = c->bs->drv;
7923 int ret;
7925 GLOBAL_STATE_CODE();
7926 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7928 if (!drv->bdrv_make_empty) {
7929 error_setg(errp, "%s does not support emptying nodes",
7930 drv->format_name);
7931 return -ENOTSUP;
7934 ret = drv->bdrv_make_empty(c->bs);
7935 if (ret < 0) {
7936 error_setg_errno(errp, -ret, "Failed to empty %s",
7937 c->bs->filename);
7938 return ret;
7941 return 0;
7945 * Return the child that @bs acts as an overlay for, and from which data may be
7946 * copied in COW or COR operations. Usually this is the backing file.
7948 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7950 IO_CODE();
7952 if (!bs || !bs->drv) {
7953 return NULL;
7956 if (bs->drv->is_filter) {
7957 return NULL;
7960 if (!bs->backing) {
7961 return NULL;
7964 assert(bs->backing->role & BDRV_CHILD_COW);
7965 return bs->backing;
7969 * If @bs acts as a filter for exactly one of its children, return
7970 * that child.
7972 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7974 BdrvChild *c;
7975 IO_CODE();
7977 if (!bs || !bs->drv) {
7978 return NULL;
7981 if (!bs->drv->is_filter) {
7982 return NULL;
7985 /* Only one of @backing or @file may be used */
7986 assert(!(bs->backing && bs->file));
7988 c = bs->backing ?: bs->file;
7989 if (!c) {
7990 return NULL;
7993 assert(c->role & BDRV_CHILD_FILTERED);
7994 return c;
7998 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7999 * whichever is non-NULL.
8001 * Return NULL if both are NULL.
8003 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8005 BdrvChild *cow_child = bdrv_cow_child(bs);
8006 BdrvChild *filter_child = bdrv_filter_child(bs);
8007 IO_CODE();
8009 /* Filter nodes cannot have COW backing files */
8010 assert(!(cow_child && filter_child));
8012 return cow_child ?: filter_child;
8016 * Return the primary child of this node: For filters, that is the
8017 * filtered child. For other nodes, that is usually the child storing
8018 * metadata.
8019 * (A generally more helpful description is that this is (usually) the
8020 * child that has the same filename as @bs.)
8022 * Drivers do not necessarily have a primary child; for example quorum
8023 * does not.
8025 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8027 BdrvChild *c, *found = NULL;
8028 IO_CODE();
8030 QLIST_FOREACH(c, &bs->children, next) {
8031 if (c->role & BDRV_CHILD_PRIMARY) {
8032 assert(!found);
8033 found = c;
8037 return found;
8040 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8041 bool stop_on_explicit_filter)
8043 BdrvChild *c;
8045 if (!bs) {
8046 return NULL;
8049 while (!(stop_on_explicit_filter && !bs->implicit)) {
8050 c = bdrv_filter_child(bs);
8051 if (!c) {
8053 * A filter that is embedded in a working block graph must
8054 * have a child. Assert this here so this function does
8055 * not return a filter node that is not expected by the
8056 * caller.
8058 assert(!bs->drv || !bs->drv->is_filter);
8059 break;
8061 bs = c->bs;
8064 * Note that this treats nodes with bs->drv == NULL as not being
8065 * filters (bs->drv == NULL should be replaced by something else
8066 * anyway).
8067 * The advantage of this behavior is that this function will thus
8068 * always return a non-NULL value (given a non-NULL @bs).
8071 return bs;
8075 * Return the first BDS that has not been added implicitly or that
8076 * does not have a filtered child down the chain starting from @bs
8077 * (including @bs itself).
8079 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8081 GLOBAL_STATE_CODE();
8082 return bdrv_do_skip_filters(bs, true);
8086 * Return the first BDS that does not have a filtered child down the
8087 * chain starting from @bs (including @bs itself).
8089 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8091 IO_CODE();
8092 return bdrv_do_skip_filters(bs, false);
8096 * For a backing chain, return the first non-filter backing image of
8097 * the first non-filter image.
8099 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8101 IO_CODE();
8102 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8106 * Check whether [offset, offset + bytes) overlaps with the cached
8107 * block-status data region.
8109 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8110 * which is what bdrv_bsc_is_data()'s interface needs.
8111 * Otherwise, *pnum is not touched.
8113 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8114 int64_t offset, int64_t bytes,
8115 int64_t *pnum)
8117 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8118 bool overlaps;
8120 overlaps =
8121 qatomic_read(&bsc->valid) &&
8122 ranges_overlap(offset, bytes, bsc->data_start,
8123 bsc->data_end - bsc->data_start);
8125 if (overlaps && pnum) {
8126 *pnum = bsc->data_end - offset;
8129 return overlaps;
8133 * See block_int.h for this function's documentation.
8135 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8137 IO_CODE();
8138 RCU_READ_LOCK_GUARD();
8139 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8143 * See block_int.h for this function's documentation.
8145 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8146 int64_t offset, int64_t bytes)
8148 IO_CODE();
8149 RCU_READ_LOCK_GUARD();
8151 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8152 qatomic_set(&bs->block_status_cache->valid, false);
8157 * See block_int.h for this function's documentation.
8159 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8161 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8162 BdrvBlockStatusCache *old_bsc;
8163 IO_CODE();
8165 *new_bsc = (BdrvBlockStatusCache) {
8166 .valid = true,
8167 .data_start = offset,
8168 .data_end = offset + bytes,
8171 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8173 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8174 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8175 if (old_bsc) {
8176 g_free_rcu(old_bsc, rcu);