migration: Add Error** argument to qemu_savevm_state_setup()
[qemu/armbru.git] / block.c
blob468cf5e67d7341a83e006d13b78c9aa3b441a940
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 QDict *parse_json_filename(const char *filename, Error **errp)
2002 ERRP_GUARD();
2003 QObject *options_obj;
2004 QDict *options;
2005 int ret;
2006 GLOBAL_STATE_CODE();
2008 ret = strstart(filename, "json:", &filename);
2009 assert(ret);
2011 options_obj = qobject_from_json(filename, errp);
2012 if (!options_obj) {
2013 error_prepend(errp, "Could not parse the JSON options: ");
2014 return NULL;
2017 options = qobject_to(QDict, options_obj);
2018 if (!options) {
2019 qobject_unref(options_obj);
2020 error_setg(errp, "Invalid JSON object given");
2021 return NULL;
2024 qdict_flatten(options);
2026 return options;
2029 static void parse_json_protocol(QDict *options, const char **pfilename,
2030 Error **errp)
2032 QDict *json_options;
2033 Error *local_err = NULL;
2034 GLOBAL_STATE_CODE();
2036 /* Parse json: pseudo-protocol */
2037 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2038 return;
2041 json_options = parse_json_filename(*pfilename, &local_err);
2042 if (local_err) {
2043 error_propagate(errp, local_err);
2044 return;
2047 /* Options given in the filename have lower priority than options
2048 * specified directly */
2049 qdict_join(options, json_options, false);
2050 qobject_unref(json_options);
2051 *pfilename = NULL;
2055 * Fills in default options for opening images and converts the legacy
2056 * filename/flags pair to option QDict entries.
2057 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2058 * block driver has been specified explicitly.
2060 static int bdrv_fill_options(QDict **options, const char *filename,
2061 int *flags, Error **errp)
2063 const char *drvname;
2064 bool protocol = *flags & BDRV_O_PROTOCOL;
2065 bool parse_filename = false;
2066 BlockDriver *drv = NULL;
2067 Error *local_err = NULL;
2069 GLOBAL_STATE_CODE();
2072 * Caution: while qdict_get_try_str() is fine, getting non-string
2073 * types would require more care. When @options come from
2074 * -blockdev or blockdev_add, its members are typed according to
2075 * the QAPI schema, but when they come from -drive, they're all
2076 * QString.
2078 drvname = qdict_get_try_str(*options, "driver");
2079 if (drvname) {
2080 drv = bdrv_find_format(drvname);
2081 if (!drv) {
2082 error_setg(errp, "Unknown driver '%s'", drvname);
2083 return -ENOENT;
2085 /* If the user has explicitly specified the driver, this choice should
2086 * override the BDRV_O_PROTOCOL flag */
2087 protocol = drv->bdrv_file_open;
2090 if (protocol) {
2091 *flags |= BDRV_O_PROTOCOL;
2092 } else {
2093 *flags &= ~BDRV_O_PROTOCOL;
2096 /* Translate cache options from flags into options */
2097 update_options_from_flags(*options, *flags);
2099 /* Fetch the file name from the options QDict if necessary */
2100 if (protocol && filename) {
2101 if (!qdict_haskey(*options, "filename")) {
2102 qdict_put_str(*options, "filename", filename);
2103 parse_filename = true;
2104 } else {
2105 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2106 "the same time");
2107 return -EINVAL;
2111 /* Find the right block driver */
2112 /* See cautionary note on accessing @options above */
2113 filename = qdict_get_try_str(*options, "filename");
2115 if (!drvname && protocol) {
2116 if (filename) {
2117 drv = bdrv_find_protocol(filename, parse_filename, errp);
2118 if (!drv) {
2119 return -EINVAL;
2122 drvname = drv->format_name;
2123 qdict_put_str(*options, "driver", drvname);
2124 } else {
2125 error_setg(errp, "Must specify either driver or file");
2126 return -EINVAL;
2130 assert(drv || !protocol);
2132 /* Driver-specific filename parsing */
2133 if (drv && drv->bdrv_parse_filename && parse_filename) {
2134 drv->bdrv_parse_filename(filename, *options, &local_err);
2135 if (local_err) {
2136 error_propagate(errp, local_err);
2137 return -EINVAL;
2140 if (!drv->bdrv_needs_filename) {
2141 qdict_del(*options, "filename");
2145 return 0;
2148 typedef struct BlockReopenQueueEntry {
2149 bool prepared;
2150 BDRVReopenState state;
2151 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2152 } BlockReopenQueueEntry;
2155 * Return the flags that @bs will have after the reopens in @q have
2156 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2157 * return the current flags.
2159 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2161 BlockReopenQueueEntry *entry;
2163 if (q != NULL) {
2164 QTAILQ_FOREACH(entry, q, entry) {
2165 if (entry->state.bs == bs) {
2166 return entry->state.flags;
2171 return bs->open_flags;
2174 /* Returns whether the image file can be written to after the reopen queue @q
2175 * has been successfully applied, or right now if @q is NULL. */
2176 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2177 BlockReopenQueue *q)
2179 int flags = bdrv_reopen_get_flags(q, bs);
2181 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2185 * Return whether the BDS can be written to. This is not necessarily
2186 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2187 * be written to but do not count as read-only images.
2189 bool bdrv_is_writable(BlockDriverState *bs)
2191 IO_CODE();
2192 return bdrv_is_writable_after_reopen(bs, NULL);
2195 static char *bdrv_child_user_desc(BdrvChild *c)
2197 GLOBAL_STATE_CODE();
2198 return c->klass->get_parent_desc(c);
2202 * Check that @a allows everything that @b needs. @a and @b must reference same
2203 * child node.
2205 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2207 const char *child_bs_name;
2208 g_autofree char *a_user = NULL;
2209 g_autofree char *b_user = NULL;
2210 g_autofree char *perms = NULL;
2212 assert(a->bs);
2213 assert(a->bs == b->bs);
2214 GLOBAL_STATE_CODE();
2216 if ((b->perm & a->shared_perm) == b->perm) {
2217 return true;
2220 child_bs_name = bdrv_get_node_name(b->bs);
2221 a_user = bdrv_child_user_desc(a);
2222 b_user = bdrv_child_user_desc(b);
2223 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2225 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2226 "both required by %s (uses node '%s' as '%s' child) and "
2227 "unshared by %s (uses node '%s' as '%s' child).",
2228 child_bs_name, perms,
2229 b_user, child_bs_name, b->name,
2230 a_user, child_bs_name, a->name);
2232 return false;
2235 static bool GRAPH_RDLOCK
2236 bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2238 BdrvChild *a, *b;
2239 GLOBAL_STATE_CODE();
2242 * During the loop we'll look at each pair twice. That's correct because
2243 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2244 * directions.
2246 QLIST_FOREACH(a, &bs->parents, next_parent) {
2247 QLIST_FOREACH(b, &bs->parents, next_parent) {
2248 if (a == b) {
2249 continue;
2252 if (!bdrv_a_allow_b(a, b, errp)) {
2253 return true;
2258 return false;
2261 static void GRAPH_RDLOCK
2262 bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2263 BdrvChild *c, BdrvChildRole role,
2264 BlockReopenQueue *reopen_queue,
2265 uint64_t parent_perm, uint64_t parent_shared,
2266 uint64_t *nperm, uint64_t *nshared)
2268 assert(bs->drv && bs->drv->bdrv_child_perm);
2269 GLOBAL_STATE_CODE();
2270 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2271 parent_perm, parent_shared,
2272 nperm, nshared);
2273 /* TODO Take force_share from reopen_queue */
2274 if (child_bs && child_bs->force_share) {
2275 *nshared = BLK_PERM_ALL;
2280 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2281 * nodes that are already in the @list, of course) so that final list is
2282 * topologically sorted. Return the result (GSList @list object is updated, so
2283 * don't use old reference after function call).
2285 * On function start @list must be already topologically sorted and for any node
2286 * in the @list the whole subtree of the node must be in the @list as well. The
2287 * simplest way to satisfy this criteria: use only result of
2288 * bdrv_topological_dfs() or NULL as @list parameter.
2290 static GSList * GRAPH_RDLOCK
2291 bdrv_topological_dfs(GSList *list, GHashTable *found, BlockDriverState *bs)
2293 BdrvChild *child;
2294 g_autoptr(GHashTable) local_found = NULL;
2296 GLOBAL_STATE_CODE();
2298 if (!found) {
2299 assert(!list);
2300 found = local_found = g_hash_table_new(NULL, NULL);
2303 if (g_hash_table_contains(found, bs)) {
2304 return list;
2306 g_hash_table_add(found, bs);
2308 QLIST_FOREACH(child, &bs->children, next) {
2309 list = bdrv_topological_dfs(list, found, child->bs);
2312 return g_slist_prepend(list, bs);
2315 typedef struct BdrvChildSetPermState {
2316 BdrvChild *child;
2317 uint64_t old_perm;
2318 uint64_t old_shared_perm;
2319 } BdrvChildSetPermState;
2321 static void bdrv_child_set_perm_abort(void *opaque)
2323 BdrvChildSetPermState *s = opaque;
2325 GLOBAL_STATE_CODE();
2327 s->child->perm = s->old_perm;
2328 s->child->shared_perm = s->old_shared_perm;
2331 static TransactionActionDrv bdrv_child_set_pem_drv = {
2332 .abort = bdrv_child_set_perm_abort,
2333 .clean = g_free,
2336 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2337 uint64_t shared, Transaction *tran)
2339 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2340 GLOBAL_STATE_CODE();
2342 *s = (BdrvChildSetPermState) {
2343 .child = c,
2344 .old_perm = c->perm,
2345 .old_shared_perm = c->shared_perm,
2348 c->perm = perm;
2349 c->shared_perm = shared;
2351 tran_add(tran, &bdrv_child_set_pem_drv, s);
2354 static void GRAPH_RDLOCK bdrv_drv_set_perm_commit(void *opaque)
2356 BlockDriverState *bs = opaque;
2357 uint64_t cumulative_perms, cumulative_shared_perms;
2358 GLOBAL_STATE_CODE();
2360 if (bs->drv->bdrv_set_perm) {
2361 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2362 &cumulative_shared_perms);
2363 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2367 static void GRAPH_RDLOCK bdrv_drv_set_perm_abort(void *opaque)
2369 BlockDriverState *bs = opaque;
2370 GLOBAL_STATE_CODE();
2372 if (bs->drv->bdrv_abort_perm_update) {
2373 bs->drv->bdrv_abort_perm_update(bs);
2377 TransactionActionDrv bdrv_drv_set_perm_drv = {
2378 .abort = bdrv_drv_set_perm_abort,
2379 .commit = bdrv_drv_set_perm_commit,
2383 * After calling this function, the transaction @tran may only be completed
2384 * while holding a reader lock for the graph.
2386 static int GRAPH_RDLOCK
2387 bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared_perm,
2388 Transaction *tran, Error **errp)
2390 GLOBAL_STATE_CODE();
2391 if (!bs->drv) {
2392 return 0;
2395 if (bs->drv->bdrv_check_perm) {
2396 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2397 if (ret < 0) {
2398 return ret;
2402 if (tran) {
2403 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2406 return 0;
2409 typedef struct BdrvReplaceChildState {
2410 BdrvChild *child;
2411 BlockDriverState *old_bs;
2412 } BdrvReplaceChildState;
2414 static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
2416 BdrvReplaceChildState *s = opaque;
2417 GLOBAL_STATE_CODE();
2419 bdrv_schedule_unref(s->old_bs);
2422 static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
2424 BdrvReplaceChildState *s = opaque;
2425 BlockDriverState *new_bs = s->child->bs;
2427 GLOBAL_STATE_CODE();
2428 assert_bdrv_graph_writable();
2430 /* old_bs reference is transparently moved from @s to @s->child */
2431 if (!s->child->bs) {
2433 * The parents were undrained when removing old_bs from the child. New
2434 * requests can't have been made, though, because the child was empty.
2436 * TODO Make bdrv_replace_child_noperm() transactionable to avoid
2437 * undraining the parent in the first place. Once this is done, having
2438 * new_bs drained when calling bdrv_replace_child_tran() is not a
2439 * requirement any more.
2441 bdrv_parent_drained_begin_single(s->child);
2442 assert(!bdrv_parent_drained_poll_single(s->child));
2444 assert(s->child->quiesced_parent);
2445 bdrv_replace_child_noperm(s->child, s->old_bs);
2447 bdrv_unref(new_bs);
2450 static TransactionActionDrv bdrv_replace_child_drv = {
2451 .commit = bdrv_replace_child_commit,
2452 .abort = bdrv_replace_child_abort,
2453 .clean = g_free,
2457 * bdrv_replace_child_tran
2459 * Note: real unref of old_bs is done only on commit.
2461 * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
2462 * kept drained until the transaction is completed.
2464 * After calling this function, the transaction @tran may only be completed
2465 * while holding a writer lock for the graph.
2467 * The function doesn't update permissions, caller is responsible for this.
2469 static void GRAPH_WRLOCK
2470 bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2471 Transaction *tran)
2473 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2475 assert(child->quiesced_parent);
2476 assert(!new_bs || new_bs->quiesce_counter);
2478 *s = (BdrvReplaceChildState) {
2479 .child = child,
2480 .old_bs = child->bs,
2482 tran_add(tran, &bdrv_replace_child_drv, s);
2484 if (new_bs) {
2485 bdrv_ref(new_bs);
2488 bdrv_replace_child_noperm(child, new_bs);
2489 /* old_bs reference is transparently moved from @child to @s */
2493 * Refresh permissions in @bs subtree. The function is intended to be called
2494 * after some graph modification that was done without permission update.
2496 * After calling this function, the transaction @tran may only be completed
2497 * while holding a reader lock for the graph.
2499 static int GRAPH_RDLOCK
2500 bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2501 Transaction *tran, Error **errp)
2503 BlockDriver *drv = bs->drv;
2504 BdrvChild *c;
2505 int ret;
2506 uint64_t cumulative_perms, cumulative_shared_perms;
2507 GLOBAL_STATE_CODE();
2509 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2511 /* Write permissions never work with read-only images */
2512 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2513 !bdrv_is_writable_after_reopen(bs, q))
2515 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2516 error_setg(errp, "Block node is read-only");
2517 } else {
2518 error_setg(errp, "Read-only block node '%s' cannot support "
2519 "read-write users", bdrv_get_node_name(bs));
2522 return -EPERM;
2526 * Unaligned requests will automatically be aligned to bl.request_alignment
2527 * and without RESIZE we can't extend requests to write to space beyond the
2528 * end of the image, so it's required that the image size is aligned.
2530 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2531 !(cumulative_perms & BLK_PERM_RESIZE))
2533 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2534 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2535 "Image size is not a multiple of request "
2536 "alignment");
2537 return -EPERM;
2541 /* Check this node */
2542 if (!drv) {
2543 return 0;
2546 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2547 errp);
2548 if (ret < 0) {
2549 return ret;
2552 /* Drivers that never have children can omit .bdrv_child_perm() */
2553 if (!drv->bdrv_child_perm) {
2554 assert(QLIST_EMPTY(&bs->children));
2555 return 0;
2558 /* Check all children */
2559 QLIST_FOREACH(c, &bs->children, next) {
2560 uint64_t cur_perm, cur_shared;
2562 bdrv_child_perm(bs, c->bs, c, c->role, q,
2563 cumulative_perms, cumulative_shared_perms,
2564 &cur_perm, &cur_shared);
2565 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2568 return 0;
2572 * @list is a product of bdrv_topological_dfs() (may be called several times) -
2573 * a topologically sorted subgraph.
2575 * After calling this function, the transaction @tran may only be completed
2576 * while holding a reader lock for the graph.
2578 static int GRAPH_RDLOCK
2579 bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2580 Error **errp)
2582 int ret;
2583 BlockDriverState *bs;
2584 GLOBAL_STATE_CODE();
2586 for ( ; list; list = list->next) {
2587 bs = list->data;
2589 if (bdrv_parent_perms_conflict(bs, errp)) {
2590 return -EINVAL;
2593 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2594 if (ret < 0) {
2595 return ret;
2599 return 0;
2603 * @list is any list of nodes. List is completed by all subtrees and
2604 * topologically sorted. It's not a problem if some node occurs in the @list
2605 * several times.
2607 * After calling this function, the transaction @tran may only be completed
2608 * while holding a reader lock for the graph.
2610 static int GRAPH_RDLOCK
2611 bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
2612 Error **errp)
2614 g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2615 g_autoptr(GSList) refresh_list = NULL;
2617 for ( ; list; list = list->next) {
2618 refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2621 return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2624 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2625 uint64_t *shared_perm)
2627 BdrvChild *c;
2628 uint64_t cumulative_perms = 0;
2629 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2631 GLOBAL_STATE_CODE();
2633 QLIST_FOREACH(c, &bs->parents, next_parent) {
2634 cumulative_perms |= c->perm;
2635 cumulative_shared_perms &= c->shared_perm;
2638 *perm = cumulative_perms;
2639 *shared_perm = cumulative_shared_perms;
2642 char *bdrv_perm_names(uint64_t perm)
2644 struct perm_name {
2645 uint64_t perm;
2646 const char *name;
2647 } permissions[] = {
2648 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2649 { BLK_PERM_WRITE, "write" },
2650 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2651 { BLK_PERM_RESIZE, "resize" },
2652 { 0, NULL }
2655 GString *result = g_string_sized_new(30);
2656 struct perm_name *p;
2658 for (p = permissions; p->name; p++) {
2659 if (perm & p->perm) {
2660 if (result->len > 0) {
2661 g_string_append(result, ", ");
2663 g_string_append(result, p->name);
2667 return g_string_free(result, FALSE);
2672 * @tran is allowed to be NULL. In this case no rollback is possible.
2674 * After calling this function, the transaction @tran may only be completed
2675 * while holding a reader lock for the graph.
2677 static int GRAPH_RDLOCK
2678 bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran, Error **errp)
2680 int ret;
2681 Transaction *local_tran = NULL;
2682 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2683 GLOBAL_STATE_CODE();
2685 if (!tran) {
2686 tran = local_tran = tran_new();
2689 ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2691 if (local_tran) {
2692 tran_finalize(local_tran, ret);
2695 return ret;
2698 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2699 Error **errp)
2701 Error *local_err = NULL;
2702 Transaction *tran = tran_new();
2703 int ret;
2705 GLOBAL_STATE_CODE();
2707 bdrv_child_set_perm(c, perm, shared, tran);
2709 ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2711 tran_finalize(tran, ret);
2713 if (ret < 0) {
2714 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2715 /* tighten permissions */
2716 error_propagate(errp, local_err);
2717 } else {
2719 * Our caller may intend to only loosen restrictions and
2720 * does not expect this function to fail. Errors are not
2721 * fatal in such a case, so we can just hide them from our
2722 * caller.
2724 error_free(local_err);
2725 ret = 0;
2729 return ret;
2732 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2734 uint64_t parent_perms, parent_shared;
2735 uint64_t perms, shared;
2737 GLOBAL_STATE_CODE();
2739 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2740 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2741 parent_perms, parent_shared, &perms, &shared);
2743 return bdrv_child_try_set_perm(c, perms, shared, errp);
2747 * Default implementation for .bdrv_child_perm() for block filters:
2748 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2749 * filtered child.
2751 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2752 BdrvChildRole role,
2753 BlockReopenQueue *reopen_queue,
2754 uint64_t perm, uint64_t shared,
2755 uint64_t *nperm, uint64_t *nshared)
2757 GLOBAL_STATE_CODE();
2758 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2759 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2762 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2763 BdrvChildRole role,
2764 BlockReopenQueue *reopen_queue,
2765 uint64_t perm, uint64_t shared,
2766 uint64_t *nperm, uint64_t *nshared)
2768 assert(role & BDRV_CHILD_COW);
2769 GLOBAL_STATE_CODE();
2772 * We want consistent read from backing files if the parent needs it.
2773 * No other operations are performed on backing files.
2775 perm &= BLK_PERM_CONSISTENT_READ;
2778 * If the parent can deal with changing data, we're okay with a
2779 * writable and resizable backing file.
2780 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2782 if (shared & BLK_PERM_WRITE) {
2783 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2784 } else {
2785 shared = 0;
2788 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2790 if (bs->open_flags & BDRV_O_INACTIVE) {
2791 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2794 *nperm = perm;
2795 *nshared = shared;
2798 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2799 BdrvChildRole role,
2800 BlockReopenQueue *reopen_queue,
2801 uint64_t perm, uint64_t shared,
2802 uint64_t *nperm, uint64_t *nshared)
2804 int flags;
2806 GLOBAL_STATE_CODE();
2807 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2809 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2812 * Apart from the modifications below, the same permissions are
2813 * forwarded and left alone as for filters
2815 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2816 perm, shared, &perm, &shared);
2818 if (role & BDRV_CHILD_METADATA) {
2819 /* Format drivers may touch metadata even if the guest doesn't write */
2820 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2821 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2825 * bs->file always needs to be consistent because of the
2826 * metadata. We can never allow other users to resize or write
2827 * to it.
2829 if (!(flags & BDRV_O_NO_IO)) {
2830 perm |= BLK_PERM_CONSISTENT_READ;
2832 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2835 if (role & BDRV_CHILD_DATA) {
2837 * Technically, everything in this block is a subset of the
2838 * BDRV_CHILD_METADATA path taken above, and so this could
2839 * be an "else if" branch. However, that is not obvious, and
2840 * this function is not performance critical, therefore we let
2841 * this be an independent "if".
2845 * We cannot allow other users to resize the file because the
2846 * format driver might have some assumptions about the size
2847 * (e.g. because it is stored in metadata, or because the file
2848 * is split into fixed-size data files).
2850 shared &= ~BLK_PERM_RESIZE;
2853 * WRITE_UNCHANGED often cannot be performed as such on the
2854 * data file. For example, the qcow2 driver may still need to
2855 * write copied clusters on copy-on-read.
2857 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2858 perm |= BLK_PERM_WRITE;
2862 * If the data file is written to, the format driver may
2863 * expect to be able to resize it by writing beyond the EOF.
2865 if (perm & BLK_PERM_WRITE) {
2866 perm |= BLK_PERM_RESIZE;
2870 if (bs->open_flags & BDRV_O_INACTIVE) {
2871 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2874 *nperm = perm;
2875 *nshared = shared;
2878 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2879 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2880 uint64_t perm, uint64_t shared,
2881 uint64_t *nperm, uint64_t *nshared)
2883 GLOBAL_STATE_CODE();
2884 if (role & BDRV_CHILD_FILTERED) {
2885 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2886 BDRV_CHILD_COW)));
2887 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2888 perm, shared, nperm, nshared);
2889 } else if (role & BDRV_CHILD_COW) {
2890 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2891 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2892 perm, shared, nperm, nshared);
2893 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2894 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2895 perm, shared, nperm, nshared);
2896 } else {
2897 g_assert_not_reached();
2901 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2903 static const uint64_t permissions[] = {
2904 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2905 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2906 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2907 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2910 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2911 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2913 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2915 return permissions[qapi_perm];
2919 * Replaces the node that a BdrvChild points to without updating permissions.
2921 * If @new_bs is non-NULL, the parent of @child must already be drained through
2922 * @child.
2924 static void GRAPH_WRLOCK
2925 bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
2927 BlockDriverState *old_bs = child->bs;
2928 int new_bs_quiesce_counter;
2930 assert(!child->frozen);
2933 * If we want to change the BdrvChild to point to a drained node as its new
2934 * child->bs, we need to make sure that its new parent is drained, too. In
2935 * other words, either child->quiesce_parent must already be true or we must
2936 * be able to set it and keep the parent's quiesce_counter consistent with
2937 * that, but without polling or starting new requests (this function
2938 * guarantees that it doesn't poll, and starting new requests would be
2939 * against the invariants of drain sections).
2941 * To keep things simple, we pick the first option (child->quiesce_parent
2942 * must already be true). We also generalise the rule a bit to make it
2943 * easier to verify in callers and more likely to be covered in test cases:
2944 * The parent must be quiesced through this child even if new_bs isn't
2945 * currently drained.
2947 * The only exception is for callers that always pass new_bs == NULL. In
2948 * this case, we obviously never need to consider the case of a drained
2949 * new_bs, so we can keep the callers simpler by allowing them not to drain
2950 * the parent.
2952 assert(!new_bs || child->quiesced_parent);
2953 assert(old_bs != new_bs);
2954 GLOBAL_STATE_CODE();
2956 if (old_bs && new_bs) {
2957 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2960 if (old_bs) {
2961 if (child->klass->detach) {
2962 child->klass->detach(child);
2964 QLIST_REMOVE(child, next_parent);
2967 child->bs = new_bs;
2969 if (new_bs) {
2970 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2971 if (child->klass->attach) {
2972 child->klass->attach(child);
2977 * If the parent was drained through this BdrvChild previously, but new_bs
2978 * is not drained, allow requests to come in only after the new node has
2979 * been attached.
2981 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2982 if (!new_bs_quiesce_counter && child->quiesced_parent) {
2983 bdrv_parent_drained_end_single(child);
2988 * Free the given @child.
2990 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2991 * unused (i.e. not in a children list).
2993 static void bdrv_child_free(BdrvChild *child)
2995 assert(!child->bs);
2996 GLOBAL_STATE_CODE();
2997 GRAPH_RDLOCK_GUARD_MAINLOOP();
2999 assert(!child->next.le_prev); /* not in children list */
3001 g_free(child->name);
3002 g_free(child);
3005 typedef struct BdrvAttachChildCommonState {
3006 BdrvChild *child;
3007 AioContext *old_parent_ctx;
3008 AioContext *old_child_ctx;
3009 } BdrvAttachChildCommonState;
3011 static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
3013 BdrvAttachChildCommonState *s = opaque;
3014 BlockDriverState *bs = s->child->bs;
3016 GLOBAL_STATE_CODE();
3017 assert_bdrv_graph_writable();
3019 bdrv_replace_child_noperm(s->child, NULL);
3021 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
3022 bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
3025 if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
3026 Transaction *tran;
3027 GHashTable *visited;
3028 bool ret;
3030 tran = tran_new();
3032 /* No need to visit `child`, because it has been detached already */
3033 visited = g_hash_table_new(NULL, NULL);
3034 ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
3035 visited, tran, &error_abort);
3036 g_hash_table_destroy(visited);
3038 /* transaction is supposed to always succeed */
3039 assert(ret == true);
3040 tran_commit(tran);
3043 bdrv_schedule_unref(bs);
3044 bdrv_child_free(s->child);
3047 static TransactionActionDrv bdrv_attach_child_common_drv = {
3048 .abort = bdrv_attach_child_common_abort,
3049 .clean = g_free,
3053 * Common part of attaching bdrv child to bs or to blk or to job
3055 * Function doesn't update permissions, caller is responsible for this.
3057 * After calling this function, the transaction @tran may only be completed
3058 * while holding a writer lock for the graph.
3060 * Returns new created child.
3062 * Both @parent_bs and @child_bs can move to a different AioContext in this
3063 * function.
3065 static BdrvChild * GRAPH_WRLOCK
3066 bdrv_attach_child_common(BlockDriverState *child_bs,
3067 const char *child_name,
3068 const BdrvChildClass *child_class,
3069 BdrvChildRole child_role,
3070 uint64_t perm, uint64_t shared_perm,
3071 void *opaque,
3072 Transaction *tran, Error **errp)
3074 BdrvChild *new_child;
3075 AioContext *parent_ctx;
3076 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3078 assert(child_class->get_parent_desc);
3079 GLOBAL_STATE_CODE();
3081 new_child = g_new(BdrvChild, 1);
3082 *new_child = (BdrvChild) {
3083 .bs = NULL,
3084 .name = g_strdup(child_name),
3085 .klass = child_class,
3086 .role = child_role,
3087 .perm = perm,
3088 .shared_perm = shared_perm,
3089 .opaque = opaque,
3093 * If the AioContexts don't match, first try to move the subtree of
3094 * child_bs into the AioContext of the new parent. If this doesn't work,
3095 * try moving the parent into the AioContext of child_bs instead.
3097 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3098 if (child_ctx != parent_ctx) {
3099 Error *local_err = NULL;
3100 int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3101 &local_err);
3103 if (ret < 0 && child_class->change_aio_ctx) {
3104 Transaction *aio_ctx_tran = tran_new();
3105 GHashTable *visited = g_hash_table_new(NULL, NULL);
3106 bool ret_child;
3108 g_hash_table_add(visited, new_child);
3109 ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3110 visited, aio_ctx_tran,
3111 NULL);
3112 if (ret_child == true) {
3113 error_free(local_err);
3114 ret = 0;
3116 tran_finalize(aio_ctx_tran, ret_child == true ? 0 : -1);
3117 g_hash_table_destroy(visited);
3120 if (ret < 0) {
3121 error_propagate(errp, local_err);
3122 bdrv_child_free(new_child);
3123 return NULL;
3127 bdrv_ref(child_bs);
3129 * Let every new BdrvChild start with a drained parent. Inserting the child
3130 * in the graph with bdrv_replace_child_noperm() will undrain it if
3131 * @child_bs is not drained.
3133 * The child was only just created and is not yet visible in global state
3134 * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
3135 * could have sent requests and polling is not necessary.
3137 * Note that this means that the parent isn't fully drained yet, we only
3138 * stop new requests from coming in. This is fine, we don't care about the
3139 * old requests here, they are not for this child. If another place enters a
3140 * drain section for the same parent, but wants it to be fully quiesced, it
3141 * will not run most of the the code in .drained_begin() again (which is not
3142 * a problem, we already did this), but it will still poll until the parent
3143 * is fully quiesced, so it will not be negatively affected either.
3145 bdrv_parent_drained_begin_single(new_child);
3146 bdrv_replace_child_noperm(new_child, child_bs);
3148 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3149 *s = (BdrvAttachChildCommonState) {
3150 .child = new_child,
3151 .old_parent_ctx = parent_ctx,
3152 .old_child_ctx = child_ctx,
3154 tran_add(tran, &bdrv_attach_child_common_drv, s);
3156 return new_child;
3160 * Function doesn't update permissions, caller is responsible for this.
3162 * Both @parent_bs and @child_bs can move to a different AioContext in this
3163 * function.
3165 * After calling this function, the transaction @tran may only be completed
3166 * while holding a writer lock for the graph.
3168 static BdrvChild * GRAPH_WRLOCK
3169 bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3170 BlockDriverState *child_bs,
3171 const char *child_name,
3172 const BdrvChildClass *child_class,
3173 BdrvChildRole child_role,
3174 Transaction *tran,
3175 Error **errp)
3177 uint64_t perm, shared_perm;
3179 assert(parent_bs->drv);
3180 GLOBAL_STATE_CODE();
3182 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3183 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3184 child_bs->node_name, child_name, parent_bs->node_name);
3185 return NULL;
3188 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3189 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3190 perm, shared_perm, &perm, &shared_perm);
3192 return bdrv_attach_child_common(child_bs, child_name, child_class,
3193 child_role, perm, shared_perm, parent_bs,
3194 tran, errp);
3198 * This function steals the reference to child_bs from the caller.
3199 * That reference is later dropped by bdrv_root_unref_child().
3201 * On failure NULL is returned, errp is set and the reference to
3202 * child_bs is also dropped.
3204 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3205 const char *child_name,
3206 const BdrvChildClass *child_class,
3207 BdrvChildRole child_role,
3208 uint64_t perm, uint64_t shared_perm,
3209 void *opaque, Error **errp)
3211 int ret;
3212 BdrvChild *child;
3213 Transaction *tran = tran_new();
3215 GLOBAL_STATE_CODE();
3217 child = bdrv_attach_child_common(child_bs, child_name, child_class,
3218 child_role, perm, shared_perm, opaque,
3219 tran, errp);
3220 if (!child) {
3221 ret = -EINVAL;
3222 goto out;
3225 ret = bdrv_refresh_perms(child_bs, tran, errp);
3227 out:
3228 tran_finalize(tran, ret);
3230 bdrv_schedule_unref(child_bs);
3232 return ret < 0 ? NULL : child;
3236 * This function transfers the reference to child_bs from the caller
3237 * to parent_bs. That reference is later dropped by parent_bs on
3238 * bdrv_close() or if someone calls bdrv_unref_child().
3240 * On failure NULL is returned, errp is set and the reference to
3241 * child_bs is also dropped.
3243 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3244 BlockDriverState *child_bs,
3245 const char *child_name,
3246 const BdrvChildClass *child_class,
3247 BdrvChildRole child_role,
3248 Error **errp)
3250 int ret;
3251 BdrvChild *child;
3252 Transaction *tran = tran_new();
3254 GLOBAL_STATE_CODE();
3256 child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3257 child_class, child_role, tran, errp);
3258 if (!child) {
3259 ret = -EINVAL;
3260 goto out;
3263 ret = bdrv_refresh_perms(parent_bs, tran, errp);
3264 if (ret < 0) {
3265 goto out;
3268 out:
3269 tran_finalize(tran, ret);
3271 bdrv_schedule_unref(child_bs);
3273 return ret < 0 ? NULL : child;
3276 /* Callers must ensure that child->frozen is false. */
3277 void bdrv_root_unref_child(BdrvChild *child)
3279 BlockDriverState *child_bs = child->bs;
3281 GLOBAL_STATE_CODE();
3282 bdrv_replace_child_noperm(child, NULL);
3283 bdrv_child_free(child);
3285 if (child_bs) {
3287 * Update permissions for old node. We're just taking a parent away, so
3288 * we're loosening restrictions. Errors of permission update are not
3289 * fatal in this case, ignore them.
3291 bdrv_refresh_perms(child_bs, NULL, NULL);
3294 * When the parent requiring a non-default AioContext is removed, the
3295 * node moves back to the main AioContext
3297 bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3298 NULL);
3301 bdrv_schedule_unref(child_bs);
3304 typedef struct BdrvSetInheritsFrom {
3305 BlockDriverState *bs;
3306 BlockDriverState *old_inherits_from;
3307 } BdrvSetInheritsFrom;
3309 static void bdrv_set_inherits_from_abort(void *opaque)
3311 BdrvSetInheritsFrom *s = opaque;
3313 s->bs->inherits_from = s->old_inherits_from;
3316 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3317 .abort = bdrv_set_inherits_from_abort,
3318 .clean = g_free,
3321 /* @tran is allowed to be NULL. In this case no rollback is possible */
3322 static void bdrv_set_inherits_from(BlockDriverState *bs,
3323 BlockDriverState *new_inherits_from,
3324 Transaction *tran)
3326 if (tran) {
3327 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3329 *s = (BdrvSetInheritsFrom) {
3330 .bs = bs,
3331 .old_inherits_from = bs->inherits_from,
3334 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3337 bs->inherits_from = new_inherits_from;
3341 * Clear all inherits_from pointers from children and grandchildren of
3342 * @root that point to @root, where necessary.
3343 * @tran is allowed to be NULL. In this case no rollback is possible
3345 static void GRAPH_WRLOCK
3346 bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3347 Transaction *tran)
3349 BdrvChild *c;
3351 if (child->bs->inherits_from == root) {
3353 * Remove inherits_from only when the last reference between root and
3354 * child->bs goes away.
3356 QLIST_FOREACH(c, &root->children, next) {
3357 if (c != child && c->bs == child->bs) {
3358 break;
3361 if (c == NULL) {
3362 bdrv_set_inherits_from(child->bs, NULL, tran);
3366 QLIST_FOREACH(c, &child->bs->children, next) {
3367 bdrv_unset_inherits_from(root, c, tran);
3371 /* Callers must ensure that child->frozen is false. */
3372 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3374 GLOBAL_STATE_CODE();
3375 if (child == NULL) {
3376 return;
3379 bdrv_unset_inherits_from(parent, child, NULL);
3380 bdrv_root_unref_child(child);
3384 static void GRAPH_RDLOCK
3385 bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3387 BdrvChild *c;
3388 GLOBAL_STATE_CODE();
3389 QLIST_FOREACH(c, &bs->parents, next_parent) {
3390 if (c->klass->change_media) {
3391 c->klass->change_media(c, load);
3396 /* Return true if you can reach parent going through child->inherits_from
3397 * recursively. If parent or child are NULL, return false */
3398 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3399 BlockDriverState *parent)
3401 while (child && child != parent) {
3402 child = child->inherits_from;
3405 return child != NULL;
3409 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3410 * mostly used for COW backing children (role = COW), but also for
3411 * filtered children (role = FILTERED | PRIMARY).
3413 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3415 if (bs->drv && bs->drv->is_filter) {
3416 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3417 } else {
3418 return BDRV_CHILD_COW;
3423 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3424 * callers which don't need their own reference any more must call bdrv_unref().
3426 * If the respective child is already present (i.e. we're detaching a node),
3427 * that child node must be drained.
3429 * Function doesn't update permissions, caller is responsible for this.
3431 * Both @parent_bs and @child_bs can move to a different AioContext in this
3432 * function.
3434 * After calling this function, the transaction @tran may only be completed
3435 * while holding a writer lock for the graph.
3437 static int GRAPH_WRLOCK
3438 bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3439 BlockDriverState *child_bs,
3440 bool is_backing,
3441 Transaction *tran, Error **errp)
3443 bool update_inherits_from =
3444 bdrv_inherits_from_recursive(child_bs, parent_bs);
3445 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3446 BdrvChildRole role;
3448 GLOBAL_STATE_CODE();
3450 if (!parent_bs->drv) {
3452 * Node without drv is an object without a class :/. TODO: finally fix
3453 * qcow2 driver to never clear bs->drv and implement format corruption
3454 * handling in other way.
3456 error_setg(errp, "Node corrupted");
3457 return -EINVAL;
3460 if (child && child->frozen) {
3461 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3462 child->name, parent_bs->node_name, child->bs->node_name);
3463 return -EPERM;
3466 if (is_backing && !parent_bs->drv->is_filter &&
3467 !parent_bs->drv->supports_backing)
3469 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3470 "files", parent_bs->drv->format_name, parent_bs->node_name);
3471 return -EINVAL;
3474 if (parent_bs->drv->is_filter) {
3475 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3476 } else if (is_backing) {
3477 role = BDRV_CHILD_COW;
3478 } else {
3480 * We only can use same role as it is in existing child. We don't have
3481 * infrastructure to determine role of file child in generic way
3483 if (!child) {
3484 error_setg(errp, "Cannot set file child to format node without "
3485 "file child");
3486 return -EINVAL;
3488 role = child->role;
3491 if (child) {
3492 assert(child->bs->quiesce_counter);
3493 bdrv_unset_inherits_from(parent_bs, child, tran);
3494 bdrv_remove_child(child, tran);
3497 if (!child_bs) {
3498 goto out;
3501 child = bdrv_attach_child_noperm(parent_bs, child_bs,
3502 is_backing ? "backing" : "file",
3503 &child_of_bds, role,
3504 tran, errp);
3505 if (!child) {
3506 return -EINVAL;
3511 * If inherits_from pointed recursively to bs then let's update it to
3512 * point directly to bs (else it will become NULL).
3514 if (update_inherits_from) {
3515 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3518 out:
3519 bdrv_refresh_limits(parent_bs, tran, NULL);
3521 return 0;
3525 * Both @bs and @backing_hd can move to a different AioContext in this
3526 * function.
3528 * If a backing child is already present (i.e. we're detaching a node), that
3529 * child node must be drained.
3531 int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3532 BlockDriverState *backing_hd,
3533 Error **errp)
3535 int ret;
3536 Transaction *tran = tran_new();
3538 GLOBAL_STATE_CODE();
3539 assert(bs->quiesce_counter > 0);
3540 if (bs->backing) {
3541 assert(bs->backing->bs->quiesce_counter > 0);
3544 ret = bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3545 if (ret < 0) {
3546 goto out;
3549 ret = bdrv_refresh_perms(bs, tran, errp);
3550 out:
3551 tran_finalize(tran, ret);
3552 return ret;
3555 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3556 Error **errp)
3558 BlockDriverState *drain_bs;
3559 int ret;
3560 GLOBAL_STATE_CODE();
3562 bdrv_graph_rdlock_main_loop();
3563 drain_bs = bs->backing ? bs->backing->bs : bs;
3564 bdrv_graph_rdunlock_main_loop();
3566 bdrv_ref(drain_bs);
3567 bdrv_drained_begin(drain_bs);
3568 bdrv_graph_wrlock();
3569 ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
3570 bdrv_graph_wrunlock();
3571 bdrv_drained_end(drain_bs);
3572 bdrv_unref(drain_bs);
3574 return ret;
3578 * Opens the backing file for a BlockDriverState if not yet open
3580 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3581 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3582 * itself, all options starting with "${bdref_key}." are considered part of the
3583 * BlockdevRef.
3585 * TODO Can this be unified with bdrv_open_image()?
3587 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3588 const char *bdref_key, Error **errp)
3590 ERRP_GUARD();
3591 char *backing_filename = NULL;
3592 char *bdref_key_dot;
3593 const char *reference = NULL;
3594 int ret = 0;
3595 bool implicit_backing = false;
3596 BlockDriverState *backing_hd;
3597 QDict *options;
3598 QDict *tmp_parent_options = NULL;
3599 Error *local_err = NULL;
3601 GLOBAL_STATE_CODE();
3602 GRAPH_RDLOCK_GUARD_MAINLOOP();
3604 if (bs->backing != NULL) {
3605 goto free_exit;
3608 /* NULL means an empty set of options */
3609 if (parent_options == NULL) {
3610 tmp_parent_options = qdict_new();
3611 parent_options = tmp_parent_options;
3614 bs->open_flags &= ~BDRV_O_NO_BACKING;
3616 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3617 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3618 g_free(bdref_key_dot);
3621 * Caution: while qdict_get_try_str() is fine, getting non-string
3622 * types would require more care. When @parent_options come from
3623 * -blockdev or blockdev_add, its members are typed according to
3624 * the QAPI schema, but when they come from -drive, they're all
3625 * QString.
3627 reference = qdict_get_try_str(parent_options, bdref_key);
3628 if (reference || qdict_haskey(options, "file.filename")) {
3629 /* keep backing_filename NULL */
3630 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3631 qobject_unref(options);
3632 goto free_exit;
3633 } else {
3634 if (qdict_size(options) == 0) {
3635 /* If the user specifies options that do not modify the
3636 * backing file's behavior, we might still consider it the
3637 * implicit backing file. But it's easier this way, and
3638 * just specifying some of the backing BDS's options is
3639 * only possible with -drive anyway (otherwise the QAPI
3640 * schema forces the user to specify everything). */
3641 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3644 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3645 if (local_err) {
3646 ret = -EINVAL;
3647 error_propagate(errp, local_err);
3648 qobject_unref(options);
3649 goto free_exit;
3653 if (!bs->drv || !bs->drv->supports_backing) {
3654 ret = -EINVAL;
3655 error_setg(errp, "Driver doesn't support backing files");
3656 qobject_unref(options);
3657 goto free_exit;
3660 if (!reference &&
3661 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3662 qdict_put_str(options, "driver", bs->backing_format);
3665 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3666 &child_of_bds, bdrv_backing_role(bs), errp);
3667 if (!backing_hd) {
3668 bs->open_flags |= BDRV_O_NO_BACKING;
3669 error_prepend(errp, "Could not open backing file: ");
3670 ret = -EINVAL;
3671 goto free_exit;
3674 if (implicit_backing) {
3675 bdrv_refresh_filename(backing_hd);
3676 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3677 backing_hd->filename);
3680 /* Hook up the backing file link; drop our reference, bs owns the
3681 * backing_hd reference now */
3682 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3683 bdrv_unref(backing_hd);
3685 if (ret < 0) {
3686 goto free_exit;
3689 qdict_del(parent_options, bdref_key);
3691 free_exit:
3692 g_free(backing_filename);
3693 qobject_unref(tmp_parent_options);
3694 return ret;
3697 static BlockDriverState *
3698 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3699 BlockDriverState *parent, const BdrvChildClass *child_class,
3700 BdrvChildRole child_role, bool allow_none, Error **errp)
3702 BlockDriverState *bs = NULL;
3703 QDict *image_options;
3704 char *bdref_key_dot;
3705 const char *reference;
3707 assert(child_class != NULL);
3709 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3710 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3711 g_free(bdref_key_dot);
3714 * Caution: while qdict_get_try_str() is fine, getting non-string
3715 * types would require more care. When @options come from
3716 * -blockdev or blockdev_add, its members are typed according to
3717 * the QAPI schema, but when they come from -drive, they're all
3718 * QString.
3720 reference = qdict_get_try_str(options, bdref_key);
3721 if (!filename && !reference && !qdict_size(image_options)) {
3722 if (!allow_none) {
3723 error_setg(errp, "A block device must be specified for \"%s\"",
3724 bdref_key);
3726 qobject_unref(image_options);
3727 goto done;
3730 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3731 parent, child_class, child_role, errp);
3732 if (!bs) {
3733 goto done;
3736 done:
3737 qdict_del(options, bdref_key);
3738 return bs;
3742 * Opens a disk image whose options are given as BlockdevRef in another block
3743 * device's options.
3745 * If allow_none is true, no image will be opened if filename is false and no
3746 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3748 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3749 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3750 * itself, all options starting with "${bdref_key}." are considered part of the
3751 * BlockdevRef.
3753 * The BlockdevRef will be removed from the options QDict.
3755 * @parent can move to a different AioContext in this function.
3757 BdrvChild *bdrv_open_child(const char *filename,
3758 QDict *options, const char *bdref_key,
3759 BlockDriverState *parent,
3760 const BdrvChildClass *child_class,
3761 BdrvChildRole child_role,
3762 bool allow_none, Error **errp)
3764 BlockDriverState *bs;
3765 BdrvChild *child;
3767 GLOBAL_STATE_CODE();
3769 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3770 child_role, allow_none, errp);
3771 if (bs == NULL) {
3772 return NULL;
3775 bdrv_graph_wrlock();
3776 child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3777 errp);
3778 bdrv_graph_wrunlock();
3780 return child;
3784 * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3786 * @parent can move to a different AioContext in this function.
3788 int bdrv_open_file_child(const char *filename,
3789 QDict *options, const char *bdref_key,
3790 BlockDriverState *parent, Error **errp)
3792 BdrvChildRole role;
3794 /* commit_top and mirror_top don't use this function */
3795 assert(!parent->drv->filtered_child_is_backing);
3796 role = parent->drv->is_filter ?
3797 (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3799 if (!bdrv_open_child(filename, options, bdref_key, parent,
3800 &child_of_bds, role, false, errp))
3802 return -EINVAL;
3805 return 0;
3809 * TODO Future callers may need to specify parent/child_class in order for
3810 * option inheritance to work. Existing callers use it for the root node.
3812 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3814 BlockDriverState *bs = NULL;
3815 QObject *obj = NULL;
3816 QDict *qdict = NULL;
3817 const char *reference = NULL;
3818 Visitor *v = NULL;
3820 GLOBAL_STATE_CODE();
3822 if (ref->type == QTYPE_QSTRING) {
3823 reference = ref->u.reference;
3824 } else {
3825 BlockdevOptions *options = &ref->u.definition;
3826 assert(ref->type == QTYPE_QDICT);
3828 v = qobject_output_visitor_new(&obj);
3829 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3830 visit_complete(v, &obj);
3832 qdict = qobject_to(QDict, obj);
3833 qdict_flatten(qdict);
3835 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3836 * compatibility with other callers) rather than what we want as the
3837 * real defaults. Apply the defaults here instead. */
3838 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3839 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3840 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3841 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3845 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3846 obj = NULL;
3847 qobject_unref(obj);
3848 visit_free(v);
3849 return bs;
3852 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3853 int flags,
3854 QDict *snapshot_options,
3855 Error **errp)
3857 ERRP_GUARD();
3858 g_autofree char *tmp_filename = NULL;
3859 int64_t total_size;
3860 QemuOpts *opts = NULL;
3861 BlockDriverState *bs_snapshot = NULL;
3862 int ret;
3864 GLOBAL_STATE_CODE();
3866 /* if snapshot, we create a temporary backing file and open it
3867 instead of opening 'filename' directly */
3869 /* Get the required size from the image */
3870 total_size = bdrv_getlength(bs);
3872 if (total_size < 0) {
3873 error_setg_errno(errp, -total_size, "Could not get image size");
3874 goto out;
3877 /* Create the temporary image */
3878 tmp_filename = create_tmp_file(errp);
3879 if (!tmp_filename) {
3880 goto out;
3883 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3884 &error_abort);
3885 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3886 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3887 qemu_opts_del(opts);
3888 if (ret < 0) {
3889 error_prepend(errp, "Could not create temporary overlay '%s': ",
3890 tmp_filename);
3891 goto out;
3894 /* Prepare options QDict for the temporary file */
3895 qdict_put_str(snapshot_options, "file.driver", "file");
3896 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3897 qdict_put_str(snapshot_options, "driver", "qcow2");
3899 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3900 snapshot_options = NULL;
3901 if (!bs_snapshot) {
3902 goto out;
3905 ret = bdrv_append(bs_snapshot, bs, errp);
3906 if (ret < 0) {
3907 bs_snapshot = NULL;
3908 goto out;
3911 out:
3912 qobject_unref(snapshot_options);
3913 return bs_snapshot;
3917 * Opens a disk image (raw, qcow2, vmdk, ...)
3919 * options is a QDict of options to pass to the block drivers, or NULL for an
3920 * empty set of options. The reference to the QDict belongs to the block layer
3921 * after the call (even on failure), so if the caller intends to reuse the
3922 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3924 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3925 * If it is not NULL, the referenced BDS will be reused.
3927 * The reference parameter may be used to specify an existing block device which
3928 * should be opened. If specified, neither options nor a filename may be given,
3929 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3931 static BlockDriverState * no_coroutine_fn
3932 bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
3933 int flags, BlockDriverState *parent,
3934 const BdrvChildClass *child_class, BdrvChildRole child_role,
3935 Error **errp)
3937 int ret;
3938 BlockBackend *file = NULL;
3939 BlockDriverState *bs;
3940 BlockDriver *drv = NULL;
3941 BdrvChild *child;
3942 const char *drvname;
3943 const char *backing;
3944 Error *local_err = NULL;
3945 QDict *snapshot_options = NULL;
3946 int snapshot_flags = 0;
3948 assert(!child_class || !flags);
3949 assert(!child_class == !parent);
3950 GLOBAL_STATE_CODE();
3951 assert(!qemu_in_coroutine());
3953 /* TODO We'll eventually have to take a writer lock in this function */
3954 GRAPH_RDLOCK_GUARD_MAINLOOP();
3956 if (reference) {
3957 bool options_non_empty = options ? qdict_size(options) : false;
3958 qobject_unref(options);
3960 if (filename || options_non_empty) {
3961 error_setg(errp, "Cannot reference an existing block device with "
3962 "additional options or a new filename");
3963 return NULL;
3966 bs = bdrv_lookup_bs(reference, reference, errp);
3967 if (!bs) {
3968 return NULL;
3971 bdrv_ref(bs);
3972 return bs;
3975 bs = bdrv_new();
3977 /* NULL means an empty set of options */
3978 if (options == NULL) {
3979 options = qdict_new();
3982 /* json: syntax counts as explicit options, as if in the QDict */
3983 parse_json_protocol(options, &filename, &local_err);
3984 if (local_err) {
3985 goto fail;
3988 bs->explicit_options = qdict_clone_shallow(options);
3990 if (child_class) {
3991 bool parent_is_format;
3993 if (parent->drv) {
3994 parent_is_format = parent->drv->is_format;
3995 } else {
3997 * parent->drv is not set yet because this node is opened for
3998 * (potential) format probing. That means that @parent is going
3999 * to be a format node.
4001 parent_is_format = true;
4004 bs->inherits_from = parent;
4005 child_class->inherit_options(child_role, parent_is_format,
4006 &flags, options,
4007 parent->open_flags, parent->options);
4010 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
4011 if (ret < 0) {
4012 goto fail;
4016 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4017 * Caution: getting a boolean member of @options requires care.
4018 * When @options come from -blockdev or blockdev_add, members are
4019 * typed according to the QAPI schema, but when they come from
4020 * -drive, they're all QString.
4022 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
4023 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
4024 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
4025 } else {
4026 flags &= ~BDRV_O_RDWR;
4029 if (flags & BDRV_O_SNAPSHOT) {
4030 snapshot_options = qdict_new();
4031 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
4032 flags, options);
4033 /* Let bdrv_backing_options() override "read-only" */
4034 qdict_del(options, BDRV_OPT_READ_ONLY);
4035 bdrv_inherited_options(BDRV_CHILD_COW, true,
4036 &flags, options, flags, options);
4039 bs->open_flags = flags;
4040 bs->options = options;
4041 options = qdict_clone_shallow(options);
4043 /* Find the right image format driver */
4044 /* See cautionary note on accessing @options above */
4045 drvname = qdict_get_try_str(options, "driver");
4046 if (drvname) {
4047 drv = bdrv_find_format(drvname);
4048 if (!drv) {
4049 error_setg(errp, "Unknown driver: '%s'", drvname);
4050 goto fail;
4054 assert(drvname || !(flags & BDRV_O_PROTOCOL));
4056 /* See cautionary note on accessing @options above */
4057 backing = qdict_get_try_str(options, "backing");
4058 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
4059 (backing && *backing == '\0'))
4061 if (backing) {
4062 warn_report("Use of \"backing\": \"\" is deprecated; "
4063 "use \"backing\": null instead");
4065 flags |= BDRV_O_NO_BACKING;
4066 qdict_del(bs->explicit_options, "backing");
4067 qdict_del(bs->options, "backing");
4068 qdict_del(options, "backing");
4071 /* Open image file without format layer. This BlockBackend is only used for
4072 * probing, the block drivers will do their own bdrv_open_child() for the
4073 * same BDS, which is why we put the node name back into options. */
4074 if ((flags & BDRV_O_PROTOCOL) == 0) {
4075 BlockDriverState *file_bs;
4077 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
4078 &child_of_bds, BDRV_CHILD_IMAGE,
4079 true, &local_err);
4080 if (local_err) {
4081 goto fail;
4083 if (file_bs != NULL) {
4084 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4085 * looking at the header to guess the image format. This works even
4086 * in cases where a guest would not see a consistent state. */
4087 AioContext *ctx = bdrv_get_aio_context(file_bs);
4088 file = blk_new(ctx, 0, BLK_PERM_ALL);
4089 blk_insert_bs(file, file_bs, &local_err);
4090 bdrv_unref(file_bs);
4092 if (local_err) {
4093 goto fail;
4096 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
4100 /* Image format probing */
4101 bs->probed = !drv;
4102 if (!drv && file) {
4103 ret = find_image_format(file, filename, &drv, &local_err);
4104 if (ret < 0) {
4105 goto fail;
4108 * This option update would logically belong in bdrv_fill_options(),
4109 * but we first need to open bs->file for the probing to work, while
4110 * opening bs->file already requires the (mostly) final set of options
4111 * so that cache mode etc. can be inherited.
4113 * Adding the driver later is somewhat ugly, but it's not an option
4114 * that would ever be inherited, so it's correct. We just need to make
4115 * sure to update both bs->options (which has the full effective
4116 * options for bs) and options (which has file.* already removed).
4118 qdict_put_str(bs->options, "driver", drv->format_name);
4119 qdict_put_str(options, "driver", drv->format_name);
4120 } else if (!drv) {
4121 error_setg(errp, "Must specify either driver or file");
4122 goto fail;
4125 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
4126 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
4127 /* file must be NULL if a protocol BDS is about to be created
4128 * (the inverse results in an error message from bdrv_open_common()) */
4129 assert(!(flags & BDRV_O_PROTOCOL) || !file);
4131 /* Open the image */
4132 ret = bdrv_open_common(bs, file, options, &local_err);
4133 if (ret < 0) {
4134 goto fail;
4137 if (file) {
4138 blk_unref(file);
4139 file = NULL;
4142 /* If there is a backing file, use it */
4143 if ((flags & BDRV_O_NO_BACKING) == 0) {
4144 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4145 if (ret < 0) {
4146 goto close_and_fail;
4150 /* Remove all children options and references
4151 * from bs->options and bs->explicit_options */
4152 QLIST_FOREACH(child, &bs->children, next) {
4153 char *child_key_dot;
4154 child_key_dot = g_strdup_printf("%s.", child->name);
4155 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4156 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4157 qdict_del(bs->explicit_options, child->name);
4158 qdict_del(bs->options, child->name);
4159 g_free(child_key_dot);
4162 /* Check if any unknown options were used */
4163 if (qdict_size(options) != 0) {
4164 const QDictEntry *entry = qdict_first(options);
4165 if (flags & BDRV_O_PROTOCOL) {
4166 error_setg(errp, "Block protocol '%s' doesn't support the option "
4167 "'%s'", drv->format_name, entry->key);
4168 } else {
4169 error_setg(errp,
4170 "Block format '%s' does not support the option '%s'",
4171 drv->format_name, entry->key);
4174 goto close_and_fail;
4177 bdrv_parent_cb_change_media(bs, true);
4179 qobject_unref(options);
4180 options = NULL;
4182 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4183 * temporary snapshot afterwards. */
4184 if (snapshot_flags) {
4185 BlockDriverState *snapshot_bs;
4186 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4187 snapshot_options, &local_err);
4188 snapshot_options = NULL;
4189 if (local_err) {
4190 goto close_and_fail;
4192 /* We are not going to return bs but the overlay on top of it
4193 * (snapshot_bs); thus, we have to drop the strong reference to bs
4194 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4195 * though, because the overlay still has a reference to it. */
4196 bdrv_unref(bs);
4197 bs = snapshot_bs;
4200 return bs;
4202 fail:
4203 blk_unref(file);
4204 qobject_unref(snapshot_options);
4205 qobject_unref(bs->explicit_options);
4206 qobject_unref(bs->options);
4207 qobject_unref(options);
4208 bs->options = NULL;
4209 bs->explicit_options = NULL;
4210 bdrv_unref(bs);
4211 error_propagate(errp, local_err);
4212 return NULL;
4214 close_and_fail:
4215 bdrv_unref(bs);
4216 qobject_unref(snapshot_options);
4217 qobject_unref(options);
4218 error_propagate(errp, local_err);
4219 return NULL;
4222 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4223 QDict *options, int flags, Error **errp)
4225 GLOBAL_STATE_CODE();
4227 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4228 NULL, 0, errp);
4231 /* Return true if the NULL-terminated @list contains @str */
4232 static bool is_str_in_list(const char *str, const char *const *list)
4234 if (str && list) {
4235 int i;
4236 for (i = 0; list[i] != NULL; i++) {
4237 if (!strcmp(str, list[i])) {
4238 return true;
4242 return false;
4246 * Check that every option set in @bs->options is also set in
4247 * @new_opts.
4249 * Options listed in the common_options list and in
4250 * @bs->drv->mutable_opts are skipped.
4252 * Return 0 on success, otherwise return -EINVAL and set @errp.
4254 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4255 const QDict *new_opts, Error **errp)
4257 const QDictEntry *e;
4258 /* These options are common to all block drivers and are handled
4259 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4260 const char *const common_options[] = {
4261 "node-name", "discard", "cache.direct", "cache.no-flush",
4262 "read-only", "auto-read-only", "detect-zeroes", NULL
4265 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4266 if (!qdict_haskey(new_opts, e->key) &&
4267 !is_str_in_list(e->key, common_options) &&
4268 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4269 error_setg(errp, "Option '%s' cannot be reset "
4270 "to its default value", e->key);
4271 return -EINVAL;
4275 return 0;
4279 * Returns true if @child can be reached recursively from @bs
4281 static bool GRAPH_RDLOCK
4282 bdrv_recurse_has_child(BlockDriverState *bs, BlockDriverState *child)
4284 BdrvChild *c;
4286 if (bs == child) {
4287 return true;
4290 QLIST_FOREACH(c, &bs->children, next) {
4291 if (bdrv_recurse_has_child(c->bs, child)) {
4292 return true;
4296 return false;
4300 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4301 * reopen of multiple devices.
4303 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4304 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4305 * be created and initialized. This newly created BlockReopenQueue should be
4306 * passed back in for subsequent calls that are intended to be of the same
4307 * atomic 'set'.
4309 * bs is the BlockDriverState to add to the reopen queue.
4311 * options contains the changed options for the associated bs
4312 * (the BlockReopenQueue takes ownership)
4314 * flags contains the open flags for the associated bs
4316 * returns a pointer to bs_queue, which is either the newly allocated
4317 * bs_queue, or the existing bs_queue being used.
4319 * bs is drained here and undrained by bdrv_reopen_queue_free().
4321 * To be called with bs->aio_context locked.
4323 static BlockReopenQueue * GRAPH_RDLOCK
4324 bdrv_reopen_queue_child(BlockReopenQueue *bs_queue, BlockDriverState *bs,
4325 QDict *options, const BdrvChildClass *klass,
4326 BdrvChildRole role, bool parent_is_format,
4327 QDict *parent_options, int parent_flags,
4328 bool keep_old_opts)
4330 assert(bs != NULL);
4332 BlockReopenQueueEntry *bs_entry;
4333 BdrvChild *child;
4334 QDict *old_options, *explicit_options, *options_copy;
4335 int flags;
4336 QemuOpts *opts;
4338 GLOBAL_STATE_CODE();
4341 * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
4342 * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
4343 * in practice.
4345 bdrv_drained_begin(bs);
4347 if (bs_queue == NULL) {
4348 bs_queue = g_new0(BlockReopenQueue, 1);
4349 QTAILQ_INIT(bs_queue);
4352 if (!options) {
4353 options = qdict_new();
4356 /* Check if this BlockDriverState is already in the queue */
4357 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4358 if (bs == bs_entry->state.bs) {
4359 break;
4364 * Precedence of options:
4365 * 1. Explicitly passed in options (highest)
4366 * 2. Retained from explicitly set options of bs
4367 * 3. Inherited from parent node
4368 * 4. Retained from effective options of bs
4371 /* Old explicitly set values (don't overwrite by inherited value) */
4372 if (bs_entry || keep_old_opts) {
4373 old_options = qdict_clone_shallow(bs_entry ?
4374 bs_entry->state.explicit_options :
4375 bs->explicit_options);
4376 bdrv_join_options(bs, options, old_options);
4377 qobject_unref(old_options);
4380 explicit_options = qdict_clone_shallow(options);
4382 /* Inherit from parent node */
4383 if (parent_options) {
4384 flags = 0;
4385 klass->inherit_options(role, parent_is_format, &flags, options,
4386 parent_flags, parent_options);
4387 } else {
4388 flags = bdrv_get_flags(bs);
4391 if (keep_old_opts) {
4392 /* Old values are used for options that aren't set yet */
4393 old_options = qdict_clone_shallow(bs->options);
4394 bdrv_join_options(bs, options, old_options);
4395 qobject_unref(old_options);
4398 /* We have the final set of options so let's update the flags */
4399 options_copy = qdict_clone_shallow(options);
4400 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4401 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4402 update_flags_from_options(&flags, opts);
4403 qemu_opts_del(opts);
4404 qobject_unref(options_copy);
4406 /* bdrv_open_inherit() sets and clears some additional flags internally */
4407 flags &= ~BDRV_O_PROTOCOL;
4408 if (flags & BDRV_O_RDWR) {
4409 flags |= BDRV_O_ALLOW_RDWR;
4412 if (!bs_entry) {
4413 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4414 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4415 } else {
4416 qobject_unref(bs_entry->state.options);
4417 qobject_unref(bs_entry->state.explicit_options);
4420 bs_entry->state.bs = bs;
4421 bs_entry->state.options = options;
4422 bs_entry->state.explicit_options = explicit_options;
4423 bs_entry->state.flags = flags;
4426 * If keep_old_opts is false then it means that unspecified
4427 * options must be reset to their original value. We don't allow
4428 * resetting 'backing' but we need to know if the option is
4429 * missing in order to decide if we have to return an error.
4431 if (!keep_old_opts) {
4432 bs_entry->state.backing_missing =
4433 !qdict_haskey(options, "backing") &&
4434 !qdict_haskey(options, "backing.driver");
4437 QLIST_FOREACH(child, &bs->children, next) {
4438 QDict *new_child_options = NULL;
4439 bool child_keep_old = keep_old_opts;
4441 /* reopen can only change the options of block devices that were
4442 * implicitly created and inherited options. For other (referenced)
4443 * block devices, a syntax like "backing.foo" results in an error. */
4444 if (child->bs->inherits_from != bs) {
4445 continue;
4448 /* Check if the options contain a child reference */
4449 if (qdict_haskey(options, child->name)) {
4450 const char *childref = qdict_get_try_str(options, child->name);
4452 * The current child must not be reopened if the child
4453 * reference is null or points to a different node.
4455 if (g_strcmp0(childref, child->bs->node_name)) {
4456 continue;
4459 * If the child reference points to the current child then
4460 * reopen it with its existing set of options (note that
4461 * it can still inherit new options from the parent).
4463 child_keep_old = true;
4464 } else {
4465 /* Extract child options ("child-name.*") */
4466 char *child_key_dot = g_strdup_printf("%s.", child->name);
4467 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4468 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4469 g_free(child_key_dot);
4472 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4473 child->klass, child->role, bs->drv->is_format,
4474 options, flags, child_keep_old);
4477 return bs_queue;
4480 /* To be called with bs->aio_context locked */
4481 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4482 BlockDriverState *bs,
4483 QDict *options, bool keep_old_opts)
4485 GLOBAL_STATE_CODE();
4486 GRAPH_RDLOCK_GUARD_MAINLOOP();
4488 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4489 NULL, 0, keep_old_opts);
4492 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4494 GLOBAL_STATE_CODE();
4495 if (bs_queue) {
4496 BlockReopenQueueEntry *bs_entry, *next;
4497 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4498 bdrv_drained_end(bs_entry->state.bs);
4499 qobject_unref(bs_entry->state.explicit_options);
4500 qobject_unref(bs_entry->state.options);
4501 g_free(bs_entry);
4503 g_free(bs_queue);
4508 * Reopen multiple BlockDriverStates atomically & transactionally.
4510 * The queue passed in (bs_queue) must have been built up previous
4511 * via bdrv_reopen_queue().
4513 * Reopens all BDS specified in the queue, with the appropriate
4514 * flags. All devices are prepared for reopen, and failure of any
4515 * device will cause all device changes to be abandoned, and intermediate
4516 * data cleaned up.
4518 * If all devices prepare successfully, then the changes are committed
4519 * to all devices.
4521 * All affected nodes must be drained between bdrv_reopen_queue() and
4522 * bdrv_reopen_multiple().
4524 * To be called from the main thread, with all other AioContexts unlocked.
4526 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4528 int ret = -1;
4529 BlockReopenQueueEntry *bs_entry, *next;
4530 Transaction *tran = tran_new();
4531 g_autoptr(GSList) refresh_list = NULL;
4533 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4534 assert(bs_queue != NULL);
4535 GLOBAL_STATE_CODE();
4537 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4538 ret = bdrv_flush(bs_entry->state.bs);
4539 if (ret < 0) {
4540 error_setg_errno(errp, -ret, "Error flushing drive");
4541 goto abort;
4545 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4546 assert(bs_entry->state.bs->quiesce_counter > 0);
4547 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4548 if (ret < 0) {
4549 goto abort;
4551 bs_entry->prepared = true;
4554 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4555 BDRVReopenState *state = &bs_entry->state;
4557 refresh_list = g_slist_prepend(refresh_list, state->bs);
4558 if (state->old_backing_bs) {
4559 refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4561 if (state->old_file_bs) {
4562 refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4567 * Note that file-posix driver rely on permission update done during reopen
4568 * (even if no permission changed), because it wants "new" permissions for
4569 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4570 * in raw_reopen_prepare() which is called with "old" permissions.
4572 bdrv_graph_rdlock_main_loop();
4573 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4574 bdrv_graph_rdunlock_main_loop();
4576 if (ret < 0) {
4577 goto abort;
4581 * If we reach this point, we have success and just need to apply the
4582 * changes.
4584 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4585 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4586 * children are usually goes after parents in reopen-queue, so go from last
4587 * to first element.
4589 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4590 bdrv_reopen_commit(&bs_entry->state);
4593 bdrv_graph_wrlock();
4594 tran_commit(tran);
4595 bdrv_graph_wrunlock();
4597 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4598 BlockDriverState *bs = bs_entry->state.bs;
4600 if (bs->drv->bdrv_reopen_commit_post) {
4601 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4605 ret = 0;
4606 goto cleanup;
4608 abort:
4609 bdrv_graph_wrlock();
4610 tran_abort(tran);
4611 bdrv_graph_wrunlock();
4613 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4614 if (bs_entry->prepared) {
4615 bdrv_reopen_abort(&bs_entry->state);
4619 cleanup:
4620 bdrv_reopen_queue_free(bs_queue);
4622 return ret;
4625 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4626 Error **errp)
4628 BlockReopenQueue *queue;
4630 GLOBAL_STATE_CODE();
4632 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4634 return bdrv_reopen_multiple(queue, errp);
4637 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4638 Error **errp)
4640 QDict *opts = qdict_new();
4642 GLOBAL_STATE_CODE();
4644 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4646 return bdrv_reopen(bs, opts, true, errp);
4650 * Take a BDRVReopenState and check if the value of 'backing' in the
4651 * reopen_state->options QDict is valid or not.
4653 * If 'backing' is missing from the QDict then return 0.
4655 * If 'backing' contains the node name of the backing file of
4656 * reopen_state->bs then return 0.
4658 * If 'backing' contains a different node name (or is null) then check
4659 * whether the current backing file can be replaced with the new one.
4660 * If that's the case then reopen_state->replace_backing_bs is set to
4661 * true and reopen_state->new_backing_bs contains a pointer to the new
4662 * backing BlockDriverState (or NULL).
4664 * After calling this function, the transaction @tran may only be completed
4665 * while holding a writer lock for the graph.
4667 * Return 0 on success, otherwise return < 0 and set @errp.
4669 * @reopen_state->bs can move to a different AioContext in this function.
4671 static int GRAPH_UNLOCKED
4672 bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4673 bool is_backing, Transaction *tran,
4674 Error **errp)
4676 BlockDriverState *bs = reopen_state->bs;
4677 BlockDriverState *new_child_bs;
4678 BlockDriverState *old_child_bs;
4680 const char *child_name = is_backing ? "backing" : "file";
4681 QObject *value;
4682 const char *str;
4683 bool has_child;
4684 int ret;
4686 GLOBAL_STATE_CODE();
4688 value = qdict_get(reopen_state->options, child_name);
4689 if (value == NULL) {
4690 return 0;
4693 bdrv_graph_rdlock_main_loop();
4695 switch (qobject_type(value)) {
4696 case QTYPE_QNULL:
4697 assert(is_backing); /* The 'file' option does not allow a null value */
4698 new_child_bs = NULL;
4699 break;
4700 case QTYPE_QSTRING:
4701 str = qstring_get_str(qobject_to(QString, value));
4702 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4703 if (new_child_bs == NULL) {
4704 ret = -EINVAL;
4705 goto out_rdlock;
4708 has_child = bdrv_recurse_has_child(new_child_bs, bs);
4709 if (has_child) {
4710 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4711 "cycle", str, child_name, bs->node_name);
4712 ret = -EINVAL;
4713 goto out_rdlock;
4715 break;
4716 default:
4718 * The options QDict has been flattened, so 'backing' and 'file'
4719 * do not allow any other data type here.
4721 g_assert_not_reached();
4724 old_child_bs = is_backing ? child_bs(bs->backing) : child_bs(bs->file);
4725 if (old_child_bs == new_child_bs) {
4726 ret = 0;
4727 goto out_rdlock;
4730 if (old_child_bs) {
4731 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4732 ret = 0;
4733 goto out_rdlock;
4736 if (old_child_bs->implicit) {
4737 error_setg(errp, "Cannot replace implicit %s child of %s",
4738 child_name, bs->node_name);
4739 ret = -EPERM;
4740 goto out_rdlock;
4744 if (bs->drv->is_filter && !old_child_bs) {
4746 * Filters always have a file or a backing child, so we are trying to
4747 * change wrong child
4749 error_setg(errp, "'%s' is a %s filter node that does not support a "
4750 "%s child", bs->node_name, bs->drv->format_name, child_name);
4751 ret = -EINVAL;
4752 goto out_rdlock;
4755 if (is_backing) {
4756 reopen_state->old_backing_bs = old_child_bs;
4757 } else {
4758 reopen_state->old_file_bs = old_child_bs;
4761 if (old_child_bs) {
4762 bdrv_ref(old_child_bs);
4763 bdrv_drained_begin(old_child_bs);
4766 bdrv_graph_rdunlock_main_loop();
4767 bdrv_graph_wrlock();
4769 ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4770 tran, errp);
4772 bdrv_graph_wrunlock();
4774 if (old_child_bs) {
4775 bdrv_drained_end(old_child_bs);
4776 bdrv_unref(old_child_bs);
4779 return ret;
4781 out_rdlock:
4782 bdrv_graph_rdunlock_main_loop();
4783 return ret;
4787 * Prepares a BlockDriverState for reopen. All changes are staged in the
4788 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4789 * the block driver layer .bdrv_reopen_prepare()
4791 * bs is the BlockDriverState to reopen
4792 * flags are the new open flags
4793 * queue is the reopen queue
4795 * Returns 0 on success, non-zero on error. On error errp will be set
4796 * as well.
4798 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4799 * It is the responsibility of the caller to then call the abort() or
4800 * commit() for any other BDS that have been left in a prepare() state
4802 * After calling this function, the transaction @change_child_tran may only be
4803 * completed while holding a writer lock for the graph.
4805 static int GRAPH_UNLOCKED
4806 bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4807 Transaction *change_child_tran, Error **errp)
4809 int ret = -1;
4810 int old_flags;
4811 Error *local_err = NULL;
4812 BlockDriver *drv;
4813 QemuOpts *opts;
4814 QDict *orig_reopen_opts;
4815 char *discard = NULL;
4816 bool read_only;
4817 bool drv_prepared = false;
4819 assert(reopen_state != NULL);
4820 assert(reopen_state->bs->drv != NULL);
4821 GLOBAL_STATE_CODE();
4822 drv = reopen_state->bs->drv;
4824 /* This function and each driver's bdrv_reopen_prepare() remove
4825 * entries from reopen_state->options as they are processed, so
4826 * we need to make a copy of the original QDict. */
4827 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4829 /* Process generic block layer options */
4830 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4831 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4832 ret = -EINVAL;
4833 goto error;
4836 /* This was already called in bdrv_reopen_queue_child() so the flags
4837 * are up-to-date. This time we simply want to remove the options from
4838 * QemuOpts in order to indicate that they have been processed. */
4839 old_flags = reopen_state->flags;
4840 update_flags_from_options(&reopen_state->flags, opts);
4841 assert(old_flags == reopen_state->flags);
4843 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4844 if (discard != NULL) {
4845 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4846 error_setg(errp, "Invalid discard option");
4847 ret = -EINVAL;
4848 goto error;
4852 reopen_state->detect_zeroes =
4853 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4854 if (local_err) {
4855 error_propagate(errp, local_err);
4856 ret = -EINVAL;
4857 goto error;
4860 /* All other options (including node-name and driver) must be unchanged.
4861 * Put them back into the QDict, so that they are checked at the end
4862 * of this function. */
4863 qemu_opts_to_qdict(opts, reopen_state->options);
4865 /* If we are to stay read-only, do not allow permission change
4866 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4867 * not set, or if the BDS still has copy_on_read enabled */
4868 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4870 bdrv_graph_rdlock_main_loop();
4871 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4872 bdrv_graph_rdunlock_main_loop();
4873 if (local_err) {
4874 error_propagate(errp, local_err);
4875 goto error;
4878 if (drv->bdrv_reopen_prepare) {
4880 * If a driver-specific option is missing, it means that we
4881 * should reset it to its default value.
4882 * But not all options allow that, so we need to check it first.
4884 ret = bdrv_reset_options_allowed(reopen_state->bs,
4885 reopen_state->options, errp);
4886 if (ret) {
4887 goto error;
4890 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4891 if (ret) {
4892 if (local_err != NULL) {
4893 error_propagate(errp, local_err);
4894 } else {
4895 bdrv_graph_rdlock_main_loop();
4896 bdrv_refresh_filename(reopen_state->bs);
4897 bdrv_graph_rdunlock_main_loop();
4898 error_setg(errp, "failed while preparing to reopen image '%s'",
4899 reopen_state->bs->filename);
4901 goto error;
4903 } else {
4904 /* It is currently mandatory to have a bdrv_reopen_prepare()
4905 * handler for each supported drv. */
4906 bdrv_graph_rdlock_main_loop();
4907 error_setg(errp, "Block format '%s' used by node '%s' "
4908 "does not support reopening files", drv->format_name,
4909 bdrv_get_device_or_node_name(reopen_state->bs));
4910 bdrv_graph_rdunlock_main_loop();
4911 ret = -1;
4912 goto error;
4915 drv_prepared = true;
4918 * We must provide the 'backing' option if the BDS has a backing
4919 * file or if the image file has a backing file name as part of
4920 * its metadata. Otherwise the 'backing' option can be omitted.
4922 bdrv_graph_rdlock_main_loop();
4923 if (drv->supports_backing && reopen_state->backing_missing &&
4924 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4925 error_setg(errp, "backing is missing for '%s'",
4926 reopen_state->bs->node_name);
4927 bdrv_graph_rdunlock_main_loop();
4928 ret = -EINVAL;
4929 goto error;
4931 bdrv_graph_rdunlock_main_loop();
4934 * Allow changing the 'backing' option. The new value can be
4935 * either a reference to an existing node (using its node name)
4936 * or NULL to simply detach the current backing file.
4938 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4939 change_child_tran, errp);
4940 if (ret < 0) {
4941 goto error;
4943 qdict_del(reopen_state->options, "backing");
4945 /* Allow changing the 'file' option. In this case NULL is not allowed */
4946 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4947 change_child_tran, errp);
4948 if (ret < 0) {
4949 goto error;
4951 qdict_del(reopen_state->options, "file");
4953 /* Options that are not handled are only okay if they are unchanged
4954 * compared to the old state. It is expected that some options are only
4955 * used for the initial open, but not reopen (e.g. filename) */
4956 if (qdict_size(reopen_state->options)) {
4957 const QDictEntry *entry = qdict_first(reopen_state->options);
4959 GRAPH_RDLOCK_GUARD_MAINLOOP();
4961 do {
4962 QObject *new = entry->value;
4963 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4965 /* Allow child references (child_name=node_name) as long as they
4966 * point to the current child (i.e. everything stays the same). */
4967 if (qobject_type(new) == QTYPE_QSTRING) {
4968 BdrvChild *child;
4969 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4970 if (!strcmp(child->name, entry->key)) {
4971 break;
4975 if (child) {
4976 if (!strcmp(child->bs->node_name,
4977 qstring_get_str(qobject_to(QString, new)))) {
4978 continue; /* Found child with this name, skip option */
4984 * TODO: When using -drive to specify blockdev options, all values
4985 * will be strings; however, when using -blockdev, blockdev-add or
4986 * filenames using the json:{} pseudo-protocol, they will be
4987 * correctly typed.
4988 * In contrast, reopening options are (currently) always strings
4989 * (because you can only specify them through qemu-io; all other
4990 * callers do not specify any options).
4991 * Therefore, when using anything other than -drive to create a BDS,
4992 * this cannot detect non-string options as unchanged, because
4993 * qobject_is_equal() always returns false for objects of different
4994 * type. In the future, this should be remedied by correctly typing
4995 * all options. For now, this is not too big of an issue because
4996 * the user can simply omit options which cannot be changed anyway,
4997 * so they will stay unchanged.
4999 if (!qobject_is_equal(new, old)) {
5000 error_setg(errp, "Cannot change the option '%s'", entry->key);
5001 ret = -EINVAL;
5002 goto error;
5004 } while ((entry = qdict_next(reopen_state->options, entry)));
5007 ret = 0;
5009 /* Restore the original reopen_state->options QDict */
5010 qobject_unref(reopen_state->options);
5011 reopen_state->options = qobject_ref(orig_reopen_opts);
5013 error:
5014 if (ret < 0 && drv_prepared) {
5015 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
5016 * call drv->bdrv_reopen_abort() before signaling an error
5017 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
5018 * when the respective bdrv_reopen_prepare() has failed) */
5019 if (drv->bdrv_reopen_abort) {
5020 drv->bdrv_reopen_abort(reopen_state);
5023 qemu_opts_del(opts);
5024 qobject_unref(orig_reopen_opts);
5025 g_free(discard);
5026 return ret;
5030 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5031 * makes them final by swapping the staging BlockDriverState contents into
5032 * the active BlockDriverState contents.
5034 static void GRAPH_UNLOCKED bdrv_reopen_commit(BDRVReopenState *reopen_state)
5036 BlockDriver *drv;
5037 BlockDriverState *bs;
5038 BdrvChild *child;
5040 assert(reopen_state != NULL);
5041 bs = reopen_state->bs;
5042 drv = bs->drv;
5043 assert(drv != NULL);
5044 GLOBAL_STATE_CODE();
5046 /* If there are any driver level actions to take */
5047 if (drv->bdrv_reopen_commit) {
5048 drv->bdrv_reopen_commit(reopen_state);
5051 GRAPH_RDLOCK_GUARD_MAINLOOP();
5053 /* set BDS specific flags now */
5054 qobject_unref(bs->explicit_options);
5055 qobject_unref(bs->options);
5056 qobject_ref(reopen_state->explicit_options);
5057 qobject_ref(reopen_state->options);
5059 bs->explicit_options = reopen_state->explicit_options;
5060 bs->options = reopen_state->options;
5061 bs->open_flags = reopen_state->flags;
5062 bs->detect_zeroes = reopen_state->detect_zeroes;
5064 /* Remove child references from bs->options and bs->explicit_options.
5065 * Child options were already removed in bdrv_reopen_queue_child() */
5066 QLIST_FOREACH(child, &bs->children, next) {
5067 qdict_del(bs->explicit_options, child->name);
5068 qdict_del(bs->options, child->name);
5070 /* backing is probably removed, so it's not handled by previous loop */
5071 qdict_del(bs->explicit_options, "backing");
5072 qdict_del(bs->options, "backing");
5074 bdrv_refresh_limits(bs, NULL, NULL);
5075 bdrv_refresh_total_sectors(bs, bs->total_sectors);
5079 * Abort the reopen, and delete and free the staged changes in
5080 * reopen_state
5082 static void GRAPH_UNLOCKED bdrv_reopen_abort(BDRVReopenState *reopen_state)
5084 BlockDriver *drv;
5086 assert(reopen_state != NULL);
5087 drv = reopen_state->bs->drv;
5088 assert(drv != NULL);
5089 GLOBAL_STATE_CODE();
5091 if (drv->bdrv_reopen_abort) {
5092 drv->bdrv_reopen_abort(reopen_state);
5097 static void bdrv_close(BlockDriverState *bs)
5099 BdrvAioNotifier *ban, *ban_next;
5100 BdrvChild *child, *next;
5102 GLOBAL_STATE_CODE();
5103 assert(!bs->refcnt);
5105 bdrv_drained_begin(bs); /* complete I/O */
5106 bdrv_flush(bs);
5107 bdrv_drain(bs); /* in case flush left pending I/O */
5109 if (bs->drv) {
5110 if (bs->drv->bdrv_close) {
5111 /* Must unfreeze all children, so bdrv_unref_child() works */
5112 bs->drv->bdrv_close(bs);
5114 bs->drv = NULL;
5117 bdrv_graph_wrlock();
5118 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
5119 bdrv_unref_child(bs, child);
5122 assert(!bs->backing);
5123 assert(!bs->file);
5124 bdrv_graph_wrunlock();
5126 g_free(bs->opaque);
5127 bs->opaque = NULL;
5128 qatomic_set(&bs->copy_on_read, 0);
5129 bs->backing_file[0] = '\0';
5130 bs->backing_format[0] = '\0';
5131 bs->total_sectors = 0;
5132 bs->encrypted = false;
5133 bs->sg = false;
5134 qobject_unref(bs->options);
5135 qobject_unref(bs->explicit_options);
5136 bs->options = NULL;
5137 bs->explicit_options = NULL;
5138 qobject_unref(bs->full_open_options);
5139 bs->full_open_options = NULL;
5140 g_free(bs->block_status_cache);
5141 bs->block_status_cache = NULL;
5143 bdrv_release_named_dirty_bitmaps(bs);
5144 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5146 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
5147 g_free(ban);
5149 QLIST_INIT(&bs->aio_notifiers);
5150 bdrv_drained_end(bs);
5153 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
5154 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
5155 * gets called.
5157 if (bs->quiesce_counter) {
5158 bdrv_drain_all_end_quiesce(bs);
5162 void bdrv_close_all(void)
5164 GLOBAL_STATE_CODE();
5165 assert(job_next(NULL) == NULL);
5167 /* Drop references from requests still in flight, such as canceled block
5168 * jobs whose AIO context has not been polled yet */
5169 bdrv_drain_all();
5171 blk_remove_all_bs();
5172 blockdev_close_all_bdrv_states();
5174 assert(QTAILQ_EMPTY(&all_bdrv_states));
5177 static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
5179 GQueue *queue;
5180 GHashTable *found;
5181 bool ret;
5183 if (c->klass->stay_at_node) {
5184 return false;
5187 /* If the child @c belongs to the BDS @to, replacing the current
5188 * c->bs by @to would mean to create a loop.
5190 * Such a case occurs when appending a BDS to a backing chain.
5191 * For instance, imagine the following chain:
5193 * guest device -> node A -> further backing chain...
5195 * Now we create a new BDS B which we want to put on top of this
5196 * chain, so we first attach A as its backing node:
5198 * node B
5201 * guest device -> node A -> further backing chain...
5203 * Finally we want to replace A by B. When doing that, we want to
5204 * replace all pointers to A by pointers to B -- except for the
5205 * pointer from B because (1) that would create a loop, and (2)
5206 * that pointer should simply stay intact:
5208 * guest device -> node B
5211 * node A -> further backing chain...
5213 * In general, when replacing a node A (c->bs) by a node B (@to),
5214 * if A is a child of B, that means we cannot replace A by B there
5215 * because that would create a loop. Silently detaching A from B
5216 * is also not really an option. So overall just leaving A in
5217 * place there is the most sensible choice.
5219 * We would also create a loop in any cases where @c is only
5220 * indirectly referenced by @to. Prevent this by returning false
5221 * if @c is found (by breadth-first search) anywhere in the whole
5222 * subtree of @to.
5225 ret = true;
5226 found = g_hash_table_new(NULL, NULL);
5227 g_hash_table_add(found, to);
5228 queue = g_queue_new();
5229 g_queue_push_tail(queue, to);
5231 while (!g_queue_is_empty(queue)) {
5232 BlockDriverState *v = g_queue_pop_head(queue);
5233 BdrvChild *c2;
5235 QLIST_FOREACH(c2, &v->children, next) {
5236 if (c2 == c) {
5237 ret = false;
5238 break;
5241 if (g_hash_table_contains(found, c2->bs)) {
5242 continue;
5245 g_queue_push_tail(queue, c2->bs);
5246 g_hash_table_add(found, c2->bs);
5250 g_queue_free(queue);
5251 g_hash_table_destroy(found);
5253 return ret;
5256 static void bdrv_remove_child_commit(void *opaque)
5258 GLOBAL_STATE_CODE();
5259 bdrv_child_free(opaque);
5262 static TransactionActionDrv bdrv_remove_child_drv = {
5263 .commit = bdrv_remove_child_commit,
5267 * Function doesn't update permissions, caller is responsible for this.
5269 * @child->bs (if non-NULL) must be drained.
5271 * After calling this function, the transaction @tran may only be completed
5272 * while holding a writer lock for the graph.
5274 static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
5276 if (!child) {
5277 return;
5280 if (child->bs) {
5281 assert(child->quiesced_parent);
5282 bdrv_replace_child_tran(child, NULL, tran);
5285 tran_add(tran, &bdrv_remove_child_drv, child);
5289 * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
5290 * until the transaction is completed.
5292 * After calling this function, the transaction @tran may only be completed
5293 * while holding a writer lock for the graph.
5295 static int GRAPH_WRLOCK
5296 bdrv_replace_node_noperm(BlockDriverState *from,
5297 BlockDriverState *to,
5298 bool auto_skip, Transaction *tran,
5299 Error **errp)
5301 BdrvChild *c, *next;
5303 GLOBAL_STATE_CODE();
5305 assert(from->quiesce_counter);
5306 assert(to->quiesce_counter);
5308 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5309 assert(c->bs == from);
5310 if (!should_update_child(c, to)) {
5311 if (auto_skip) {
5312 continue;
5314 error_setg(errp, "Should not change '%s' link to '%s'",
5315 c->name, from->node_name);
5316 return -EINVAL;
5318 if (c->frozen) {
5319 error_setg(errp, "Cannot change '%s' link to '%s'",
5320 c->name, from->node_name);
5321 return -EPERM;
5323 bdrv_replace_child_tran(c, to, tran);
5326 return 0;
5330 * Switch all parents of @from to point to @to instead. @from and @to must be in
5331 * the same AioContext and both must be drained.
5333 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5334 * if it creates a parent-child relation loop or if parent is block-job.
5336 * With auto_skip=false the error is returned if from has a parent which should
5337 * not be updated.
5339 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5340 * case backing link of the cow-parent of @to is removed.
5342 static int GRAPH_WRLOCK
5343 bdrv_replace_node_common(BlockDriverState *from, BlockDriverState *to,
5344 bool auto_skip, bool detach_subchain, Error **errp)
5346 Transaction *tran = tran_new();
5347 g_autoptr(GSList) refresh_list = NULL;
5348 BlockDriverState *to_cow_parent = NULL;
5349 int ret;
5351 GLOBAL_STATE_CODE();
5353 assert(from->quiesce_counter);
5354 assert(to->quiesce_counter);
5355 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5357 if (detach_subchain) {
5358 assert(bdrv_chain_contains(from, to));
5359 assert(from != to);
5360 for (to_cow_parent = from;
5361 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5362 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5369 * Do the replacement without permission update.
5370 * Replacement may influence the permissions, we should calculate new
5371 * permissions based on new graph. If we fail, we'll roll-back the
5372 * replacement.
5374 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5375 if (ret < 0) {
5376 goto out;
5379 if (detach_subchain) {
5380 /* to_cow_parent is already drained because from is drained */
5381 bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5384 refresh_list = g_slist_prepend(refresh_list, to);
5385 refresh_list = g_slist_prepend(refresh_list, from);
5387 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5388 if (ret < 0) {
5389 goto out;
5392 ret = 0;
5394 out:
5395 tran_finalize(tran, ret);
5396 return ret;
5399 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5400 Error **errp)
5402 return bdrv_replace_node_common(from, to, true, false, errp);
5405 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5407 BlockDriverState *child_bs;
5408 int ret;
5410 GLOBAL_STATE_CODE();
5412 bdrv_graph_rdlock_main_loop();
5413 child_bs = bdrv_filter_or_cow_bs(bs);
5414 bdrv_graph_rdunlock_main_loop();
5416 bdrv_drained_begin(child_bs);
5417 bdrv_graph_wrlock();
5418 ret = bdrv_replace_node_common(bs, child_bs, true, true, errp);
5419 bdrv_graph_wrunlock();
5420 bdrv_drained_end(child_bs);
5422 return ret;
5426 * Add new bs contents at the top of an image chain while the chain is
5427 * live, while keeping required fields on the top layer.
5429 * This will modify the BlockDriverState fields, and swap contents
5430 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5432 * bs_new must not be attached to a BlockBackend and must not have backing
5433 * child.
5435 * This function does not create any image files.
5437 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5438 Error **errp)
5440 int ret;
5441 BdrvChild *child;
5442 Transaction *tran = tran_new();
5444 GLOBAL_STATE_CODE();
5446 bdrv_graph_rdlock_main_loop();
5447 assert(!bs_new->backing);
5448 bdrv_graph_rdunlock_main_loop();
5450 bdrv_drained_begin(bs_top);
5451 bdrv_drained_begin(bs_new);
5453 bdrv_graph_wrlock();
5455 child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5456 &child_of_bds, bdrv_backing_role(bs_new),
5457 tran, errp);
5458 if (!child) {
5459 ret = -EINVAL;
5460 goto out;
5463 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5464 if (ret < 0) {
5465 goto out;
5468 ret = bdrv_refresh_perms(bs_new, tran, errp);
5469 out:
5470 tran_finalize(tran, ret);
5472 bdrv_refresh_limits(bs_top, NULL, NULL);
5473 bdrv_graph_wrunlock();
5475 bdrv_drained_end(bs_top);
5476 bdrv_drained_end(bs_new);
5478 return ret;
5481 /* Not for empty child */
5482 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5483 Error **errp)
5485 int ret;
5486 Transaction *tran = tran_new();
5487 g_autoptr(GSList) refresh_list = NULL;
5488 BlockDriverState *old_bs = child->bs;
5490 GLOBAL_STATE_CODE();
5492 bdrv_ref(old_bs);
5493 bdrv_drained_begin(old_bs);
5494 bdrv_drained_begin(new_bs);
5495 bdrv_graph_wrlock();
5497 bdrv_replace_child_tran(child, new_bs, tran);
5499 refresh_list = g_slist_prepend(refresh_list, old_bs);
5500 refresh_list = g_slist_prepend(refresh_list, new_bs);
5502 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5504 tran_finalize(tran, ret);
5506 bdrv_graph_wrunlock();
5507 bdrv_drained_end(old_bs);
5508 bdrv_drained_end(new_bs);
5509 bdrv_unref(old_bs);
5511 return ret;
5514 static void bdrv_delete(BlockDriverState *bs)
5516 assert(bdrv_op_blocker_is_empty(bs));
5517 assert(!bs->refcnt);
5518 GLOBAL_STATE_CODE();
5520 /* remove from list, if necessary */
5521 if (bs->node_name[0] != '\0') {
5522 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5524 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5526 bdrv_close(bs);
5528 qemu_mutex_destroy(&bs->reqs_lock);
5530 g_free(bs);
5535 * Replace @bs by newly created block node.
5537 * @options is a QDict of options to pass to the block drivers, or NULL for an
5538 * empty set of options. The reference to the QDict belongs to the block layer
5539 * after the call (even on failure), so if the caller intends to reuse the
5540 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5542 * The caller must make sure that @bs stays in the same AioContext, i.e.
5543 * @options must not refer to nodes in a different AioContext.
5545 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5546 int flags, Error **errp)
5548 ERRP_GUARD();
5549 int ret;
5550 AioContext *ctx = bdrv_get_aio_context(bs);
5551 BlockDriverState *new_node_bs = NULL;
5552 const char *drvname, *node_name;
5553 BlockDriver *drv;
5555 drvname = qdict_get_try_str(options, "driver");
5556 if (!drvname) {
5557 error_setg(errp, "driver is not specified");
5558 goto fail;
5561 drv = bdrv_find_format(drvname);
5562 if (!drv) {
5563 error_setg(errp, "Unknown driver: '%s'", drvname);
5564 goto fail;
5567 node_name = qdict_get_try_str(options, "node-name");
5569 GLOBAL_STATE_CODE();
5571 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5572 errp);
5573 assert(bdrv_get_aio_context(bs) == ctx);
5575 options = NULL; /* bdrv_new_open_driver() eats options */
5576 if (!new_node_bs) {
5577 error_prepend(errp, "Could not create node: ");
5578 goto fail;
5582 * Make sure that @bs doesn't go away until we have successfully attached
5583 * all of its parents to @new_node_bs and undrained it again.
5585 bdrv_ref(bs);
5586 bdrv_drained_begin(bs);
5587 bdrv_drained_begin(new_node_bs);
5588 bdrv_graph_wrlock();
5589 ret = bdrv_replace_node(bs, new_node_bs, errp);
5590 bdrv_graph_wrunlock();
5591 bdrv_drained_end(new_node_bs);
5592 bdrv_drained_end(bs);
5593 bdrv_unref(bs);
5595 if (ret < 0) {
5596 error_prepend(errp, "Could not replace node: ");
5597 goto fail;
5600 return new_node_bs;
5602 fail:
5603 qobject_unref(options);
5604 bdrv_unref(new_node_bs);
5605 return NULL;
5609 * Run consistency checks on an image
5611 * Returns 0 if the check could be completed (it doesn't mean that the image is
5612 * free of errors) or -errno when an internal error occurred. The results of the
5613 * check are stored in res.
5615 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5616 BdrvCheckResult *res, BdrvCheckMode fix)
5618 IO_CODE();
5619 assert_bdrv_graph_readable();
5620 if (bs->drv == NULL) {
5621 return -ENOMEDIUM;
5623 if (bs->drv->bdrv_co_check == NULL) {
5624 return -ENOTSUP;
5627 memset(res, 0, sizeof(*res));
5628 return bs->drv->bdrv_co_check(bs, res, fix);
5632 * Return values:
5633 * 0 - success
5634 * -EINVAL - backing format specified, but no file
5635 * -ENOSPC - can't update the backing file because no space is left in the
5636 * image file header
5637 * -ENOTSUP - format driver doesn't support changing the backing file
5639 int coroutine_fn
5640 bdrv_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
5641 const char *backing_fmt, bool require)
5643 BlockDriver *drv = bs->drv;
5644 int ret;
5646 IO_CODE();
5648 if (!drv) {
5649 return -ENOMEDIUM;
5652 /* Backing file format doesn't make sense without a backing file */
5653 if (backing_fmt && !backing_file) {
5654 return -EINVAL;
5657 if (require && backing_file && !backing_fmt) {
5658 return -EINVAL;
5661 if (drv->bdrv_co_change_backing_file != NULL) {
5662 ret = drv->bdrv_co_change_backing_file(bs, backing_file, backing_fmt);
5663 } else {
5664 ret = -ENOTSUP;
5667 if (ret == 0) {
5668 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5669 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5670 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5671 backing_file ?: "");
5673 return ret;
5677 * Finds the first non-filter node above bs in the chain between
5678 * active and bs. The returned node is either an immediate parent of
5679 * bs, or there are only filter nodes between the two.
5681 * Returns NULL if bs is not found in active's image chain,
5682 * or if active == bs.
5684 * Returns the bottommost base image if bs == NULL.
5686 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5687 BlockDriverState *bs)
5690 GLOBAL_STATE_CODE();
5692 bs = bdrv_skip_filters(bs);
5693 active = bdrv_skip_filters(active);
5695 while (active) {
5696 BlockDriverState *next = bdrv_backing_chain_next(active);
5697 if (bs == next) {
5698 return active;
5700 active = next;
5703 return NULL;
5706 /* Given a BDS, searches for the base layer. */
5707 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5709 GLOBAL_STATE_CODE();
5711 return bdrv_find_overlay(bs, NULL);
5715 * Return true if at least one of the COW (backing) and filter links
5716 * between @bs and @base is frozen. @errp is set if that's the case.
5717 * @base must be reachable from @bs, or NULL.
5719 static bool GRAPH_RDLOCK
5720 bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5721 Error **errp)
5723 BlockDriverState *i;
5724 BdrvChild *child;
5726 GLOBAL_STATE_CODE();
5728 for (i = bs; i != base; i = child_bs(child)) {
5729 child = bdrv_filter_or_cow_child(i);
5731 if (child && child->frozen) {
5732 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5733 child->name, i->node_name, child->bs->node_name);
5734 return true;
5738 return false;
5742 * Freeze all COW (backing) and filter links between @bs and @base.
5743 * If any of the links is already frozen the operation is aborted and
5744 * none of the links are modified.
5745 * @base must be reachable from @bs, or NULL.
5746 * Returns 0 on success. On failure returns < 0 and sets @errp.
5748 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5749 Error **errp)
5751 BlockDriverState *i;
5752 BdrvChild *child;
5754 GLOBAL_STATE_CODE();
5756 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5757 return -EPERM;
5760 for (i = bs; i != base; i = child_bs(child)) {
5761 child = bdrv_filter_or_cow_child(i);
5762 if (child && child->bs->never_freeze) {
5763 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5764 child->name, child->bs->node_name);
5765 return -EPERM;
5769 for (i = bs; i != base; i = child_bs(child)) {
5770 child = bdrv_filter_or_cow_child(i);
5771 if (child) {
5772 child->frozen = true;
5776 return 0;
5780 * Unfreeze all COW (backing) and filter links between @bs and @base.
5781 * The caller must ensure that all links are frozen before using this
5782 * function.
5783 * @base must be reachable from @bs, or NULL.
5785 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5787 BlockDriverState *i;
5788 BdrvChild *child;
5790 GLOBAL_STATE_CODE();
5792 for (i = bs; i != base; i = child_bs(child)) {
5793 child = bdrv_filter_or_cow_child(i);
5794 if (child) {
5795 assert(child->frozen);
5796 child->frozen = false;
5802 * Drops images above 'base' up to and including 'top', and sets the image
5803 * above 'top' to have base as its backing file.
5805 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5806 * information in 'bs' can be properly updated.
5808 * E.g., this will convert the following chain:
5809 * bottom <- base <- intermediate <- top <- active
5811 * to
5813 * bottom <- base <- active
5815 * It is allowed for bottom==base, in which case it converts:
5817 * base <- intermediate <- top <- active
5819 * to
5821 * base <- active
5823 * If backing_file_str is non-NULL, it will be used when modifying top's
5824 * overlay image metadata.
5826 * Error conditions:
5827 * if active == top, that is considered an error
5830 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5831 const char *backing_file_str,
5832 bool backing_mask_protocol)
5834 BlockDriverState *explicit_top = top;
5835 bool update_inherits_from;
5836 BdrvChild *c;
5837 Error *local_err = NULL;
5838 int ret = -EIO;
5839 g_autoptr(GSList) updated_children = NULL;
5840 GSList *p;
5842 GLOBAL_STATE_CODE();
5844 bdrv_ref(top);
5845 bdrv_drained_begin(base);
5846 bdrv_graph_wrlock();
5848 if (!top->drv || !base->drv) {
5849 goto exit_wrlock;
5852 /* Make sure that base is in the backing chain of top */
5853 if (!bdrv_chain_contains(top, base)) {
5854 goto exit_wrlock;
5857 /* If 'base' recursively inherits from 'top' then we should set
5858 * base->inherits_from to top->inherits_from after 'top' and all
5859 * other intermediate nodes have been dropped.
5860 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5861 * it because no one inherits from it. We use explicit_top for that. */
5862 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5863 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5865 /* success - we can delete the intermediate states, and link top->base */
5866 if (!backing_file_str) {
5867 bdrv_refresh_filename(base);
5868 backing_file_str = base->filename;
5871 QLIST_FOREACH(c, &top->parents, next_parent) {
5872 updated_children = g_slist_prepend(updated_children, c);
5876 * It seems correct to pass detach_subchain=true here, but it triggers
5877 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5878 * another drained section, which modify the graph (for example, removing
5879 * the child, which we keep in updated_children list). So, it's a TODO.
5881 * Note, bug triggered if pass detach_subchain=true here and run
5882 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5883 * That's a FIXME.
5885 bdrv_replace_node_common(top, base, false, false, &local_err);
5886 bdrv_graph_wrunlock();
5888 if (local_err) {
5889 error_report_err(local_err);
5890 goto exit;
5893 for (p = updated_children; p; p = p->next) {
5894 c = p->data;
5896 if (c->klass->update_filename) {
5897 ret = c->klass->update_filename(c, base, backing_file_str,
5898 backing_mask_protocol,
5899 &local_err);
5900 if (ret < 0) {
5902 * TODO: Actually, we want to rollback all previous iterations
5903 * of this loop, and (which is almost impossible) previous
5904 * bdrv_replace_node()...
5906 * Note, that c->klass->update_filename may lead to permission
5907 * update, so it's a bad idea to call it inside permission
5908 * update transaction of bdrv_replace_node.
5910 error_report_err(local_err);
5911 goto exit;
5916 if (update_inherits_from) {
5917 base->inherits_from = explicit_top->inherits_from;
5920 ret = 0;
5921 goto exit;
5923 exit_wrlock:
5924 bdrv_graph_wrunlock();
5925 exit:
5926 bdrv_drained_end(base);
5927 bdrv_unref(top);
5928 return ret;
5932 * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
5933 * sums the size of all data-bearing children. (This excludes backing
5934 * children.)
5936 static int64_t coroutine_fn GRAPH_RDLOCK
5937 bdrv_sum_allocated_file_size(BlockDriverState *bs)
5939 BdrvChild *child;
5940 int64_t child_size, sum = 0;
5942 QLIST_FOREACH(child, &bs->children, next) {
5943 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5944 BDRV_CHILD_FILTERED))
5946 child_size = bdrv_co_get_allocated_file_size(child->bs);
5947 if (child_size < 0) {
5948 return child_size;
5950 sum += child_size;
5954 return sum;
5958 * Length of a allocated file in bytes. Sparse files are counted by actual
5959 * allocated space. Return < 0 if error or unknown.
5961 int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
5963 BlockDriver *drv = bs->drv;
5964 IO_CODE();
5965 assert_bdrv_graph_readable();
5967 if (!drv) {
5968 return -ENOMEDIUM;
5970 if (drv->bdrv_co_get_allocated_file_size) {
5971 return drv->bdrv_co_get_allocated_file_size(bs);
5974 if (drv->bdrv_file_open) {
5976 * Protocol drivers default to -ENOTSUP (most of their data is
5977 * not stored in any of their children (if they even have any),
5978 * so there is no generic way to figure it out).
5980 return -ENOTSUP;
5981 } else if (drv->is_filter) {
5982 /* Filter drivers default to the size of their filtered child */
5983 return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
5984 } else {
5985 /* Other drivers default to summing their children's sizes */
5986 return bdrv_sum_allocated_file_size(bs);
5991 * bdrv_measure:
5992 * @drv: Format driver
5993 * @opts: Creation options for new image
5994 * @in_bs: Existing image containing data for new image (may be NULL)
5995 * @errp: Error object
5996 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5997 * or NULL on error
5999 * Calculate file size required to create a new image.
6001 * If @in_bs is given then space for allocated clusters and zero clusters
6002 * from that image are included in the calculation. If @opts contains a
6003 * backing file that is shared by @in_bs then backing clusters may be omitted
6004 * from the calculation.
6006 * If @in_bs is NULL then the calculation includes no allocated clusters
6007 * unless a preallocation option is given in @opts.
6009 * Note that @in_bs may use a different BlockDriver from @drv.
6011 * If an error occurs the @errp pointer is set.
6013 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
6014 BlockDriverState *in_bs, Error **errp)
6016 IO_CODE();
6017 if (!drv->bdrv_measure) {
6018 error_setg(errp, "Block driver '%s' does not support size measurement",
6019 drv->format_name);
6020 return NULL;
6023 return drv->bdrv_measure(opts, in_bs, errp);
6027 * Return number of sectors on success, -errno on error.
6029 int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
6031 BlockDriver *drv = bs->drv;
6032 IO_CODE();
6033 assert_bdrv_graph_readable();
6035 if (!drv)
6036 return -ENOMEDIUM;
6038 if (bs->bl.has_variable_length) {
6039 int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
6040 if (ret < 0) {
6041 return ret;
6044 return bs->total_sectors;
6048 * This wrapper is written by hand because this function is in the hot I/O path,
6049 * via blk_get_geometry.
6051 int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
6053 BlockDriver *drv = bs->drv;
6054 IO_CODE();
6056 if (!drv)
6057 return -ENOMEDIUM;
6059 if (bs->bl.has_variable_length) {
6060 int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6061 if (ret < 0) {
6062 return ret;
6066 return bs->total_sectors;
6070 * Return length in bytes on success, -errno on error.
6071 * The length is always a multiple of BDRV_SECTOR_SIZE.
6073 int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
6075 int64_t ret;
6076 IO_CODE();
6077 assert_bdrv_graph_readable();
6079 ret = bdrv_co_nb_sectors(bs);
6080 if (ret < 0) {
6081 return ret;
6083 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
6084 return -EFBIG;
6086 return ret * BDRV_SECTOR_SIZE;
6089 bool bdrv_is_sg(BlockDriverState *bs)
6091 IO_CODE();
6092 return bs->sg;
6096 * Return whether the given node supports compressed writes.
6098 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
6100 BlockDriverState *filtered;
6101 IO_CODE();
6103 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
6104 return false;
6107 filtered = bdrv_filter_bs(bs);
6108 if (filtered) {
6110 * Filters can only forward compressed writes, so we have to
6111 * check the child.
6113 return bdrv_supports_compressed_writes(filtered);
6116 return true;
6119 const char *bdrv_get_format_name(BlockDriverState *bs)
6121 IO_CODE();
6122 return bs->drv ? bs->drv->format_name : NULL;
6125 static int qsort_strcmp(const void *a, const void *b)
6127 return strcmp(*(char *const *)a, *(char *const *)b);
6130 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
6131 void *opaque, bool read_only)
6133 BlockDriver *drv;
6134 int count = 0;
6135 int i;
6136 const char **formats = NULL;
6138 GLOBAL_STATE_CODE();
6140 QLIST_FOREACH(drv, &bdrv_drivers, list) {
6141 if (drv->format_name) {
6142 bool found = false;
6144 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
6145 continue;
6148 i = count;
6149 while (formats && i && !found) {
6150 found = !strcmp(formats[--i], drv->format_name);
6153 if (!found) {
6154 formats = g_renew(const char *, formats, count + 1);
6155 formats[count++] = drv->format_name;
6160 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
6161 const char *format_name = block_driver_modules[i].format_name;
6163 if (format_name) {
6164 bool found = false;
6165 int j = count;
6167 if (use_bdrv_whitelist &&
6168 !bdrv_format_is_whitelisted(format_name, read_only)) {
6169 continue;
6172 while (formats && j && !found) {
6173 found = !strcmp(formats[--j], format_name);
6176 if (!found) {
6177 formats = g_renew(const char *, formats, count + 1);
6178 formats[count++] = format_name;
6183 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6185 for (i = 0; i < count; i++) {
6186 it(opaque, formats[i]);
6189 g_free(formats);
6192 /* This function is to find a node in the bs graph */
6193 BlockDriverState *bdrv_find_node(const char *node_name)
6195 BlockDriverState *bs;
6197 assert(node_name);
6198 GLOBAL_STATE_CODE();
6200 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6201 if (!strcmp(node_name, bs->node_name)) {
6202 return bs;
6205 return NULL;
6208 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6209 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6210 Error **errp)
6212 BlockDeviceInfoList *list;
6213 BlockDriverState *bs;
6215 GLOBAL_STATE_CODE();
6216 GRAPH_RDLOCK_GUARD_MAINLOOP();
6218 list = NULL;
6219 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6220 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6221 if (!info) {
6222 qapi_free_BlockDeviceInfoList(list);
6223 return NULL;
6225 QAPI_LIST_PREPEND(list, info);
6228 return list;
6231 typedef struct XDbgBlockGraphConstructor {
6232 XDbgBlockGraph *graph;
6233 GHashTable *graph_nodes;
6234 } XDbgBlockGraphConstructor;
6236 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6238 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6240 gr->graph = g_new0(XDbgBlockGraph, 1);
6241 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6243 return gr;
6246 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6248 XDbgBlockGraph *graph = gr->graph;
6250 g_hash_table_destroy(gr->graph_nodes);
6251 g_free(gr);
6253 return graph;
6256 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6258 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6260 if (ret != 0) {
6261 return ret;
6265 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6266 * answer of g_hash_table_lookup.
6268 ret = g_hash_table_size(gr->graph_nodes) + 1;
6269 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6271 return ret;
6274 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6275 XDbgBlockGraphNodeType type, const char *name)
6277 XDbgBlockGraphNode *n;
6279 n = g_new0(XDbgBlockGraphNode, 1);
6281 n->id = xdbg_graph_node_num(gr, node);
6282 n->type = type;
6283 n->name = g_strdup(name);
6285 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6288 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6289 const BdrvChild *child)
6291 BlockPermission qapi_perm;
6292 XDbgBlockGraphEdge *edge;
6293 GLOBAL_STATE_CODE();
6295 edge = g_new0(XDbgBlockGraphEdge, 1);
6297 edge->parent = xdbg_graph_node_num(gr, parent);
6298 edge->child = xdbg_graph_node_num(gr, child->bs);
6299 edge->name = g_strdup(child->name);
6301 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6302 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6304 if (flag & child->perm) {
6305 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6307 if (flag & child->shared_perm) {
6308 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6312 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6316 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6318 BlockBackend *blk;
6319 BlockJob *job;
6320 BlockDriverState *bs;
6321 BdrvChild *child;
6322 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6324 GLOBAL_STATE_CODE();
6326 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6327 char *allocated_name = NULL;
6328 const char *name = blk_name(blk);
6330 if (!*name) {
6331 name = allocated_name = blk_get_attached_dev_id(blk);
6333 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6334 name);
6335 g_free(allocated_name);
6336 if (blk_root(blk)) {
6337 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6341 WITH_JOB_LOCK_GUARD() {
6342 for (job = block_job_next_locked(NULL); job;
6343 job = block_job_next_locked(job)) {
6344 GSList *el;
6346 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6347 job->job.id);
6348 for (el = job->nodes; el; el = el->next) {
6349 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6354 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6355 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6356 bs->node_name);
6357 QLIST_FOREACH(child, &bs->children, next) {
6358 xdbg_graph_add_edge(gr, bs, child);
6362 return xdbg_graph_finalize(gr);
6365 BlockDriverState *bdrv_lookup_bs(const char *device,
6366 const char *node_name,
6367 Error **errp)
6369 BlockBackend *blk;
6370 BlockDriverState *bs;
6372 GLOBAL_STATE_CODE();
6374 if (device) {
6375 blk = blk_by_name(device);
6377 if (blk) {
6378 bs = blk_bs(blk);
6379 if (!bs) {
6380 error_setg(errp, "Device '%s' has no medium", device);
6383 return bs;
6387 if (node_name) {
6388 bs = bdrv_find_node(node_name);
6390 if (bs) {
6391 return bs;
6395 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6396 device ? device : "",
6397 node_name ? node_name : "");
6398 return NULL;
6401 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6402 * return false. If either argument is NULL, return false. */
6403 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6406 GLOBAL_STATE_CODE();
6408 while (top && top != base) {
6409 top = bdrv_filter_or_cow_bs(top);
6412 return top != NULL;
6415 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6417 GLOBAL_STATE_CODE();
6418 if (!bs) {
6419 return QTAILQ_FIRST(&graph_bdrv_states);
6421 return QTAILQ_NEXT(bs, node_list);
6424 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6426 GLOBAL_STATE_CODE();
6427 if (!bs) {
6428 return QTAILQ_FIRST(&all_bdrv_states);
6430 return QTAILQ_NEXT(bs, bs_list);
6433 const char *bdrv_get_node_name(const BlockDriverState *bs)
6435 IO_CODE();
6436 return bs->node_name;
6439 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6441 BdrvChild *c;
6442 const char *name;
6443 IO_CODE();
6445 /* If multiple parents have a name, just pick the first one. */
6446 QLIST_FOREACH(c, &bs->parents, next_parent) {
6447 if (c->klass->get_name) {
6448 name = c->klass->get_name(c);
6449 if (name && *name) {
6450 return name;
6455 return NULL;
6458 /* TODO check what callers really want: bs->node_name or blk_name() */
6459 const char *bdrv_get_device_name(const BlockDriverState *bs)
6461 IO_CODE();
6462 return bdrv_get_parent_name(bs) ?: "";
6465 /* This can be used to identify nodes that might not have a device
6466 * name associated. Since node and device names live in the same
6467 * namespace, the result is unambiguous. The exception is if both are
6468 * absent, then this returns an empty (non-null) string. */
6469 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6471 IO_CODE();
6472 return bdrv_get_parent_name(bs) ?: bs->node_name;
6475 int bdrv_get_flags(BlockDriverState *bs)
6477 IO_CODE();
6478 return bs->open_flags;
6481 int bdrv_has_zero_init_1(BlockDriverState *bs)
6483 GLOBAL_STATE_CODE();
6484 return 1;
6487 int coroutine_mixed_fn bdrv_has_zero_init(BlockDriverState *bs)
6489 BlockDriverState *filtered;
6490 GLOBAL_STATE_CODE();
6492 if (!bs->drv) {
6493 return 0;
6496 /* If BS is a copy on write image, it is initialized to
6497 the contents of the base image, which may not be zeroes. */
6498 if (bdrv_cow_child(bs)) {
6499 return 0;
6501 if (bs->drv->bdrv_has_zero_init) {
6502 return bs->drv->bdrv_has_zero_init(bs);
6505 filtered = bdrv_filter_bs(bs);
6506 if (filtered) {
6507 return bdrv_has_zero_init(filtered);
6510 /* safe default */
6511 return 0;
6514 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6516 IO_CODE();
6517 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6518 return false;
6521 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6524 void bdrv_get_backing_filename(BlockDriverState *bs,
6525 char *filename, int filename_size)
6527 IO_CODE();
6528 pstrcpy(filename, filename_size, bs->backing_file);
6531 int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6533 int ret;
6534 BlockDriver *drv = bs->drv;
6535 IO_CODE();
6536 assert_bdrv_graph_readable();
6538 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6539 if (!drv) {
6540 return -ENOMEDIUM;
6542 if (!drv->bdrv_co_get_info) {
6543 BlockDriverState *filtered = bdrv_filter_bs(bs);
6544 if (filtered) {
6545 return bdrv_co_get_info(filtered, bdi);
6547 return -ENOTSUP;
6549 memset(bdi, 0, sizeof(*bdi));
6550 ret = drv->bdrv_co_get_info(bs, bdi);
6551 if (bdi->subcluster_size == 0) {
6553 * If the driver left this unset, subclusters are not supported.
6554 * Then it is safe to treat each cluster as having only one subcluster.
6556 bdi->subcluster_size = bdi->cluster_size;
6558 if (ret < 0) {
6559 return ret;
6562 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6563 return -EINVAL;
6566 return 0;
6569 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6570 Error **errp)
6572 BlockDriver *drv = bs->drv;
6573 IO_CODE();
6574 if (drv && drv->bdrv_get_specific_info) {
6575 return drv->bdrv_get_specific_info(bs, errp);
6577 return NULL;
6580 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6582 BlockDriver *drv = bs->drv;
6583 IO_CODE();
6584 if (!drv || !drv->bdrv_get_specific_stats) {
6585 return NULL;
6587 return drv->bdrv_get_specific_stats(bs);
6590 void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6592 IO_CODE();
6593 assert_bdrv_graph_readable();
6595 if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
6596 return;
6599 bs->drv->bdrv_co_debug_event(bs, event);
6602 static BlockDriverState * GRAPH_RDLOCK
6603 bdrv_find_debug_node(BlockDriverState *bs)
6605 GLOBAL_STATE_CODE();
6606 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6607 bs = bdrv_primary_bs(bs);
6610 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6611 assert(bs->drv->bdrv_debug_remove_breakpoint);
6612 return bs;
6615 return NULL;
6618 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6619 const char *tag)
6621 GLOBAL_STATE_CODE();
6622 GRAPH_RDLOCK_GUARD_MAINLOOP();
6624 bs = bdrv_find_debug_node(bs);
6625 if (bs) {
6626 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6629 return -ENOTSUP;
6632 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6634 GLOBAL_STATE_CODE();
6635 GRAPH_RDLOCK_GUARD_MAINLOOP();
6637 bs = bdrv_find_debug_node(bs);
6638 if (bs) {
6639 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6642 return -ENOTSUP;
6645 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6647 GLOBAL_STATE_CODE();
6648 GRAPH_RDLOCK_GUARD_MAINLOOP();
6650 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6651 bs = bdrv_primary_bs(bs);
6654 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6655 return bs->drv->bdrv_debug_resume(bs, tag);
6658 return -ENOTSUP;
6661 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6663 GLOBAL_STATE_CODE();
6664 GRAPH_RDLOCK_GUARD_MAINLOOP();
6666 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6667 bs = bdrv_primary_bs(bs);
6670 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6671 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6674 return false;
6677 /* backing_file can either be relative, or absolute, or a protocol. If it is
6678 * relative, it must be relative to the chain. So, passing in bs->filename
6679 * from a BDS as backing_file should not be done, as that may be relative to
6680 * the CWD rather than the chain. */
6681 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6682 const char *backing_file)
6684 char *filename_full = NULL;
6685 char *backing_file_full = NULL;
6686 char *filename_tmp = NULL;
6687 int is_protocol = 0;
6688 bool filenames_refreshed = false;
6689 BlockDriverState *curr_bs = NULL;
6690 BlockDriverState *retval = NULL;
6691 BlockDriverState *bs_below;
6693 GLOBAL_STATE_CODE();
6694 GRAPH_RDLOCK_GUARD_MAINLOOP();
6696 if (!bs || !bs->drv || !backing_file) {
6697 return NULL;
6700 filename_full = g_malloc(PATH_MAX);
6701 backing_file_full = g_malloc(PATH_MAX);
6703 is_protocol = path_has_protocol(backing_file);
6706 * Being largely a legacy function, skip any filters here
6707 * (because filters do not have normal filenames, so they cannot
6708 * match anyway; and allowing json:{} filenames is a bit out of
6709 * scope).
6711 for (curr_bs = bdrv_skip_filters(bs);
6712 bdrv_cow_child(curr_bs) != NULL;
6713 curr_bs = bs_below)
6715 bs_below = bdrv_backing_chain_next(curr_bs);
6717 if (bdrv_backing_overridden(curr_bs)) {
6719 * If the backing file was overridden, we can only compare
6720 * directly against the backing node's filename.
6723 if (!filenames_refreshed) {
6725 * This will automatically refresh all of the
6726 * filenames in the rest of the backing chain, so we
6727 * only need to do this once.
6729 bdrv_refresh_filename(bs_below);
6730 filenames_refreshed = true;
6733 if (strcmp(backing_file, bs_below->filename) == 0) {
6734 retval = bs_below;
6735 break;
6737 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6739 * If either of the filename paths is actually a protocol, then
6740 * compare unmodified paths; otherwise make paths relative.
6742 char *backing_file_full_ret;
6744 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6745 retval = bs_below;
6746 break;
6748 /* Also check against the full backing filename for the image */
6749 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6750 NULL);
6751 if (backing_file_full_ret) {
6752 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6753 g_free(backing_file_full_ret);
6754 if (equal) {
6755 retval = bs_below;
6756 break;
6759 } else {
6760 /* If not an absolute filename path, make it relative to the current
6761 * image's filename path */
6762 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6763 NULL);
6764 /* We are going to compare canonicalized absolute pathnames */
6765 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6766 g_free(filename_tmp);
6767 continue;
6769 g_free(filename_tmp);
6771 /* We need to make sure the backing filename we are comparing against
6772 * is relative to the current image filename (or absolute) */
6773 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6774 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6775 g_free(filename_tmp);
6776 continue;
6778 g_free(filename_tmp);
6780 if (strcmp(backing_file_full, filename_full) == 0) {
6781 retval = bs_below;
6782 break;
6787 g_free(filename_full);
6788 g_free(backing_file_full);
6789 return retval;
6792 void bdrv_init(void)
6794 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6795 use_bdrv_whitelist = 1;
6796 #endif
6797 module_call_init(MODULE_INIT_BLOCK);
6800 void bdrv_init_with_whitelist(void)
6802 use_bdrv_whitelist = 1;
6803 bdrv_init();
6806 int bdrv_activate(BlockDriverState *bs, Error **errp)
6808 BdrvChild *child, *parent;
6809 Error *local_err = NULL;
6810 int ret;
6811 BdrvDirtyBitmap *bm;
6813 GLOBAL_STATE_CODE();
6814 GRAPH_RDLOCK_GUARD_MAINLOOP();
6816 if (!bs->drv) {
6817 return -ENOMEDIUM;
6820 QLIST_FOREACH(child, &bs->children, next) {
6821 bdrv_activate(child->bs, &local_err);
6822 if (local_err) {
6823 error_propagate(errp, local_err);
6824 return -EINVAL;
6829 * Update permissions, they may differ for inactive nodes.
6831 * Note that the required permissions of inactive images are always a
6832 * subset of the permissions required after activating the image. This
6833 * allows us to just get the permissions upfront without restricting
6834 * bdrv_co_invalidate_cache().
6836 * It also means that in error cases, we don't have to try and revert to
6837 * the old permissions (which is an operation that could fail, too). We can
6838 * just keep the extended permissions for the next time that an activation
6839 * of the image is tried.
6841 if (bs->open_flags & BDRV_O_INACTIVE) {
6842 bs->open_flags &= ~BDRV_O_INACTIVE;
6843 ret = bdrv_refresh_perms(bs, NULL, errp);
6844 if (ret < 0) {
6845 bs->open_flags |= BDRV_O_INACTIVE;
6846 return ret;
6849 ret = bdrv_invalidate_cache(bs, errp);
6850 if (ret < 0) {
6851 bs->open_flags |= BDRV_O_INACTIVE;
6852 return ret;
6855 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6856 bdrv_dirty_bitmap_skip_store(bm, false);
6859 ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
6860 if (ret < 0) {
6861 bs->open_flags |= BDRV_O_INACTIVE;
6862 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6863 return ret;
6867 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6868 if (parent->klass->activate) {
6869 parent->klass->activate(parent, &local_err);
6870 if (local_err) {
6871 bs->open_flags |= BDRV_O_INACTIVE;
6872 error_propagate(errp, local_err);
6873 return -EINVAL;
6878 return 0;
6881 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6883 Error *local_err = NULL;
6884 IO_CODE();
6886 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6887 assert_bdrv_graph_readable();
6889 if (bs->drv->bdrv_co_invalidate_cache) {
6890 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6891 if (local_err) {
6892 error_propagate(errp, local_err);
6893 return -EINVAL;
6897 return 0;
6900 void bdrv_activate_all(Error **errp)
6902 BlockDriverState *bs;
6903 BdrvNextIterator it;
6905 GLOBAL_STATE_CODE();
6906 GRAPH_RDLOCK_GUARD_MAINLOOP();
6908 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6909 int ret;
6911 ret = bdrv_activate(bs, errp);
6912 if (ret < 0) {
6913 bdrv_next_cleanup(&it);
6914 return;
6919 static bool GRAPH_RDLOCK
6920 bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6922 BdrvChild *parent;
6923 GLOBAL_STATE_CODE();
6925 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6926 if (parent->klass->parent_is_bds) {
6927 BlockDriverState *parent_bs = parent->opaque;
6928 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6929 return true;
6934 return false;
6937 static int GRAPH_RDLOCK bdrv_inactivate_recurse(BlockDriverState *bs)
6939 BdrvChild *child, *parent;
6940 int ret;
6941 uint64_t cumulative_perms, cumulative_shared_perms;
6943 GLOBAL_STATE_CODE();
6945 if (!bs->drv) {
6946 return -ENOMEDIUM;
6949 /* Make sure that we don't inactivate a child before its parent.
6950 * It will be covered by recursion from the yet active parent. */
6951 if (bdrv_has_bds_parent(bs, true)) {
6952 return 0;
6955 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6957 /* Inactivate this node */
6958 if (bs->drv->bdrv_inactivate) {
6959 ret = bs->drv->bdrv_inactivate(bs);
6960 if (ret < 0) {
6961 return ret;
6965 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6966 if (parent->klass->inactivate) {
6967 ret = parent->klass->inactivate(parent);
6968 if (ret < 0) {
6969 return ret;
6974 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6975 &cumulative_shared_perms);
6976 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6977 /* Our inactive parents still need write access. Inactivation failed. */
6978 return -EPERM;
6981 bs->open_flags |= BDRV_O_INACTIVE;
6984 * Update permissions, they may differ for inactive nodes.
6985 * We only tried to loosen restrictions, so errors are not fatal, ignore
6986 * them.
6988 bdrv_refresh_perms(bs, NULL, NULL);
6990 /* Recursively inactivate children */
6991 QLIST_FOREACH(child, &bs->children, next) {
6992 ret = bdrv_inactivate_recurse(child->bs);
6993 if (ret < 0) {
6994 return ret;
6998 return 0;
7001 int bdrv_inactivate_all(void)
7003 BlockDriverState *bs = NULL;
7004 BdrvNextIterator it;
7005 int ret = 0;
7007 GLOBAL_STATE_CODE();
7008 GRAPH_RDLOCK_GUARD_MAINLOOP();
7010 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
7011 /* Nodes with BDS parents are covered by recursion from the last
7012 * parent that gets inactivated. Don't inactivate them a second
7013 * time if that has already happened. */
7014 if (bdrv_has_bds_parent(bs, false)) {
7015 continue;
7017 ret = bdrv_inactivate_recurse(bs);
7018 if (ret < 0) {
7019 bdrv_next_cleanup(&it);
7020 break;
7024 return ret;
7027 /**************************************************************/
7028 /* removable device support */
7031 * Return TRUE if the media is present
7033 bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
7035 BlockDriver *drv = bs->drv;
7036 BdrvChild *child;
7037 IO_CODE();
7038 assert_bdrv_graph_readable();
7040 if (!drv) {
7041 return false;
7043 if (drv->bdrv_co_is_inserted) {
7044 return drv->bdrv_co_is_inserted(bs);
7046 QLIST_FOREACH(child, &bs->children, next) {
7047 if (!bdrv_co_is_inserted(child->bs)) {
7048 return false;
7051 return true;
7055 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
7057 void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
7059 BlockDriver *drv = bs->drv;
7060 IO_CODE();
7061 assert_bdrv_graph_readable();
7063 if (drv && drv->bdrv_co_eject) {
7064 drv->bdrv_co_eject(bs, eject_flag);
7069 * Lock or unlock the media (if it is locked, the user won't be able
7070 * to eject it manually).
7072 void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
7074 BlockDriver *drv = bs->drv;
7075 IO_CODE();
7076 assert_bdrv_graph_readable();
7077 trace_bdrv_lock_medium(bs, locked);
7079 if (drv && drv->bdrv_co_lock_medium) {
7080 drv->bdrv_co_lock_medium(bs, locked);
7084 /* Get a reference to bs */
7085 void bdrv_ref(BlockDriverState *bs)
7087 GLOBAL_STATE_CODE();
7088 bs->refcnt++;
7091 /* Release a previously grabbed reference to bs.
7092 * If after releasing, reference count is zero, the BlockDriverState is
7093 * deleted. */
7094 void bdrv_unref(BlockDriverState *bs)
7096 GLOBAL_STATE_CODE();
7097 if (!bs) {
7098 return;
7100 assert(bs->refcnt > 0);
7101 if (--bs->refcnt == 0) {
7102 bdrv_delete(bs);
7106 static void bdrv_schedule_unref_bh(void *opaque)
7108 BlockDriverState *bs = opaque;
7110 bdrv_unref(bs);
7114 * Release a BlockDriverState reference while holding the graph write lock.
7116 * Calling bdrv_unref() directly is forbidden while holding the graph lock
7117 * because bdrv_close() both involves polling and taking the graph lock
7118 * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7119 * possibly closing @bs until the graph lock is released.
7121 void bdrv_schedule_unref(BlockDriverState *bs)
7123 if (!bs) {
7124 return;
7126 aio_bh_schedule_oneshot(qemu_get_aio_context(), bdrv_schedule_unref_bh, bs);
7129 struct BdrvOpBlocker {
7130 Error *reason;
7131 QLIST_ENTRY(BdrvOpBlocker) list;
7134 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
7136 BdrvOpBlocker *blocker;
7137 GLOBAL_STATE_CODE();
7139 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7140 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
7141 blocker = QLIST_FIRST(&bs->op_blockers[op]);
7142 error_propagate_prepend(errp, error_copy(blocker->reason),
7143 "Node '%s' is busy: ",
7144 bdrv_get_device_or_node_name(bs));
7145 return true;
7147 return false;
7150 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
7152 BdrvOpBlocker *blocker;
7153 GLOBAL_STATE_CODE();
7154 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7156 blocker = g_new0(BdrvOpBlocker, 1);
7157 blocker->reason = reason;
7158 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
7161 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
7163 BdrvOpBlocker *blocker, *next;
7164 GLOBAL_STATE_CODE();
7165 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7166 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
7167 if (blocker->reason == reason) {
7168 QLIST_REMOVE(blocker, list);
7169 g_free(blocker);
7174 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
7176 int i;
7177 GLOBAL_STATE_CODE();
7178 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7179 bdrv_op_block(bs, i, reason);
7183 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
7185 int i;
7186 GLOBAL_STATE_CODE();
7187 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7188 bdrv_op_unblock(bs, i, reason);
7192 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
7194 int i;
7195 GLOBAL_STATE_CODE();
7196 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7197 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
7198 return false;
7201 return true;
7205 * Must not be called while holding the lock of an AioContext other than the
7206 * current one.
7208 void bdrv_img_create(const char *filename, const char *fmt,
7209 const char *base_filename, const char *base_fmt,
7210 char *options, uint64_t img_size, int flags, bool quiet,
7211 Error **errp)
7213 QemuOptsList *create_opts = NULL;
7214 QemuOpts *opts = NULL;
7215 const char *backing_fmt, *backing_file;
7216 int64_t size;
7217 BlockDriver *drv, *proto_drv;
7218 Error *local_err = NULL;
7219 int ret = 0;
7221 GLOBAL_STATE_CODE();
7223 /* Find driver and parse its options */
7224 drv = bdrv_find_format(fmt);
7225 if (!drv) {
7226 error_setg(errp, "Unknown file format '%s'", fmt);
7227 return;
7230 proto_drv = bdrv_find_protocol(filename, true, errp);
7231 if (!proto_drv) {
7232 return;
7235 if (!drv->create_opts) {
7236 error_setg(errp, "Format driver '%s' does not support image creation",
7237 drv->format_name);
7238 return;
7241 if (!proto_drv->create_opts) {
7242 error_setg(errp, "Protocol driver '%s' does not support image creation",
7243 proto_drv->format_name);
7244 return;
7247 /* Create parameter list */
7248 create_opts = qemu_opts_append(create_opts, drv->create_opts);
7249 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7251 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7253 /* Parse -o options */
7254 if (options) {
7255 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7256 goto out;
7260 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7261 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7262 } else if (img_size != UINT64_C(-1)) {
7263 error_setg(errp, "The image size must be specified only once");
7264 goto out;
7267 if (base_filename) {
7268 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
7269 NULL)) {
7270 error_setg(errp, "Backing file not supported for file format '%s'",
7271 fmt);
7272 goto out;
7276 if (base_fmt) {
7277 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
7278 error_setg(errp, "Backing file format not supported for file "
7279 "format '%s'", fmt);
7280 goto out;
7284 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7285 if (backing_file) {
7286 if (!strcmp(filename, backing_file)) {
7287 error_setg(errp, "Error: Trying to create an image with the "
7288 "same filename as the backing file");
7289 goto out;
7291 if (backing_file[0] == '\0') {
7292 error_setg(errp, "Expected backing file name, got empty string");
7293 goto out;
7297 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7299 /* The size for the image must always be specified, unless we have a backing
7300 * file and we have not been forbidden from opening it. */
7301 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
7302 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7303 BlockDriverState *bs;
7304 char *full_backing;
7305 int back_flags;
7306 QDict *backing_options = NULL;
7308 full_backing =
7309 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7310 &local_err);
7311 if (local_err) {
7312 goto out;
7314 assert(full_backing);
7317 * No need to do I/O here, which allows us to open encrypted
7318 * backing images without needing the secret
7320 back_flags = flags;
7321 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7322 back_flags |= BDRV_O_NO_IO;
7324 backing_options = qdict_new();
7325 if (backing_fmt) {
7326 qdict_put_str(backing_options, "driver", backing_fmt);
7328 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7330 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7331 &local_err);
7332 g_free(full_backing);
7333 if (!bs) {
7334 error_append_hint(&local_err, "Could not open backing image.\n");
7335 goto out;
7336 } else {
7337 if (!backing_fmt) {
7338 error_setg(&local_err,
7339 "Backing file specified without backing format");
7340 error_append_hint(&local_err, "Detected format of %s.\n",
7341 bs->drv->format_name);
7342 goto out;
7344 if (size == -1) {
7345 /* Opened BS, have no size */
7346 size = bdrv_getlength(bs);
7347 if (size < 0) {
7348 error_setg_errno(errp, -size, "Could not get size of '%s'",
7349 backing_file);
7350 bdrv_unref(bs);
7351 goto out;
7353 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7355 bdrv_unref(bs);
7357 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7358 } else if (backing_file && !backing_fmt) {
7359 error_setg(&local_err,
7360 "Backing file specified without backing format");
7361 goto out;
7364 /* Parameter 'size' is not needed for detached LUKS header */
7365 if (size == -1 &&
7366 !(!strcmp(fmt, "luks") &&
7367 qemu_opt_get_bool(opts, "detached-header", false))) {
7368 error_setg(errp, "Image creation needs a size parameter");
7369 goto out;
7372 if (!quiet) {
7373 printf("Formatting '%s', fmt=%s ", filename, fmt);
7374 qemu_opts_print(opts, " ");
7375 puts("");
7376 fflush(stdout);
7379 ret = bdrv_create(drv, filename, opts, &local_err);
7381 if (ret == -EFBIG) {
7382 /* This is generally a better message than whatever the driver would
7383 * deliver (especially because of the cluster_size_hint), since that
7384 * is most probably not much different from "image too large". */
7385 const char *cluster_size_hint = "";
7386 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7387 cluster_size_hint = " (try using a larger cluster size)";
7389 error_setg(errp, "The image size is too large for file format '%s'"
7390 "%s", fmt, cluster_size_hint);
7391 error_free(local_err);
7392 local_err = NULL;
7395 out:
7396 qemu_opts_del(opts);
7397 qemu_opts_free(create_opts);
7398 error_propagate(errp, local_err);
7401 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7403 IO_CODE();
7404 return bs ? bs->aio_context : qemu_get_aio_context();
7407 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7409 Coroutine *self = qemu_coroutine_self();
7410 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7411 AioContext *new_ctx;
7412 IO_CODE();
7415 * Increase bs->in_flight to ensure that this operation is completed before
7416 * moving the node to a different AioContext. Read new_ctx only afterwards.
7418 bdrv_inc_in_flight(bs);
7420 new_ctx = bdrv_get_aio_context(bs);
7421 aio_co_reschedule_self(new_ctx);
7422 return old_ctx;
7425 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7427 IO_CODE();
7428 aio_co_reschedule_self(old_ctx);
7429 bdrv_dec_in_flight(bs);
7432 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7434 GLOBAL_STATE_CODE();
7435 QLIST_REMOVE(ban, list);
7436 g_free(ban);
7439 static void bdrv_detach_aio_context(BlockDriverState *bs)
7441 BdrvAioNotifier *baf, *baf_tmp;
7443 assert(!bs->walking_aio_notifiers);
7444 GLOBAL_STATE_CODE();
7445 bs->walking_aio_notifiers = true;
7446 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7447 if (baf->deleted) {
7448 bdrv_do_remove_aio_context_notifier(baf);
7449 } else {
7450 baf->detach_aio_context(baf->opaque);
7453 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7454 * remove remaining aio notifiers if we aren't called again.
7456 bs->walking_aio_notifiers = false;
7458 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7459 bs->drv->bdrv_detach_aio_context(bs);
7462 bs->aio_context = NULL;
7465 static void bdrv_attach_aio_context(BlockDriverState *bs,
7466 AioContext *new_context)
7468 BdrvAioNotifier *ban, *ban_tmp;
7469 GLOBAL_STATE_CODE();
7471 bs->aio_context = new_context;
7473 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7474 bs->drv->bdrv_attach_aio_context(bs, new_context);
7477 assert(!bs->walking_aio_notifiers);
7478 bs->walking_aio_notifiers = true;
7479 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7480 if (ban->deleted) {
7481 bdrv_do_remove_aio_context_notifier(ban);
7482 } else {
7483 ban->attached_aio_context(new_context, ban->opaque);
7486 bs->walking_aio_notifiers = false;
7489 typedef struct BdrvStateSetAioContext {
7490 AioContext *new_ctx;
7491 BlockDriverState *bs;
7492 } BdrvStateSetAioContext;
7494 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7495 GHashTable *visited,
7496 Transaction *tran,
7497 Error **errp)
7499 GLOBAL_STATE_CODE();
7500 if (g_hash_table_contains(visited, c)) {
7501 return true;
7503 g_hash_table_add(visited, c);
7506 * A BdrvChildClass that doesn't handle AioContext changes cannot
7507 * tolerate any AioContext changes
7509 if (!c->klass->change_aio_ctx) {
7510 char *user = bdrv_child_user_desc(c);
7511 error_setg(errp, "Changing iothreads is not supported by %s", user);
7512 g_free(user);
7513 return false;
7515 if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7516 assert(!errp || *errp);
7517 return false;
7519 return true;
7522 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7523 GHashTable *visited, Transaction *tran,
7524 Error **errp)
7526 GLOBAL_STATE_CODE();
7527 if (g_hash_table_contains(visited, c)) {
7528 return true;
7530 g_hash_table_add(visited, c);
7531 return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7534 static void bdrv_set_aio_context_clean(void *opaque)
7536 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7537 BlockDriverState *bs = (BlockDriverState *) state->bs;
7539 /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7540 bdrv_drained_end(bs);
7542 g_free(state);
7545 static void bdrv_set_aio_context_commit(void *opaque)
7547 BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7548 BlockDriverState *bs = (BlockDriverState *) state->bs;
7549 AioContext *new_context = state->new_ctx;
7551 bdrv_detach_aio_context(bs);
7552 bdrv_attach_aio_context(bs, new_context);
7555 static TransactionActionDrv set_aio_context = {
7556 .commit = bdrv_set_aio_context_commit,
7557 .clean = bdrv_set_aio_context_clean,
7561 * Changes the AioContext used for fd handlers, timers, and BHs by this
7562 * BlockDriverState and all its children and parents.
7564 * Must be called from the main AioContext.
7566 * @visited will accumulate all visited BdrvChild objects. The caller is
7567 * responsible for freeing the list afterwards.
7569 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7570 GHashTable *visited, Transaction *tran,
7571 Error **errp)
7573 BdrvChild *c;
7574 BdrvStateSetAioContext *state;
7576 GLOBAL_STATE_CODE();
7578 if (bdrv_get_aio_context(bs) == ctx) {
7579 return true;
7582 bdrv_graph_rdlock_main_loop();
7583 QLIST_FOREACH(c, &bs->parents, next_parent) {
7584 if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7585 bdrv_graph_rdunlock_main_loop();
7586 return false;
7590 QLIST_FOREACH(c, &bs->children, next) {
7591 if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7592 bdrv_graph_rdunlock_main_loop();
7593 return false;
7596 bdrv_graph_rdunlock_main_loop();
7598 state = g_new(BdrvStateSetAioContext, 1);
7599 *state = (BdrvStateSetAioContext) {
7600 .new_ctx = ctx,
7601 .bs = bs,
7604 /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7605 bdrv_drained_begin(bs);
7607 tran_add(tran, &set_aio_context, state);
7609 return true;
7613 * Change bs's and recursively all of its parents' and children's AioContext
7614 * to the given new context, returning an error if that isn't possible.
7616 * If ignore_child is not NULL, that child (and its subgraph) will not
7617 * be touched.
7619 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7620 BdrvChild *ignore_child, Error **errp)
7622 Transaction *tran;
7623 GHashTable *visited;
7624 int ret;
7625 GLOBAL_STATE_CODE();
7628 * Recursion phase: go through all nodes of the graph.
7629 * Take care of checking that all nodes support changing AioContext
7630 * and drain them, building a linear list of callbacks to run if everything
7631 * is successful (the transaction itself).
7633 tran = tran_new();
7634 visited = g_hash_table_new(NULL, NULL);
7635 if (ignore_child) {
7636 g_hash_table_add(visited, ignore_child);
7638 ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7639 g_hash_table_destroy(visited);
7642 * Linear phase: go through all callbacks collected in the transaction.
7643 * Run all callbacks collected in the recursion to switch every node's
7644 * AioContext (transaction commit), or undo all changes done in the
7645 * recursion (transaction abort).
7648 if (!ret) {
7649 /* Just run clean() callbacks. No AioContext changed. */
7650 tran_abort(tran);
7651 return -EPERM;
7654 tran_commit(tran);
7655 return 0;
7658 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7659 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7660 void (*detach_aio_context)(void *opaque), void *opaque)
7662 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7663 *ban = (BdrvAioNotifier){
7664 .attached_aio_context = attached_aio_context,
7665 .detach_aio_context = detach_aio_context,
7666 .opaque = opaque
7668 GLOBAL_STATE_CODE();
7670 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7673 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7674 void (*attached_aio_context)(AioContext *,
7675 void *),
7676 void (*detach_aio_context)(void *),
7677 void *opaque)
7679 BdrvAioNotifier *ban, *ban_next;
7680 GLOBAL_STATE_CODE();
7682 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7683 if (ban->attached_aio_context == attached_aio_context &&
7684 ban->detach_aio_context == detach_aio_context &&
7685 ban->opaque == opaque &&
7686 ban->deleted == false)
7688 if (bs->walking_aio_notifiers) {
7689 ban->deleted = true;
7690 } else {
7691 bdrv_do_remove_aio_context_notifier(ban);
7693 return;
7697 abort();
7700 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7701 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7702 bool force,
7703 Error **errp)
7705 GLOBAL_STATE_CODE();
7706 if (!bs->drv) {
7707 error_setg(errp, "Node is ejected");
7708 return -ENOMEDIUM;
7710 if (!bs->drv->bdrv_amend_options) {
7711 error_setg(errp, "Block driver '%s' does not support option amendment",
7712 bs->drv->format_name);
7713 return -ENOTSUP;
7715 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7716 cb_opaque, force, errp);
7720 * This function checks whether the given @to_replace is allowed to be
7721 * replaced by a node that always shows the same data as @bs. This is
7722 * used for example to verify whether the mirror job can replace
7723 * @to_replace by the target mirrored from @bs.
7724 * To be replaceable, @bs and @to_replace may either be guaranteed to
7725 * always show the same data (because they are only connected through
7726 * filters), or some driver may allow replacing one of its children
7727 * because it can guarantee that this child's data is not visible at
7728 * all (for example, for dissenting quorum children that have no other
7729 * parents).
7731 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7732 BlockDriverState *to_replace)
7734 BlockDriverState *filtered;
7736 GLOBAL_STATE_CODE();
7738 if (!bs || !bs->drv) {
7739 return false;
7742 if (bs == to_replace) {
7743 return true;
7746 /* See what the driver can do */
7747 if (bs->drv->bdrv_recurse_can_replace) {
7748 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7751 /* For filters without an own implementation, we can recurse on our own */
7752 filtered = bdrv_filter_bs(bs);
7753 if (filtered) {
7754 return bdrv_recurse_can_replace(filtered, to_replace);
7757 /* Safe default */
7758 return false;
7762 * Check whether the given @node_name can be replaced by a node that
7763 * has the same data as @parent_bs. If so, return @node_name's BDS;
7764 * NULL otherwise.
7766 * @node_name must be a (recursive) *child of @parent_bs (or this
7767 * function will return NULL).
7769 * The result (whether the node can be replaced or not) is only valid
7770 * for as long as no graph or permission changes occur.
7772 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7773 const char *node_name, Error **errp)
7775 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7777 GLOBAL_STATE_CODE();
7779 if (!to_replace_bs) {
7780 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7781 return NULL;
7784 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7785 return NULL;
7788 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7789 * most non filter in order to prevent data corruption.
7790 * Another benefit is that this tests exclude backing files which are
7791 * blocked by the backing blockers.
7793 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7794 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7795 "because it cannot be guaranteed that doing so would not "
7796 "lead to an abrupt change of visible data",
7797 node_name, parent_bs->node_name);
7798 return NULL;
7801 return to_replace_bs;
7805 * Iterates through the list of runtime option keys that are said to
7806 * be "strong" for a BDS. An option is called "strong" if it changes
7807 * a BDS's data. For example, the null block driver's "size" and
7808 * "read-zeroes" options are strong, but its "latency-ns" option is
7809 * not.
7811 * If a key returned by this function ends with a dot, all options
7812 * starting with that prefix are strong.
7814 static const char *const *strong_options(BlockDriverState *bs,
7815 const char *const *curopt)
7817 static const char *const global_options[] = {
7818 "driver", "filename", NULL
7821 if (!curopt) {
7822 return &global_options[0];
7825 curopt++;
7826 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7827 curopt = bs->drv->strong_runtime_opts;
7830 return (curopt && *curopt) ? curopt : NULL;
7834 * Copies all strong runtime options from bs->options to the given
7835 * QDict. The set of strong option keys is determined by invoking
7836 * strong_options().
7838 * Returns true iff any strong option was present in bs->options (and
7839 * thus copied to the target QDict) with the exception of "filename"
7840 * and "driver". The caller is expected to use this value to decide
7841 * whether the existence of strong options prevents the generation of
7842 * a plain filename.
7844 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7846 bool found_any = false;
7847 const char *const *option_name = NULL;
7849 if (!bs->drv) {
7850 return false;
7853 while ((option_name = strong_options(bs, option_name))) {
7854 bool option_given = false;
7856 assert(strlen(*option_name) > 0);
7857 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7858 QObject *entry = qdict_get(bs->options, *option_name);
7859 if (!entry) {
7860 continue;
7863 qdict_put_obj(d, *option_name, qobject_ref(entry));
7864 option_given = true;
7865 } else {
7866 const QDictEntry *entry;
7867 for (entry = qdict_first(bs->options); entry;
7868 entry = qdict_next(bs->options, entry))
7870 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7871 qdict_put_obj(d, qdict_entry_key(entry),
7872 qobject_ref(qdict_entry_value(entry)));
7873 option_given = true;
7878 /* While "driver" and "filename" need to be included in a JSON filename,
7879 * their existence does not prohibit generation of a plain filename. */
7880 if (!found_any && option_given &&
7881 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7883 found_any = true;
7887 if (!qdict_haskey(d, "driver")) {
7888 /* Drivers created with bdrv_new_open_driver() may not have a
7889 * @driver option. Add it here. */
7890 qdict_put_str(d, "driver", bs->drv->format_name);
7893 return found_any;
7896 /* Note: This function may return false positives; it may return true
7897 * even if opening the backing file specified by bs's image header
7898 * would result in exactly bs->backing. */
7899 static bool GRAPH_RDLOCK bdrv_backing_overridden(BlockDriverState *bs)
7901 GLOBAL_STATE_CODE();
7902 if (bs->backing) {
7903 return strcmp(bs->auto_backing_file,
7904 bs->backing->bs->filename);
7905 } else {
7906 /* No backing BDS, so if the image header reports any backing
7907 * file, it must have been suppressed */
7908 return bs->auto_backing_file[0] != '\0';
7912 /* Updates the following BDS fields:
7913 * - exact_filename: A filename which may be used for opening a block device
7914 * which (mostly) equals the given BDS (even without any
7915 * other options; so reading and writing must return the same
7916 * results, but caching etc. may be different)
7917 * - full_open_options: Options which, when given when opening a block device
7918 * (without a filename), result in a BDS (mostly)
7919 * equalling the given one
7920 * - filename: If exact_filename is set, it is copied here. Otherwise,
7921 * full_open_options is converted to a JSON object, prefixed with
7922 * "json:" (for use through the JSON pseudo protocol) and put here.
7924 void bdrv_refresh_filename(BlockDriverState *bs)
7926 BlockDriver *drv = bs->drv;
7927 BdrvChild *child;
7928 BlockDriverState *primary_child_bs;
7929 QDict *opts;
7930 bool backing_overridden;
7931 bool generate_json_filename; /* Whether our default implementation should
7932 fill exact_filename (false) or not (true) */
7934 GLOBAL_STATE_CODE();
7936 if (!drv) {
7937 return;
7940 /* This BDS's file name may depend on any of its children's file names, so
7941 * refresh those first */
7942 QLIST_FOREACH(child, &bs->children, next) {
7943 bdrv_refresh_filename(child->bs);
7946 if (bs->implicit) {
7947 /* For implicit nodes, just copy everything from the single child */
7948 child = QLIST_FIRST(&bs->children);
7949 assert(QLIST_NEXT(child, next) == NULL);
7951 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7952 child->bs->exact_filename);
7953 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7955 qobject_unref(bs->full_open_options);
7956 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7958 return;
7961 backing_overridden = bdrv_backing_overridden(bs);
7963 if (bs->open_flags & BDRV_O_NO_IO) {
7964 /* Without I/O, the backing file does not change anything.
7965 * Therefore, in such a case (primarily qemu-img), we can
7966 * pretend the backing file has not been overridden even if
7967 * it technically has been. */
7968 backing_overridden = false;
7971 /* Gather the options QDict */
7972 opts = qdict_new();
7973 generate_json_filename = append_strong_runtime_options(opts, bs);
7974 generate_json_filename |= backing_overridden;
7976 if (drv->bdrv_gather_child_options) {
7977 /* Some block drivers may not want to present all of their children's
7978 * options, or name them differently from BdrvChild.name */
7979 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7980 } else {
7981 QLIST_FOREACH(child, &bs->children, next) {
7982 if (child == bs->backing && !backing_overridden) {
7983 /* We can skip the backing BDS if it has not been overridden */
7984 continue;
7987 qdict_put(opts, child->name,
7988 qobject_ref(child->bs->full_open_options));
7991 if (backing_overridden && !bs->backing) {
7992 /* Force no backing file */
7993 qdict_put_null(opts, "backing");
7997 qobject_unref(bs->full_open_options);
7998 bs->full_open_options = opts;
8000 primary_child_bs = bdrv_primary_bs(bs);
8002 if (drv->bdrv_refresh_filename) {
8003 /* Obsolete information is of no use here, so drop the old file name
8004 * information before refreshing it */
8005 bs->exact_filename[0] = '\0';
8007 drv->bdrv_refresh_filename(bs);
8008 } else if (primary_child_bs) {
8010 * Try to reconstruct valid information from the underlying
8011 * file -- this only works for format nodes (filter nodes
8012 * cannot be probed and as such must be selected by the user
8013 * either through an options dict, or through a special
8014 * filename which the filter driver must construct in its
8015 * .bdrv_refresh_filename() implementation).
8018 bs->exact_filename[0] = '\0';
8021 * We can use the underlying file's filename if:
8022 * - it has a filename,
8023 * - the current BDS is not a filter,
8024 * - the file is a protocol BDS, and
8025 * - opening that file (as this BDS's format) will automatically create
8026 * the BDS tree we have right now, that is:
8027 * - the user did not significantly change this BDS's behavior with
8028 * some explicit (strong) options
8029 * - no non-file child of this BDS has been overridden by the user
8030 * Both of these conditions are represented by generate_json_filename.
8032 if (primary_child_bs->exact_filename[0] &&
8033 primary_child_bs->drv->bdrv_file_open &&
8034 !drv->is_filter && !generate_json_filename)
8036 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8040 if (bs->exact_filename[0]) {
8041 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
8042 } else {
8043 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
8044 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8045 json->str) >= sizeof(bs->filename)) {
8046 /* Give user a hint if we truncated things. */
8047 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
8049 g_string_free(json, true);
8053 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
8055 BlockDriver *drv = bs->drv;
8056 BlockDriverState *child_bs;
8058 GLOBAL_STATE_CODE();
8060 if (!drv) {
8061 error_setg(errp, "Node '%s' is ejected", bs->node_name);
8062 return NULL;
8065 if (drv->bdrv_dirname) {
8066 return drv->bdrv_dirname(bs, errp);
8069 child_bs = bdrv_primary_bs(bs);
8070 if (child_bs) {
8071 return bdrv_dirname(child_bs, errp);
8074 bdrv_refresh_filename(bs);
8075 if (bs->exact_filename[0] != '\0') {
8076 return path_combine(bs->exact_filename, "");
8079 error_setg(errp, "Cannot generate a base directory for %s nodes",
8080 drv->format_name);
8081 return NULL;
8085 * Hot add/remove a BDS's child. So the user can take a child offline when
8086 * it is broken and take a new child online
8088 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8089 Error **errp)
8091 GLOBAL_STATE_CODE();
8092 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8093 error_setg(errp, "The node %s does not support adding a child",
8094 bdrv_get_device_or_node_name(parent_bs));
8095 return;
8099 * Non-zoned block drivers do not follow zoned storage constraints
8100 * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8101 * drivers in a graph.
8103 if (!parent_bs->drv->supports_zoned_children &&
8104 child_bs->bl.zoned == BLK_Z_HM) {
8106 * The host-aware model allows zoned storage constraints and random
8107 * write. Allow mixing host-aware and non-zoned drivers. Using
8108 * host-aware device as a regular device.
8110 error_setg(errp, "Cannot add a %s child to a %s parent",
8111 child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
8112 parent_bs->drv->supports_zoned_children ?
8113 "support zoned children" : "not support zoned children");
8114 return;
8117 if (!QLIST_EMPTY(&child_bs->parents)) {
8118 error_setg(errp, "The node %s already has a parent",
8119 child_bs->node_name);
8120 return;
8123 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8126 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8128 BdrvChild *tmp;
8130 GLOBAL_STATE_CODE();
8131 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8132 error_setg(errp, "The node %s does not support removing a child",
8133 bdrv_get_device_or_node_name(parent_bs));
8134 return;
8137 QLIST_FOREACH(tmp, &parent_bs->children, next) {
8138 if (tmp == child) {
8139 break;
8143 if (!tmp) {
8144 error_setg(errp, "The node %s does not have a child named %s",
8145 bdrv_get_device_or_node_name(parent_bs),
8146 bdrv_get_device_or_node_name(child->bs));
8147 return;
8150 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8153 int bdrv_make_empty(BdrvChild *c, Error **errp)
8155 BlockDriver *drv = c->bs->drv;
8156 int ret;
8158 GLOBAL_STATE_CODE();
8159 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
8161 if (!drv->bdrv_make_empty) {
8162 error_setg(errp, "%s does not support emptying nodes",
8163 drv->format_name);
8164 return -ENOTSUP;
8167 ret = drv->bdrv_make_empty(c->bs);
8168 if (ret < 0) {
8169 error_setg_errno(errp, -ret, "Failed to empty %s",
8170 c->bs->filename);
8171 return ret;
8174 return 0;
8178 * Return the child that @bs acts as an overlay for, and from which data may be
8179 * copied in COW or COR operations. Usually this is the backing file.
8181 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8183 IO_CODE();
8185 if (!bs || !bs->drv) {
8186 return NULL;
8189 if (bs->drv->is_filter) {
8190 return NULL;
8193 if (!bs->backing) {
8194 return NULL;
8197 assert(bs->backing->role & BDRV_CHILD_COW);
8198 return bs->backing;
8202 * If @bs acts as a filter for exactly one of its children, return
8203 * that child.
8205 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8207 BdrvChild *c;
8208 IO_CODE();
8210 if (!bs || !bs->drv) {
8211 return NULL;
8214 if (!bs->drv->is_filter) {
8215 return NULL;
8218 /* Only one of @backing or @file may be used */
8219 assert(!(bs->backing && bs->file));
8221 c = bs->backing ?: bs->file;
8222 if (!c) {
8223 return NULL;
8226 assert(c->role & BDRV_CHILD_FILTERED);
8227 return c;
8231 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8232 * whichever is non-NULL.
8234 * Return NULL if both are NULL.
8236 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8238 BdrvChild *cow_child = bdrv_cow_child(bs);
8239 BdrvChild *filter_child = bdrv_filter_child(bs);
8240 IO_CODE();
8242 /* Filter nodes cannot have COW backing files */
8243 assert(!(cow_child && filter_child));
8245 return cow_child ?: filter_child;
8249 * Return the primary child of this node: For filters, that is the
8250 * filtered child. For other nodes, that is usually the child storing
8251 * metadata.
8252 * (A generally more helpful description is that this is (usually) the
8253 * child that has the same filename as @bs.)
8255 * Drivers do not necessarily have a primary child; for example quorum
8256 * does not.
8258 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8260 BdrvChild *c, *found = NULL;
8261 IO_CODE();
8263 QLIST_FOREACH(c, &bs->children, next) {
8264 if (c->role & BDRV_CHILD_PRIMARY) {
8265 assert(!found);
8266 found = c;
8270 return found;
8273 static BlockDriverState * GRAPH_RDLOCK
8274 bdrv_do_skip_filters(BlockDriverState *bs, bool stop_on_explicit_filter)
8276 BdrvChild *c;
8278 if (!bs) {
8279 return NULL;
8282 while (!(stop_on_explicit_filter && !bs->implicit)) {
8283 c = bdrv_filter_child(bs);
8284 if (!c) {
8286 * A filter that is embedded in a working block graph must
8287 * have a child. Assert this here so this function does
8288 * not return a filter node that is not expected by the
8289 * caller.
8291 assert(!bs->drv || !bs->drv->is_filter);
8292 break;
8294 bs = c->bs;
8297 * Note that this treats nodes with bs->drv == NULL as not being
8298 * filters (bs->drv == NULL should be replaced by something else
8299 * anyway).
8300 * The advantage of this behavior is that this function will thus
8301 * always return a non-NULL value (given a non-NULL @bs).
8304 return bs;
8308 * Return the first BDS that has not been added implicitly or that
8309 * does not have a filtered child down the chain starting from @bs
8310 * (including @bs itself).
8312 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8314 GLOBAL_STATE_CODE();
8315 return bdrv_do_skip_filters(bs, true);
8319 * Return the first BDS that does not have a filtered child down the
8320 * chain starting from @bs (including @bs itself).
8322 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8324 IO_CODE();
8325 return bdrv_do_skip_filters(bs, false);
8329 * For a backing chain, return the first non-filter backing image of
8330 * the first non-filter image.
8332 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8334 IO_CODE();
8335 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8339 * Check whether [offset, offset + bytes) overlaps with the cached
8340 * block-status data region.
8342 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8343 * which is what bdrv_bsc_is_data()'s interface needs.
8344 * Otherwise, *pnum is not touched.
8346 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8347 int64_t offset, int64_t bytes,
8348 int64_t *pnum)
8350 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8351 bool overlaps;
8353 overlaps =
8354 qatomic_read(&bsc->valid) &&
8355 ranges_overlap(offset, bytes, bsc->data_start,
8356 bsc->data_end - bsc->data_start);
8358 if (overlaps && pnum) {
8359 *pnum = bsc->data_end - offset;
8362 return overlaps;
8366 * See block_int.h for this function's documentation.
8368 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8370 IO_CODE();
8371 RCU_READ_LOCK_GUARD();
8372 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8376 * See block_int.h for this function's documentation.
8378 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8379 int64_t offset, int64_t bytes)
8381 IO_CODE();
8382 RCU_READ_LOCK_GUARD();
8384 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8385 qatomic_set(&bs->block_status_cache->valid, false);
8390 * See block_int.h for this function's documentation.
8392 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8394 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8395 BdrvBlockStatusCache *old_bsc;
8396 IO_CODE();
8398 *new_bsc = (BdrvBlockStatusCache) {
8399 .valid = true,
8400 .data_start = offset,
8401 .data_end = offset + bytes,
8404 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8406 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8407 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8408 if (old_bsc) {
8409 g_free_rcu(old_bsc, rcu);