Merge tag 'v9.0.0-rc3'
[qemu/ar7.git] / block.c
blob046a87d34b9da06a38411eef4ef6db78d3ff42ca
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
5 * Copyright (c) 2020 Virtuozzo International GmbH.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/dirty-bitmap.h"
31 #include "block/fuse.h"
32 #include "block/nbd.h"
33 #include "block/qdict.h"
34 #include "qemu/error-report.h"
35 #include "block/module_block.h"
36 #include "qemu/main-loop.h"
37 #include "qemu/module.h"
38 #include "qapi/error.h"
39 #include "qapi/qmp/qdict.h"
40 #include "qapi/qmp/qjson.h"
41 #include "qapi/qmp/qnull.h"
42 #include "qapi/qmp/qstring.h"
43 #include "qapi/qobject-output-visitor.h"
44 #include "qapi/qapi-visit-block-core.h"
45 #include "sysemu/block-backend.h"
46 #include "qemu/notify.h"
47 #include "qemu/option.h"
48 #include "qemu/coroutine.h"
49 #include "block/qapi.h"
50 #include "qemu/timer.h"
51 #include "qemu/cutils.h"
52 #include "qemu/id.h"
53 #include "qemu/range.h"
54 #include "qemu/rcu.h"
55 #include "block/coroutines.h"
57 #ifdef CONFIG_BSD
58 #include <sys/ioctl.h>
59 #include <sys/queue.h>
60 #if defined(HAVE_SYS_DISK_H)
61 #include <sys/disk.h>
62 #endif
63 #endif
65 #ifdef _WIN32
66 #include <windows.h>
67 #endif
69 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
71 /* Protected by BQL */
72 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
73 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
75 /* Protected by BQL */
76 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
77 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
79 /* Protected by BQL */
80 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
81 QLIST_HEAD_INITIALIZER(bdrv_drivers);
83 static BlockDriverState *bdrv_open_inherit(const char *filename,
84 const char *reference,
85 QDict *options, int flags,
86 BlockDriverState *parent,
87 const BdrvChildClass *child_class,
88 BdrvChildRole child_role,
89 Error **errp);
91 static bool bdrv_recurse_has_child(BlockDriverState *bs,
92 BlockDriverState *child);
94 static void GRAPH_WRLOCK
95 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs);
97 static void GRAPH_WRLOCK
98 bdrv_remove_child(BdrvChild *child, Transaction *tran);
100 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
101 BlockReopenQueue *queue,
102 Transaction *change_child_tran, Error **errp);
103 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
104 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
106 static bool bdrv_backing_overridden(BlockDriverState *bs);
108 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
109 GHashTable *visited, Transaction *tran,
110 Error **errp);
112 /* If non-zero, use only whitelisted block drivers */
113 static int use_bdrv_whitelist;
115 #ifdef _WIN32
116 static int is_windows_drive_prefix(const char *filename)
118 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
119 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
120 filename[1] == ':');
123 int is_windows_drive(const char *filename)
125 if (is_windows_drive_prefix(filename) &&
126 filename[2] == '\0')
127 return 1;
128 if (strstart(filename, "\\\\.\\", NULL) ||
129 strstart(filename, "//./", NULL))
130 return 1;
131 return 0;
133 #endif
135 size_t bdrv_opt_mem_align(BlockDriverState *bs)
137 if (!bs || !bs->drv) {
138 /* page size or 4k (hdd sector size) should be on the safe side */
139 return MAX(4096, qemu_real_host_page_size());
141 IO_CODE();
143 return bs->bl.opt_mem_alignment;
146 size_t bdrv_min_mem_align(BlockDriverState *bs)
148 if (!bs || !bs->drv) {
149 /* page size or 4k (hdd sector size) should be on the safe side */
150 return MAX(4096, qemu_real_host_page_size());
152 IO_CODE();
154 return bs->bl.min_mem_alignment;
157 /* check if the path starts with "<protocol>:" */
158 int path_has_protocol(const char *path)
160 const char *p;
162 #ifdef _WIN32
163 if (is_windows_drive(path) ||
164 is_windows_drive_prefix(path)) {
165 return 0;
167 p = path + strcspn(path, ":/\\");
168 #else
169 p = path + strcspn(path, ":/");
170 #endif
172 return *p == ':';
175 int path_is_absolute(const char *path)
177 #ifdef _WIN32
178 /* specific case for names like: "\\.\d:" */
179 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
180 return 1;
182 return (*path == '/' || *path == '\\');
183 #else
184 return (*path == '/');
185 #endif
188 /* if filename is absolute, just return its duplicate. Otherwise, build a
189 path to it by considering it is relative to base_path. URL are
190 supported. */
191 char *path_combine(const char *base_path, const char *filename)
193 const char *protocol_stripped = NULL;
194 const char *p, *p1;
195 char *result;
196 int len;
198 if (path_is_absolute(filename)) {
199 return g_strdup(filename);
202 if (path_has_protocol(base_path)) {
203 protocol_stripped = strchr(base_path, ':');
204 if (protocol_stripped) {
205 protocol_stripped++;
208 p = protocol_stripped ?: base_path;
210 p1 = strrchr(base_path, '/');
211 #ifdef _WIN32
213 const char *p2;
214 p2 = strrchr(base_path, '\\');
215 if (!p1 || p2 > p1) {
216 p1 = p2;
219 #endif
220 if (p1) {
221 p1++;
222 } else {
223 p1 = base_path;
225 if (p1 > p) {
226 p = p1;
228 len = p - base_path;
230 result = g_malloc(len + strlen(filename) + 1);
231 memcpy(result, base_path, len);
232 strcpy(result + len, filename);
234 return result;
238 * Helper function for bdrv_parse_filename() implementations to remove optional
239 * protocol prefixes (especially "file:") from a filename and for putting the
240 * stripped filename into the options QDict if there is such a prefix.
242 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
243 QDict *options)
245 if (strstart(filename, prefix, &filename)) {
246 /* Stripping the explicit protocol prefix may result in a protocol
247 * prefix being (wrongly) detected (if the filename contains a colon) */
248 if (path_has_protocol(filename)) {
249 GString *fat_filename;
251 /* This means there is some colon before the first slash; therefore,
252 * this cannot be an absolute path */
253 assert(!path_is_absolute(filename));
255 /* And we can thus fix the protocol detection issue by prefixing it
256 * by "./" */
257 fat_filename = g_string_new("./");
258 g_string_append(fat_filename, filename);
260 assert(!path_has_protocol(fat_filename->str));
262 qdict_put(options, "filename",
263 qstring_from_gstring(fat_filename));
264 } else {
265 /* If no protocol prefix was detected, we can use the shortened
266 * filename as-is */
267 qdict_put_str(options, "filename", filename);
273 /* Returns whether the image file is opened as read-only. Note that this can
274 * return false and writing to the image file is still not possible because the
275 * image is inactivated. */
276 bool bdrv_is_read_only(BlockDriverState *bs)
278 IO_CODE();
279 return !(bs->open_flags & BDRV_O_RDWR);
282 static int GRAPH_RDLOCK
283 bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
284 bool ignore_allow_rdw, Error **errp)
286 IO_CODE();
288 /* Do not set read_only if copy_on_read is enabled */
289 if (bs->copy_on_read && read_only) {
290 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
291 bdrv_get_device_or_node_name(bs));
292 return -EINVAL;
295 /* Do not clear read_only if it is prohibited */
296 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
297 !ignore_allow_rdw)
299 error_setg(errp, "Node '%s' is read only",
300 bdrv_get_device_or_node_name(bs));
301 return -EPERM;
304 return 0;
308 * Called by a driver that can only provide a read-only image.
310 * Returns 0 if the node is already read-only or it could switch the node to
311 * read-only because BDRV_O_AUTO_RDONLY is set.
313 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
314 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
315 * is not NULL, it is used as the error message for the Error object.
317 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
318 Error **errp)
320 int ret = 0;
321 IO_CODE();
323 if (!(bs->open_flags & BDRV_O_RDWR)) {
324 return 0;
326 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
327 goto fail;
330 ret = bdrv_can_set_read_only(bs, true, false, NULL);
331 if (ret < 0) {
332 goto fail;
335 bs->open_flags &= ~BDRV_O_RDWR;
337 return 0;
339 fail:
340 error_setg(errp, "%s", errmsg ?: "Image is read-only");
341 return -EACCES;
345 * If @backing is empty, this function returns NULL without setting
346 * @errp. In all other cases, NULL will only be returned with @errp
347 * set.
349 * Therefore, a return value of NULL without @errp set means that
350 * there is no backing file; if @errp is set, there is one but its
351 * absolute filename cannot be generated.
353 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
354 const char *backing,
355 Error **errp)
357 if (backing[0] == '\0') {
358 return NULL;
359 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
360 return g_strdup(backing);
361 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
362 error_setg(errp, "Cannot use relative backing file names for '%s'",
363 backed);
364 return NULL;
365 } else {
366 return path_combine(backed, backing);
371 * If @filename is empty or NULL, this function returns NULL without
372 * setting @errp. In all other cases, NULL will only be returned with
373 * @errp set.
375 static char * GRAPH_RDLOCK
376 bdrv_make_absolute_filename(BlockDriverState *relative_to,
377 const char *filename, Error **errp)
379 char *dir, *full_name;
381 if (!filename || filename[0] == '\0') {
382 return NULL;
383 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
384 return g_strdup(filename);
387 dir = bdrv_dirname(relative_to, errp);
388 if (!dir) {
389 return NULL;
392 full_name = g_strconcat(dir, filename, NULL);
393 g_free(dir);
394 return full_name;
397 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
399 GLOBAL_STATE_CODE();
400 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
403 void bdrv_register(BlockDriver *bdrv)
405 assert(bdrv->format_name);
406 GLOBAL_STATE_CODE();
407 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
410 BlockDriverState *bdrv_new(void)
412 BlockDriverState *bs;
413 int i;
415 GLOBAL_STATE_CODE();
417 bs = g_new0(BlockDriverState, 1);
418 QLIST_INIT(&bs->dirty_bitmaps);
419 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
420 QLIST_INIT(&bs->op_blockers[i]);
422 qemu_mutex_init(&bs->reqs_lock);
423 qemu_mutex_init(&bs->dirty_bitmap_mutex);
424 bs->refcnt = 1;
425 bs->aio_context = qemu_get_aio_context();
427 qemu_co_queue_init(&bs->flush_queue);
429 qemu_co_mutex_init(&bs->bsc_modify_lock);
430 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
432 for (i = 0; i < bdrv_drain_all_count; i++) {
433 bdrv_drained_begin(bs);
436 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
438 return bs;
441 static BlockDriver *bdrv_do_find_format(const char *format_name)
443 BlockDriver *drv1;
444 GLOBAL_STATE_CODE();
446 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
447 if (!strcmp(drv1->format_name, format_name)) {
448 return drv1;
452 return NULL;
455 BlockDriver *bdrv_find_format(const char *format_name)
457 BlockDriver *drv1;
458 int i;
460 GLOBAL_STATE_CODE();
462 drv1 = bdrv_do_find_format(format_name);
463 if (drv1) {
464 return drv1;
467 /* The driver isn't registered, maybe we need to load a module */
468 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
469 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
470 Error *local_err = NULL;
471 int rv = block_module_load(block_driver_modules[i].library_name,
472 &local_err);
473 if (rv > 0) {
474 return bdrv_do_find_format(format_name);
475 } else if (rv < 0) {
476 error_report_err(local_err);
478 break;
481 return NULL;
484 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
486 static const char *whitelist_rw[] = {
487 CONFIG_BDRV_RW_WHITELIST
488 NULL
490 static const char *whitelist_ro[] = {
491 CONFIG_BDRV_RO_WHITELIST
492 NULL
494 const char **p;
496 if (!whitelist_rw[0] && !whitelist_ro[0]) {
497 return 1; /* no whitelist, anything goes */
500 for (p = whitelist_rw; *p; p++) {
501 if (!strcmp(format_name, *p)) {
502 return 1;
505 if (read_only) {
506 for (p = whitelist_ro; *p; p++) {
507 if (!strcmp(format_name, *p)) {
508 return 1;
512 return 0;
515 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
517 GLOBAL_STATE_CODE();
518 return bdrv_format_is_whitelisted(drv->format_name, read_only);
521 bool bdrv_uses_whitelist(void)
523 return use_bdrv_whitelist;
526 typedef struct CreateCo {
527 BlockDriver *drv;
528 char *filename;
529 QemuOpts *opts;
530 int ret;
531 Error *err;
532 } CreateCo;
534 int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
535 QemuOpts *opts, Error **errp)
537 ERRP_GUARD();
538 int ret;
539 GLOBAL_STATE_CODE();
541 if (!drv->bdrv_co_create_opts) {
542 error_setg(errp, "Driver '%s' does not support image creation",
543 drv->format_name);
544 return -ENOTSUP;
547 ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
548 if (ret < 0 && !*errp) {
549 error_setg_errno(errp, -ret, "Could not create image");
552 return ret;
556 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
557 * least the given @minimum_size.
559 * On success, return @blk's actual length.
560 * Otherwise, return -errno.
562 static int64_t coroutine_fn GRAPH_UNLOCKED
563 create_file_fallback_truncate(BlockBackend *blk, int64_t minimum_size,
564 Error **errp)
566 Error *local_err = NULL;
567 int64_t size;
568 int ret;
570 GLOBAL_STATE_CODE();
572 ret = blk_co_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
573 &local_err);
574 if (ret < 0 && ret != -ENOTSUP) {
575 error_propagate(errp, local_err);
576 return ret;
579 size = blk_co_getlength(blk);
580 if (size < 0) {
581 error_free(local_err);
582 error_setg_errno(errp, -size,
583 "Failed to inquire the new image file's length");
584 return size;
587 if (size < minimum_size) {
588 /* Need to grow the image, but we failed to do that */
589 error_propagate(errp, local_err);
590 return -ENOTSUP;
593 error_free(local_err);
594 local_err = NULL;
596 return size;
600 * Helper function for bdrv_create_file_fallback(): Zero the first
601 * sector to remove any potentially pre-existing image header.
603 static int coroutine_fn
604 create_file_fallback_zero_first_sector(BlockBackend *blk,
605 int64_t current_size,
606 Error **errp)
608 int64_t bytes_to_clear;
609 int ret;
611 GLOBAL_STATE_CODE();
613 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
614 if (bytes_to_clear) {
615 ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
616 if (ret < 0) {
617 error_setg_errno(errp, -ret,
618 "Failed to clear the new image's first sector");
619 return ret;
623 return 0;
627 * Simple implementation of bdrv_co_create_opts for protocol drivers
628 * which only support creation via opening a file
629 * (usually existing raw storage device)
631 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
632 const char *filename,
633 QemuOpts *opts,
634 Error **errp)
636 ERRP_GUARD();
637 BlockBackend *blk;
638 QDict *options;
639 int64_t size = 0;
640 char *buf = NULL;
641 PreallocMode prealloc;
642 Error *local_err = NULL;
643 int ret;
645 GLOBAL_STATE_CODE();
647 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
648 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
649 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
650 PREALLOC_MODE_OFF, &local_err);
651 g_free(buf);
652 if (local_err) {
653 error_propagate(errp, local_err);
654 return -EINVAL;
657 if (prealloc != PREALLOC_MODE_OFF) {
658 error_setg(errp, "Unsupported preallocation mode '%s'",
659 PreallocMode_str(prealloc));
660 return -ENOTSUP;
663 options = qdict_new();
664 qdict_put_str(options, "driver", drv->format_name);
666 blk = blk_co_new_open(filename, NULL, options,
667 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
668 if (!blk) {
669 error_prepend(errp, "Protocol driver '%s' does not support creating "
670 "new images, so an existing image must be selected as "
671 "the target; however, opening the given target as an "
672 "existing image failed: ",
673 drv->format_name);
674 return -EINVAL;
677 size = create_file_fallback_truncate(blk, size, errp);
678 if (size < 0) {
679 ret = size;
680 goto out;
683 ret = create_file_fallback_zero_first_sector(blk, size, errp);
684 if (ret < 0) {
685 goto out;
688 ret = 0;
689 out:
690 blk_co_unref(blk);
691 return ret;
694 int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
695 Error **errp)
697 QemuOpts *protocol_opts;
698 BlockDriver *drv;
699 QDict *qdict;
700 int ret;
702 GLOBAL_STATE_CODE();
704 drv = bdrv_find_protocol(filename, true, errp);
705 if (drv == NULL) {
706 return -ENOENT;
709 if (!drv->create_opts) {
710 error_setg(errp, "Driver '%s' does not support image creation",
711 drv->format_name);
712 return -ENOTSUP;
716 * 'opts' contains a QemuOptsList with a combination of format and protocol
717 * default values.
719 * The format properly removes its options, but the default values remain
720 * in 'opts->list'. So if the protocol has options with the same name
721 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
722 * of the format, since for overlapping options, the format wins.
724 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
725 * only the set options, and then convert it back to QemuOpts, using the
726 * create_opts of the protocol. So the new QemuOpts, will contain only the
727 * protocol defaults.
729 qdict = qemu_opts_to_qdict(opts, NULL);
730 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
731 if (protocol_opts == NULL) {
732 ret = -EINVAL;
733 goto out;
736 ret = bdrv_co_create(drv, filename, protocol_opts, errp);
737 out:
738 qemu_opts_del(protocol_opts);
739 qobject_unref(qdict);
740 return ret;
743 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
745 Error *local_err = NULL;
746 int ret;
748 IO_CODE();
749 assert(bs != NULL);
750 assert_bdrv_graph_readable();
752 if (!bs->drv) {
753 error_setg(errp, "Block node '%s' is not opened", bs->filename);
754 return -ENOMEDIUM;
757 if (!bs->drv->bdrv_co_delete_file) {
758 error_setg(errp, "Driver '%s' does not support image deletion",
759 bs->drv->format_name);
760 return -ENOTSUP;
763 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
764 if (ret < 0) {
765 error_propagate(errp, local_err);
768 return ret;
771 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
773 Error *local_err = NULL;
774 int ret;
775 IO_CODE();
777 if (!bs) {
778 return;
781 ret = bdrv_co_delete_file(bs, &local_err);
783 * ENOTSUP will happen if the block driver doesn't support
784 * the 'bdrv_co_delete_file' interface. This is a predictable
785 * scenario and shouldn't be reported back to the user.
787 if (ret == -ENOTSUP) {
788 error_free(local_err);
789 } else if (ret < 0) {
790 error_report_err(local_err);
795 * Try to get @bs's logical and physical block size.
796 * On success, store them in @bsz struct and return 0.
797 * On failure return -errno.
798 * @bs must not be empty.
800 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
802 BlockDriver *drv = bs->drv;
803 BlockDriverState *filtered = bdrv_filter_bs(bs);
804 GLOBAL_STATE_CODE();
806 if (drv && drv->bdrv_probe_blocksizes) {
807 return drv->bdrv_probe_blocksizes(bs, bsz);
808 } else if (filtered) {
809 return bdrv_probe_blocksizes(filtered, bsz);
812 return -ENOTSUP;
816 * Try to get @bs's geometry (cyls, heads, sectors).
817 * On success, store them in @geo struct and return 0.
818 * On failure return -errno.
819 * @bs must not be empty.
821 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
823 BlockDriver *drv = bs->drv;
824 BlockDriverState *filtered;
826 GLOBAL_STATE_CODE();
827 GRAPH_RDLOCK_GUARD_MAINLOOP();
829 if (drv && drv->bdrv_probe_geometry) {
830 return drv->bdrv_probe_geometry(bs, geo);
833 filtered = bdrv_filter_bs(bs);
834 if (filtered) {
835 return bdrv_probe_geometry(filtered, geo);
838 return -ENOTSUP;
842 * Create a uniquely-named empty temporary file.
843 * Return the actual file name used upon success, otherwise NULL.
844 * This string should be freed with g_free() when not needed any longer.
846 * Note: creating a temporary file for the caller to (re)open is
847 * inherently racy. Use g_file_open_tmp() instead whenever practical.
849 char *create_tmp_file(Error **errp)
851 int fd;
852 const char *tmpdir;
853 g_autofree char *filename = NULL;
855 tmpdir = g_get_tmp_dir();
856 #ifndef _WIN32
858 * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
860 * This function is used to create temporary disk images (like -snapshot),
861 * so the files can become very large. /tmp is often a tmpfs where as
862 * /var/tmp is usually on a disk, so more appropriate for disk images.
864 if (!g_strcmp0(tmpdir, "/tmp")) {
865 tmpdir = "/var/tmp";
867 #endif
869 filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
870 fd = g_mkstemp(filename);
871 if (fd < 0) {
872 error_setg_errno(errp, errno, "Could not open temporary file '%s'",
873 filename);
874 return NULL;
876 close(fd);
878 return g_steal_pointer(&filename);
882 * Detect host devices. By convention, /dev/cdrom[N] is always
883 * recognized as a host CDROM.
885 static BlockDriver *find_hdev_driver(const char *filename)
887 int score_max = 0, score;
888 BlockDriver *drv = NULL, *d;
889 GLOBAL_STATE_CODE();
891 QLIST_FOREACH(d, &bdrv_drivers, list) {
892 if (d->bdrv_probe_device) {
893 score = d->bdrv_probe_device(filename);
894 if (score > score_max) {
895 score_max = score;
896 drv = d;
901 return drv;
904 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
906 BlockDriver *drv1;
907 GLOBAL_STATE_CODE();
909 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
910 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
911 return drv1;
915 return NULL;
918 BlockDriver *bdrv_find_protocol(const char *filename,
919 bool allow_protocol_prefix,
920 Error **errp)
922 BlockDriver *drv1;
923 char protocol[128];
924 int len;
925 const char *p;
926 int i;
928 GLOBAL_STATE_CODE();
929 /* TODO Drivers without bdrv_file_open must be specified explicitly */
932 * XXX(hch): we really should not let host device detection
933 * override an explicit protocol specification, but moving this
934 * later breaks access to device names with colons in them.
935 * Thanks to the brain-dead persistent naming schemes on udev-
936 * based Linux systems those actually are quite common.
938 drv1 = find_hdev_driver(filename);
939 if (drv1) {
940 return drv1;
943 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
944 return &bdrv_file;
947 p = strchr(filename, ':');
948 assert(p != NULL);
949 len = p - filename;
950 if (len > sizeof(protocol) - 1)
951 len = sizeof(protocol) - 1;
952 memcpy(protocol, filename, len);
953 protocol[len] = '\0';
955 drv1 = bdrv_do_find_protocol(protocol);
956 if (drv1) {
957 return drv1;
960 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
961 if (block_driver_modules[i].protocol_name &&
962 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
963 int rv = block_module_load(block_driver_modules[i].library_name, errp);
964 if (rv > 0) {
965 drv1 = bdrv_do_find_protocol(protocol);
966 } else if (rv < 0) {
967 return NULL;
969 break;
973 if (!drv1) {
974 error_setg(errp, "Unknown protocol '%s'", protocol);
976 return drv1;
980 * Guess image format by probing its contents.
981 * This is not a good idea when your image is raw (CVE-2008-2004), but
982 * we do it anyway for backward compatibility.
984 * @buf contains the image's first @buf_size bytes.
985 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
986 * but can be smaller if the image file is smaller)
987 * @filename is its filename.
989 * For all block drivers, call the bdrv_probe() method to get its
990 * probing score.
991 * Return the first block driver with the highest probing score.
993 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
994 const char *filename)
996 int score_max = 0, score;
997 BlockDriver *drv = NULL, *d;
998 IO_CODE();
1000 QLIST_FOREACH(d, &bdrv_drivers, list) {
1001 if (d->bdrv_probe) {
1002 score = d->bdrv_probe(buf, buf_size, filename);
1003 if (score > score_max) {
1004 score_max = score;
1005 drv = d;
1010 return drv;
1013 static int find_image_format(BlockBackend *file, const char *filename,
1014 BlockDriver **pdrv, Error **errp)
1016 BlockDriver *drv;
1017 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1018 int ret = 0;
1020 GLOBAL_STATE_CODE();
1022 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1023 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1024 *pdrv = &bdrv_raw;
1025 return ret;
1028 ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1029 if (ret < 0) {
1030 error_setg_errno(errp, -ret, "Could not read image for determining its "
1031 "format");
1032 *pdrv = NULL;
1033 return ret;
1036 drv = bdrv_probe_all(buf, sizeof(buf), filename);
1037 if (!drv) {
1038 error_setg(errp, "Could not determine image format: No compatible "
1039 "driver found");
1040 *pdrv = NULL;
1041 return -ENOENT;
1044 *pdrv = drv;
1045 return 0;
1049 * Set the current 'total_sectors' value
1050 * Return 0 on success, -errno on error.
1052 int coroutine_fn bdrv_co_refresh_total_sectors(BlockDriverState *bs,
1053 int64_t hint)
1055 BlockDriver *drv = bs->drv;
1056 IO_CODE();
1057 assert_bdrv_graph_readable();
1059 if (!drv) {
1060 return -ENOMEDIUM;
1063 /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
1064 if (bdrv_is_sg(bs))
1065 return 0;
1067 /* query actual device if possible, otherwise just trust the hint */
1068 if (drv->bdrv_co_getlength) {
1069 int64_t length = drv->bdrv_co_getlength(bs);
1070 if (length < 0) {
1071 return length;
1073 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1076 bs->total_sectors = hint;
1078 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1079 return -EFBIG;
1082 return 0;
1086 * Combines a QDict of new block driver @options with any missing options taken
1087 * from @old_options, so that leaving out an option defaults to its old value.
1089 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1090 QDict *old_options)
1092 GLOBAL_STATE_CODE();
1093 if (bs->drv && bs->drv->bdrv_join_options) {
1094 bs->drv->bdrv_join_options(options, old_options);
1095 } else {
1096 qdict_join(options, old_options, false);
1100 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1101 int open_flags,
1102 Error **errp)
1104 Error *local_err = NULL;
1105 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1106 BlockdevDetectZeroesOptions detect_zeroes =
1107 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1108 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1109 GLOBAL_STATE_CODE();
1110 g_free(value);
1111 if (local_err) {
1112 error_propagate(errp, local_err);
1113 return detect_zeroes;
1116 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1117 !(open_flags & BDRV_O_UNMAP))
1119 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1120 "without setting discard operation to unmap");
1123 return detect_zeroes;
1127 * Set open flags for aio engine
1129 * Return 0 on success, -1 if the engine specified is invalid
1131 int bdrv_parse_aio(const char *mode, int *flags)
1133 if (!strcmp(mode, "threads")) {
1134 /* do nothing, default */
1135 } else if (!strcmp(mode, "native")) {
1136 *flags |= BDRV_O_NATIVE_AIO;
1137 #ifdef CONFIG_LINUX_IO_URING
1138 } else if (!strcmp(mode, "io_uring")) {
1139 *flags |= BDRV_O_IO_URING;
1140 #endif
1141 } else {
1142 return -1;
1145 return 0;
1149 * Set open flags for a given discard mode
1151 * Return 0 on success, -1 if the discard mode was invalid.
1153 int bdrv_parse_discard_flags(const char *mode, int *flags)
1155 *flags &= ~BDRV_O_UNMAP;
1157 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1158 /* do nothing */
1159 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1160 *flags |= BDRV_O_UNMAP;
1161 } else {
1162 return -1;
1165 return 0;
1169 * Set open flags for a given cache mode
1171 * Return 0 on success, -1 if the cache mode was invalid.
1173 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1175 *flags &= ~BDRV_O_CACHE_MASK;
1177 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1178 *writethrough = false;
1179 *flags |= BDRV_O_NOCACHE;
1180 } else if (!strcmp(mode, "directsync")) {
1181 *writethrough = true;
1182 *flags |= BDRV_O_NOCACHE;
1183 } else if (!strcmp(mode, "writeback")) {
1184 *writethrough = false;
1185 } else if (!strcmp(mode, "unsafe")) {
1186 *writethrough = false;
1187 *flags |= BDRV_O_NO_FLUSH;
1188 } else if (!strcmp(mode, "writethrough")) {
1189 *writethrough = true;
1190 } else {
1191 return -1;
1194 return 0;
1197 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1199 BlockDriverState *parent = c->opaque;
1200 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1203 static void GRAPH_RDLOCK bdrv_child_cb_drained_begin(BdrvChild *child)
1205 BlockDriverState *bs = child->opaque;
1206 bdrv_do_drained_begin_quiesce(bs, NULL);
1209 static bool GRAPH_RDLOCK bdrv_child_cb_drained_poll(BdrvChild *child)
1211 BlockDriverState *bs = child->opaque;
1212 return bdrv_drain_poll(bs, NULL, false);
1215 static void GRAPH_RDLOCK bdrv_child_cb_drained_end(BdrvChild *child)
1217 BlockDriverState *bs = child->opaque;
1218 bdrv_drained_end(bs);
1221 static int bdrv_child_cb_inactivate(BdrvChild *child)
1223 BlockDriverState *bs = child->opaque;
1224 GLOBAL_STATE_CODE();
1225 assert(bs->open_flags & BDRV_O_INACTIVE);
1226 return 0;
1229 static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1230 GHashTable *visited, Transaction *tran,
1231 Error **errp)
1233 BlockDriverState *bs = child->opaque;
1234 return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
1238 * Returns the options and flags that a temporary snapshot should get, based on
1239 * the originally requested flags (the originally requested image will have
1240 * flags like a backing file)
1242 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1243 int parent_flags, QDict *parent_options)
1245 GLOBAL_STATE_CODE();
1246 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1248 /* For temporary files, unconditional cache=unsafe is fine */
1249 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1250 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1252 /* Copy the read-only and discard options from the parent */
1253 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1254 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1256 /* aio=native doesn't work for cache.direct=off, so disable it for the
1257 * temporary snapshot */
1258 *child_flags &= ~BDRV_O_NATIVE_AIO;
1261 static void GRAPH_WRLOCK bdrv_backing_attach(BdrvChild *c)
1263 BlockDriverState *parent = c->opaque;
1264 BlockDriverState *backing_hd = c->bs;
1266 GLOBAL_STATE_CODE();
1267 assert(!parent->backing_blocker);
1268 error_setg(&parent->backing_blocker,
1269 "node is used as backing hd of '%s'",
1270 bdrv_get_device_or_node_name(parent));
1272 bdrv_refresh_filename(backing_hd);
1274 parent->open_flags &= ~BDRV_O_NO_BACKING;
1276 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1277 /* Otherwise we won't be able to commit or stream */
1278 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1279 parent->backing_blocker);
1280 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1281 parent->backing_blocker);
1283 * We do backup in 3 ways:
1284 * 1. drive backup
1285 * The target bs is new opened, and the source is top BDS
1286 * 2. blockdev backup
1287 * Both the source and the target are top BDSes.
1288 * 3. internal backup(used for block replication)
1289 * Both the source and the target are backing file
1291 * In case 1 and 2, neither the source nor the target is the backing file.
1292 * In case 3, we will block the top BDS, so there is only one block job
1293 * for the top BDS and its backing chain.
1295 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1296 parent->backing_blocker);
1297 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1298 parent->backing_blocker);
1301 static void bdrv_backing_detach(BdrvChild *c)
1303 BlockDriverState *parent = c->opaque;
1305 GLOBAL_STATE_CODE();
1306 assert(parent->backing_blocker);
1307 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1308 error_free(parent->backing_blocker);
1309 parent->backing_blocker = NULL;
1312 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1313 const char *filename,
1314 bool backing_mask_protocol,
1315 Error **errp)
1317 BlockDriverState *parent = c->opaque;
1318 bool read_only = bdrv_is_read_only(parent);
1319 int ret;
1320 const char *format_name;
1321 GLOBAL_STATE_CODE();
1323 if (read_only) {
1324 ret = bdrv_reopen_set_read_only(parent, false, errp);
1325 if (ret < 0) {
1326 return ret;
1330 if (base->drv) {
1332 * If the new base image doesn't have a format driver layer, which we
1333 * detect by the fact that @base is a protocol driver, we record
1334 * 'raw' as the format instead of putting the protocol name as the
1335 * backing format
1337 if (backing_mask_protocol && base->drv->protocol_name) {
1338 format_name = "raw";
1339 } else {
1340 format_name = base->drv->format_name;
1342 } else {
1343 format_name = "";
1346 ret = bdrv_change_backing_file(parent, filename, format_name, false);
1347 if (ret < 0) {
1348 error_setg_errno(errp, -ret, "Could not update backing file link");
1351 if (read_only) {
1352 bdrv_reopen_set_read_only(parent, true, NULL);
1355 return ret;
1359 * Returns the options and flags that a generic child of a BDS should
1360 * get, based on the given options and flags for the parent BDS.
1362 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1363 int *child_flags, QDict *child_options,
1364 int parent_flags, QDict *parent_options)
1366 int flags = parent_flags;
1367 GLOBAL_STATE_CODE();
1370 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1371 * Generally, the question to answer is: Should this child be
1372 * format-probed by default?
1376 * Pure and non-filtered data children of non-format nodes should
1377 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1378 * set). This only affects a very limited set of drivers (namely
1379 * quorum and blkverify when this comment was written).
1380 * Force-clear BDRV_O_PROTOCOL then.
1382 if (!parent_is_format &&
1383 (role & BDRV_CHILD_DATA) &&
1384 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1386 flags &= ~BDRV_O_PROTOCOL;
1390 * All children of format nodes (except for COW children) and all
1391 * metadata children in general should never be format-probed.
1392 * Force-set BDRV_O_PROTOCOL then.
1394 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1395 (role & BDRV_CHILD_METADATA))
1397 flags |= BDRV_O_PROTOCOL;
1401 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1402 * the parent.
1404 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1405 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1406 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1408 if (role & BDRV_CHILD_COW) {
1409 /* backing files are opened read-only by default */
1410 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1411 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1412 } else {
1413 /* Inherit the read-only option from the parent if it's not set */
1414 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1415 qdict_copy_default(child_options, parent_options,
1416 BDRV_OPT_AUTO_READ_ONLY);
1420 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1421 * can default to enable it on lower layers regardless of the
1422 * parent option.
1424 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1426 /* Clear flags that only apply to the top layer */
1427 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1429 if (role & BDRV_CHILD_METADATA) {
1430 flags &= ~BDRV_O_NO_IO;
1432 if (role & BDRV_CHILD_COW) {
1433 flags &= ~BDRV_O_TEMPORARY;
1436 *child_flags = flags;
1439 static void GRAPH_WRLOCK bdrv_child_cb_attach(BdrvChild *child)
1441 BlockDriverState *bs = child->opaque;
1443 assert_bdrv_graph_writable();
1444 QLIST_INSERT_HEAD(&bs->children, child, next);
1445 if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1447 * Here we handle filters and block/raw-format.c when it behave like
1448 * filter. They generally have a single PRIMARY child, which is also the
1449 * FILTERED child, and that they may have multiple more children, which
1450 * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1451 * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1452 * into bs->backing on exceptional cases; and bs->backing will be
1453 * nothing else.
1455 assert(!(child->role & BDRV_CHILD_COW));
1456 if (child->role & BDRV_CHILD_PRIMARY) {
1457 assert(child->role & BDRV_CHILD_FILTERED);
1458 assert(!bs->backing);
1459 assert(!bs->file);
1461 if (bs->drv->filtered_child_is_backing) {
1462 bs->backing = child;
1463 } else {
1464 bs->file = child;
1466 } else {
1467 assert(!(child->role & BDRV_CHILD_FILTERED));
1469 } else if (child->role & BDRV_CHILD_COW) {
1470 assert(bs->drv->supports_backing);
1471 assert(!(child->role & BDRV_CHILD_PRIMARY));
1472 assert(!bs->backing);
1473 bs->backing = child;
1474 bdrv_backing_attach(child);
1475 } else if (child->role & BDRV_CHILD_PRIMARY) {
1476 assert(!bs->file);
1477 bs->file = child;
1481 static void GRAPH_WRLOCK bdrv_child_cb_detach(BdrvChild *child)
1483 BlockDriverState *bs = child->opaque;
1485 if (child->role & BDRV_CHILD_COW) {
1486 bdrv_backing_detach(child);
1489 assert_bdrv_graph_writable();
1490 QLIST_REMOVE(child, next);
1491 if (child == bs->backing) {
1492 assert(child != bs->file);
1493 bs->backing = NULL;
1494 } else if (child == bs->file) {
1495 bs->file = NULL;
1499 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1500 const char *filename,
1501 bool backing_mask_protocol,
1502 Error **errp)
1504 if (c->role & BDRV_CHILD_COW) {
1505 return bdrv_backing_update_filename(c, base, filename,
1506 backing_mask_protocol,
1507 errp);
1509 return 0;
1512 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1514 BlockDriverState *bs = c->opaque;
1515 IO_CODE();
1517 return bdrv_get_aio_context(bs);
1520 const BdrvChildClass child_of_bds = {
1521 .parent_is_bds = true,
1522 .get_parent_desc = bdrv_child_get_parent_desc,
1523 .inherit_options = bdrv_inherited_options,
1524 .drained_begin = bdrv_child_cb_drained_begin,
1525 .drained_poll = bdrv_child_cb_drained_poll,
1526 .drained_end = bdrv_child_cb_drained_end,
1527 .attach = bdrv_child_cb_attach,
1528 .detach = bdrv_child_cb_detach,
1529 .inactivate = bdrv_child_cb_inactivate,
1530 .change_aio_ctx = bdrv_child_cb_change_aio_ctx,
1531 .update_filename = bdrv_child_cb_update_filename,
1532 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1535 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1537 IO_CODE();
1538 return c->klass->get_parent_aio_context(c);
1541 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1543 int open_flags = flags;
1544 GLOBAL_STATE_CODE();
1547 * Clear flags that are internal to the block layer before opening the
1548 * image.
1550 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1552 return open_flags;
1555 static void update_flags_from_options(int *flags, QemuOpts *opts)
1557 GLOBAL_STATE_CODE();
1559 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1561 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1562 *flags |= BDRV_O_NO_FLUSH;
1565 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1566 *flags |= BDRV_O_NOCACHE;
1569 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1570 *flags |= BDRV_O_RDWR;
1573 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1574 *flags |= BDRV_O_AUTO_RDONLY;
1578 static void update_options_from_flags(QDict *options, int flags)
1580 GLOBAL_STATE_CODE();
1581 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1582 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1584 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1585 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1586 flags & BDRV_O_NO_FLUSH);
1588 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1589 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1591 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1592 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1593 flags & BDRV_O_AUTO_RDONLY);
1597 static void bdrv_assign_node_name(BlockDriverState *bs,
1598 const char *node_name,
1599 Error **errp)
1601 char *gen_node_name = NULL;
1602 GLOBAL_STATE_CODE();
1604 if (!node_name) {
1605 node_name = gen_node_name = id_generate(ID_BLOCK);
1606 } else if (!id_wellformed(node_name)) {
1608 * Check for empty string or invalid characters, but not if it is
1609 * generated (generated names use characters not available to the user)
1611 error_setg(errp, "Invalid node-name: '%s'", node_name);
1612 return;
1615 /* takes care of avoiding namespaces collisions */
1616 if (blk_by_name(node_name)) {
1617 error_setg(errp, "node-name=%s is conflicting with a device id",
1618 node_name);
1619 goto out;
1622 /* takes care of avoiding duplicates node names */
1623 if (bdrv_find_node(node_name)) {
1624 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1625 goto out;
1628 /* Make sure that the node name isn't truncated */
1629 if (strlen(node_name) >= sizeof(bs->node_name)) {
1630 error_setg(errp, "Node name too long");
1631 goto out;
1634 /* copy node name into the bs and insert it into the graph list */
1635 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1636 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1637 out:
1638 g_free(gen_node_name);
1641 static int no_coroutine_fn GRAPH_UNLOCKED
1642 bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, const char *node_name,
1643 QDict *options, int open_flags, Error **errp)
1645 Error *local_err = NULL;
1646 int i, ret;
1647 GLOBAL_STATE_CODE();
1649 bdrv_assign_node_name(bs, node_name, &local_err);
1650 if (local_err) {
1651 error_propagate(errp, local_err);
1652 return -EINVAL;
1655 bs->drv = drv;
1656 bs->opaque = g_malloc0(drv->instance_size);
1658 if (drv->bdrv_file_open) {
1659 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1660 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1661 } else if (drv->bdrv_open) {
1662 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1663 } else {
1664 ret = 0;
1667 if (ret < 0) {
1668 if (local_err) {
1669 error_propagate(errp, local_err);
1670 } else if (bs->filename[0]) {
1671 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1672 } else {
1673 error_setg_errno(errp, -ret, "Could not open image");
1675 goto open_failed;
1678 assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1679 assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1682 * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1683 * drivers that pass read/write requests through to a child the trouble of
1684 * declaring support explicitly.
1686 * Drivers must not propagate this flag accidentally when they initiate I/O
1687 * to a bounce buffer. That case should be rare though.
1689 bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1690 bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1692 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
1693 if (ret < 0) {
1694 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1695 return ret;
1698 bdrv_graph_rdlock_main_loop();
1699 bdrv_refresh_limits(bs, NULL, &local_err);
1700 bdrv_graph_rdunlock_main_loop();
1702 if (local_err) {
1703 error_propagate(errp, local_err);
1704 return -EINVAL;
1707 assert(bdrv_opt_mem_align(bs) != 0);
1708 assert(bdrv_min_mem_align(bs) != 0);
1709 assert(is_power_of_2(bs->bl.request_alignment));
1711 for (i = 0; i < bs->quiesce_counter; i++) {
1712 if (drv->bdrv_drain_begin) {
1713 drv->bdrv_drain_begin(bs);
1717 return 0;
1718 open_failed:
1719 bs->drv = NULL;
1721 bdrv_graph_wrlock();
1722 if (bs->file != NULL) {
1723 bdrv_unref_child(bs, bs->file);
1724 assert(!bs->file);
1726 bdrv_graph_wrunlock();
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 GLOBAL_STATE_CODE();
1871 bdrv_graph_rdlock_main_loop();
1872 assert(bs->file == NULL);
1873 assert(options != NULL && bs->options != options);
1874 bdrv_graph_rdunlock_main_loop();
1876 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1877 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1878 ret = -EINVAL;
1879 goto fail_opts;
1882 update_flags_from_options(&bs->open_flags, opts);
1884 driver_name = qemu_opt_get(opts, "driver");
1885 drv = bdrv_find_format(driver_name);
1886 assert(drv != NULL);
1888 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1890 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1891 error_setg(errp,
1892 BDRV_OPT_FORCE_SHARE
1893 "=on can only be used with read-only images");
1894 ret = -EINVAL;
1895 goto fail_opts;
1898 if (file != NULL) {
1899 bdrv_graph_rdlock_main_loop();
1900 bdrv_refresh_filename(blk_bs(file));
1901 bdrv_graph_rdunlock_main_loop();
1903 filename = blk_bs(file)->filename;
1904 } else {
1906 * Caution: while qdict_get_try_str() is fine, getting
1907 * non-string types would require more care. When @options
1908 * come from -blockdev or blockdev_add, its members are typed
1909 * according to the QAPI schema, but when they come from
1910 * -drive, they're all QString.
1912 filename = qdict_get_try_str(options, "filename");
1915 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1916 error_setg(errp, "The '%s' block driver requires a file name",
1917 drv->format_name);
1918 ret = -EINVAL;
1919 goto fail_opts;
1922 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1923 drv->format_name);
1925 ro = bdrv_is_read_only(bs);
1927 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1928 if (!ro && bdrv_is_whitelisted(drv, true)) {
1929 bdrv_graph_rdlock_main_loop();
1930 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1931 bdrv_graph_rdunlock_main_loop();
1932 } else {
1933 ret = -ENOTSUP;
1935 if (ret < 0) {
1936 error_setg(errp,
1937 !ro && bdrv_is_whitelisted(drv, true)
1938 ? "Driver '%s' can only be used for read-only devices"
1939 : "Driver '%s' is not whitelisted",
1940 drv->format_name);
1941 goto fail_opts;
1945 /* bdrv_new() and bdrv_close() make it so */
1946 assert(qatomic_read(&bs->copy_on_read) == 0);
1948 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1949 if (!ro) {
1950 bdrv_enable_copy_on_read(bs);
1951 } else {
1952 error_setg(errp, "Can't use copy-on-read on read-only device");
1953 ret = -EINVAL;
1954 goto fail_opts;
1958 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1959 if (discard != NULL) {
1960 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1961 error_setg(errp, "Invalid discard option");
1962 ret = -EINVAL;
1963 goto fail_opts;
1967 bs->detect_zeroes =
1968 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1969 if (local_err) {
1970 error_propagate(errp, local_err);
1971 ret = -EINVAL;
1972 goto fail_opts;
1975 if (filename != NULL) {
1976 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1977 } else {
1978 bs->filename[0] = '\0';
1980 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1982 /* Open the image, either directly or using a protocol */
1983 open_flags = bdrv_open_flags(bs, bs->open_flags);
1984 node_name = qemu_opt_get(opts, "node-name");
1986 assert(!drv->bdrv_file_open || file == NULL);
1987 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1988 if (ret < 0) {
1989 goto fail_opts;
1992 qemu_opts_del(opts);
1993 return 0;
1995 fail_opts:
1996 qemu_opts_del(opts);
1997 return ret;
2000 static G_GNUC_PRINTF(1, 0)
2001 QDict *parse_json_filename(const char *filename, Error **errp)
2003 ERRP_GUARD();
2004 QObject *options_obj;
2005 QDict *options;
2006 int ret;
2007 GLOBAL_STATE_CODE();
2009 ret = strstart(filename, "json:", &filename);
2010 assert(ret);
2012 options_obj = qobject_from_json(filename, errp);
2013 if (!options_obj) {
2014 error_prepend(errp, "Could not parse the JSON options: ");
2015 return NULL;
2018 options = qobject_to(QDict, options_obj);
2019 if (!options) {
2020 qobject_unref(options_obj);
2021 error_setg(errp, "Invalid JSON object given");
2022 return NULL;
2025 qdict_flatten(options);
2027 return options;
2030 static void parse_json_protocol(QDict *options, const char **pfilename,
2031 Error **errp)
2033 QDict *json_options;
2034 Error *local_err = NULL;
2035 GLOBAL_STATE_CODE();
2037 /* Parse json: pseudo-protocol */
2038 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2039 return;
2042 json_options = parse_json_filename(*pfilename, &local_err);
2043 if (local_err) {
2044 error_propagate(errp, local_err);
2045 return;
2048 /* Options given in the filename have lower priority than options
2049 * specified directly */
2050 qdict_join(options, json_options, false);
2051 qobject_unref(json_options);
2052 *pfilename = NULL;
2056 * Fills in default options for opening images and converts the legacy
2057 * filename/flags pair to option QDict entries.
2058 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2059 * block driver has been specified explicitly.
2061 static int bdrv_fill_options(QDict **options, const char *filename,
2062 int *flags, Error **errp)
2064 const char *drvname;
2065 bool protocol = *flags & BDRV_O_PROTOCOL;
2066 bool parse_filename = false;
2067 BlockDriver *drv = NULL;
2068 Error *local_err = NULL;
2070 GLOBAL_STATE_CODE();
2073 * Caution: while qdict_get_try_str() is fine, getting non-string
2074 * types would require more care. When @options come from
2075 * -blockdev or blockdev_add, its members are typed according to
2076 * the QAPI schema, but when they come from -drive, they're all
2077 * QString.
2079 drvname = qdict_get_try_str(*options, "driver");
2080 if (drvname) {
2081 drv = bdrv_find_format(drvname);
2082 if (!drv) {
2083 error_setg(errp, "Unknown driver '%s'", drvname);
2084 return -ENOENT;
2086 /* If the user has explicitly specified the driver, this choice should
2087 * override the BDRV_O_PROTOCOL flag */
2088 protocol = drv->bdrv_file_open;
2091 if (protocol) {
2092 *flags |= BDRV_O_PROTOCOL;
2093 } else {
2094 *flags &= ~BDRV_O_PROTOCOL;
2097 /* Translate cache options from flags into options */
2098 update_options_from_flags(*options, *flags);
2100 /* Fetch the file name from the options QDict if necessary */
2101 if (protocol && filename) {
2102 if (!qdict_haskey(*options, "filename")) {
2103 qdict_put_str(*options, "filename", filename);
2104 parse_filename = true;
2105 } else {
2106 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2107 "the same time");
2108 return -EINVAL;
2112 /* Find the right block driver */
2113 /* See cautionary note on accessing @options above */
2114 filename = qdict_get_try_str(*options, "filename");
2116 if (!drvname && protocol) {
2117 if (filename) {
2118 drv = bdrv_find_protocol(filename, parse_filename, errp);
2119 if (!drv) {
2120 return -EINVAL;
2123 drvname = drv->format_name;
2124 qdict_put_str(*options, "driver", drvname);
2125 } else {
2126 error_setg(errp, "Must specify either driver or file");
2127 return -EINVAL;
2131 assert(drv || !protocol);
2133 /* Driver-specific filename parsing */
2134 if (drv && drv->bdrv_parse_filename && parse_filename) {
2135 drv->bdrv_parse_filename(filename, *options, &local_err);
2136 if (local_err) {
2137 error_propagate(errp, local_err);
2138 return -EINVAL;
2141 if (!drv->bdrv_needs_filename) {
2142 qdict_del(*options, "filename");
2146 return 0;
2149 typedef struct BlockReopenQueueEntry {
2150 bool prepared;
2151 BDRVReopenState state;
2152 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2153 } BlockReopenQueueEntry;
2156 * Return the flags that @bs will have after the reopens in @q have
2157 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2158 * return the current flags.
2160 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2162 BlockReopenQueueEntry *entry;
2164 if (q != NULL) {
2165 QTAILQ_FOREACH(entry, q, entry) {
2166 if (entry->state.bs == bs) {
2167 return entry->state.flags;
2172 return bs->open_flags;
2175 /* Returns whether the image file can be written to after the reopen queue @q
2176 * has been successfully applied, or right now if @q is NULL. */
2177 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2178 BlockReopenQueue *q)
2180 int flags = bdrv_reopen_get_flags(q, bs);
2182 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2186 * Return whether the BDS can be written to. This is not necessarily
2187 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2188 * be written to but do not count as read-only images.
2190 bool bdrv_is_writable(BlockDriverState *bs)
2192 IO_CODE();
2193 return bdrv_is_writable_after_reopen(bs, NULL);
2196 static char *bdrv_child_user_desc(BdrvChild *c)
2198 GLOBAL_STATE_CODE();
2199 return c->klass->get_parent_desc(c);
2203 * Check that @a allows everything that @b needs. @a and @b must reference same
2204 * child node.
2206 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2208 const char *child_bs_name;
2209 g_autofree char *a_user = NULL;
2210 g_autofree char *b_user = NULL;
2211 g_autofree char *perms = NULL;
2213 assert(a->bs);
2214 assert(a->bs == b->bs);
2215 GLOBAL_STATE_CODE();
2217 if ((b->perm & a->shared_perm) == b->perm) {
2218 return true;
2221 child_bs_name = bdrv_get_node_name(b->bs);
2222 a_user = bdrv_child_user_desc(a);
2223 b_user = bdrv_child_user_desc(b);
2224 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2226 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2227 "both required by %s (uses node '%s' as '%s' child) and "
2228 "unshared by %s (uses node '%s' as '%s' child).",
2229 child_bs_name, perms,
2230 b_user, child_bs_name, b->name,
2231 a_user, child_bs_name, a->name);
2233 return false;
2236 static bool GRAPH_RDLOCK
2237 bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2239 BdrvChild *a, *b;
2240 GLOBAL_STATE_CODE();
2243 * During the loop we'll look at each pair twice. That's correct because
2244 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2245 * directions.
2247 QLIST_FOREACH(a, &bs->parents, next_parent) {
2248 QLIST_FOREACH(b, &bs->parents, next_parent) {
2249 if (a == b) {
2250 continue;
2253 if (!bdrv_a_allow_b(a, b, errp)) {
2254 return true;
2259 return false;
2262 static void GRAPH_RDLOCK
2263 bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2264 BdrvChild *c, BdrvChildRole role,
2265 BlockReopenQueue *reopen_queue,
2266 uint64_t parent_perm, uint64_t parent_shared,
2267 uint64_t *nperm, uint64_t *nshared)
2269 assert(bs->drv && bs->drv->bdrv_child_perm);
2270 GLOBAL_STATE_CODE();
2271 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2272 parent_perm, parent_shared,
2273 nperm, nshared);
2274 /* TODO Take force_share from reopen_queue */
2275 if (child_bs && child_bs->force_share) {
2276 *nshared = BLK_PERM_ALL;
2281 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2282 * nodes that are already in the @list, of course) so that final list is
2283 * topologically sorted. Return the result (GSList @list object is updated, so
2284 * don't use old reference after function call).
2286 * On function start @list must be already topologically sorted and for any node
2287 * in the @list the whole subtree of the node must be in the @list as well. The
2288 * simplest way to satisfy this criteria: use only result of
2289 * bdrv_topological_dfs() or NULL as @list parameter.
2291 static GSList * GRAPH_RDLOCK
2292 bdrv_topological_dfs(GSList *list, GHashTable *found, BlockDriverState *bs)
2294 BdrvChild *child;
2295 g_autoptr(GHashTable) local_found = NULL;
2297 GLOBAL_STATE_CODE();
2299 if (!found) {
2300 assert(!list);
2301 found = local_found = g_hash_table_new(NULL, NULL);
2304 if (g_hash_table_contains(found, bs)) {
2305 return list;
2307 g_hash_table_add(found, bs);
2309 QLIST_FOREACH(child, &bs->children, next) {
2310 list = bdrv_topological_dfs(list, found, child->bs);
2313 return g_slist_prepend(list, bs);
2316 typedef struct BdrvChildSetPermState {
2317 BdrvChild *child;
2318 uint64_t old_perm;
2319 uint64_t old_shared_perm;
2320 } BdrvChildSetPermState;
2322 static void bdrv_child_set_perm_abort(void *opaque)
2324 BdrvChildSetPermState *s = opaque;
2326 GLOBAL_STATE_CODE();
2328 s->child->perm = s->old_perm;
2329 s->child->shared_perm = s->old_shared_perm;
2332 static TransactionActionDrv bdrv_child_set_pem_drv = {
2333 .abort = bdrv_child_set_perm_abort,
2334 .clean = g_free,
2337 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2338 uint64_t shared, Transaction *tran)
2340 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2341 GLOBAL_STATE_CODE();
2343 *s = (BdrvChildSetPermState) {
2344 .child = c,
2345 .old_perm = c->perm,
2346 .old_shared_perm = c->shared_perm,
2349 c->perm = perm;
2350 c->shared_perm = shared;
2352 tran_add(tran, &bdrv_child_set_pem_drv, s);
2355 static void GRAPH_RDLOCK bdrv_drv_set_perm_commit(void *opaque)
2357 BlockDriverState *bs = opaque;
2358 uint64_t cumulative_perms, cumulative_shared_perms;
2359 GLOBAL_STATE_CODE();
2361 if (bs->drv->bdrv_set_perm) {
2362 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2363 &cumulative_shared_perms);
2364 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2368 static void GRAPH_RDLOCK bdrv_drv_set_perm_abort(void *opaque)
2370 BlockDriverState *bs = opaque;
2371 GLOBAL_STATE_CODE();
2373 if (bs->drv->bdrv_abort_perm_update) {
2374 bs->drv->bdrv_abort_perm_update(bs);
2378 TransactionActionDrv bdrv_drv_set_perm_drv = {
2379 .abort = bdrv_drv_set_perm_abort,
2380 .commit = bdrv_drv_set_perm_commit,
2384 * After calling this function, the transaction @tran may only be completed
2385 * while holding a reader lock for the graph.
2387 static int GRAPH_RDLOCK
2388 bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared_perm,
2389 Transaction *tran, Error **errp)
2391 GLOBAL_STATE_CODE();
2392 if (!bs->drv) {
2393 return 0;
2396 if (bs->drv->bdrv_check_perm) {
2397 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2398 if (ret < 0) {
2399 return ret;
2403 if (tran) {
2404 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2407 return 0;
2410 typedef struct BdrvReplaceChildState {
2411 BdrvChild *child;
2412 BlockDriverState *old_bs;
2413 } BdrvReplaceChildState;
2415 static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
2417 BdrvReplaceChildState *s = opaque;
2418 GLOBAL_STATE_CODE();
2420 bdrv_schedule_unref(s->old_bs);
2423 static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
2425 BdrvReplaceChildState *s = opaque;
2426 BlockDriverState *new_bs = s->child->bs;
2428 GLOBAL_STATE_CODE();
2429 assert_bdrv_graph_writable();
2431 /* old_bs reference is transparently moved from @s to @s->child */
2432 if (!s->child->bs) {
2434 * The parents were undrained when removing old_bs from the child. New
2435 * requests can't have been made, though, because the child was empty.
2437 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2438 * undraining the parent in the first place. Once this is done, having
2439 * new_bs drained when calling bdrv_replace_child_tran() is not a
2440 * requirement any more.
2442 bdrv_parent_drained_begin_single(s->child);
2443 assert(!bdrv_parent_drained_poll_single(s->child));
2445 assert(s->child->quiesced_parent);
2446 bdrv_replace_child_noperm(s->child, s->old_bs);
2448 bdrv_unref(new_bs);
2451 static TransactionActionDrv bdrv_replace_child_drv = {
2452 .commit = bdrv_replace_child_commit,
2453 .abort = bdrv_replace_child_abort,
2454 .clean = g_free,
2458 * bdrv_replace_child_tran
2460 * Note: real unref of old_bs is done only on commit.
2462 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2463 * kept drained until the transaction is completed.
2465 * After calling this function, the transaction @tran may only be completed
2466 * while holding a writer lock for the graph.
2468 * The function doesn't update permissions, caller is responsible for this.
2470 static void GRAPH_WRLOCK
2471 bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2472 Transaction *tran)
2474 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2476 assert(child->quiesced_parent);
2477 assert(!new_bs || new_bs->quiesce_counter);
2479 *s = (BdrvReplaceChildState) {
2480 .child = child,
2481 .old_bs = child->bs,
2483 tran_add(tran, &bdrv_replace_child_drv, s);
2485 if (new_bs) {
2486 bdrv_ref(new_bs);
2489 bdrv_replace_child_noperm(child, new_bs);
2490 /* old_bs reference is transparently moved from @child to @s */
2494 * Refresh permissions in @bs subtree. The function is intended to be called
2495 * after some graph modification that was done without permission update.
2497 * After calling this function, the transaction @tran may only be completed
2498 * while holding a reader lock for the graph.
2500 static int GRAPH_RDLOCK
2501 bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2502 Transaction *tran, Error **errp)
2504 BlockDriver *drv = bs->drv;
2505 BdrvChild *c;
2506 int ret;
2507 uint64_t cumulative_perms, cumulative_shared_perms;
2508 GLOBAL_STATE_CODE();
2510 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2512 /* Write permissions never work with read-only images */
2513 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2514 !bdrv_is_writable_after_reopen(bs, q))
2516 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2517 error_setg(errp, "Block node is read-only");
2518 } else {
2519 error_setg(errp, "Read-only block node '%s' cannot support "
2520 "read-write users", bdrv_get_node_name(bs));
2523 return -EPERM;
2527 * Unaligned requests will automatically be aligned to bl.request_alignment
2528 * and without RESIZE we can't extend requests to write to space beyond the
2529 * end of the image, so it's required that the image size is aligned.
2531 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2532 !(cumulative_perms & BLK_PERM_RESIZE))
2534 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2535 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2536 "Image size is not a multiple of request "
2537 "alignment");
2538 return -EPERM;
2542 /* Check this node */
2543 if (!drv) {
2544 return 0;
2547 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2548 errp);
2549 if (ret < 0) {
2550 return ret;
2553 /* Drivers that never have children can omit .bdrv_child_perm() */
2554 if (!drv->bdrv_child_perm) {
2555 assert(QLIST_EMPTY(&bs->children));
2556 return 0;
2559 /* Check all children */
2560 QLIST_FOREACH(c, &bs->children, next) {
2561 uint64_t cur_perm, cur_shared;
2563 bdrv_child_perm(bs, c->bs, c, c->role, q,
2564 cumulative_perms, cumulative_shared_perms,
2565 &cur_perm, &cur_shared);
2566 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2569 return 0;
2573 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2574 * a topologically sorted subgraph.
2576 * After calling this function, the transaction @tran may only be completed
2577 * while holding a reader lock for the graph.
2579 static int GRAPH_RDLOCK
2580 bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2581 Error **errp)
2583 int ret;
2584 BlockDriverState *bs;
2585 GLOBAL_STATE_CODE();
2587 for ( ; list; list = list->next) {
2588 bs = list->data;
2590 if (bdrv_parent_perms_conflict(bs, errp)) {
2591 return -EINVAL;
2594 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2595 if (ret < 0) {
2596 return ret;
2600 return 0;
2604 * @list is any list of nodes. List is completed by all subtrees and
2605 * topologically sorted. It's not a problem if some node occurs in the @list
2606 * several times.
2608 * After calling this function, the transaction @tran may only be completed
2609 * while holding a reader lock for the graph.
2611 static int GRAPH_RDLOCK
2612 bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2613 Error **errp)
2615 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2616 g_autoptr(GSList) refresh_list = NULL;
2618 for ( ; list; list = list->next) {
2619 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2622 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2625 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2626 uint64_t *shared_perm)
2628 BdrvChild *c;
2629 uint64_t cumulative_perms = 0;
2630 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2632 GLOBAL_STATE_CODE();
2634 QLIST_FOREACH(c, &bs->parents, next_parent) {
2635 cumulative_perms |= c->perm;
2636 cumulative_shared_perms &= c->shared_perm;
2639 *perm = cumulative_perms;
2640 *shared_perm = cumulative_shared_perms;
2643 char *bdrv_perm_names(uint64_t perm)
2645 struct perm_name {
2646 uint64_t perm;
2647 const char *name;
2648 } permissions[] = {
2649 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2650 { BLK_PERM_WRITE, "write" },
2651 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2652 { BLK_PERM_RESIZE, "resize" },
2653 { 0, NULL }
2656 GString *result = g_string_sized_new(30);
2657 struct perm_name *p;
2659 for (p = permissions; p->name; p++) {
2660 if (perm & p->perm) {
2661 if (result->len > 0) {
2662 g_string_append(result, ", ");
2664 g_string_append(result, p->name);
2668 return g_string_free(result, FALSE);
2673 * @tran is allowed to be NULL. In this case no rollback is possible.
2675 * After calling this function, the transaction @tran may only be completed
2676 * while holding a reader lock for the graph.
2678 static int GRAPH_RDLOCK
2679 bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran, Error **errp)
2681 int ret;
2682 Transaction *local_tran = NULL;
2683 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2684 GLOBAL_STATE_CODE();
2686 if (!tran) {
2687 tran = local_tran = tran_new();
2690 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2692 if (local_tran) {
2693 tran_finalize(local_tran, ret);
2696 return ret;
2699 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2700 Error **errp)
2702 Error *local_err = NULL;
2703 Transaction *tran = tran_new();
2704 int ret;
2706 GLOBAL_STATE_CODE();
2708 bdrv_child_set_perm(c, perm, shared, tran);
2710 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2712 tran_finalize(tran, ret);
2714 if (ret < 0) {
2715 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2716 /* tighten permissions */
2717 error_propagate(errp, local_err);
2718 } else {
2720 * Our caller may intend to only loosen restrictions and
2721 * does not expect this function to fail. Errors are not
2722 * fatal in such a case, so we can just hide them from our
2723 * caller.
2725 error_free(local_err);
2726 ret = 0;
2730 return ret;
2733 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2735 uint64_t parent_perms, parent_shared;
2736 uint64_t perms, shared;
2738 GLOBAL_STATE_CODE();
2740 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2741 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2742 parent_perms, parent_shared, &perms, &shared);
2744 return bdrv_child_try_set_perm(c, perms, shared, errp);
2748 * Default implementation for .bdrv_child_perm() for block filters:
2749 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2750 * filtered child.
2752 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2753 BdrvChildRole role,
2754 BlockReopenQueue *reopen_queue,
2755 uint64_t perm, uint64_t shared,
2756 uint64_t *nperm, uint64_t *nshared)
2758 GLOBAL_STATE_CODE();
2759 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2760 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2763 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2764 BdrvChildRole role,
2765 BlockReopenQueue *reopen_queue,
2766 uint64_t perm, uint64_t shared,
2767 uint64_t *nperm, uint64_t *nshared)
2769 assert(role & BDRV_CHILD_COW);
2770 GLOBAL_STATE_CODE();
2773 * We want consistent read from backing files if the parent needs it.
2774 * No other operations are performed on backing files.
2776 perm &= BLK_PERM_CONSISTENT_READ;
2779 * If the parent can deal with changing data, we're okay with a
2780 * writable and resizable backing file.
2781 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2783 if (shared & BLK_PERM_WRITE) {
2784 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2785 } else {
2786 shared = 0;
2789 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2791 if (bs->open_flags & BDRV_O_INACTIVE) {
2792 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2795 *nperm = perm;
2796 *nshared = shared;
2799 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2800 BdrvChildRole role,
2801 BlockReopenQueue *reopen_queue,
2802 uint64_t perm, uint64_t shared,
2803 uint64_t *nperm, uint64_t *nshared)
2805 int flags;
2807 GLOBAL_STATE_CODE();
2808 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2810 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2813 * Apart from the modifications below, the same permissions are
2814 * forwarded and left alone as for filters
2816 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2817 perm, shared, &perm, &shared);
2819 if (role & BDRV_CHILD_METADATA) {
2820 /* Format drivers may touch metadata even if the guest doesn't write */
2821 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2822 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2826 * bs->file always needs to be consistent because of the
2827 * metadata. We can never allow other users to resize or write
2828 * to it.
2830 if (!(flags & BDRV_O_NO_IO)) {
2831 perm |= BLK_PERM_CONSISTENT_READ;
2833 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2836 if (role & BDRV_CHILD_DATA) {
2838 * Technically, everything in this block is a subset of the
2839 * BDRV_CHILD_METADATA path taken above, and so this could
2840 * be an "else if" branch. However, that is not obvious, and
2841 * this function is not performance critical, therefore we let
2842 * this be an independent "if".
2846 * We cannot allow other users to resize the file because the
2847 * format driver might have some assumptions about the size
2848 * (e.g. because it is stored in metadata, or because the file
2849 * is split into fixed-size data files).
2851 shared &= ~BLK_PERM_RESIZE;
2854 * WRITE_UNCHANGED often cannot be performed as such on the
2855 * data file. For example, the qcow2 driver may still need to
2856 * write copied clusters on copy-on-read.
2858 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2859 perm |= BLK_PERM_WRITE;
2863 * If the data file is written to, the format driver may
2864 * expect to be able to resize it by writing beyond the EOF.
2866 if (perm & BLK_PERM_WRITE) {
2867 perm |= BLK_PERM_RESIZE;
2871 if (bs->open_flags & BDRV_O_INACTIVE) {
2872 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2875 *nperm = perm;
2876 *nshared = shared;
2879 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2880 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2881 uint64_t perm, uint64_t shared,
2882 uint64_t *nperm, uint64_t *nshared)
2884 GLOBAL_STATE_CODE();
2885 if (role & BDRV_CHILD_FILTERED) {
2886 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2887 BDRV_CHILD_COW)));
2888 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2889 perm, shared, nperm, nshared);
2890 } else if (role & BDRV_CHILD_COW) {
2891 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2892 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2893 perm, shared, nperm, nshared);
2894 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2895 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2896 perm, shared, nperm, nshared);
2897 } else {
2898 g_assert_not_reached();
2902 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2904 static const uint64_t permissions[] = {
2905 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2906 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2907 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2908 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2911 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2912 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2914 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2916 return permissions[qapi_perm];
2920 * Replaces the node that a BdrvChild points to without updating permissions.
2922 * If @new_bs is non-NULL, the parent of @child must already be drained through
2923 * @child.
2925 static void GRAPH_WRLOCK
2926 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
2928 BlockDriverState *old_bs = child->bs;
2929 int new_bs_quiesce_counter;
2931 assert(!child->frozen);
2934 * If we want to change the BdrvChild to point to a drained node as its new
2935 * child->bs, we need to make sure that its new parent is drained, too. In
2936 * other words, either child->quiesce_parent must already be true or we must
2937 * be able to set it and keep the parent's quiesce_counter consistent with
2938 * that, but without polling or starting new requests (this function
2939 * guarantees that it doesn't poll, and starting new requests would be
2940 * against the invariants of drain sections).
2942 * To keep things simple, we pick the first option (child->quiesce_parent
2943 * must already be true). We also generalise the rule a bit to make it
2944 * easier to verify in callers and more likely to be covered in test cases:
2945 * The parent must be quiesced through this child even if new_bs isn't
2946 * currently drained.
2948 * The only exception is for callers that always pass new_bs == NULL. In
2949 * this case, we obviously never need to consider the case of a drained
2950 * new_bs, so we can keep the callers simpler by allowing them not to drain
2951 * the parent.
2953 assert(!new_bs || child->quiesced_parent);
2954 assert(old_bs != new_bs);
2955 GLOBAL_STATE_CODE();
2957 if (old_bs && new_bs) {
2958 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2961 if (old_bs) {
2962 if (child->klass->detach) {
2963 child->klass->detach(child);
2965 QLIST_REMOVE(child, next_parent);
2968 child->bs = new_bs;
2970 if (new_bs) {
2971 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2972 if (child->klass->attach) {
2973 child->klass->attach(child);
2978 * If the parent was drained through this BdrvChild previously, but new_bs
2979 * is not drained, allow requests to come in only after the new node has
2980 * been attached.
2982 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2983 if (!new_bs_quiesce_counter && child->quiesced_parent) {
2984 bdrv_parent_drained_end_single(child);
2989 * Free the given @child.
2991 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2992 * unused (i.e. not in a children list).
2994 static void bdrv_child_free(BdrvChild *child)
2996 assert(!child->bs);
2997 GLOBAL_STATE_CODE();
2998 GRAPH_RDLOCK_GUARD_MAINLOOP();
3000 assert(!child->next.le_prev); /* not in children list */
3002 g_free(child->name);
3003 g_free(child);
3006 typedef struct BdrvAttachChildCommonState {
3007 BdrvChild *child;
3008 AioContext *old_parent_ctx;
3009 AioContext *old_child_ctx;
3010 } BdrvAttachChildCommonState;
3012 static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
3014 BdrvAttachChildCommonState *s = opaque;
3015 BlockDriverState *bs = s->child->bs;
3017 GLOBAL_STATE_CODE();
3018 assert_bdrv_graph_writable();
3020 bdrv_replace_child_noperm(s->child, NULL);
3022 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
3023 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
3026 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
3027 Transaction *tran;
3028 GHashTable *visited;
3029 bool ret;
3031 tran = tran_new();
3033 /* No need to visit `child`, because it has been detached already */
3034 visited = g_hash_table_new(NULL, NULL);
3035 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
3036 visited, tran, &error_abort);
3037 g_hash_table_destroy(visited);
3039 /* transaction is supposed to always succeed */
3040 assert(ret == true);
3041 tran_commit(tran);
3044 bdrv_schedule_unref(bs);
3045 bdrv_child_free(s->child);
3048 static TransactionActionDrv bdrv_attach_child_common_drv = {
3049 .abort = bdrv_attach_child_common_abort,
3050 .clean = g_free,
3054 * Common part of attaching bdrv child to bs or to blk or to job
3056 * Function doesn't update permissions, caller is responsible for this.
3058 * After calling this function, the transaction @tran may only be completed
3059 * while holding a writer lock for the graph.
3061 * Returns new created child.
3063 * Both @parent_bs and @child_bs can move to a different AioContext in this
3064 * function.
3066 static BdrvChild * GRAPH_WRLOCK
3067 bdrv_attach_child_common(BlockDriverState *child_bs,
3068 const char *child_name,
3069 const BdrvChildClass *child_class,
3070 BdrvChildRole child_role,
3071 uint64_t perm, uint64_t shared_perm,
3072 void *opaque,
3073 Transaction *tran, Error **errp)
3075 BdrvChild *new_child;
3076 AioContext *parent_ctx;
3077 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3079 assert(child_class->get_parent_desc);
3080 GLOBAL_STATE_CODE();
3082 new_child = g_new(BdrvChild, 1);
3083 *new_child = (BdrvChild) {
3084 .bs = NULL,
3085 .name = g_strdup(child_name),
3086 .klass = child_class,
3087 .role = child_role,
3088 .perm = perm,
3089 .shared_perm = shared_perm,
3090 .opaque = opaque,
3094 * If the AioContexts don't match, first try to move the subtree of
3095 * child_bs into the AioContext of the new parent. If this doesn't work,
3096 * try moving the parent into the AioContext of child_bs instead.
3098 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3099 if (child_ctx != parent_ctx) {
3100 Error *local_err = NULL;
3101 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3102 &local_err);
3104 if (ret < 0 && child_class->change_aio_ctx) {
3105 Transaction *aio_ctx_tran = tran_new();
3106 GHashTable *visited = g_hash_table_new(NULL, NULL);
3107 bool ret_child;
3109 g_hash_table_add(visited, new_child);
3110 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3111 visited, aio_ctx_tran,
3112 NULL);
3113 if (ret_child == true) {
3114 error_free(local_err);
3115 ret = 0;
3117 tran_finalize(aio_ctx_tran, ret_child == true ? 0 : -1);
3118 g_hash_table_destroy(visited);
3121 if (ret < 0) {
3122 error_propagate(errp, local_err);
3123 bdrv_child_free(new_child);
3124 return NULL;
3128 bdrv_ref(child_bs);
3130 * Let every new BdrvChild start with a drained parent. Inserting the child
3131 * in the graph with bdrv_replace_child_noperm() will undrain it if
3132 * @child_bs is not drained.
3134 * The child was only just created and is not yet visible in global state
3135 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3136 * could have sent requests and polling is not necessary.
3138 * Note that this means that the parent isn't fully drained yet, we only
3139 * stop new requests from coming in. This is fine, we don't care about the
3140 * old requests here, they are not for this child. If another place enters a
3141 * drain section for the same parent, but wants it to be fully quiesced, it
3142 * will not run most of the the code in .drained_begin() again (which is not
3143 * a problem, we already did this), but it will still poll until the parent
3144 * is fully quiesced, so it will not be negatively affected either.
3146 bdrv_parent_drained_begin_single(new_child);
3147 bdrv_replace_child_noperm(new_child, child_bs);
3149 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3150 *s = (BdrvAttachChildCommonState) {
3151 .child = new_child,
3152 .old_parent_ctx = parent_ctx,
3153 .old_child_ctx = child_ctx,
3155 tran_add(tran, &bdrv_attach_child_common_drv, s);
3157 return new_child;
3161 * Function doesn't update permissions, caller is responsible for this.
3163 * Both @parent_bs and @child_bs can move to a different AioContext in this
3164 * function.
3166 * After calling this function, the transaction @tran may only be completed
3167 * while holding a writer lock for the graph.
3169 static BdrvChild * GRAPH_WRLOCK
3170 bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3171 BlockDriverState *child_bs,
3172 const char *child_name,
3173 const BdrvChildClass *child_class,
3174 BdrvChildRole child_role,
3175 Transaction *tran,
3176 Error **errp)
3178 uint64_t perm, shared_perm;
3180 assert(parent_bs->drv);
3181 GLOBAL_STATE_CODE();
3183 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3184 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3185 child_bs->node_name, child_name, parent_bs->node_name);
3186 return NULL;
3189 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3190 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3191 perm, shared_perm, &perm, &shared_perm);
3193 return bdrv_attach_child_common(child_bs, child_name, child_class,
3194 child_role, perm, shared_perm, parent_bs,
3195 tran, errp);
3199 * This function steals the reference to child_bs from the caller.
3200 * That reference is later dropped by bdrv_root_unref_child().
3202 * On failure NULL is returned, errp is set and the reference to
3203 * child_bs is also dropped.
3205 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3206 const char *child_name,
3207 const BdrvChildClass *child_class,
3208 BdrvChildRole child_role,
3209 uint64_t perm, uint64_t shared_perm,
3210 void *opaque, Error **errp)
3212 int ret;
3213 BdrvChild *child;
3214 Transaction *tran = tran_new();
3216 GLOBAL_STATE_CODE();
3218 child = bdrv_attach_child_common(child_bs, child_name, child_class,
3219 child_role, perm, shared_perm, opaque,
3220 tran, errp);
3221 if (!child) {
3222 ret = -EINVAL;
3223 goto out;
3226 ret = bdrv_refresh_perms(child_bs, tran, errp);
3228 out:
3229 tran_finalize(tran, ret);
3231 bdrv_schedule_unref(child_bs);
3233 return ret < 0 ? NULL : child;
3237 * This function transfers the reference to child_bs from the caller
3238 * to parent_bs. That reference is later dropped by parent_bs on
3239 * bdrv_close() or if someone calls bdrv_unref_child().
3241 * On failure NULL is returned, errp is set and the reference to
3242 * child_bs is also dropped.
3244 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3245 BlockDriverState *child_bs,
3246 const char *child_name,
3247 const BdrvChildClass *child_class,
3248 BdrvChildRole child_role,
3249 Error **errp)
3251 int ret;
3252 BdrvChild *child;
3253 Transaction *tran = tran_new();
3255 GLOBAL_STATE_CODE();
3257 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3258 child_class, child_role, tran, errp);
3259 if (!child) {
3260 ret = -EINVAL;
3261 goto out;
3264 ret = bdrv_refresh_perms(parent_bs, tran, errp);
3265 if (ret < 0) {
3266 goto out;
3269 out:
3270 tran_finalize(tran, ret);
3272 bdrv_schedule_unref(child_bs);
3274 return ret < 0 ? NULL : child;
3277 /* Callers must ensure that child->frozen is false. */
3278 void bdrv_root_unref_child(BdrvChild *child)
3280 BlockDriverState *child_bs = child->bs;
3282 GLOBAL_STATE_CODE();
3283 bdrv_replace_child_noperm(child, NULL);
3284 bdrv_child_free(child);
3286 if (child_bs) {
3288 * Update permissions for old node. We're just taking a parent away, so
3289 * we're loosening restrictions. Errors of permission update are not
3290 * fatal in this case, ignore them.
3292 bdrv_refresh_perms(child_bs, NULL, NULL);
3295 * When the parent requiring a non-default AioContext is removed, the
3296 * node moves back to the main AioContext
3298 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3299 NULL);
3302 bdrv_schedule_unref(child_bs);
3305 typedef struct BdrvSetInheritsFrom {
3306 BlockDriverState *bs;
3307 BlockDriverState *old_inherits_from;
3308 } BdrvSetInheritsFrom;
3310 static void bdrv_set_inherits_from_abort(void *opaque)
3312 BdrvSetInheritsFrom *s = opaque;
3314 s->bs->inherits_from = s->old_inherits_from;
3317 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3318 .abort = bdrv_set_inherits_from_abort,
3319 .clean = g_free,
3322 /* @tran is allowed to be NULL. In this case no rollback is possible */
3323 static void bdrv_set_inherits_from(BlockDriverState *bs,
3324 BlockDriverState *new_inherits_from,
3325 Transaction *tran)
3327 if (tran) {
3328 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3330 *s = (BdrvSetInheritsFrom) {
3331 .bs = bs,
3332 .old_inherits_from = bs->inherits_from,
3335 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3338 bs->inherits_from = new_inherits_from;
3342 * Clear all inherits_from pointers from children and grandchildren of
3343 * @root that point to @root, where necessary.
3344 * @tran is allowed to be NULL. In this case no rollback is possible
3346 static void GRAPH_WRLOCK
3347 bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3348 Transaction *tran)
3350 BdrvChild *c;
3352 if (child->bs->inherits_from == root) {
3354 * Remove inherits_from only when the last reference between root and
3355 * child->bs goes away.
3357 QLIST_FOREACH(c, &root->children, next) {
3358 if (c != child && c->bs == child->bs) {
3359 break;
3362 if (c == NULL) {
3363 bdrv_set_inherits_from(child->bs, NULL, tran);
3367 QLIST_FOREACH(c, &child->bs->children, next) {
3368 bdrv_unset_inherits_from(root, c, tran);
3372 /* Callers must ensure that child->frozen is false. */
3373 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3375 GLOBAL_STATE_CODE();
3376 if (child == NULL) {
3377 return;
3380 bdrv_unset_inherits_from(parent, child, NULL);
3381 bdrv_root_unref_child(child);
3385 static void GRAPH_RDLOCK
3386 bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3388 BdrvChild *c;
3389 GLOBAL_STATE_CODE();
3390 QLIST_FOREACH(c, &bs->parents, next_parent) {
3391 if (c->klass->change_media) {
3392 c->klass->change_media(c, load);
3397 /* Return true if you can reach parent going through child->inherits_from
3398 * recursively. If parent or child are NULL, return false */
3399 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3400 BlockDriverState *parent)
3402 while (child && child != parent) {
3403 child = child->inherits_from;
3406 return child != NULL;
3410 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3411 * mostly used for COW backing children (role = COW), but also for
3412 * filtered children (role = FILTERED | PRIMARY).
3414 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3416 if (bs->drv && bs->drv->is_filter) {
3417 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3418 } else {
3419 return BDRV_CHILD_COW;
3424 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3425 * callers which don't need their own reference any more must call bdrv_unref().
3427 * If the respective child is already present (i.e. we're detaching a node),
3428 * that child node must be drained.
3430 * Function doesn't update permissions, caller is responsible for this.
3432 * Both @parent_bs and @child_bs can move to a different AioContext in this
3433 * function.
3435 * After calling this function, the transaction @tran may only be completed
3436 * while holding a writer lock for the graph.
3438 static int GRAPH_WRLOCK
3439 bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3440 BlockDriverState *child_bs,
3441 bool is_backing,
3442 Transaction *tran, Error **errp)
3444 bool update_inherits_from =
3445 bdrv_inherits_from_recursive(child_bs, parent_bs);
3446 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3447 BdrvChildRole role;
3449 GLOBAL_STATE_CODE();
3451 if (!parent_bs->drv) {
3453 * Node without drv is an object without a class :/. TODO: finally fix
3454 * qcow2 driver to never clear bs->drv and implement format corruption
3455 * handling in other way.
3457 error_setg(errp, "Node corrupted");
3458 return -EINVAL;
3461 if (child && child->frozen) {
3462 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3463 child->name, parent_bs->node_name, child->bs->node_name);
3464 return -EPERM;
3467 if (is_backing && !parent_bs->drv->is_filter &&
3468 !parent_bs->drv->supports_backing)
3470 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3471 "files", parent_bs->drv->format_name, parent_bs->node_name);
3472 return -EINVAL;
3475 if (parent_bs->drv->is_filter) {
3476 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3477 } else if (is_backing) {
3478 role = BDRV_CHILD_COW;
3479 } else {
3481 * We only can use same role as it is in existing child. We don't have
3482 * infrastructure to determine role of file child in generic way
3484 if (!child) {
3485 error_setg(errp, "Cannot set file child to format node without "
3486 "file child");
3487 return -EINVAL;
3489 role = child->role;
3492 if (child) {
3493 assert(child->bs->quiesce_counter);
3494 bdrv_unset_inherits_from(parent_bs, child, tran);
3495 bdrv_remove_child(child, tran);
3498 if (!child_bs) {
3499 goto out;
3502 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3503 is_backing ? "backing" : "file",
3504 &child_of_bds, role,
3505 tran, errp);
3506 if (!child) {
3507 return -EINVAL;
3512 * If inherits_from pointed recursively to bs then let's update it to
3513 * point directly to bs (else it will become NULL).
3515 if (update_inherits_from) {
3516 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3519 out:
3520 bdrv_refresh_limits(parent_bs, tran, NULL);
3522 return 0;
3526 * Both @bs and @backing_hd can move to a different AioContext in this
3527 * function.
3529 * If a backing child is already present (i.e. we're detaching a node), that
3530 * child node must be drained.
3532 int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3533 BlockDriverState *backing_hd,
3534 Error **errp)
3536 int ret;
3537 Transaction *tran = tran_new();
3539 GLOBAL_STATE_CODE();
3540 assert(bs->quiesce_counter > 0);
3541 if (bs->backing) {
3542 assert(bs->backing->bs->quiesce_counter > 0);
3545 ret = bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3546 if (ret < 0) {
3547 goto out;
3550 ret = bdrv_refresh_perms(bs, tran, errp);
3551 out:
3552 tran_finalize(tran, ret);
3553 return ret;
3556 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3557 Error **errp)
3559 BlockDriverState *drain_bs;
3560 int ret;
3561 GLOBAL_STATE_CODE();
3563 bdrv_graph_rdlock_main_loop();
3564 drain_bs = bs->backing ? bs->backing->bs : bs;
3565 bdrv_graph_rdunlock_main_loop();
3567 bdrv_ref(drain_bs);
3568 bdrv_drained_begin(drain_bs);
3569 bdrv_graph_wrlock();
3570 ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
3571 bdrv_graph_wrunlock();
3572 bdrv_drained_end(drain_bs);
3573 bdrv_unref(drain_bs);
3575 return ret;
3579 * Opens the backing file for a BlockDriverState if not yet open
3581 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3582 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3583 * itself, all options starting with "${bdref_key}." are considered part of the
3584 * BlockdevRef.
3586 * TODO Can this be unified with bdrv_open_image()?
3588 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3589 const char *bdref_key, Error **errp)
3591 ERRP_GUARD();
3592 char *backing_filename = NULL;
3593 char *bdref_key_dot;
3594 const char *reference = NULL;
3595 int ret = 0;
3596 bool implicit_backing = false;
3597 BlockDriverState *backing_hd;
3598 QDict *options;
3599 QDict *tmp_parent_options = NULL;
3600 Error *local_err = NULL;
3602 GLOBAL_STATE_CODE();
3603 GRAPH_RDLOCK_GUARD_MAINLOOP();
3605 if (bs->backing != NULL) {
3606 goto free_exit;
3609 /* NULL means an empty set of options */
3610 if (parent_options == NULL) {
3611 tmp_parent_options = qdict_new();
3612 parent_options = tmp_parent_options;
3615 bs->open_flags &= ~BDRV_O_NO_BACKING;
3617 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3618 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3619 g_free(bdref_key_dot);
3622 * Caution: while qdict_get_try_str() is fine, getting non-string
3623 * types would require more care. When @parent_options come from
3624 * -blockdev or blockdev_add, its members are typed according to
3625 * the QAPI schema, but when they come from -drive, they're all
3626 * QString.
3628 reference = qdict_get_try_str(parent_options, bdref_key);
3629 if (reference || qdict_haskey(options, "file.filename")) {
3630 /* keep backing_filename NULL */
3631 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3632 qobject_unref(options);
3633 goto free_exit;
3634 } else {
3635 if (qdict_size(options) == 0) {
3636 /* If the user specifies options that do not modify the
3637 * backing file's behavior, we might still consider it the
3638 * implicit backing file. But it's easier this way, and
3639 * just specifying some of the backing BDS's options is
3640 * only possible with -drive anyway (otherwise the QAPI
3641 * schema forces the user to specify everything). */
3642 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3645 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3646 if (local_err) {
3647 ret = -EINVAL;
3648 error_propagate(errp, local_err);
3649 qobject_unref(options);
3650 goto free_exit;
3654 if (!bs->drv || !bs->drv->supports_backing) {
3655 ret = -EINVAL;
3656 error_setg(errp, "Driver doesn't support backing files");
3657 qobject_unref(options);
3658 goto free_exit;
3661 if (!reference &&
3662 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3663 qdict_put_str(options, "driver", bs->backing_format);
3666 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3667 &child_of_bds, bdrv_backing_role(bs), errp);
3668 if (!backing_hd) {
3669 bs->open_flags |= BDRV_O_NO_BACKING;
3670 error_prepend(errp, "Could not open backing file: ");
3671 ret = -EINVAL;
3672 goto free_exit;
3675 if (implicit_backing) {
3676 bdrv_refresh_filename(backing_hd);
3677 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3678 backing_hd->filename);
3681 /* Hook up the backing file link; drop our reference, bs owns the
3682 * backing_hd reference now */
3683 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3684 bdrv_unref(backing_hd);
3686 if (ret < 0) {
3687 goto free_exit;
3690 qdict_del(parent_options, bdref_key);
3692 free_exit:
3693 g_free(backing_filename);
3694 qobject_unref(tmp_parent_options);
3695 return ret;
3698 static BlockDriverState *
3699 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3700 BlockDriverState *parent, const BdrvChildClass *child_class,
3701 BdrvChildRole child_role, bool allow_none, Error **errp)
3703 BlockDriverState *bs = NULL;
3704 QDict *image_options;
3705 char *bdref_key_dot;
3706 const char *reference;
3708 assert(child_class != NULL);
3710 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3711 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3712 g_free(bdref_key_dot);
3715 * Caution: while qdict_get_try_str() is fine, getting non-string
3716 * types would require more care. When @options come from
3717 * -blockdev or blockdev_add, its members are typed according to
3718 * the QAPI schema, but when they come from -drive, they're all
3719 * QString.
3721 reference = qdict_get_try_str(options, bdref_key);
3722 if (!filename && !reference && !qdict_size(image_options)) {
3723 if (!allow_none) {
3724 error_setg(errp, "A block device must be specified for \"%s\"",
3725 bdref_key);
3727 qobject_unref(image_options);
3728 goto done;
3731 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3732 parent, child_class, child_role, errp);
3733 if (!bs) {
3734 goto done;
3737 done:
3738 qdict_del(options, bdref_key);
3739 return bs;
3743 * Opens a disk image whose options are given as BlockdevRef in another block
3744 * device's options.
3746 * If allow_none is true, no image will be opened if filename is false and no
3747 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3749 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3750 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3751 * itself, all options starting with "${bdref_key}." are considered part of the
3752 * BlockdevRef.
3754 * The BlockdevRef will be removed from the options QDict.
3756 * @parent can move to a different AioContext in this function.
3758 BdrvChild *bdrv_open_child(const char *filename,
3759 QDict *options, const char *bdref_key,
3760 BlockDriverState *parent,
3761 const BdrvChildClass *child_class,
3762 BdrvChildRole child_role,
3763 bool allow_none, Error **errp)
3765 BlockDriverState *bs;
3766 BdrvChild *child;
3768 GLOBAL_STATE_CODE();
3770 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3771 child_role, allow_none, errp);
3772 if (bs == NULL) {
3773 return NULL;
3776 bdrv_graph_wrlock();
3777 child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3778 errp);
3779 bdrv_graph_wrunlock();
3781 return child;
3785 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3787 * @parent can move to a different AioContext in this function.
3789 int bdrv_open_file_child(const char *filename,
3790 QDict *options, const char *bdref_key,
3791 BlockDriverState *parent, Error **errp)
3793 BdrvChildRole role;
3795 /* commit_top and mirror_top don't use this function */
3796 assert(!parent->drv->filtered_child_is_backing);
3797 role = parent->drv->is_filter ?
3798 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3800 if (!bdrv_open_child(filename, options, bdref_key, parent,
3801 &child_of_bds, role, false, errp))
3803 return -EINVAL;
3806 return 0;
3810 * TODO Future callers may need to specify parent/child_class in order for
3811 * option inheritance to work. Existing callers use it for the root node.
3813 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3815 BlockDriverState *bs = NULL;
3816 QObject *obj = NULL;
3817 QDict *qdict = NULL;
3818 const char *reference = NULL;
3819 Visitor *v = NULL;
3821 GLOBAL_STATE_CODE();
3823 if (ref->type == QTYPE_QSTRING) {
3824 reference = ref->u.reference;
3825 } else {
3826 BlockdevOptions *options = &ref->u.definition;
3827 assert(ref->type == QTYPE_QDICT);
3829 v = qobject_output_visitor_new(&obj);
3830 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3831 visit_complete(v, &obj);
3833 qdict = qobject_to(QDict, obj);
3834 qdict_flatten(qdict);
3836 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3837 * compatibility with other callers) rather than what we want as the
3838 * real defaults. Apply the defaults here instead. */
3839 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3840 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3841 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3842 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3846 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3847 obj = NULL;
3848 qobject_unref(obj);
3849 visit_free(v);
3850 return bs;
3853 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3854 int flags,
3855 QDict *snapshot_options,
3856 Error **errp)
3858 ERRP_GUARD();
3859 g_autofree char *tmp_filename = NULL;
3860 int64_t total_size;
3861 QemuOpts *opts = NULL;
3862 BlockDriverState *bs_snapshot = NULL;
3863 int ret;
3865 GLOBAL_STATE_CODE();
3867 /* if snapshot, we create a temporary backing file and open it
3868 instead of opening 'filename' directly */
3870 /* Get the required size from the image */
3871 total_size = bdrv_getlength(bs);
3873 if (total_size < 0) {
3874 error_setg_errno(errp, -total_size, "Could not get image size");
3875 goto out;
3878 /* Create the temporary image */
3879 tmp_filename = create_tmp_file(errp);
3880 if (!tmp_filename) {
3881 goto out;
3884 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3885 &error_abort);
3886 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3887 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3888 qemu_opts_del(opts);
3889 if (ret < 0) {
3890 error_prepend(errp, "Could not create temporary overlay '%s': ",
3891 tmp_filename);
3892 goto out;
3895 /* Prepare options QDict for the temporary file */
3896 qdict_put_str(snapshot_options, "file.driver", "file");
3897 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3898 qdict_put_str(snapshot_options, "driver", "qcow2");
3900 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3901 snapshot_options = NULL;
3902 if (!bs_snapshot) {
3903 goto out;
3906 ret = bdrv_append(bs_snapshot, bs, errp);
3907 if (ret < 0) {
3908 bs_snapshot = NULL;
3909 goto out;
3912 out:
3913 qobject_unref(snapshot_options);
3914 return bs_snapshot;
3918 * Opens a disk image (raw, qcow2, vmdk, ...)
3920 * options is a QDict of options to pass to the block drivers, or NULL for an
3921 * empty set of options. The reference to the QDict belongs to the block layer
3922 * after the call (even on failure), so if the caller intends to reuse the
3923 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3925 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3926 * If it is not NULL, the referenced BDS will be reused.
3928 * The reference parameter may be used to specify an existing block device which
3929 * should be opened. If specified, neither options nor a filename may be given,
3930 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3932 static BlockDriverState * no_coroutine_fn
3933 bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
3934 int flags, BlockDriverState *parent,
3935 const BdrvChildClass *child_class, BdrvChildRole child_role,
3936 Error **errp)
3938 int ret;
3939 BlockBackend *file = NULL;
3940 BlockDriverState *bs;
3941 BlockDriver *drv = NULL;
3942 BdrvChild *child;
3943 const char *drvname;
3944 const char *backing;
3945 Error *local_err = NULL;
3946 QDict *snapshot_options = NULL;
3947 int snapshot_flags = 0;
3949 assert(!child_class || !flags);
3950 assert(!child_class == !parent);
3951 GLOBAL_STATE_CODE();
3952 assert(!qemu_in_coroutine());
3954 /* TODO We'll eventually have to take a writer lock in this function */
3955 GRAPH_RDLOCK_GUARD_MAINLOOP();
3957 if (reference) {
3958 bool options_non_empty = options ? qdict_size(options) : false;
3959 qobject_unref(options);
3961 if (filename || options_non_empty) {
3962 error_setg(errp, "Cannot reference an existing block device with "
3963 "additional options or a new filename");
3964 return NULL;
3967 bs = bdrv_lookup_bs(reference, reference, errp);
3968 if (!bs) {
3969 return NULL;
3972 bdrv_ref(bs);
3973 return bs;
3976 bs = bdrv_new();
3978 /* NULL means an empty set of options */
3979 if (options == NULL) {
3980 options = qdict_new();
3983 /* json: syntax counts as explicit options, as if in the QDict */
3984 parse_json_protocol(options, &filename, &local_err);
3985 if (local_err) {
3986 goto fail;
3989 bs->explicit_options = qdict_clone_shallow(options);
3991 if (child_class) {
3992 bool parent_is_format;
3994 if (parent->drv) {
3995 parent_is_format = parent->drv->is_format;
3996 } else {
3998 * parent->drv is not set yet because this node is opened for
3999 * (potential) format probing. That means that @parent is going
4000 * to be a format node.
4002 parent_is_format = true;
4005 bs->inherits_from = parent;
4006 child_class->inherit_options(child_role, parent_is_format,
4007 &flags, options,
4008 parent->open_flags, parent->options);
4011 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
4012 if (ret < 0) {
4013 goto fail;
4017 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4018 * Caution: getting a boolean member of @options requires care.
4019 * When @options come from -blockdev or blockdev_add, members are
4020 * typed according to the QAPI schema, but when they come from
4021 * -drive, they're all QString.
4023 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
4024 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
4025 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
4026 } else {
4027 flags &= ~BDRV_O_RDWR;
4030 if (flags & BDRV_O_SNAPSHOT) {
4031 snapshot_options = qdict_new();
4032 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
4033 flags, options);
4034 /* Let bdrv_backing_options() override "read-only" */
4035 qdict_del(options, BDRV_OPT_READ_ONLY);
4036 bdrv_inherited_options(BDRV_CHILD_COW, true,
4037 &flags, options, flags, options);
4040 bs->open_flags = flags;
4041 bs->options = options;
4042 options = qdict_clone_shallow(options);
4044 /* Find the right image format driver */
4045 /* See cautionary note on accessing @options above */
4046 drvname = qdict_get_try_str(options, "driver");
4047 if (drvname) {
4048 drv = bdrv_find_format(drvname);
4049 if (!drv) {
4050 error_setg(errp, "Unknown driver: '%s'", drvname);
4051 goto fail;
4055 assert(drvname || !(flags & BDRV_O_PROTOCOL));
4057 /* See cautionary note on accessing @options above */
4058 backing = qdict_get_try_str(options, "backing");
4059 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
4060 (backing && *backing == '\0'))
4062 if (backing) {
4063 warn_report("Use of \"backing\": \"\" is deprecated; "
4064 "use \"backing\": null instead");
4066 flags |= BDRV_O_NO_BACKING;
4067 qdict_del(bs->explicit_options, "backing");
4068 qdict_del(bs->options, "backing");
4069 qdict_del(options, "backing");
4072 /* Open image file without format layer. This BlockBackend is only used for
4073 * probing, the block drivers will do their own bdrv_open_child() for the
4074 * same BDS, which is why we put the node name back into options. */
4075 if ((flags & BDRV_O_PROTOCOL) == 0) {
4076 BlockDriverState *file_bs;
4078 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
4079 &child_of_bds, BDRV_CHILD_IMAGE,
4080 true, &local_err);
4081 if (local_err) {
4082 goto fail;
4084 if (file_bs != NULL) {
4085 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4086 * looking at the header to guess the image format. This works even
4087 * in cases where a guest would not see a consistent state. */
4088 AioContext *ctx = bdrv_get_aio_context(file_bs);
4089 file = blk_new(ctx, 0, BLK_PERM_ALL);
4090 blk_insert_bs(file, file_bs, &local_err);
4091 bdrv_unref(file_bs);
4093 if (local_err) {
4094 goto fail;
4097 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4101 /* Image format probing */
4102 bs->probed = !drv;
4103 if (!drv && file) {
4104 ret = find_image_format(file, filename, &drv, &local_err);
4105 if (ret < 0) {
4106 goto fail;
4109 * This option update would logically belong in bdrv_fill_options(),
4110 * but we first need to open bs->file for the probing to work, while
4111 * opening bs->file already requires the (mostly) final set of options
4112 * so that cache mode etc. can be inherited.
4114 * Adding the driver later is somewhat ugly, but it's not an option
4115 * that would ever be inherited, so it's correct. We just need to make
4116 * sure to update both bs->options (which has the full effective
4117 * options for bs) and options (which has file.* already removed).
4119 qdict_put_str(bs->options, "driver", drv->format_name);
4120 qdict_put_str(options, "driver", drv->format_name);
4121 } else if (!drv) {
4122 error_setg(errp, "Must specify either driver or file");
4123 goto fail;
4126 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4127 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
4128 /* file must be NULL if a protocol BDS is about to be created
4129 * (the inverse results in an error message from bdrv_open_common()) */
4130 assert(!(flags & BDRV_O_PROTOCOL) || !file);
4132 /* Open the image */
4133 ret = bdrv_open_common(bs, file, options, &local_err);
4134 if (ret < 0) {
4135 goto fail;
4138 if (file) {
4139 blk_unref(file);
4140 file = NULL;
4143 /* If there is a backing file, use it */
4144 if ((flags & BDRV_O_NO_BACKING) == 0) {
4145 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4146 if (ret < 0) {
4147 goto close_and_fail;
4151 /* Remove all children options and references
4152 * from bs->options and bs->explicit_options */
4153 QLIST_FOREACH(child, &bs->children, next) {
4154 char *child_key_dot;
4155 child_key_dot = g_strdup_printf("%s.", child->name);
4156 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4157 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4158 qdict_del(bs->explicit_options, child->name);
4159 qdict_del(bs->options, child->name);
4160 g_free(child_key_dot);
4163 /* Check if any unknown options were used */
4164 if (qdict_size(options) != 0) {
4165 const QDictEntry *entry = qdict_first(options);
4166 if (flags & BDRV_O_PROTOCOL) {
4167 error_setg(errp, "Block protocol '%s' doesn't support the option "
4168 "'%s'", drv->format_name, entry->key);
4169 } else {
4170 error_setg(errp,
4171 "Block format '%s' does not support the option '%s'",
4172 drv->format_name, entry->key);
4175 goto close_and_fail;
4178 bdrv_parent_cb_change_media(bs, true);
4180 qobject_unref(options);
4181 options = NULL;
4183 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4184 * temporary snapshot afterwards. */
4185 if (snapshot_flags) {
4186 BlockDriverState *snapshot_bs;
4187 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4188 snapshot_options, &local_err);
4189 snapshot_options = NULL;
4190 if (local_err) {
4191 goto close_and_fail;
4193 /* We are not going to return bs but the overlay on top of it
4194 * (snapshot_bs); thus, we have to drop the strong reference to bs
4195 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4196 * though, because the overlay still has a reference to it. */
4197 bdrv_unref(bs);
4198 bs = snapshot_bs;
4201 return bs;
4203 fail:
4204 blk_unref(file);
4205 qobject_unref(snapshot_options);
4206 qobject_unref(bs->explicit_options);
4207 qobject_unref(bs->options);
4208 qobject_unref(options);
4209 bs->options = NULL;
4210 bs->explicit_options = NULL;
4211 bdrv_unref(bs);
4212 error_propagate(errp, local_err);
4213 return NULL;
4215 close_and_fail:
4216 bdrv_unref(bs);
4217 qobject_unref(snapshot_options);
4218 qobject_unref(options);
4219 error_propagate(errp, local_err);
4220 return NULL;
4223 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4224 QDict *options, int flags, Error **errp)
4226 GLOBAL_STATE_CODE();
4228 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4229 NULL, 0, errp);
4232 /* Return true if the NULL-terminated @list contains @str */
4233 static bool is_str_in_list(const char *str, const char *const *list)
4235 if (str && list) {
4236 int i;
4237 for (i = 0; list[i] != NULL; i++) {
4238 if (!strcmp(str, list[i])) {
4239 return true;
4243 return false;
4247 * Check that every option set in @bs->options is also set in
4248 * @new_opts.
4250 * Options listed in the common_options list and in
4251 * @bs->drv->mutable_opts are skipped.
4253 * Return 0 on success, otherwise return -EINVAL and set @errp.
4255 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4256 const QDict *new_opts, Error **errp)
4258 const QDictEntry *e;
4259 /* These options are common to all block drivers and are handled
4260 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4261 const char *const common_options[] = {
4262 "node-name", "discard", "cache.direct", "cache.no-flush",
4263 "read-only", "auto-read-only", "detect-zeroes", NULL
4266 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4267 if (!qdict_haskey(new_opts, e->key) &&
4268 !is_str_in_list(e->key, common_options) &&
4269 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4270 error_setg(errp, "Option '%s' cannot be reset "
4271 "to its default value", e->key);
4272 return -EINVAL;
4276 return 0;
4280 * Returns true if @child can be reached recursively from @bs
4282 static bool GRAPH_RDLOCK
4283 bdrv_recurse_has_child(BlockDriverState *bs, BlockDriverState *child)
4285 BdrvChild *c;
4287 if (bs == child) {
4288 return true;
4291 QLIST_FOREACH(c, &bs->children, next) {
4292 if (bdrv_recurse_has_child(c->bs, child)) {
4293 return true;
4297 return false;
4301 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4302 * reopen of multiple devices.
4304 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4305 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4306 * be created and initialized. This newly created BlockReopenQueue should be
4307 * passed back in for subsequent calls that are intended to be of the same
4308 * atomic 'set'.
4310 * bs is the BlockDriverState to add to the reopen queue.
4312 * options contains the changed options for the associated bs
4313 * (the BlockReopenQueue takes ownership)
4315 * flags contains the open flags for the associated bs
4317 * returns a pointer to bs_queue, which is either the newly allocated
4318 * bs_queue, or the existing bs_queue being used.
4320 * bs is drained here and undrained by bdrv_reopen_queue_free().
4322 * To be called with bs->aio_context locked.
4324 static BlockReopenQueue * GRAPH_RDLOCK
4325 bdrv_reopen_queue_child(BlockReopenQueue *bs_queue, BlockDriverState *bs,
4326 QDict *options, const BdrvChildClass *klass,
4327 BdrvChildRole role, bool parent_is_format,
4328 QDict *parent_options, int parent_flags,
4329 bool keep_old_opts)
4331 assert(bs != NULL);
4333 BlockReopenQueueEntry *bs_entry;
4334 BdrvChild *child;
4335 QDict *old_options, *explicit_options, *options_copy;
4336 int flags;
4337 QemuOpts *opts;
4339 GLOBAL_STATE_CODE();
4342 * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
4343 * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
4344 * in practice.
4346 bdrv_drained_begin(bs);
4348 if (bs_queue == NULL) {
4349 bs_queue = g_new0(BlockReopenQueue, 1);
4350 QTAILQ_INIT(bs_queue);
4353 if (!options) {
4354 options = qdict_new();
4357 /* Check if this BlockDriverState is already in the queue */
4358 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4359 if (bs == bs_entry->state.bs) {
4360 break;
4365 * Precedence of options:
4366 * 1. Explicitly passed in options (highest)
4367 * 2. Retained from explicitly set options of bs
4368 * 3. Inherited from parent node
4369 * 4. Retained from effective options of bs
4372 /* Old explicitly set values (don't overwrite by inherited value) */
4373 if (bs_entry || keep_old_opts) {
4374 old_options = qdict_clone_shallow(bs_entry ?
4375 bs_entry->state.explicit_options :
4376 bs->explicit_options);
4377 bdrv_join_options(bs, options, old_options);
4378 qobject_unref(old_options);
4381 explicit_options = qdict_clone_shallow(options);
4383 /* Inherit from parent node */
4384 if (parent_options) {
4385 flags = 0;
4386 klass->inherit_options(role, parent_is_format, &flags, options,
4387 parent_flags, parent_options);
4388 } else {
4389 flags = bdrv_get_flags(bs);
4392 if (keep_old_opts) {
4393 /* Old values are used for options that aren't set yet */
4394 old_options = qdict_clone_shallow(bs->options);
4395 bdrv_join_options(bs, options, old_options);
4396 qobject_unref(old_options);
4399 /* We have the final set of options so let's update the flags */
4400 options_copy = qdict_clone_shallow(options);
4401 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4402 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4403 update_flags_from_options(&flags, opts);
4404 qemu_opts_del(opts);
4405 qobject_unref(options_copy);
4407 /* bdrv_open_inherit() sets and clears some additional flags internally */
4408 flags &= ~BDRV_O_PROTOCOL;
4409 if (flags & BDRV_O_RDWR) {
4410 flags |= BDRV_O_ALLOW_RDWR;
4413 if (!bs_entry) {
4414 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4415 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4416 } else {
4417 qobject_unref(bs_entry->state.options);
4418 qobject_unref(bs_entry->state.explicit_options);
4421 bs_entry->state.bs = bs;
4422 bs_entry->state.options = options;
4423 bs_entry->state.explicit_options = explicit_options;
4424 bs_entry->state.flags = flags;
4427 * If keep_old_opts is false then it means that unspecified
4428 * options must be reset to their original value. We don't allow
4429 * resetting 'backing' but we need to know if the option is
4430 * missing in order to decide if we have to return an error.
4432 if (!keep_old_opts) {
4433 bs_entry->state.backing_missing =
4434 !qdict_haskey(options, "backing") &&
4435 !qdict_haskey(options, "backing.driver");
4438 QLIST_FOREACH(child, &bs->children, next) {
4439 QDict *new_child_options = NULL;
4440 bool child_keep_old = keep_old_opts;
4442 /* reopen can only change the options of block devices that were
4443 * implicitly created and inherited options. For other (referenced)
4444 * block devices, a syntax like "backing.foo" results in an error. */
4445 if (child->bs->inherits_from != bs) {
4446 continue;
4449 /* Check if the options contain a child reference */
4450 if (qdict_haskey(options, child->name)) {
4451 const char *childref = qdict_get_try_str(options, child->name);
4453 * The current child must not be reopened if the child
4454 * reference is null or points to a different node.
4456 if (g_strcmp0(childref, child->bs->node_name)) {
4457 continue;
4460 * If the child reference points to the current child then
4461 * reopen it with its existing set of options (note that
4462 * it can still inherit new options from the parent).
4464 child_keep_old = true;
4465 } else {
4466 /* Extract child options ("child-name.*") */
4467 char *child_key_dot = g_strdup_printf("%s.", child->name);
4468 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4469 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4470 g_free(child_key_dot);
4473 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4474 child->klass, child->role, bs->drv->is_format,
4475 options, flags, child_keep_old);
4478 return bs_queue;
4481 /* To be called with bs->aio_context locked */
4482 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4483 BlockDriverState *bs,
4484 QDict *options, bool keep_old_opts)
4486 GLOBAL_STATE_CODE();
4487 GRAPH_RDLOCK_GUARD_MAINLOOP();
4489 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4490 NULL, 0, keep_old_opts);
4493 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4495 GLOBAL_STATE_CODE();
4496 if (bs_queue) {
4497 BlockReopenQueueEntry *bs_entry, *next;
4498 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4499 bdrv_drained_end(bs_entry->state.bs);
4500 qobject_unref(bs_entry->state.explicit_options);
4501 qobject_unref(bs_entry->state.options);
4502 g_free(bs_entry);
4504 g_free(bs_queue);
4509 * Reopen multiple BlockDriverStates atomically & transactionally.
4511 * The queue passed in (bs_queue) must have been built up previous
4512 * via bdrv_reopen_queue().
4514 * Reopens all BDS specified in the queue, with the appropriate
4515 * flags. All devices are prepared for reopen, and failure of any
4516 * device will cause all device changes to be abandoned, and intermediate
4517 * data cleaned up.
4519 * If all devices prepare successfully, then the changes are committed
4520 * to all devices.
4522 * All affected nodes must be drained between bdrv_reopen_queue() and
4523 * bdrv_reopen_multiple().
4525 * To be called from the main thread, with all other AioContexts unlocked.
4527 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4529 int ret = -1;
4530 BlockReopenQueueEntry *bs_entry, *next;
4531 Transaction *tran = tran_new();
4532 g_autoptr(GSList) refresh_list = NULL;
4534 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4535 assert(bs_queue != NULL);
4536 GLOBAL_STATE_CODE();
4538 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4539 ret = bdrv_flush(bs_entry->state.bs);
4540 if (ret < 0) {
4541 error_setg_errno(errp, -ret, "Error flushing drive");
4542 goto abort;
4546 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4547 assert(bs_entry->state.bs->quiesce_counter > 0);
4548 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4549 if (ret < 0) {
4550 goto abort;
4552 bs_entry->prepared = true;
4555 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4556 BDRVReopenState *state = &bs_entry->state;
4558 refresh_list = g_slist_prepend(refresh_list, state->bs);
4559 if (state->old_backing_bs) {
4560 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4562 if (state->old_file_bs) {
4563 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4568 * Note that file-posix driver rely on permission update done during reopen
4569 * (even if no permission changed), because it wants "new" permissions for
4570 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4571 * in raw_reopen_prepare() which is called with "old" permissions.
4573 bdrv_graph_rdlock_main_loop();
4574 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4575 bdrv_graph_rdunlock_main_loop();
4577 if (ret < 0) {
4578 goto abort;
4582 * If we reach this point, we have success and just need to apply the
4583 * changes.
4585 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4586 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4587 * children are usually goes after parents in reopen-queue, so go from last
4588 * to first element.
4590 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4591 bdrv_reopen_commit(&bs_entry->state);
4594 bdrv_graph_wrlock();
4595 tran_commit(tran);
4596 bdrv_graph_wrunlock();
4598 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4599 BlockDriverState *bs = bs_entry->state.bs;
4601 if (bs->drv->bdrv_reopen_commit_post) {
4602 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4606 ret = 0;
4607 goto cleanup;
4609 abort:
4610 bdrv_graph_wrlock();
4611 tran_abort(tran);
4612 bdrv_graph_wrunlock();
4614 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4615 if (bs_entry->prepared) {
4616 bdrv_reopen_abort(&bs_entry->state);
4620 cleanup:
4621 bdrv_reopen_queue_free(bs_queue);
4623 return ret;
4626 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4627 Error **errp)
4629 BlockReopenQueue *queue;
4631 GLOBAL_STATE_CODE();
4633 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4635 return bdrv_reopen_multiple(queue, errp);
4638 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4639 Error **errp)
4641 QDict *opts = qdict_new();
4643 GLOBAL_STATE_CODE();
4645 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4647 return bdrv_reopen(bs, opts, true, errp);
4651 * Take a BDRVReopenState and check if the value of 'backing' in the
4652 * reopen_state->options QDict is valid or not.
4654 * If 'backing' is missing from the QDict then return 0.
4656 * If 'backing' contains the node name of the backing file of
4657 * reopen_state->bs then return 0.
4659 * If 'backing' contains a different node name (or is null) then check
4660 * whether the current backing file can be replaced with the new one.
4661 * If that's the case then reopen_state->replace_backing_bs is set to
4662 * true and reopen_state->new_backing_bs contains a pointer to the new
4663 * backing BlockDriverState (or NULL).
4665 * After calling this function, the transaction @tran may only be completed
4666 * while holding a writer lock for the graph.
4668 * Return 0 on success, otherwise return < 0 and set @errp.
4670 * @reopen_state->bs can move to a different AioContext in this function.
4672 static int GRAPH_UNLOCKED
4673 bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4674 bool is_backing, Transaction *tran,
4675 Error **errp)
4677 BlockDriverState *bs = reopen_state->bs;
4678 BlockDriverState *new_child_bs;
4679 BlockDriverState *old_child_bs;
4681 const char *child_name = is_backing ? "backing" : "file";
4682 QObject *value;
4683 const char *str;
4684 bool has_child;
4685 int ret;
4687 GLOBAL_STATE_CODE();
4689 value = qdict_get(reopen_state->options, child_name);
4690 if (value == NULL) {
4691 return 0;
4694 bdrv_graph_rdlock_main_loop();
4696 switch (qobject_type(value)) {
4697 case QTYPE_QNULL:
4698 assert(is_backing); /* The 'file' option does not allow a null value */
4699 new_child_bs = NULL;
4700 break;
4701 case QTYPE_QSTRING:
4702 str = qstring_get_str(qobject_to(QString, value));
4703 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4704 if (new_child_bs == NULL) {
4705 ret = -EINVAL;
4706 goto out_rdlock;
4709 has_child = bdrv_recurse_has_child(new_child_bs, bs);
4710 if (has_child) {
4711 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4712 "cycle", str, child_name, bs->node_name);
4713 ret = -EINVAL;
4714 goto out_rdlock;
4716 break;
4717 default:
4719 * The options QDict has been flattened, so 'backing' and 'file'
4720 * do not allow any other data type here.
4722 g_assert_not_reached();
4725 old_child_bs = is_backing ? child_bs(bs->backing) : child_bs(bs->file);
4726 if (old_child_bs == new_child_bs) {
4727 ret = 0;
4728 goto out_rdlock;
4731 if (old_child_bs) {
4732 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4733 ret = 0;
4734 goto out_rdlock;
4737 if (old_child_bs->implicit) {
4738 error_setg(errp, "Cannot replace implicit %s child of %s",
4739 child_name, bs->node_name);
4740 ret = -EPERM;
4741 goto out_rdlock;
4745 if (bs->drv->is_filter && !old_child_bs) {
4747 * Filters always have a file or a backing child, so we are trying to
4748 * change wrong child
4750 error_setg(errp, "'%s' is a %s filter node that does not support a "
4751 "%s child", bs->node_name, bs->drv->format_name, child_name);
4752 ret = -EINVAL;
4753 goto out_rdlock;
4756 if (is_backing) {
4757 reopen_state->old_backing_bs = old_child_bs;
4758 } else {
4759 reopen_state->old_file_bs = old_child_bs;
4762 if (old_child_bs) {
4763 bdrv_ref(old_child_bs);
4764 bdrv_drained_begin(old_child_bs);
4767 bdrv_graph_rdunlock_main_loop();
4768 bdrv_graph_wrlock();
4770 ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4771 tran, errp);
4773 bdrv_graph_wrunlock();
4775 if (old_child_bs) {
4776 bdrv_drained_end(old_child_bs);
4777 bdrv_unref(old_child_bs);
4780 return ret;
4782 out_rdlock:
4783 bdrv_graph_rdunlock_main_loop();
4784 return ret;
4788 * Prepares a BlockDriverState for reopen. All changes are staged in the
4789 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4790 * the block driver layer .bdrv_reopen_prepare()
4792 * bs is the BlockDriverState to reopen
4793 * flags are the new open flags
4794 * queue is the reopen queue
4796 * Returns 0 on success, non-zero on error. On error errp will be set
4797 * as well.
4799 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4800 * It is the responsibility of the caller to then call the abort() or
4801 * commit() for any other BDS that have been left in a prepare() state
4803 * After calling this function, the transaction @change_child_tran may only be
4804 * completed while holding a writer lock for the graph.
4806 static int GRAPH_UNLOCKED
4807 bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4808 Transaction *change_child_tran, Error **errp)
4810 int ret = -1;
4811 int old_flags;
4812 Error *local_err = NULL;
4813 BlockDriver *drv;
4814 QemuOpts *opts;
4815 QDict *orig_reopen_opts;
4816 char *discard = NULL;
4817 bool read_only;
4818 bool drv_prepared = false;
4820 assert(reopen_state != NULL);
4821 assert(reopen_state->bs->drv != NULL);
4822 GLOBAL_STATE_CODE();
4823 drv = reopen_state->bs->drv;
4825 /* This function and each driver's bdrv_reopen_prepare() remove
4826 * entries from reopen_state->options as they are processed, so
4827 * we need to make a copy of the original QDict. */
4828 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4830 /* Process generic block layer options */
4831 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4832 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4833 ret = -EINVAL;
4834 goto error;
4837 /* This was already called in bdrv_reopen_queue_child() so the flags
4838 * are up-to-date. This time we simply want to remove the options from
4839 * QemuOpts in order to indicate that they have been processed. */
4840 old_flags = reopen_state->flags;
4841 update_flags_from_options(&reopen_state->flags, opts);
4842 assert(old_flags == reopen_state->flags);
4844 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4845 if (discard != NULL) {
4846 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4847 error_setg(errp, "Invalid discard option");
4848 ret = -EINVAL;
4849 goto error;
4853 reopen_state->detect_zeroes =
4854 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4855 if (local_err) {
4856 error_propagate(errp, local_err);
4857 ret = -EINVAL;
4858 goto error;
4861 /* All other options (including node-name and driver) must be unchanged.
4862 * Put them back into the QDict, so that they are checked at the end
4863 * of this function. */
4864 qemu_opts_to_qdict(opts, reopen_state->options);
4866 /* If we are to stay read-only, do not allow permission change
4867 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4868 * not set, or if the BDS still has copy_on_read enabled */
4869 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4871 bdrv_graph_rdlock_main_loop();
4872 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4873 bdrv_graph_rdunlock_main_loop();
4874 if (local_err) {
4875 error_propagate(errp, local_err);
4876 goto error;
4879 if (drv->bdrv_reopen_prepare) {
4881 * If a driver-specific option is missing, it means that we
4882 * should reset it to its default value.
4883 * But not all options allow that, so we need to check it first.
4885 ret = bdrv_reset_options_allowed(reopen_state->bs,
4886 reopen_state->options, errp);
4887 if (ret) {
4888 goto error;
4891 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4892 if (ret) {
4893 if (local_err != NULL) {
4894 error_propagate(errp, local_err);
4895 } else {
4896 bdrv_graph_rdlock_main_loop();
4897 bdrv_refresh_filename(reopen_state->bs);
4898 bdrv_graph_rdunlock_main_loop();
4899 error_setg(errp, "failed while preparing to reopen image '%s'",
4900 reopen_state->bs->filename);
4902 goto error;
4904 } else {
4905 /* It is currently mandatory to have a bdrv_reopen_prepare()
4906 * handler for each supported drv. */
4907 bdrv_graph_rdlock_main_loop();
4908 error_setg(errp, "Block format '%s' used by node '%s' "
4909 "does not support reopening files", drv->format_name,
4910 bdrv_get_device_or_node_name(reopen_state->bs));
4911 bdrv_graph_rdunlock_main_loop();
4912 ret = -1;
4913 goto error;
4916 drv_prepared = true;
4919 * We must provide the 'backing' option if the BDS has a backing
4920 * file or if the image file has a backing file name as part of
4921 * its metadata. Otherwise the 'backing' option can be omitted.
4923 bdrv_graph_rdlock_main_loop();
4924 if (drv->supports_backing && reopen_state->backing_missing &&
4925 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4926 error_setg(errp, "backing is missing for '%s'",
4927 reopen_state->bs->node_name);
4928 bdrv_graph_rdunlock_main_loop();
4929 ret = -EINVAL;
4930 goto error;
4932 bdrv_graph_rdunlock_main_loop();
4935 * Allow changing the 'backing' option. The new value can be
4936 * either a reference to an existing node (using its node name)
4937 * or NULL to simply detach the current backing file.
4939 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4940 change_child_tran, errp);
4941 if (ret < 0) {
4942 goto error;
4944 qdict_del(reopen_state->options, "backing");
4946 /* Allow changing the 'file' option. In this case NULL is not allowed */
4947 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4948 change_child_tran, errp);
4949 if (ret < 0) {
4950 goto error;
4952 qdict_del(reopen_state->options, "file");
4954 /* Options that are not handled are only okay if they are unchanged
4955 * compared to the old state. It is expected that some options are only
4956 * used for the initial open, but not reopen (e.g. filename) */
4957 if (qdict_size(reopen_state->options)) {
4958 const QDictEntry *entry = qdict_first(reopen_state->options);
4960 GRAPH_RDLOCK_GUARD_MAINLOOP();
4962 do {
4963 QObject *new = entry->value;
4964 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4966 /* Allow child references (child_name=node_name) as long as they
4967 * point to the current child (i.e. everything stays the same). */
4968 if (qobject_type(new) == QTYPE_QSTRING) {
4969 BdrvChild *child;
4970 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4971 if (!strcmp(child->name, entry->key)) {
4972 break;
4976 if (child) {
4977 if (!strcmp(child->bs->node_name,
4978 qstring_get_str(qobject_to(QString, new)))) {
4979 continue; /* Found child with this name, skip option */
4985 * TODO: When using -drive to specify blockdev options, all values
4986 * will be strings; however, when using -blockdev, blockdev-add or
4987 * filenames using the json:{} pseudo-protocol, they will be
4988 * correctly typed.
4989 * In contrast, reopening options are (currently) always strings
4990 * (because you can only specify them through qemu-io; all other
4991 * callers do not specify any options).
4992 * Therefore, when using anything other than -drive to create a BDS,
4993 * this cannot detect non-string options as unchanged, because
4994 * qobject_is_equal() always returns false for objects of different
4995 * type. In the future, this should be remedied by correctly typing
4996 * all options. For now, this is not too big of an issue because
4997 * the user can simply omit options which cannot be changed anyway,
4998 * so they will stay unchanged.
5000 if (!qobject_is_equal(new, old)) {
5001 error_setg(errp, "Cannot change the option '%s'", entry->key);
5002 ret = -EINVAL;
5003 goto error;
5005 } while ((entry = qdict_next(reopen_state->options, entry)));
5008 ret = 0;
5010 /* Restore the original reopen_state->options QDict */
5011 qobject_unref(reopen_state->options);
5012 reopen_state->options = qobject_ref(orig_reopen_opts);
5014 error:
5015 if (ret < 0 && drv_prepared) {
5016 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
5017 * call drv->bdrv_reopen_abort() before signaling an error
5018 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
5019 * when the respective bdrv_reopen_prepare() has failed) */
5020 if (drv->bdrv_reopen_abort) {
5021 drv->bdrv_reopen_abort(reopen_state);
5024 qemu_opts_del(opts);
5025 qobject_unref(orig_reopen_opts);
5026 g_free(discard);
5027 return ret;
5031 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5032 * makes them final by swapping the staging BlockDriverState contents into
5033 * the active BlockDriverState contents.
5035 static void GRAPH_UNLOCKED bdrv_reopen_commit(BDRVReopenState *reopen_state)
5037 BlockDriver *drv;
5038 BlockDriverState *bs;
5039 BdrvChild *child;
5041 assert(reopen_state != NULL);
5042 bs = reopen_state->bs;
5043 drv = bs->drv;
5044 assert(drv != NULL);
5045 GLOBAL_STATE_CODE();
5047 /* If there are any driver level actions to take */
5048 if (drv->bdrv_reopen_commit) {
5049 drv->bdrv_reopen_commit(reopen_state);
5052 GRAPH_RDLOCK_GUARD_MAINLOOP();
5054 /* set BDS specific flags now */
5055 qobject_unref(bs->explicit_options);
5056 qobject_unref(bs->options);
5057 qobject_ref(reopen_state->explicit_options);
5058 qobject_ref(reopen_state->options);
5060 bs->explicit_options = reopen_state->explicit_options;
5061 bs->options = reopen_state->options;
5062 bs->open_flags = reopen_state->flags;
5063 bs->detect_zeroes = reopen_state->detect_zeroes;
5065 /* Remove child references from bs->options and bs->explicit_options.
5066 * Child options were already removed in bdrv_reopen_queue_child() */
5067 QLIST_FOREACH(child, &bs->children, next) {
5068 qdict_del(bs->explicit_options, child->name);
5069 qdict_del(bs->options, child->name);
5071 /* backing is probably removed, so it's not handled by previous loop */
5072 qdict_del(bs->explicit_options, "backing");
5073 qdict_del(bs->options, "backing");
5075 bdrv_refresh_limits(bs, NULL, NULL);
5076 bdrv_refresh_total_sectors(bs, bs->total_sectors);
5080 * Abort the reopen, and delete and free the staged changes in
5081 * reopen_state
5083 static void GRAPH_UNLOCKED bdrv_reopen_abort(BDRVReopenState *reopen_state)
5085 BlockDriver *drv;
5087 assert(reopen_state != NULL);
5088 drv = reopen_state->bs->drv;
5089 assert(drv != NULL);
5090 GLOBAL_STATE_CODE();
5092 if (drv->bdrv_reopen_abort) {
5093 drv->bdrv_reopen_abort(reopen_state);
5098 static void bdrv_close(BlockDriverState *bs)
5100 BdrvAioNotifier *ban, *ban_next;
5101 BdrvChild *child, *next;
5103 GLOBAL_STATE_CODE();
5104 assert(!bs->refcnt);
5106 bdrv_drained_begin(bs); /* complete I/O */
5107 bdrv_flush(bs);
5108 bdrv_drain(bs); /* in case flush left pending I/O */
5110 if (bs->drv) {
5111 if (bs->drv->bdrv_close) {
5112 /* Must unfreeze all children, so bdrv_unref_child() works */
5113 bs->drv->bdrv_close(bs);
5115 bs->drv = NULL;
5118 bdrv_graph_wrlock();
5119 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
5120 bdrv_unref_child(bs, child);
5123 assert(!bs->backing);
5124 assert(!bs->file);
5125 bdrv_graph_wrunlock();
5127 g_free(bs->opaque);
5128 bs->opaque = NULL;
5129 qatomic_set(&bs->copy_on_read, 0);
5130 bs->backing_file[0] = '\0';
5131 bs->backing_format[0] = '\0';
5132 bs->total_sectors = 0;
5133 bs->encrypted = false;
5134 bs->sg = false;
5135 qobject_unref(bs->options);
5136 qobject_unref(bs->explicit_options);
5137 bs->options = NULL;
5138 bs->explicit_options = NULL;
5139 qobject_unref(bs->full_open_options);
5140 bs->full_open_options = NULL;
5141 g_free(bs->block_status_cache);
5142 bs->block_status_cache = NULL;
5144 bdrv_release_named_dirty_bitmaps(bs);
5145 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5147 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5148 g_free(ban);
5150 QLIST_INIT(&bs->aio_notifiers);
5151 bdrv_drained_end(bs);
5154 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5155 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5156 * gets called.
5158 if (bs->quiesce_counter) {
5159 bdrv_drain_all_end_quiesce(bs);
5163 void bdrv_close_all(void)
5165 GLOBAL_STATE_CODE();
5166 assert(job_next(NULL) == NULL);
5168 /* Drop references from requests still in flight, such as canceled block
5169 * jobs whose AIO context has not been polled yet */
5170 bdrv_drain_all();
5172 blk_remove_all_bs();
5173 blockdev_close_all_bdrv_states();
5175 assert(QTAILQ_EMPTY(&all_bdrv_states));
5178 static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
5180 GQueue *queue;
5181 GHashTable *found;
5182 bool ret;
5184 if (c->klass->stay_at_node) {
5185 return false;
5188 /* If the child @c belongs to the BDS @to, replacing the current
5189 * c->bs by @to would mean to create a loop.
5191 * Such a case occurs when appending a BDS to a backing chain.
5192 * For instance, imagine the following chain:
5194 * guest device -> node A -> further backing chain...
5196 * Now we create a new BDS B which we want to put on top of this
5197 * chain, so we first attach A as its backing node:
5199 * node B
5202 * guest device -> node A -> further backing chain...
5204 * Finally we want to replace A by B. When doing that, we want to
5205 * replace all pointers to A by pointers to B -- except for the
5206 * pointer from B because (1) that would create a loop, and (2)
5207 * that pointer should simply stay intact:
5209 * guest device -> node B
5212 * node A -> further backing chain...
5214 * In general, when replacing a node A (c->bs) by a node B (@to),
5215 * if A is a child of B, that means we cannot replace A by B there
5216 * because that would create a loop. Silently detaching A from B
5217 * is also not really an option. So overall just leaving A in
5218 * place there is the most sensible choice.
5220 * We would also create a loop in any cases where @c is only
5221 * indirectly referenced by @to. Prevent this by returning false
5222 * if @c is found (by breadth-first search) anywhere in the whole
5223 * subtree of @to.
5226 ret = true;
5227 found = g_hash_table_new(NULL, NULL);
5228 g_hash_table_add(found, to);
5229 queue = g_queue_new();
5230 g_queue_push_tail(queue, to);
5232 while (!g_queue_is_empty(queue)) {
5233 BlockDriverState *v = g_queue_pop_head(queue);
5234 BdrvChild *c2;
5236 QLIST_FOREACH(c2, &v->children, next) {
5237 if (c2 == c) {
5238 ret = false;
5239 break;
5242 if (g_hash_table_contains(found, c2->bs)) {
5243 continue;
5246 g_queue_push_tail(queue, c2->bs);
5247 g_hash_table_add(found, c2->bs);
5251 g_queue_free(queue);
5252 g_hash_table_destroy(found);
5254 return ret;
5257 static void bdrv_remove_child_commit(void *opaque)
5259 GLOBAL_STATE_CODE();
5260 bdrv_child_free(opaque);
5263 static TransactionActionDrv bdrv_remove_child_drv = {
5264 .commit = bdrv_remove_child_commit,
5268 * Function doesn't update permissions, caller is responsible for this.
5270 * @child->bs (if non-NULL) must be drained.
5272 * After calling this function, the transaction @tran may only be completed
5273 * while holding a writer lock for the graph.
5275 static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
5277 if (!child) {
5278 return;
5281 if (child->bs) {
5282 assert(child->quiesced_parent);
5283 bdrv_replace_child_tran(child, NULL, tran);
5286 tran_add(tran, &bdrv_remove_child_drv, child);
5290 * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
5291 * until the transaction is completed.
5293 * After calling this function, the transaction @tran may only be completed
5294 * while holding a writer lock for the graph.
5296 static int GRAPH_WRLOCK
5297 bdrv_replace_node_noperm(BlockDriverState *from,
5298 BlockDriverState *to,
5299 bool auto_skip, Transaction *tran,
5300 Error **errp)
5302 BdrvChild *c, *next;
5304 GLOBAL_STATE_CODE();
5306 assert(from->quiesce_counter);
5307 assert(to->quiesce_counter);
5309 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5310 assert(c->bs == from);
5311 if (!should_update_child(c, to)) {
5312 if (auto_skip) {
5313 continue;
5315 error_setg(errp, "Should not change '%s' link to '%s'",
5316 c->name, from->node_name);
5317 return -EINVAL;
5319 if (c->frozen) {
5320 error_setg(errp, "Cannot change '%s' link to '%s'",
5321 c->name, from->node_name);
5322 return -EPERM;
5324 bdrv_replace_child_tran(c, to, tran);
5327 return 0;
5331 * Switch all parents of @from to point to @to instead. @from and @to must be in
5332 * the same AioContext and both must be drained.
5334 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5335 * if it creates a parent-child relation loop or if parent is block-job.
5337 * With auto_skip=false the error is returned if from has a parent which should
5338 * not be updated.
5340 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5341 * case backing link of the cow-parent of @to is removed.
5343 static int GRAPH_WRLOCK
5344 bdrv_replace_node_common(BlockDriverState *from, BlockDriverState *to,
5345 bool auto_skip, bool detach_subchain, Error **errp)
5347 Transaction *tran = tran_new();
5348 g_autoptr(GSList) refresh_list = NULL;
5349 BlockDriverState *to_cow_parent = NULL;
5350 int ret;
5352 GLOBAL_STATE_CODE();
5354 assert(from->quiesce_counter);
5355 assert(to->quiesce_counter);
5356 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5358 if (detach_subchain) {
5359 assert(bdrv_chain_contains(from, to));
5360 assert(from != to);
5361 for (to_cow_parent = from;
5362 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5363 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5370 * Do the replacement without permission update.
5371 * Replacement may influence the permissions, we should calculate new
5372 * permissions based on new graph. If we fail, we'll roll-back the
5373 * replacement.
5375 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5376 if (ret < 0) {
5377 goto out;
5380 if (detach_subchain) {
5381 /* to_cow_parent is already drained because from is drained */
5382 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5385 refresh_list = g_slist_prepend(refresh_list, to);
5386 refresh_list = g_slist_prepend(refresh_list, from);
5388 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5389 if (ret < 0) {
5390 goto out;
5393 ret = 0;
5395 out:
5396 tran_finalize(tran, ret);
5397 return ret;
5400 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5401 Error **errp)
5403 return bdrv_replace_node_common(from, to, true, false, errp);
5406 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5408 BlockDriverState *child_bs;
5409 int ret;
5411 GLOBAL_STATE_CODE();
5413 bdrv_graph_rdlock_main_loop();
5414 child_bs = bdrv_filter_or_cow_bs(bs);
5415 bdrv_graph_rdunlock_main_loop();
5417 bdrv_drained_begin(child_bs);
5418 bdrv_graph_wrlock();
5419 ret = bdrv_replace_node_common(bs, child_bs, true, true, errp);
5420 bdrv_graph_wrunlock();
5421 bdrv_drained_end(child_bs);
5423 return ret;
5427 * Add new bs contents at the top of an image chain while the chain is
5428 * live, while keeping required fields on the top layer.
5430 * This will modify the BlockDriverState fields, and swap contents
5431 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5433 * bs_new must not be attached to a BlockBackend and must not have backing
5434 * child.
5436 * This function does not create any image files.
5438 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5439 Error **errp)
5441 int ret;
5442 BdrvChild *child;
5443 Transaction *tran = tran_new();
5445 GLOBAL_STATE_CODE();
5447 bdrv_graph_rdlock_main_loop();
5448 assert(!bs_new->backing);
5449 bdrv_graph_rdunlock_main_loop();
5451 bdrv_drained_begin(bs_top);
5452 bdrv_drained_begin(bs_new);
5454 bdrv_graph_wrlock();
5456 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5457 &child_of_bds, bdrv_backing_role(bs_new),
5458 tran, errp);
5459 if (!child) {
5460 ret = -EINVAL;
5461 goto out;
5464 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5465 if (ret < 0) {
5466 goto out;
5469 ret = bdrv_refresh_perms(bs_new, tran, errp);
5470 out:
5471 tran_finalize(tran, ret);
5473 bdrv_refresh_limits(bs_top, NULL, NULL);
5474 bdrv_graph_wrunlock();
5476 bdrv_drained_end(bs_top);
5477 bdrv_drained_end(bs_new);
5479 return ret;
5482 /* Not for empty child */
5483 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5484 Error **errp)
5486 int ret;
5487 Transaction *tran = tran_new();
5488 g_autoptr(GSList) refresh_list = NULL;
5489 BlockDriverState *old_bs = child->bs;
5491 GLOBAL_STATE_CODE();
5493 bdrv_ref(old_bs);
5494 bdrv_drained_begin(old_bs);
5495 bdrv_drained_begin(new_bs);
5496 bdrv_graph_wrlock();
5498 bdrv_replace_child_tran(child, new_bs, tran);
5500 refresh_list = g_slist_prepend(refresh_list, old_bs);
5501 refresh_list = g_slist_prepend(refresh_list, new_bs);
5503 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5505 tran_finalize(tran, ret);
5507 bdrv_graph_wrunlock();
5508 bdrv_drained_end(old_bs);
5509 bdrv_drained_end(new_bs);
5510 bdrv_unref(old_bs);
5512 return ret;
5515 static void bdrv_delete(BlockDriverState *bs)
5517 assert(bdrv_op_blocker_is_empty(bs));
5518 assert(!bs->refcnt);
5519 GLOBAL_STATE_CODE();
5521 /* remove from list, if necessary */
5522 if (bs->node_name[0] != '\0') {
5523 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5525 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5527 bdrv_close(bs);
5529 qemu_mutex_destroy(&bs->reqs_lock);
5531 g_free(bs);
5536 * Replace @bs by newly created block node.
5538 * @options is a QDict of options to pass to the block drivers, or NULL for an
5539 * empty set of options. The reference to the QDict belongs to the block layer
5540 * after the call (even on failure), so if the caller intends to reuse the
5541 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5543 * The caller must make sure that @bs stays in the same AioContext, i.e.
5544 * @options must not refer to nodes in a different AioContext.
5546 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5547 int flags, Error **errp)
5549 ERRP_GUARD();
5550 int ret;
5551 AioContext *ctx = bdrv_get_aio_context(bs);
5552 BlockDriverState *new_node_bs = NULL;
5553 const char *drvname, *node_name;
5554 BlockDriver *drv;
5556 drvname = qdict_get_try_str(options, "driver");
5557 if (!drvname) {
5558 error_setg(errp, "driver is not specified");
5559 goto fail;
5562 drv = bdrv_find_format(drvname);
5563 if (!drv) {
5564 error_setg(errp, "Unknown driver: '%s'", drvname);
5565 goto fail;
5568 node_name = qdict_get_try_str(options, "node-name");
5570 GLOBAL_STATE_CODE();
5572 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5573 errp);
5574 assert(bdrv_get_aio_context(bs) == ctx);
5576 options = NULL; /* bdrv_new_open_driver() eats options */
5577 if (!new_node_bs) {
5578 error_prepend(errp, "Could not create node: ");
5579 goto fail;
5583 * Make sure that @bs doesn't go away until we have successfully attached
5584 * all of its parents to @new_node_bs and undrained it again.
5586 bdrv_ref(bs);
5587 bdrv_drained_begin(bs);
5588 bdrv_drained_begin(new_node_bs);
5589 bdrv_graph_wrlock();
5590 ret = bdrv_replace_node(bs, new_node_bs, errp);
5591 bdrv_graph_wrunlock();
5592 bdrv_drained_end(new_node_bs);
5593 bdrv_drained_end(bs);
5594 bdrv_unref(bs);
5596 if (ret < 0) {
5597 error_prepend(errp, "Could not replace node: ");
5598 goto fail;
5601 return new_node_bs;
5603 fail:
5604 qobject_unref(options);
5605 bdrv_unref(new_node_bs);
5606 return NULL;
5610 * Run consistency checks on an image
5612 * Returns 0 if the check could be completed (it doesn't mean that the image is
5613 * free of errors) or -errno when an internal error occurred. The results of the
5614 * check are stored in res.
5616 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5617 BdrvCheckResult *res, BdrvCheckMode fix)
5619 IO_CODE();
5620 assert_bdrv_graph_readable();
5621 if (bs->drv == NULL) {
5622 return -ENOMEDIUM;
5624 if (bs->drv->bdrv_co_check == NULL) {
5625 return -ENOTSUP;
5628 memset(res, 0, sizeof(*res));
5629 return bs->drv->bdrv_co_check(bs, res, fix);
5633 * Return values:
5634 * 0 - success
5635 * -EINVAL - backing format specified, but no file
5636 * -ENOSPC - can't update the backing file because no space is left in the
5637 * image file header
5638 * -ENOTSUP - format driver doesn't support changing the backing file
5640 int coroutine_fn
5641 bdrv_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
5642 const char *backing_fmt, bool require)
5644 BlockDriver *drv = bs->drv;
5645 int ret;
5647 IO_CODE();
5649 if (!drv) {
5650 return -ENOMEDIUM;
5653 /* Backing file format doesn't make sense without a backing file */
5654 if (backing_fmt && !backing_file) {
5655 return -EINVAL;
5658 if (require && backing_file && !backing_fmt) {
5659 return -EINVAL;
5662 if (drv->bdrv_co_change_backing_file != NULL) {
5663 ret = drv->bdrv_co_change_backing_file(bs, backing_file, backing_fmt);
5664 } else {
5665 ret = -ENOTSUP;
5668 if (ret == 0) {
5669 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5670 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5671 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5672 backing_file ?: "");
5674 return ret;
5678 * Finds the first non-filter node above bs in the chain between
5679 * active and bs. The returned node is either an immediate parent of
5680 * bs, or there are only filter nodes between the two.
5682 * Returns NULL if bs is not found in active's image chain,
5683 * or if active == bs.
5685 * Returns the bottommost base image if bs == NULL.
5687 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5688 BlockDriverState *bs)
5691 GLOBAL_STATE_CODE();
5693 bs = bdrv_skip_filters(bs);
5694 active = bdrv_skip_filters(active);
5696 while (active) {
5697 BlockDriverState *next = bdrv_backing_chain_next(active);
5698 if (bs == next) {
5699 return active;
5701 active = next;
5704 return NULL;
5707 /* Given a BDS, searches for the base layer. */
5708 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5710 GLOBAL_STATE_CODE();
5712 return bdrv_find_overlay(bs, NULL);
5716 * Return true if at least one of the COW (backing) and filter links
5717 * between @bs and @base is frozen. @errp is set if that's the case.
5718 * @base must be reachable from @bs, or NULL.
5720 static bool GRAPH_RDLOCK
5721 bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5722 Error **errp)
5724 BlockDriverState *i;
5725 BdrvChild *child;
5727 GLOBAL_STATE_CODE();
5729 for (i = bs; i != base; i = child_bs(child)) {
5730 child = bdrv_filter_or_cow_child(i);
5732 if (child && child->frozen) {
5733 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5734 child->name, i->node_name, child->bs->node_name);
5735 return true;
5739 return false;
5743 * Freeze all COW (backing) and filter links between @bs and @base.
5744 * If any of the links is already frozen the operation is aborted and
5745 * none of the links are modified.
5746 * @base must be reachable from @bs, or NULL.
5747 * Returns 0 on success. On failure returns < 0 and sets @errp.
5749 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5750 Error **errp)
5752 BlockDriverState *i;
5753 BdrvChild *child;
5755 GLOBAL_STATE_CODE();
5757 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5758 return -EPERM;
5761 for (i = bs; i != base; i = child_bs(child)) {
5762 child = bdrv_filter_or_cow_child(i);
5763 if (child && child->bs->never_freeze) {
5764 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5765 child->name, child->bs->node_name);
5766 return -EPERM;
5770 for (i = bs; i != base; i = child_bs(child)) {
5771 child = bdrv_filter_or_cow_child(i);
5772 if (child) {
5773 child->frozen = true;
5777 return 0;
5781 * Unfreeze all COW (backing) and filter links between @bs and @base.
5782 * The caller must ensure that all links are frozen before using this
5783 * function.
5784 * @base must be reachable from @bs, or NULL.
5786 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5788 BlockDriverState *i;
5789 BdrvChild *child;
5791 GLOBAL_STATE_CODE();
5793 for (i = bs; i != base; i = child_bs(child)) {
5794 child = bdrv_filter_or_cow_child(i);
5795 if (child) {
5796 assert(child->frozen);
5797 child->frozen = false;
5803 * Drops images above 'base' up to and including 'top', and sets the image
5804 * above 'top' to have base as its backing file.
5806 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5807 * information in 'bs' can be properly updated.
5809 * E.g., this will convert the following chain:
5810 * bottom <- base <- intermediate <- top <- active
5812 * to
5814 * bottom <- base <- active
5816 * It is allowed for bottom==base, in which case it converts:
5818 * base <- intermediate <- top <- active
5820 * to
5822 * base <- active
5824 * If backing_file_str is non-NULL, it will be used when modifying top's
5825 * overlay image metadata.
5827 * Error conditions:
5828 * if active == top, that is considered an error
5831 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5832 const char *backing_file_str,
5833 bool backing_mask_protocol)
5835 BlockDriverState *explicit_top = top;
5836 bool update_inherits_from;
5837 BdrvChild *c;
5838 Error *local_err = NULL;
5839 int ret = -EIO;
5840 g_autoptr(GSList) updated_children = NULL;
5841 GSList *p;
5843 GLOBAL_STATE_CODE();
5845 bdrv_ref(top);
5846 bdrv_drained_begin(base);
5847 bdrv_graph_wrlock();
5849 if (!top->drv || !base->drv) {
5850 goto exit_wrlock;
5853 /* Make sure that base is in the backing chain of top */
5854 if (!bdrv_chain_contains(top, base)) {
5855 goto exit_wrlock;
5858 /* If 'base' recursively inherits from 'top' then we should set
5859 * base->inherits_from to top->inherits_from after 'top' and all
5860 * other intermediate nodes have been dropped.
5861 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5862 * it because no one inherits from it. We use explicit_top for that. */
5863 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5864 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5866 /* success - we can delete the intermediate states, and link top->base */
5867 if (!backing_file_str) {
5868 bdrv_refresh_filename(base);
5869 backing_file_str = base->filename;
5872 QLIST_FOREACH(c, &top->parents, next_parent) {
5873 updated_children = g_slist_prepend(updated_children, c);
5877 * It seems correct to pass detach_subchain=true here, but it triggers
5878 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5879 * another drained section, which modify the graph (for example, removing
5880 * the child, which we keep in updated_children list). So, it's a TODO.
5882 * Note, bug triggered if pass detach_subchain=true here and run
5883 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5884 * That's a FIXME.
5886 bdrv_replace_node_common(top, base, false, false, &local_err);
5887 bdrv_graph_wrunlock();
5889 if (local_err) {
5890 error_report_err(local_err);
5891 goto exit;
5894 for (p = updated_children; p; p = p->next) {
5895 c = p->data;
5897 if (c->klass->update_filename) {
5898 ret = c->klass->update_filename(c, base, backing_file_str,
5899 backing_mask_protocol,
5900 &local_err);
5901 if (ret < 0) {
5903 * TODO: Actually, we want to rollback all previous iterations
5904 * of this loop, and (which is almost impossible) previous
5905 * bdrv_replace_node()...
5907 * Note, that c->klass->update_filename may lead to permission
5908 * update, so it's a bad idea to call it inside permission
5909 * update transaction of bdrv_replace_node.
5911 error_report_err(local_err);
5912 goto exit;
5917 if (update_inherits_from) {
5918 base->inherits_from = explicit_top->inherits_from;
5921 ret = 0;
5922 goto exit;
5924 exit_wrlock:
5925 bdrv_graph_wrunlock();
5926 exit:
5927 bdrv_drained_end(base);
5928 bdrv_unref(top);
5929 return ret;
5933 * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
5934 * sums the size of all data-bearing children. (This excludes backing
5935 * children.)
5937 static int64_t coroutine_fn GRAPH_RDLOCK
5938 bdrv_sum_allocated_file_size(BlockDriverState *bs)
5940 BdrvChild *child;
5941 int64_t child_size, sum = 0;
5943 QLIST_FOREACH(child, &bs->children, next) {
5944 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5945 BDRV_CHILD_FILTERED))
5947 child_size = bdrv_co_get_allocated_file_size(child->bs);
5948 if (child_size < 0) {
5949 return child_size;
5951 sum += child_size;
5955 return sum;
5959 * Length of a allocated file in bytes. Sparse files are counted by actual
5960 * allocated space. Return < 0 if error or unknown.
5962 int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
5964 BlockDriver *drv = bs->drv;
5965 IO_CODE();
5966 assert_bdrv_graph_readable();
5968 if (!drv) {
5969 return -ENOMEDIUM;
5971 if (drv->bdrv_co_get_allocated_file_size) {
5972 return drv->bdrv_co_get_allocated_file_size(bs);
5975 if (drv->bdrv_file_open) {
5977 * Protocol drivers default to -ENOTSUP (most of their data is
5978 * not stored in any of their children (if they even have any),
5979 * so there is no generic way to figure it out).
5981 return -ENOTSUP;
5982 } else if (drv->is_filter) {
5983 /* Filter drivers default to the size of their filtered child */
5984 return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
5985 } else {
5986 /* Other drivers default to summing their children's sizes */
5987 return bdrv_sum_allocated_file_size(bs);
5992 * bdrv_measure:
5993 * @drv: Format driver
5994 * @opts: Creation options for new image
5995 * @in_bs: Existing image containing data for new image (may be NULL)
5996 * @errp: Error object
5997 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5998 * or NULL on error
6000 * Calculate file size required to create a new image.
6002 * If @in_bs is given then space for allocated clusters and zero clusters
6003 * from that image are included in the calculation. If @opts contains a
6004 * backing file that is shared by @in_bs then backing clusters may be omitted
6005 * from the calculation.
6007 * If @in_bs is NULL then the calculation includes no allocated clusters
6008 * unless a preallocation option is given in @opts.
6010 * Note that @in_bs may use a different BlockDriver from @drv.
6012 * If an error occurs the @errp pointer is set.
6014 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
6015 BlockDriverState *in_bs, Error **errp)
6017 IO_CODE();
6018 if (!drv->bdrv_measure) {
6019 error_setg(errp, "Block driver '%s' does not support size measurement",
6020 drv->format_name);
6021 return NULL;
6024 return drv->bdrv_measure(opts, in_bs, errp);
6028 * Return number of sectors on success, -errno on error.
6030 int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
6032 BlockDriver *drv = bs->drv;
6033 IO_CODE();
6034 assert_bdrv_graph_readable();
6036 if (!drv)
6037 return -ENOMEDIUM;
6039 if (bs->bl.has_variable_length) {
6040 int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
6041 if (ret < 0) {
6042 return ret;
6045 return bs->total_sectors;
6049 * This wrapper is written by hand because this function is in the hot I/O path,
6050 * via blk_get_geometry.
6052 int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
6054 BlockDriver *drv = bs->drv;
6055 IO_CODE();
6057 if (!drv)
6058 return -ENOMEDIUM;
6060 if (bs->bl.has_variable_length) {
6061 int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6062 if (ret < 0) {
6063 return ret;
6067 return bs->total_sectors;
6071 * Return length in bytes on success, -errno on error.
6072 * The length is always a multiple of BDRV_SECTOR_SIZE.
6074 int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
6076 int64_t ret;
6077 IO_CODE();
6078 assert_bdrv_graph_readable();
6080 ret = bdrv_co_nb_sectors(bs);
6081 if (ret < 0) {
6082 return ret;
6084 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
6085 return -EFBIG;
6087 return ret * BDRV_SECTOR_SIZE;
6090 bool bdrv_is_sg(BlockDriverState *bs)
6092 IO_CODE();
6093 return bs->sg;
6097 * Return whether the given node supports compressed writes.
6099 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
6101 BlockDriverState *filtered;
6102 IO_CODE();
6104 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
6105 return false;
6108 filtered = bdrv_filter_bs(bs);
6109 if (filtered) {
6111 * Filters can only forward compressed writes, so we have to
6112 * check the child.
6114 return bdrv_supports_compressed_writes(filtered);
6117 return true;
6120 const char *bdrv_get_format_name(BlockDriverState *bs)
6122 IO_CODE();
6123 return bs->drv ? bs->drv->format_name : NULL;
6126 static int qsort_strcmp(const void *a, const void *b)
6128 return strcmp(*(char *const *)a, *(char *const *)b);
6131 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
6132 void *opaque, bool read_only)
6134 BlockDriver *drv;
6135 int count = 0;
6136 int i;
6137 const char **formats = NULL;
6139 GLOBAL_STATE_CODE();
6141 QLIST_FOREACH(drv, &bdrv_drivers, list) {
6142 if (drv->format_name) {
6143 bool found = false;
6145 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
6146 continue;
6149 i = count;
6150 while (formats && i && !found) {
6151 found = !strcmp(formats[--i], drv->format_name);
6154 if (!found) {
6155 formats = g_renew(const char *, formats, count + 1);
6156 formats[count++] = drv->format_name;
6161 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
6162 const char *format_name = block_driver_modules[i].format_name;
6164 if (format_name) {
6165 bool found = false;
6166 int j = count;
6168 if (use_bdrv_whitelist &&
6169 !bdrv_format_is_whitelisted(format_name, read_only)) {
6170 continue;
6173 while (formats && j && !found) {
6174 found = !strcmp(formats[--j], format_name);
6177 if (!found) {
6178 formats = g_renew(const char *, formats, count + 1);
6179 formats[count++] = format_name;
6184 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6186 for (i = 0; i < count; i++) {
6187 it(opaque, formats[i]);
6190 g_free(formats);
6193 /* This function is to find a node in the bs graph */
6194 BlockDriverState *bdrv_find_node(const char *node_name)
6196 BlockDriverState *bs;
6198 assert(node_name);
6199 GLOBAL_STATE_CODE();
6201 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6202 if (!strcmp(node_name, bs->node_name)) {
6203 return bs;
6206 return NULL;
6209 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6210 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6211 Error **errp)
6213 BlockDeviceInfoList *list;
6214 BlockDriverState *bs;
6216 GLOBAL_STATE_CODE();
6217 GRAPH_RDLOCK_GUARD_MAINLOOP();
6219 list = NULL;
6220 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6221 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6222 if (!info) {
6223 qapi_free_BlockDeviceInfoList(list);
6224 return NULL;
6226 QAPI_LIST_PREPEND(list, info);
6229 return list;
6232 typedef struct XDbgBlockGraphConstructor {
6233 XDbgBlockGraph *graph;
6234 GHashTable *graph_nodes;
6235 } XDbgBlockGraphConstructor;
6237 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6239 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6241 gr->graph = g_new0(XDbgBlockGraph, 1);
6242 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6244 return gr;
6247 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6249 XDbgBlockGraph *graph = gr->graph;
6251 g_hash_table_destroy(gr->graph_nodes);
6252 g_free(gr);
6254 return graph;
6257 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6259 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6261 if (ret != 0) {
6262 return ret;
6266 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6267 * answer of g_hash_table_lookup.
6269 ret = g_hash_table_size(gr->graph_nodes) + 1;
6270 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6272 return ret;
6275 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6276 XDbgBlockGraphNodeType type, const char *name)
6278 XDbgBlockGraphNode *n;
6280 n = g_new0(XDbgBlockGraphNode, 1);
6282 n->id = xdbg_graph_node_num(gr, node);
6283 n->type = type;
6284 n->name = g_strdup(name);
6286 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6289 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6290 const BdrvChild *child)
6292 BlockPermission qapi_perm;
6293 XDbgBlockGraphEdge *edge;
6294 GLOBAL_STATE_CODE();
6296 edge = g_new0(XDbgBlockGraphEdge, 1);
6298 edge->parent = xdbg_graph_node_num(gr, parent);
6299 edge->child = xdbg_graph_node_num(gr, child->bs);
6300 edge->name = g_strdup(child->name);
6302 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6303 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6305 if (flag & child->perm) {
6306 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6308 if (flag & child->shared_perm) {
6309 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6313 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6317 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6319 BlockBackend *blk;
6320 BlockJob *job;
6321 BlockDriverState *bs;
6322 BdrvChild *child;
6323 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6325 GLOBAL_STATE_CODE();
6327 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6328 char *allocated_name = NULL;
6329 const char *name = blk_name(blk);
6331 if (!*name) {
6332 name = allocated_name = blk_get_attached_dev_id(blk);
6334 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6335 name);
6336 g_free(allocated_name);
6337 if (blk_root(blk)) {
6338 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6342 WITH_JOB_LOCK_GUARD() {
6343 for (job = block_job_next_locked(NULL); job;
6344 job = block_job_next_locked(job)) {
6345 GSList *el;
6347 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6348 job->job.id);
6349 for (el = job->nodes; el; el = el->next) {
6350 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6355 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6356 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6357 bs->node_name);
6358 QLIST_FOREACH(child, &bs->children, next) {
6359 xdbg_graph_add_edge(gr, bs, child);
6363 return xdbg_graph_finalize(gr);
6366 BlockDriverState *bdrv_lookup_bs(const char *device,
6367 const char *node_name,
6368 Error **errp)
6370 BlockBackend *blk;
6371 BlockDriverState *bs;
6373 GLOBAL_STATE_CODE();
6375 if (device) {
6376 blk = blk_by_name(device);
6378 if (blk) {
6379 bs = blk_bs(blk);
6380 if (!bs) {
6381 error_setg(errp, "Device '%s' has no medium", device);
6384 return bs;
6388 if (node_name) {
6389 bs = bdrv_find_node(node_name);
6391 if (bs) {
6392 return bs;
6396 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6397 device ? device : "",
6398 node_name ? node_name : "");
6399 return NULL;
6402 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6403 * return false. If either argument is NULL, return false. */
6404 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6407 GLOBAL_STATE_CODE();
6409 while (top && top != base) {
6410 top = bdrv_filter_or_cow_bs(top);
6413 return top != NULL;
6416 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6418 GLOBAL_STATE_CODE();
6419 if (!bs) {
6420 return QTAILQ_FIRST(&graph_bdrv_states);
6422 return QTAILQ_NEXT(bs, node_list);
6425 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6427 GLOBAL_STATE_CODE();
6428 if (!bs) {
6429 return QTAILQ_FIRST(&all_bdrv_states);
6431 return QTAILQ_NEXT(bs, bs_list);
6434 const char *bdrv_get_node_name(const BlockDriverState *bs)
6436 IO_CODE();
6437 return bs->node_name;
6440 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6442 BdrvChild *c;
6443 const char *name;
6444 IO_CODE();
6446 /* If multiple parents have a name, just pick the first one. */
6447 QLIST_FOREACH(c, &bs->parents, next_parent) {
6448 if (c->klass->get_name) {
6449 name = c->klass->get_name(c);
6450 if (name && *name) {
6451 return name;
6456 return NULL;
6459 /* TODO check what callers really want: bs->node_name or blk_name() */
6460 const char *bdrv_get_device_name(const BlockDriverState *bs)
6462 IO_CODE();
6463 return bdrv_get_parent_name(bs) ?: "";
6466 /* This can be used to identify nodes that might not have a device
6467 * name associated. Since node and device names live in the same
6468 * namespace, the result is unambiguous. The exception is if both are
6469 * absent, then this returns an empty (non-null) string. */
6470 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6472 IO_CODE();
6473 return bdrv_get_parent_name(bs) ?: bs->node_name;
6476 int bdrv_get_flags(BlockDriverState *bs)
6478 IO_CODE();
6479 return bs->open_flags;
6482 int bdrv_has_zero_init_1(BlockDriverState *bs)
6484 GLOBAL_STATE_CODE();
6485 return 1;
6488 int coroutine_mixed_fn bdrv_has_zero_init(BlockDriverState *bs)
6490 BlockDriverState *filtered;
6491 GLOBAL_STATE_CODE();
6493 if (!bs->drv) {
6494 return 0;
6497 /* If BS is a copy on write image, it is initialized to
6498 the contents of the base image, which may not be zeroes. */
6499 if (bdrv_cow_child(bs)) {
6500 return 0;
6502 if (bs->drv->bdrv_has_zero_init) {
6503 return bs->drv->bdrv_has_zero_init(bs);
6506 filtered = bdrv_filter_bs(bs);
6507 if (filtered) {
6508 return bdrv_has_zero_init(filtered);
6511 /* safe default */
6512 return 0;
6515 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6517 IO_CODE();
6518 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6519 return false;
6522 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6525 void bdrv_get_backing_filename(BlockDriverState *bs,
6526 char *filename, int filename_size)
6528 IO_CODE();
6529 pstrcpy(filename, filename_size, bs->backing_file);
6532 int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6534 int ret;
6535 BlockDriver *drv = bs->drv;
6536 IO_CODE();
6537 assert_bdrv_graph_readable();
6539 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6540 if (!drv) {
6541 return -ENOMEDIUM;
6543 if (!drv->bdrv_co_get_info) {
6544 BlockDriverState *filtered = bdrv_filter_bs(bs);
6545 if (filtered) {
6546 return bdrv_co_get_info(filtered, bdi);
6548 return -ENOTSUP;
6550 memset(bdi, 0, sizeof(*bdi));
6551 ret = drv->bdrv_co_get_info(bs, bdi);
6552 if (bdi->subcluster_size == 0) {
6554 * If the driver left this unset, subclusters are not supported.
6555 * Then it is safe to treat each cluster as having only one subcluster.
6557 bdi->subcluster_size = bdi->cluster_size;
6559 if (ret < 0) {
6560 return ret;
6563 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6564 return -EINVAL;
6567 return 0;
6570 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6571 Error **errp)
6573 BlockDriver *drv = bs->drv;
6574 IO_CODE();
6575 if (drv && drv->bdrv_get_specific_info) {
6576 return drv->bdrv_get_specific_info(bs, errp);
6578 return NULL;
6581 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6583 BlockDriver *drv = bs->drv;
6584 IO_CODE();
6585 if (!drv || !drv->bdrv_get_specific_stats) {
6586 return NULL;
6588 return drv->bdrv_get_specific_stats(bs);
6591 void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6593 IO_CODE();
6594 assert_bdrv_graph_readable();
6596 if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
6597 return;
6600 bs->drv->bdrv_co_debug_event(bs, event);
6603 static BlockDriverState * GRAPH_RDLOCK
6604 bdrv_find_debug_node(BlockDriverState *bs)
6606 GLOBAL_STATE_CODE();
6607 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6608 bs = bdrv_primary_bs(bs);
6611 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6612 assert(bs->drv->bdrv_debug_remove_breakpoint);
6613 return bs;
6616 return NULL;
6619 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6620 const char *tag)
6622 GLOBAL_STATE_CODE();
6623 GRAPH_RDLOCK_GUARD_MAINLOOP();
6625 bs = bdrv_find_debug_node(bs);
6626 if (bs) {
6627 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6630 return -ENOTSUP;
6633 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6635 GLOBAL_STATE_CODE();
6636 GRAPH_RDLOCK_GUARD_MAINLOOP();
6638 bs = bdrv_find_debug_node(bs);
6639 if (bs) {
6640 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6643 return -ENOTSUP;
6646 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6648 GLOBAL_STATE_CODE();
6649 GRAPH_RDLOCK_GUARD_MAINLOOP();
6651 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6652 bs = bdrv_primary_bs(bs);
6655 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6656 return bs->drv->bdrv_debug_resume(bs, tag);
6659 return -ENOTSUP;
6662 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6664 GLOBAL_STATE_CODE();
6665 GRAPH_RDLOCK_GUARD_MAINLOOP();
6667 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6668 bs = bdrv_primary_bs(bs);
6671 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6672 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6675 return false;
6678 /* backing_file can either be relative, or absolute, or a protocol. If it is
6679 * relative, it must be relative to the chain. So, passing in bs->filename
6680 * from a BDS as backing_file should not be done, as that may be relative to
6681 * the CWD rather than the chain. */
6682 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6683 const char *backing_file)
6685 char *filename_full = NULL;
6686 char *backing_file_full = NULL;
6687 char *filename_tmp = NULL;
6688 int is_protocol = 0;
6689 bool filenames_refreshed = false;
6690 BlockDriverState *curr_bs = NULL;
6691 BlockDriverState *retval = NULL;
6692 BlockDriverState *bs_below;
6694 GLOBAL_STATE_CODE();
6695 GRAPH_RDLOCK_GUARD_MAINLOOP();
6697 if (!bs || !bs->drv || !backing_file) {
6698 return NULL;
6701 filename_full = g_malloc(PATH_MAX);
6702 backing_file_full = g_malloc(PATH_MAX);
6704 is_protocol = path_has_protocol(backing_file);
6707 * Being largely a legacy function, skip any filters here
6708 * (because filters do not have normal filenames, so they cannot
6709 * match anyway; and allowing json:{} filenames is a bit out of
6710 * scope).
6712 for (curr_bs = bdrv_skip_filters(bs);
6713 bdrv_cow_child(curr_bs) != NULL;
6714 curr_bs = bs_below)
6716 bs_below = bdrv_backing_chain_next(curr_bs);
6718 if (bdrv_backing_overridden(curr_bs)) {
6720 * If the backing file was overridden, we can only compare
6721 * directly against the backing node's filename.
6724 if (!filenames_refreshed) {
6726 * This will automatically refresh all of the
6727 * filenames in the rest of the backing chain, so we
6728 * only need to do this once.
6730 bdrv_refresh_filename(bs_below);
6731 filenames_refreshed = true;
6734 if (strcmp(backing_file, bs_below->filename) == 0) {
6735 retval = bs_below;
6736 break;
6738 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6740 * If either of the filename paths is actually a protocol, then
6741 * compare unmodified paths; otherwise make paths relative.
6743 char *backing_file_full_ret;
6745 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6746 retval = bs_below;
6747 break;
6749 /* Also check against the full backing filename for the image */
6750 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6751 NULL);
6752 if (backing_file_full_ret) {
6753 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6754 g_free(backing_file_full_ret);
6755 if (equal) {
6756 retval = bs_below;
6757 break;
6760 } else {
6761 /* If not an absolute filename path, make it relative to the current
6762 * image's filename path */
6763 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6764 NULL);
6765 /* We are going to compare canonicalized absolute pathnames */
6766 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6767 g_free(filename_tmp);
6768 continue;
6770 g_free(filename_tmp);
6772 /* We need to make sure the backing filename we are comparing against
6773 * is relative to the current image filename (or absolute) */
6774 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6775 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6776 g_free(filename_tmp);
6777 continue;
6779 g_free(filename_tmp);
6781 if (strcmp(backing_file_full, filename_full) == 0) {
6782 retval = bs_below;
6783 break;
6788 g_free(filename_full);
6789 g_free(backing_file_full);
6790 return retval;
6793 void bdrv_init(void)
6795 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6796 use_bdrv_whitelist = 1;
6797 #endif
6798 module_call_init(MODULE_INIT_BLOCK);
6801 void bdrv_init_with_whitelist(void)
6803 use_bdrv_whitelist = 1;
6804 bdrv_init();
6807 int bdrv_activate(BlockDriverState *bs, Error **errp)
6809 BdrvChild *child, *parent;
6810 Error *local_err = NULL;
6811 int ret;
6812 BdrvDirtyBitmap *bm;
6814 GLOBAL_STATE_CODE();
6815 GRAPH_RDLOCK_GUARD_MAINLOOP();
6817 if (!bs->drv) {
6818 return -ENOMEDIUM;
6821 QLIST_FOREACH(child, &bs->children, next) {
6822 bdrv_activate(child->bs, &local_err);
6823 if (local_err) {
6824 error_propagate(errp, local_err);
6825 return -EINVAL;
6830 * Update permissions, they may differ for inactive nodes.
6832 * Note that the required permissions of inactive images are always a
6833 * subset of the permissions required after activating the image. This
6834 * allows us to just get the permissions upfront without restricting
6835 * bdrv_co_invalidate_cache().
6837 * It also means that in error cases, we don't have to try and revert to
6838 * the old permissions (which is an operation that could fail, too). We can
6839 * just keep the extended permissions for the next time that an activation
6840 * of the image is tried.
6842 if (bs->open_flags & BDRV_O_INACTIVE) {
6843 bs->open_flags &= ~BDRV_O_INACTIVE;
6844 ret = bdrv_refresh_perms(bs, NULL, errp);
6845 if (ret < 0) {
6846 bs->open_flags |= BDRV_O_INACTIVE;
6847 return ret;
6850 ret = bdrv_invalidate_cache(bs, errp);
6851 if (ret < 0) {
6852 bs->open_flags |= BDRV_O_INACTIVE;
6853 return ret;
6856 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6857 bdrv_dirty_bitmap_skip_store(bm, false);
6860 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6861 if (ret < 0) {
6862 bs->open_flags |= BDRV_O_INACTIVE;
6863 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6864 return ret;
6868 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6869 if (parent->klass->activate) {
6870 parent->klass->activate(parent, &local_err);
6871 if (local_err) {
6872 bs->open_flags |= BDRV_O_INACTIVE;
6873 error_propagate(errp, local_err);
6874 return -EINVAL;
6879 return 0;
6882 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6884 Error *local_err = NULL;
6885 IO_CODE();
6887 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6888 assert_bdrv_graph_readable();
6890 if (bs->drv->bdrv_co_invalidate_cache) {
6891 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6892 if (local_err) {
6893 error_propagate(errp, local_err);
6894 return -EINVAL;
6898 return 0;
6901 void bdrv_activate_all(Error **errp)
6903 BlockDriverState *bs;
6904 BdrvNextIterator it;
6906 GLOBAL_STATE_CODE();
6907 GRAPH_RDLOCK_GUARD_MAINLOOP();
6909 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6910 int ret;
6912 ret = bdrv_activate(bs, errp);
6913 if (ret < 0) {
6914 bdrv_next_cleanup(&it);
6915 return;
6920 static bool GRAPH_RDLOCK
6921 bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6923 BdrvChild *parent;
6924 GLOBAL_STATE_CODE();
6926 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6927 if (parent->klass->parent_is_bds) {
6928 BlockDriverState *parent_bs = parent->opaque;
6929 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6930 return true;
6935 return false;
6938 static int GRAPH_RDLOCK bdrv_inactivate_recurse(BlockDriverState *bs)
6940 BdrvChild *child, *parent;
6941 int ret;
6942 uint64_t cumulative_perms, cumulative_shared_perms;
6944 GLOBAL_STATE_CODE();
6946 if (!bs->drv) {
6947 return -ENOMEDIUM;
6950 /* Make sure that we don't inactivate a child before its parent.
6951 * It will be covered by recursion from the yet active parent. */
6952 if (bdrv_has_bds_parent(bs, true)) {
6953 return 0;
6956 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6958 /* Inactivate this node */
6959 if (bs->drv->bdrv_inactivate) {
6960 ret = bs->drv->bdrv_inactivate(bs);
6961 if (ret < 0) {
6962 return ret;
6966 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6967 if (parent->klass->inactivate) {
6968 ret = parent->klass->inactivate(parent);
6969 if (ret < 0) {
6970 return ret;
6975 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6976 &cumulative_shared_perms);
6977 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6978 /* Our inactive parents still need write access. Inactivation failed. */
6979 return -EPERM;
6982 bs->open_flags |= BDRV_O_INACTIVE;
6985 * Update permissions, they may differ for inactive nodes.
6986 * We only tried to loosen restrictions, so errors are not fatal, ignore
6987 * them.
6989 bdrv_refresh_perms(bs, NULL, NULL);
6991 /* Recursively inactivate children */
6992 QLIST_FOREACH(child, &bs->children, next) {
6993 ret = bdrv_inactivate_recurse(child->bs);
6994 if (ret < 0) {
6995 return ret;
6999 return 0;
7002 int bdrv_inactivate_all(void)
7004 BlockDriverState *bs = NULL;
7005 BdrvNextIterator it;
7006 int ret = 0;
7008 GLOBAL_STATE_CODE();
7009 GRAPH_RDLOCK_GUARD_MAINLOOP();
7011 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
7012 /* Nodes with BDS parents are covered by recursion from the last
7013 * parent that gets inactivated. Don't inactivate them a second
7014 * time if that has already happened. */
7015 if (bdrv_has_bds_parent(bs, false)) {
7016 continue;
7018 ret = bdrv_inactivate_recurse(bs);
7019 if (ret < 0) {
7020 bdrv_next_cleanup(&it);
7021 break;
7025 return ret;
7028 /**************************************************************/
7029 /* removable device support */
7032 * Return TRUE if the media is present
7034 bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
7036 BlockDriver *drv = bs->drv;
7037 BdrvChild *child;
7038 IO_CODE();
7039 assert_bdrv_graph_readable();
7041 if (!drv) {
7042 return false;
7044 if (drv->bdrv_co_is_inserted) {
7045 return drv->bdrv_co_is_inserted(bs);
7047 QLIST_FOREACH(child, &bs->children, next) {
7048 if (!bdrv_co_is_inserted(child->bs)) {
7049 return false;
7052 return true;
7056 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
7058 void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
7060 BlockDriver *drv = bs->drv;
7061 IO_CODE();
7062 assert_bdrv_graph_readable();
7064 if (drv && drv->bdrv_co_eject) {
7065 drv->bdrv_co_eject(bs, eject_flag);
7070 * Lock or unlock the media (if it is locked, the user won't be able
7071 * to eject it manually).
7073 void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
7075 BlockDriver *drv = bs->drv;
7076 IO_CODE();
7077 assert_bdrv_graph_readable();
7078 trace_bdrv_lock_medium(bs, locked);
7080 if (drv && drv->bdrv_co_lock_medium) {
7081 drv->bdrv_co_lock_medium(bs, locked);
7085 /* Get a reference to bs */
7086 void bdrv_ref(BlockDriverState *bs)
7088 GLOBAL_STATE_CODE();
7089 bs->refcnt++;
7092 /* Release a previously grabbed reference to bs.
7093 * If after releasing, reference count is zero, the BlockDriverState is
7094 * deleted. */
7095 void bdrv_unref(BlockDriverState *bs)
7097 GLOBAL_STATE_CODE();
7098 if (!bs) {
7099 return;
7101 assert(bs->refcnt > 0);
7102 if (--bs->refcnt == 0) {
7103 bdrv_delete(bs);
7107 static void bdrv_schedule_unref_bh(void *opaque)
7109 BlockDriverState *bs = opaque;
7111 bdrv_unref(bs);
7115 * Release a BlockDriverState reference while holding the graph write lock.
7117 * Calling bdrv_unref() directly is forbidden while holding the graph lock
7118 * because bdrv_close() both involves polling and taking the graph lock
7119 * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7120 * possibly closing @bs until the graph lock is released.
7122 void bdrv_schedule_unref(BlockDriverState *bs)
7124 if (!bs) {
7125 return;
7127 aio_bh_schedule_oneshot(qemu_get_aio_context(), bdrv_schedule_unref_bh, bs);
7130 struct BdrvOpBlocker {
7131 Error *reason;
7132 QLIST_ENTRY(BdrvOpBlocker) list;
7135 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
7137 BdrvOpBlocker *blocker;
7138 GLOBAL_STATE_CODE();
7140 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7141 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
7142 blocker = QLIST_FIRST(&bs->op_blockers[op]);
7143 error_propagate_prepend(errp, error_copy(blocker->reason),
7144 "Node '%s' is busy: ",
7145 bdrv_get_device_or_node_name(bs));
7146 return true;
7148 return false;
7151 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
7153 BdrvOpBlocker *blocker;
7154 GLOBAL_STATE_CODE();
7155 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7157 blocker = g_new0(BdrvOpBlocker, 1);
7158 blocker->reason = reason;
7159 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
7162 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
7164 BdrvOpBlocker *blocker, *next;
7165 GLOBAL_STATE_CODE();
7166 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7167 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
7168 if (blocker->reason == reason) {
7169 QLIST_REMOVE(blocker, list);
7170 g_free(blocker);
7175 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
7177 int i;
7178 GLOBAL_STATE_CODE();
7179 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7180 bdrv_op_block(bs, i, reason);
7184 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
7186 int i;
7187 GLOBAL_STATE_CODE();
7188 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7189 bdrv_op_unblock(bs, i, reason);
7193 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
7195 int i;
7196 GLOBAL_STATE_CODE();
7197 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7198 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
7199 return false;
7202 return true;
7206 * Must not be called while holding the lock of an AioContext other than the
7207 * current one.
7209 void bdrv_img_create(const char *filename, const char *fmt,
7210 const char *base_filename, const char *base_fmt,
7211 char *options, uint64_t img_size, int flags, bool quiet,
7212 Error **errp)
7214 QemuOptsList *create_opts = NULL;
7215 QemuOpts *opts = NULL;
7216 const char *backing_fmt, *backing_file;
7217 int64_t size;
7218 BlockDriver *drv, *proto_drv;
7219 Error *local_err = NULL;
7220 int ret = 0;
7222 GLOBAL_STATE_CODE();
7224 /* Find driver and parse its options */
7225 drv = bdrv_find_format(fmt);
7226 if (!drv) {
7227 error_setg(errp, "Unknown file format '%s'", fmt);
7228 return;
7231 proto_drv = bdrv_find_protocol(filename, true, errp);
7232 if (!proto_drv) {
7233 return;
7236 if (!drv->create_opts) {
7237 error_setg(errp, "Format driver '%s' does not support image creation",
7238 drv->format_name);
7239 return;
7242 if (!proto_drv->create_opts) {
7243 error_setg(errp, "Protocol driver '%s' does not support image creation",
7244 proto_drv->format_name);
7245 return;
7248 /* Create parameter list */
7249 create_opts = qemu_opts_append(create_opts, drv->create_opts);
7250 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7252 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7254 /* Parse -o options */
7255 if (options) {
7256 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7257 goto out;
7261 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7262 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7263 } else if (img_size != UINT64_C(-1)) {
7264 error_setg(errp, "The image size must be specified only once");
7265 goto out;
7268 if (base_filename) {
7269 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
7270 NULL)) {
7271 error_setg(errp, "Backing file not supported for file format '%s'",
7272 fmt);
7273 goto out;
7277 if (base_fmt) {
7278 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
7279 error_setg(errp, "Backing file format not supported for file "
7280 "format '%s'", fmt);
7281 goto out;
7285 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7286 if (backing_file) {
7287 if (!strcmp(filename, backing_file)) {
7288 error_setg(errp, "Error: Trying to create an image with the "
7289 "same filename as the backing file");
7290 goto out;
7292 if (backing_file[0] == '\0') {
7293 error_setg(errp, "Expected backing file name, got empty string");
7294 goto out;
7298 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7300 /* The size for the image must always be specified, unless we have a backing
7301 * file and we have not been forbidden from opening it. */
7302 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
7303 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7304 BlockDriverState *bs;
7305 char *full_backing;
7306 int back_flags;
7307 QDict *backing_options = NULL;
7309 full_backing =
7310 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7311 &local_err);
7312 if (local_err) {
7313 goto out;
7315 assert(full_backing);
7318 * No need to do I/O here, which allows us to open encrypted
7319 * backing images without needing the secret
7321 back_flags = flags;
7322 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7323 back_flags |= BDRV_O_NO_IO;
7325 backing_options = qdict_new();
7326 if (backing_fmt) {
7327 qdict_put_str(backing_options, "driver", backing_fmt);
7329 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7331 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7332 &local_err);
7333 g_free(full_backing);
7334 if (!bs) {
7335 error_append_hint(&local_err, "Could not open backing image.\n");
7336 goto out;
7337 } else {
7338 if (!backing_fmt) {
7339 error_setg(&local_err,
7340 "Backing file specified without backing format");
7341 error_append_hint(&local_err, "Detected format of %s.\n",
7342 bs->drv->format_name);
7343 goto out;
7345 if (size == -1) {
7346 /* Opened BS, have no size */
7347 size = bdrv_getlength(bs);
7348 if (size < 0) {
7349 error_setg_errno(errp, -size, "Could not get size of '%s'",
7350 backing_file);
7351 bdrv_unref(bs);
7352 goto out;
7354 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7356 bdrv_unref(bs);
7358 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7359 } else if (backing_file && !backing_fmt) {
7360 error_setg(&local_err,
7361 "Backing file specified without backing format");
7362 goto out;
7365 /* Parameter 'size' is not needed for detached LUKS header */
7366 if (size == -1 &&
7367 !(!strcmp(fmt, "luks") &&
7368 qemu_opt_get_bool(opts, "detached-header", false))) {
7369 error_setg(errp, "Image creation needs a size parameter");
7370 goto out;
7373 if (!quiet) {
7374 printf("Formatting '%s', fmt=%s ", filename, fmt);
7375 qemu_opts_print(opts, " ");
7376 puts("");
7377 fflush(stdout);
7380 ret = bdrv_create(drv, filename, opts, &local_err);
7382 if (ret == -EFBIG) {
7383 /* This is generally a better message than whatever the driver would
7384 * deliver (especially because of the cluster_size_hint), since that
7385 * is most probably not much different from "image too large". */
7386 const char *cluster_size_hint = "";
7387 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7388 cluster_size_hint = " (try using a larger cluster size)";
7390 error_setg(errp, "The image size is too large for file format '%s'"
7391 "%s", fmt, cluster_size_hint);
7392 error_free(local_err);
7393 local_err = NULL;
7396 out:
7397 qemu_opts_del(opts);
7398 qemu_opts_free(create_opts);
7399 error_propagate(errp, local_err);
7402 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7404 IO_CODE();
7405 return bs ? bs->aio_context : qemu_get_aio_context();
7408 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7410 Coroutine *self = qemu_coroutine_self();
7411 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7412 AioContext *new_ctx;
7413 IO_CODE();
7416 * Increase bs->in_flight to ensure that this operation is completed before
7417 * moving the node to a different AioContext. Read new_ctx only afterwards.
7419 bdrv_inc_in_flight(bs);
7421 new_ctx = bdrv_get_aio_context(bs);
7422 aio_co_reschedule_self(new_ctx);
7423 return old_ctx;
7426 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7428 IO_CODE();
7429 aio_co_reschedule_self(old_ctx);
7430 bdrv_dec_in_flight(bs);
7433 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7435 GLOBAL_STATE_CODE();
7436 QLIST_REMOVE(ban, list);
7437 g_free(ban);
7440 static void bdrv_detach_aio_context(BlockDriverState *bs)
7442 BdrvAioNotifier *baf, *baf_tmp;
7444 assert(!bs->walking_aio_notifiers);
7445 GLOBAL_STATE_CODE();
7446 bs->walking_aio_notifiers = true;
7447 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7448 if (baf->deleted) {
7449 bdrv_do_remove_aio_context_notifier(baf);
7450 } else {
7451 baf->detach_aio_context(baf->opaque);
7454 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7455 * remove remaining aio notifiers if we aren't called again.
7457 bs->walking_aio_notifiers = false;
7459 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7460 bs->drv->bdrv_detach_aio_context(bs);
7463 bs->aio_context = NULL;
7466 static void bdrv_attach_aio_context(BlockDriverState *bs,
7467 AioContext *new_context)
7469 BdrvAioNotifier *ban, *ban_tmp;
7470 GLOBAL_STATE_CODE();
7472 bs->aio_context = new_context;
7474 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7475 bs->drv->bdrv_attach_aio_context(bs, new_context);
7478 assert(!bs->walking_aio_notifiers);
7479 bs->walking_aio_notifiers = true;
7480 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7481 if (ban->deleted) {
7482 bdrv_do_remove_aio_context_notifier(ban);
7483 } else {
7484 ban->attached_aio_context(new_context, ban->opaque);
7487 bs->walking_aio_notifiers = false;
7490 typedef struct BdrvStateSetAioContext {
7491 AioContext *new_ctx;
7492 BlockDriverState *bs;
7493 } BdrvStateSetAioContext;
7495 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7496 GHashTable *visited,
7497 Transaction *tran,
7498 Error **errp)
7500 GLOBAL_STATE_CODE();
7501 if (g_hash_table_contains(visited, c)) {
7502 return true;
7504 g_hash_table_add(visited, c);
7507 * A BdrvChildClass that doesn't handle AioContext changes cannot
7508 * tolerate any AioContext changes
7510 if (!c->klass->change_aio_ctx) {
7511 char *user = bdrv_child_user_desc(c);
7512 error_setg(errp, "Changing iothreads is not supported by %s", user);
7513 g_free(user);
7514 return false;
7516 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7517 assert(!errp || *errp);
7518 return false;
7520 return true;
7523 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7524 GHashTable *visited, Transaction *tran,
7525 Error **errp)
7527 GLOBAL_STATE_CODE();
7528 if (g_hash_table_contains(visited, c)) {
7529 return true;
7531 g_hash_table_add(visited, c);
7532 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7535 static void bdrv_set_aio_context_clean(void *opaque)
7537 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7538 BlockDriverState *bs = (BlockDriverState *) state->bs;
7540 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7541 bdrv_drained_end(bs);
7543 g_free(state);
7546 static void bdrv_set_aio_context_commit(void *opaque)
7548 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7549 BlockDriverState *bs = (BlockDriverState *) state->bs;
7550 AioContext *new_context = state->new_ctx;
7552 bdrv_detach_aio_context(bs);
7553 bdrv_attach_aio_context(bs, new_context);
7556 static TransactionActionDrv set_aio_context = {
7557 .commit = bdrv_set_aio_context_commit,
7558 .clean = bdrv_set_aio_context_clean,
7562 * Changes the AioContext used for fd handlers, timers, and BHs by this
7563 * BlockDriverState and all its children and parents.
7565 * Must be called from the main AioContext.
7567 * @visited will accumulate all visited BdrvChild objects. The caller is
7568 * responsible for freeing the list afterwards.
7570 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7571 GHashTable *visited, Transaction *tran,
7572 Error **errp)
7574 BdrvChild *c;
7575 BdrvStateSetAioContext *state;
7577 GLOBAL_STATE_CODE();
7579 if (bdrv_get_aio_context(bs) == ctx) {
7580 return true;
7583 bdrv_graph_rdlock_main_loop();
7584 QLIST_FOREACH(c, &bs->parents, next_parent) {
7585 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7586 bdrv_graph_rdunlock_main_loop();
7587 return false;
7591 QLIST_FOREACH(c, &bs->children, next) {
7592 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7593 bdrv_graph_rdunlock_main_loop();
7594 return false;
7597 bdrv_graph_rdunlock_main_loop();
7599 state = g_new(BdrvStateSetAioContext, 1);
7600 *state = (BdrvStateSetAioContext) {
7601 .new_ctx = ctx,
7602 .bs = bs,
7605 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7606 bdrv_drained_begin(bs);
7608 tran_add(tran, &set_aio_context, state);
7610 return true;
7614 * Change bs's and recursively all of its parents' and children's AioContext
7615 * to the given new context, returning an error if that isn't possible.
7617 * If ignore_child is not NULL, that child (and its subgraph) will not
7618 * be touched.
7620 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7621 BdrvChild *ignore_child, Error **errp)
7623 Transaction *tran;
7624 GHashTable *visited;
7625 int ret;
7626 GLOBAL_STATE_CODE();
7629 * Recursion phase: go through all nodes of the graph.
7630 * Take care of checking that all nodes support changing AioContext
7631 * and drain them, building a linear list of callbacks to run if everything
7632 * is successful (the transaction itself).
7634 tran = tran_new();
7635 visited = g_hash_table_new(NULL, NULL);
7636 if (ignore_child) {
7637 g_hash_table_add(visited, ignore_child);
7639 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7640 g_hash_table_destroy(visited);
7643 * Linear phase: go through all callbacks collected in the transaction.
7644 * Run all callbacks collected in the recursion to switch every node's
7645 * AioContext (transaction commit), or undo all changes done in the
7646 * recursion (transaction abort).
7649 if (!ret) {
7650 /* Just run clean() callbacks. No AioContext changed. */
7651 tran_abort(tran);
7652 return -EPERM;
7655 tran_commit(tran);
7656 return 0;
7659 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7660 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7661 void (*detach_aio_context)(void *opaque), void *opaque)
7663 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7664 *ban = (BdrvAioNotifier){
7665 .attached_aio_context = attached_aio_context,
7666 .detach_aio_context = detach_aio_context,
7667 .opaque = opaque
7669 GLOBAL_STATE_CODE();
7671 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7674 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7675 void (*attached_aio_context)(AioContext *,
7676 void *),
7677 void (*detach_aio_context)(void *),
7678 void *opaque)
7680 BdrvAioNotifier *ban, *ban_next;
7681 GLOBAL_STATE_CODE();
7683 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7684 if (ban->attached_aio_context == attached_aio_context &&
7685 ban->detach_aio_context == detach_aio_context &&
7686 ban->opaque == opaque &&
7687 ban->deleted == false)
7689 if (bs->walking_aio_notifiers) {
7690 ban->deleted = true;
7691 } else {
7692 bdrv_do_remove_aio_context_notifier(ban);
7694 return;
7698 abort();
7701 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7702 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7703 bool force,
7704 Error **errp)
7706 GLOBAL_STATE_CODE();
7707 if (!bs->drv) {
7708 error_setg(errp, "Node is ejected");
7709 return -ENOMEDIUM;
7711 if (!bs->drv->bdrv_amend_options) {
7712 error_setg(errp, "Block driver '%s' does not support option amendment",
7713 bs->drv->format_name);
7714 return -ENOTSUP;
7716 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7717 cb_opaque, force, errp);
7721 * This function checks whether the given @to_replace is allowed to be
7722 * replaced by a node that always shows the same data as @bs. This is
7723 * used for example to verify whether the mirror job can replace
7724 * @to_replace by the target mirrored from @bs.
7725 * To be replaceable, @bs and @to_replace may either be guaranteed to
7726 * always show the same data (because they are only connected through
7727 * filters), or some driver may allow replacing one of its children
7728 * because it can guarantee that this child's data is not visible at
7729 * all (for example, for dissenting quorum children that have no other
7730 * parents).
7732 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7733 BlockDriverState *to_replace)
7735 BlockDriverState *filtered;
7737 GLOBAL_STATE_CODE();
7739 if (!bs || !bs->drv) {
7740 return false;
7743 if (bs == to_replace) {
7744 return true;
7747 /* See what the driver can do */
7748 if (bs->drv->bdrv_recurse_can_replace) {
7749 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7752 /* For filters without an own implementation, we can recurse on our own */
7753 filtered = bdrv_filter_bs(bs);
7754 if (filtered) {
7755 return bdrv_recurse_can_replace(filtered, to_replace);
7758 /* Safe default */
7759 return false;
7763 * Check whether the given @node_name can be replaced by a node that
7764 * has the same data as @parent_bs. If so, return @node_name's BDS;
7765 * NULL otherwise.
7767 * @node_name must be a (recursive) *child of @parent_bs (or this
7768 * function will return NULL).
7770 * The result (whether the node can be replaced or not) is only valid
7771 * for as long as no graph or permission changes occur.
7773 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7774 const char *node_name, Error **errp)
7776 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7778 GLOBAL_STATE_CODE();
7780 if (!to_replace_bs) {
7781 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7782 return NULL;
7785 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7786 return NULL;
7789 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7790 * most non filter in order to prevent data corruption.
7791 * Another benefit is that this tests exclude backing files which are
7792 * blocked by the backing blockers.
7794 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7795 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7796 "because it cannot be guaranteed that doing so would not "
7797 "lead to an abrupt change of visible data",
7798 node_name, parent_bs->node_name);
7799 return NULL;
7802 return to_replace_bs;
7806 * Iterates through the list of runtime option keys that are said to
7807 * be "strong" for a BDS. An option is called "strong" if it changes
7808 * a BDS's data. For example, the null block driver's "size" and
7809 * "read-zeroes" options are strong, but its "latency-ns" option is
7810 * not.
7812 * If a key returned by this function ends with a dot, all options
7813 * starting with that prefix are strong.
7815 static const char *const *strong_options(BlockDriverState *bs,
7816 const char *const *curopt)
7818 static const char *const global_options[] = {
7819 "driver", "filename", NULL
7822 if (!curopt) {
7823 return &global_options[0];
7826 curopt++;
7827 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7828 curopt = bs->drv->strong_runtime_opts;
7831 return (curopt && *curopt) ? curopt : NULL;
7835 * Copies all strong runtime options from bs->options to the given
7836 * QDict. The set of strong option keys is determined by invoking
7837 * strong_options().
7839 * Returns true iff any strong option was present in bs->options (and
7840 * thus copied to the target QDict) with the exception of "filename"
7841 * and "driver". The caller is expected to use this value to decide
7842 * whether the existence of strong options prevents the generation of
7843 * a plain filename.
7845 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7847 bool found_any = false;
7848 const char *const *option_name = NULL;
7850 if (!bs->drv) {
7851 return false;
7854 while ((option_name = strong_options(bs, option_name))) {
7855 bool option_given = false;
7857 assert(strlen(*option_name) > 0);
7858 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7859 QObject *entry = qdict_get(bs->options, *option_name);
7860 if (!entry) {
7861 continue;
7864 qdict_put_obj(d, *option_name, qobject_ref(entry));
7865 option_given = true;
7866 } else {
7867 const QDictEntry *entry;
7868 for (entry = qdict_first(bs->options); entry;
7869 entry = qdict_next(bs->options, entry))
7871 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7872 qdict_put_obj(d, qdict_entry_key(entry),
7873 qobject_ref(qdict_entry_value(entry)));
7874 option_given = true;
7879 /* While "driver" and "filename" need to be included in a JSON filename,
7880 * their existence does not prohibit generation of a plain filename. */
7881 if (!found_any && option_given &&
7882 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7884 found_any = true;
7888 if (!qdict_haskey(d, "driver")) {
7889 /* Drivers created with bdrv_new_open_driver() may not have a
7890 * @driver option. Add it here. */
7891 qdict_put_str(d, "driver", bs->drv->format_name);
7894 return found_any;
7897 /* Note: This function may return false positives; it may return true
7898 * even if opening the backing file specified by bs's image header
7899 * would result in exactly bs->backing. */
7900 static bool GRAPH_RDLOCK bdrv_backing_overridden(BlockDriverState *bs)
7902 GLOBAL_STATE_CODE();
7903 if (bs->backing) {
7904 return strcmp(bs->auto_backing_file,
7905 bs->backing->bs->filename);
7906 } else {
7907 /* No backing BDS, so if the image header reports any backing
7908 * file, it must have been suppressed */
7909 return bs->auto_backing_file[0] != '\0';
7913 /* Updates the following BDS fields:
7914 * - exact_filename: A filename which may be used for opening a block device
7915 * which (mostly) equals the given BDS (even without any
7916 * other options; so reading and writing must return the same
7917 * results, but caching etc. may be different)
7918 * - full_open_options: Options which, when given when opening a block device
7919 * (without a filename), result in a BDS (mostly)
7920 * equalling the given one
7921 * - filename: If exact_filename is set, it is copied here. Otherwise,
7922 * full_open_options is converted to a JSON object, prefixed with
7923 * "json:" (for use through the JSON pseudo protocol) and put here.
7925 void bdrv_refresh_filename(BlockDriverState *bs)
7927 BlockDriver *drv = bs->drv;
7928 BdrvChild *child;
7929 BlockDriverState *primary_child_bs;
7930 QDict *opts;
7931 bool backing_overridden;
7932 bool generate_json_filename; /* Whether our default implementation should
7933 fill exact_filename (false) or not (true) */
7935 GLOBAL_STATE_CODE();
7937 if (!drv) {
7938 return;
7941 /* This BDS's file name may depend on any of its children's file names, so
7942 * refresh those first */
7943 QLIST_FOREACH(child, &bs->children, next) {
7944 bdrv_refresh_filename(child->bs);
7947 if (bs->implicit) {
7948 /* For implicit nodes, just copy everything from the single child */
7949 child = QLIST_FIRST(&bs->children);
7950 assert(QLIST_NEXT(child, next) == NULL);
7952 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7953 child->bs->exact_filename);
7954 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7956 qobject_unref(bs->full_open_options);
7957 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7959 return;
7962 backing_overridden = bdrv_backing_overridden(bs);
7964 if (bs->open_flags & BDRV_O_NO_IO) {
7965 /* Without I/O, the backing file does not change anything.
7966 * Therefore, in such a case (primarily qemu-img), we can
7967 * pretend the backing file has not been overridden even if
7968 * it technically has been. */
7969 backing_overridden = false;
7972 /* Gather the options QDict */
7973 opts = qdict_new();
7974 generate_json_filename = append_strong_runtime_options(opts, bs);
7975 generate_json_filename |= backing_overridden;
7977 if (drv->bdrv_gather_child_options) {
7978 /* Some block drivers may not want to present all of their children's
7979 * options, or name them differently from BdrvChild.name */
7980 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7981 } else {
7982 QLIST_FOREACH(child, &bs->children, next) {
7983 if (child == bs->backing && !backing_overridden) {
7984 /* We can skip the backing BDS if it has not been overridden */
7985 continue;
7988 qdict_put(opts, child->name,
7989 qobject_ref(child->bs->full_open_options));
7992 if (backing_overridden && !bs->backing) {
7993 /* Force no backing file */
7994 qdict_put_null(opts, "backing");
7998 qobject_unref(bs->full_open_options);
7999 bs->full_open_options = opts;
8001 primary_child_bs = bdrv_primary_bs(bs);
8003 if (drv->bdrv_refresh_filename) {
8004 /* Obsolete information is of no use here, so drop the old file name
8005 * information before refreshing it */
8006 bs->exact_filename[0] = '\0';
8008 drv->bdrv_refresh_filename(bs);
8009 } else if (primary_child_bs) {
8011 * Try to reconstruct valid information from the underlying
8012 * file -- this only works for format nodes (filter nodes
8013 * cannot be probed and as such must be selected by the user
8014 * either through an options dict, or through a special
8015 * filename which the filter driver must construct in its
8016 * .bdrv_refresh_filename() implementation).
8019 bs->exact_filename[0] = '\0';
8022 * We can use the underlying file's filename if:
8023 * - it has a filename,
8024 * - the current BDS is not a filter,
8025 * - the file is a protocol BDS, and
8026 * - opening that file (as this BDS's format) will automatically create
8027 * the BDS tree we have right now, that is:
8028 * - the user did not significantly change this BDS's behavior with
8029 * some explicit (strong) options
8030 * - no non-file child of this BDS has been overridden by the user
8031 * Both of these conditions are represented by generate_json_filename.
8033 if (primary_child_bs->exact_filename[0] &&
8034 primary_child_bs->drv->bdrv_file_open &&
8035 !drv->is_filter && !generate_json_filename)
8037 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8041 if (bs->exact_filename[0]) {
8042 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
8043 } else {
8044 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
8045 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8046 json->str) >= sizeof(bs->filename)) {
8047 /* Give user a hint if we truncated things. */
8048 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
8050 g_string_free(json, true);
8054 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
8056 BlockDriver *drv = bs->drv;
8057 BlockDriverState *child_bs;
8059 GLOBAL_STATE_CODE();
8061 if (!drv) {
8062 error_setg(errp, "Node '%s' is ejected", bs->node_name);
8063 return NULL;
8066 if (drv->bdrv_dirname) {
8067 return drv->bdrv_dirname(bs, errp);
8070 child_bs = bdrv_primary_bs(bs);
8071 if (child_bs) {
8072 return bdrv_dirname(child_bs, errp);
8075 bdrv_refresh_filename(bs);
8076 if (bs->exact_filename[0] != '\0') {
8077 return path_combine(bs->exact_filename, "");
8080 error_setg(errp, "Cannot generate a base directory for %s nodes",
8081 drv->format_name);
8082 return NULL;
8086 * Hot add/remove a BDS's child. So the user can take a child offline when
8087 * it is broken and take a new child online
8089 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8090 Error **errp)
8092 GLOBAL_STATE_CODE();
8093 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8094 error_setg(errp, "The node %s does not support adding a child",
8095 bdrv_get_device_or_node_name(parent_bs));
8096 return;
8100 * Non-zoned block drivers do not follow zoned storage constraints
8101 * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8102 * drivers in a graph.
8104 if (!parent_bs->drv->supports_zoned_children &&
8105 child_bs->bl.zoned == BLK_Z_HM) {
8107 * The host-aware model allows zoned storage constraints and random
8108 * write. Allow mixing host-aware and non-zoned drivers. Using
8109 * host-aware device as a regular device.
8111 error_setg(errp, "Cannot add a %s child to a %s parent",
8112 child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
8113 parent_bs->drv->supports_zoned_children ?
8114 "support zoned children" : "not support zoned children");
8115 return;
8118 if (!QLIST_EMPTY(&child_bs->parents)) {
8119 error_setg(errp, "The node %s already has a parent",
8120 child_bs->node_name);
8121 return;
8124 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8127 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8129 BdrvChild *tmp;
8131 GLOBAL_STATE_CODE();
8132 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8133 error_setg(errp, "The node %s does not support removing a child",
8134 bdrv_get_device_or_node_name(parent_bs));
8135 return;
8138 QLIST_FOREACH(tmp, &parent_bs->children, next) {
8139 if (tmp == child) {
8140 break;
8144 if (!tmp) {
8145 error_setg(errp, "The node %s does not have a child named %s",
8146 bdrv_get_device_or_node_name(parent_bs),
8147 bdrv_get_device_or_node_name(child->bs));
8148 return;
8151 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8154 int bdrv_make_empty(BdrvChild *c, Error **errp)
8156 BlockDriver *drv = c->bs->drv;
8157 int ret;
8159 GLOBAL_STATE_CODE();
8160 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
8162 if (!drv->bdrv_make_empty) {
8163 error_setg(errp, "%s does not support emptying nodes",
8164 drv->format_name);
8165 return -ENOTSUP;
8168 ret = drv->bdrv_make_empty(c->bs);
8169 if (ret < 0) {
8170 error_setg_errno(errp, -ret, "Failed to empty %s",
8171 c->bs->filename);
8172 return ret;
8175 return 0;
8179 * Return the child that @bs acts as an overlay for, and from which data may be
8180 * copied in COW or COR operations. Usually this is the backing file.
8182 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8184 IO_CODE();
8186 if (!bs || !bs->drv) {
8187 return NULL;
8190 if (bs->drv->is_filter) {
8191 return NULL;
8194 if (!bs->backing) {
8195 return NULL;
8198 assert(bs->backing->role & BDRV_CHILD_COW);
8199 return bs->backing;
8203 * If @bs acts as a filter for exactly one of its children, return
8204 * that child.
8206 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8208 BdrvChild *c;
8209 IO_CODE();
8211 if (!bs || !bs->drv) {
8212 return NULL;
8215 if (!bs->drv->is_filter) {
8216 return NULL;
8219 /* Only one of @backing or @file may be used */
8220 assert(!(bs->backing && bs->file));
8222 c = bs->backing ?: bs->file;
8223 if (!c) {
8224 return NULL;
8227 assert(c->role & BDRV_CHILD_FILTERED);
8228 return c;
8232 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8233 * whichever is non-NULL.
8235 * Return NULL if both are NULL.
8237 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8239 BdrvChild *cow_child = bdrv_cow_child(bs);
8240 BdrvChild *filter_child = bdrv_filter_child(bs);
8241 IO_CODE();
8243 /* Filter nodes cannot have COW backing files */
8244 assert(!(cow_child && filter_child));
8246 return cow_child ?: filter_child;
8250 * Return the primary child of this node: For filters, that is the
8251 * filtered child. For other nodes, that is usually the child storing
8252 * metadata.
8253 * (A generally more helpful description is that this is (usually) the
8254 * child that has the same filename as @bs.)
8256 * Drivers do not necessarily have a primary child; for example quorum
8257 * does not.
8259 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8261 BdrvChild *c, *found = NULL;
8262 IO_CODE();
8264 QLIST_FOREACH(c, &bs->children, next) {
8265 if (c->role & BDRV_CHILD_PRIMARY) {
8266 assert(!found);
8267 found = c;
8271 return found;
8274 static BlockDriverState * GRAPH_RDLOCK
8275 bdrv_do_skip_filters(BlockDriverState *bs, bool stop_on_explicit_filter)
8277 BdrvChild *c;
8279 if (!bs) {
8280 return NULL;
8283 while (!(stop_on_explicit_filter && !bs->implicit)) {
8284 c = bdrv_filter_child(bs);
8285 if (!c) {
8287 * A filter that is embedded in a working block graph must
8288 * have a child. Assert this here so this function does
8289 * not return a filter node that is not expected by the
8290 * caller.
8292 assert(!bs->drv || !bs->drv->is_filter);
8293 break;
8295 bs = c->bs;
8298 * Note that this treats nodes with bs->drv == NULL as not being
8299 * filters (bs->drv == NULL should be replaced by something else
8300 * anyway).
8301 * The advantage of this behavior is that this function will thus
8302 * always return a non-NULL value (given a non-NULL @bs).
8305 return bs;
8309 * Return the first BDS that has not been added implicitly or that
8310 * does not have a filtered child down the chain starting from @bs
8311 * (including @bs itself).
8313 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8315 GLOBAL_STATE_CODE();
8316 return bdrv_do_skip_filters(bs, true);
8320 * Return the first BDS that does not have a filtered child down the
8321 * chain starting from @bs (including @bs itself).
8323 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8325 IO_CODE();
8326 return bdrv_do_skip_filters(bs, false);
8330 * For a backing chain, return the first non-filter backing image of
8331 * the first non-filter image.
8333 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8335 IO_CODE();
8336 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8340 * Check whether [offset, offset + bytes) overlaps with the cached
8341 * block-status data region.
8343 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8344 * which is what bdrv_bsc_is_data()'s interface needs.
8345 * Otherwise, *pnum is not touched.
8347 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8348 int64_t offset, int64_t bytes,
8349 int64_t *pnum)
8351 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8352 bool overlaps;
8354 overlaps =
8355 qatomic_read(&bsc->valid) &&
8356 ranges_overlap(offset, bytes, bsc->data_start,
8357 bsc->data_end - bsc->data_start);
8359 if (overlaps && pnum) {
8360 *pnum = bsc->data_end - offset;
8363 return overlaps;
8367 * See block_int.h for this function's documentation.
8369 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8371 IO_CODE();
8372 RCU_READ_LOCK_GUARD();
8373 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8377 * See block_int.h for this function's documentation.
8379 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8380 int64_t offset, int64_t bytes)
8382 IO_CODE();
8383 RCU_READ_LOCK_GUARD();
8385 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8386 qatomic_set(&bs->block_status_cache->valid, false);
8391 * See block_int.h for this function's documentation.
8393 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8395 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8396 BdrvBlockStatusCache *old_bsc;
8397 IO_CODE();
8399 *new_bsc = (BdrvBlockStatusCache) {
8400 .valid = true,
8401 .data_start = offset,
8402 .data_end = offset + bytes,
8405 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8407 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8408 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8409 if (old_bsc) {
8410 g_free_rcu(old_bsc, rcu);