assertions for blockdev.h global state API
[qemu.git] / block.c
blobd3b97c356937ae149b4139a620117eba0dd199bb
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
5 * Copyright (c) 2020 Virtuozzo International GmbH.
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
51 #include "qemu/id.h"
52 #include "qemu/range.h"
53 #include "qemu/rcu.h"
54 #include "block/coroutines.h"
56 #ifdef CONFIG_BSD
57 #include <sys/ioctl.h>
58 #include <sys/queue.h>
59 #if defined(HAVE_SYS_DISK_H)
60 #include <sys/disk.h>
61 #endif
62 #endif
64 #ifdef _WIN32
65 #include <windows.h>
66 #endif
68 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
70 /* Protected by BQL */
71 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
74 /* Protected by BQL */
75 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
78 /* Protected by BQL */
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80 QLIST_HEAD_INITIALIZER(bdrv_drivers);
82 static BlockDriverState *bdrv_open_inherit(const char *filename,
83 const char *reference,
84 QDict *options, int flags,
85 BlockDriverState *parent,
86 const BdrvChildClass *child_class,
87 BdrvChildRole child_role,
88 Error **errp);
90 static bool bdrv_recurse_has_child(BlockDriverState *bs,
91 BlockDriverState *child);
93 static void bdrv_child_free(BdrvChild *child);
94 static void bdrv_replace_child_noperm(BdrvChild **child,
95 BlockDriverState *new_bs,
96 bool free_empty_child);
97 static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
98 BdrvChild *child,
99 Transaction *tran);
100 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
101 Transaction *tran);
103 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
104 BlockReopenQueue *queue,
105 Transaction *change_child_tran, Error **errp);
106 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
107 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
109 static bool bdrv_backing_overridden(BlockDriverState *bs);
111 /* If non-zero, use only whitelisted block drivers */
112 static int use_bdrv_whitelist;
114 #ifdef _WIN32
115 static int is_windows_drive_prefix(const char *filename)
117 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
118 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
119 filename[1] == ':');
122 int is_windows_drive(const char *filename)
124 if (is_windows_drive_prefix(filename) &&
125 filename[2] == '\0')
126 return 1;
127 if (strstart(filename, "\\\\.\\", NULL) ||
128 strstart(filename, "//./", NULL))
129 return 1;
130 return 0;
132 #endif
134 size_t bdrv_opt_mem_align(BlockDriverState *bs)
136 if (!bs || !bs->drv) {
137 /* page size or 4k (hdd sector size) should be on the safe side */
138 return MAX(4096, qemu_real_host_page_size);
140 IO_CODE();
142 return bs->bl.opt_mem_alignment;
145 size_t bdrv_min_mem_align(BlockDriverState *bs)
147 if (!bs || !bs->drv) {
148 /* page size or 4k (hdd sector size) should be on the safe side */
149 return MAX(4096, qemu_real_host_page_size);
151 IO_CODE();
153 return bs->bl.min_mem_alignment;
156 /* check if the path starts with "<protocol>:" */
157 int path_has_protocol(const char *path)
159 const char *p;
161 #ifdef _WIN32
162 if (is_windows_drive(path) ||
163 is_windows_drive_prefix(path)) {
164 return 0;
166 p = path + strcspn(path, ":/\\");
167 #else
168 p = path + strcspn(path, ":/");
169 #endif
171 return *p == ':';
174 int path_is_absolute(const char *path)
176 #ifdef _WIN32
177 /* specific case for names like: "\\.\d:" */
178 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
179 return 1;
181 return (*path == '/' || *path == '\\');
182 #else
183 return (*path == '/');
184 #endif
187 /* if filename is absolute, just return its duplicate. Otherwise, build a
188 path to it by considering it is relative to base_path. URL are
189 supported. */
190 char *path_combine(const char *base_path, const char *filename)
192 const char *protocol_stripped = NULL;
193 const char *p, *p1;
194 char *result;
195 int len;
197 if (path_is_absolute(filename)) {
198 return g_strdup(filename);
201 if (path_has_protocol(base_path)) {
202 protocol_stripped = strchr(base_path, ':');
203 if (protocol_stripped) {
204 protocol_stripped++;
207 p = protocol_stripped ?: base_path;
209 p1 = strrchr(base_path, '/');
210 #ifdef _WIN32
212 const char *p2;
213 p2 = strrchr(base_path, '\\');
214 if (!p1 || p2 > p1) {
215 p1 = p2;
218 #endif
219 if (p1) {
220 p1++;
221 } else {
222 p1 = base_path;
224 if (p1 > p) {
225 p = p1;
227 len = p - base_path;
229 result = g_malloc(len + strlen(filename) + 1);
230 memcpy(result, base_path, len);
231 strcpy(result + len, filename);
233 return result;
237 * Helper function for bdrv_parse_filename() implementations to remove optional
238 * protocol prefixes (especially "file:") from a filename and for putting the
239 * stripped filename into the options QDict if there is such a prefix.
241 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
242 QDict *options)
244 if (strstart(filename, prefix, &filename)) {
245 /* Stripping the explicit protocol prefix may result in a protocol
246 * prefix being (wrongly) detected (if the filename contains a colon) */
247 if (path_has_protocol(filename)) {
248 GString *fat_filename;
250 /* This means there is some colon before the first slash; therefore,
251 * this cannot be an absolute path */
252 assert(!path_is_absolute(filename));
254 /* And we can thus fix the protocol detection issue by prefixing it
255 * by "./" */
256 fat_filename = g_string_new("./");
257 g_string_append(fat_filename, filename);
259 assert(!path_has_protocol(fat_filename->str));
261 qdict_put(options, "filename",
262 qstring_from_gstring(fat_filename));
263 } else {
264 /* If no protocol prefix was detected, we can use the shortened
265 * filename as-is */
266 qdict_put_str(options, "filename", filename);
272 /* Returns whether the image file is opened as read-only. Note that this can
273 * return false and writing to the image file is still not possible because the
274 * image is inactivated. */
275 bool bdrv_is_read_only(BlockDriverState *bs)
277 IO_CODE();
278 return !(bs->open_flags & BDRV_O_RDWR);
281 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
282 bool ignore_allow_rdw, Error **errp)
284 IO_CODE();
286 /* Do not set read_only if copy_on_read is enabled */
287 if (bs->copy_on_read && read_only) {
288 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
289 bdrv_get_device_or_node_name(bs));
290 return -EINVAL;
293 /* Do not clear read_only if it is prohibited */
294 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
295 !ignore_allow_rdw)
297 error_setg(errp, "Node '%s' is read only",
298 bdrv_get_device_or_node_name(bs));
299 return -EPERM;
302 return 0;
306 * Called by a driver that can only provide a read-only image.
308 * Returns 0 if the node is already read-only or it could switch the node to
309 * read-only because BDRV_O_AUTO_RDONLY is set.
311 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
312 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
313 * is not NULL, it is used as the error message for the Error object.
315 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
316 Error **errp)
318 int ret = 0;
319 IO_CODE();
321 if (!(bs->open_flags & BDRV_O_RDWR)) {
322 return 0;
324 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
325 goto fail;
328 ret = bdrv_can_set_read_only(bs, true, false, NULL);
329 if (ret < 0) {
330 goto fail;
333 bs->open_flags &= ~BDRV_O_RDWR;
335 return 0;
337 fail:
338 error_setg(errp, "%s", errmsg ?: "Image is read-only");
339 return -EACCES;
343 * If @backing is empty, this function returns NULL without setting
344 * @errp. In all other cases, NULL will only be returned with @errp
345 * set.
347 * Therefore, a return value of NULL without @errp set means that
348 * there is no backing file; if @errp is set, there is one but its
349 * absolute filename cannot be generated.
351 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
352 const char *backing,
353 Error **errp)
355 if (backing[0] == '\0') {
356 return NULL;
357 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
358 return g_strdup(backing);
359 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
360 error_setg(errp, "Cannot use relative backing file names for '%s'",
361 backed);
362 return NULL;
363 } else {
364 return path_combine(backed, backing);
369 * If @filename is empty or NULL, this function returns NULL without
370 * setting @errp. In all other cases, NULL will only be returned with
371 * @errp set.
373 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
374 const char *filename, Error **errp)
376 char *dir, *full_name;
378 if (!filename || filename[0] == '\0') {
379 return NULL;
380 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
381 return g_strdup(filename);
384 dir = bdrv_dirname(relative_to, errp);
385 if (!dir) {
386 return NULL;
389 full_name = g_strconcat(dir, filename, NULL);
390 g_free(dir);
391 return full_name;
394 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
396 GLOBAL_STATE_CODE();
397 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
400 void bdrv_register(BlockDriver *bdrv)
402 assert(bdrv->format_name);
403 GLOBAL_STATE_CODE();
404 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
407 BlockDriverState *bdrv_new(void)
409 BlockDriverState *bs;
410 int i;
412 GLOBAL_STATE_CODE();
414 bs = g_new0(BlockDriverState, 1);
415 QLIST_INIT(&bs->dirty_bitmaps);
416 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
417 QLIST_INIT(&bs->op_blockers[i]);
419 qemu_co_mutex_init(&bs->reqs_lock);
420 qemu_mutex_init(&bs->dirty_bitmap_mutex);
421 bs->refcnt = 1;
422 bs->aio_context = qemu_get_aio_context();
424 qemu_co_queue_init(&bs->flush_queue);
426 qemu_co_mutex_init(&bs->bsc_modify_lock);
427 bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
429 for (i = 0; i < bdrv_drain_all_count; i++) {
430 bdrv_drained_begin(bs);
433 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
435 return bs;
438 static BlockDriver *bdrv_do_find_format(const char *format_name)
440 BlockDriver *drv1;
441 GLOBAL_STATE_CODE();
443 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
444 if (!strcmp(drv1->format_name, format_name)) {
445 return drv1;
449 return NULL;
452 BlockDriver *bdrv_find_format(const char *format_name)
454 BlockDriver *drv1;
455 int i;
457 GLOBAL_STATE_CODE();
459 drv1 = bdrv_do_find_format(format_name);
460 if (drv1) {
461 return drv1;
464 /* The driver isn't registered, maybe we need to load a module */
465 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
466 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
467 block_module_load_one(block_driver_modules[i].library_name);
468 break;
472 return bdrv_do_find_format(format_name);
475 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
477 static const char *whitelist_rw[] = {
478 CONFIG_BDRV_RW_WHITELIST
479 NULL
481 static const char *whitelist_ro[] = {
482 CONFIG_BDRV_RO_WHITELIST
483 NULL
485 const char **p;
487 if (!whitelist_rw[0] && !whitelist_ro[0]) {
488 return 1; /* no whitelist, anything goes */
491 for (p = whitelist_rw; *p; p++) {
492 if (!strcmp(format_name, *p)) {
493 return 1;
496 if (read_only) {
497 for (p = whitelist_ro; *p; p++) {
498 if (!strcmp(format_name, *p)) {
499 return 1;
503 return 0;
506 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
508 GLOBAL_STATE_CODE();
509 return bdrv_format_is_whitelisted(drv->format_name, read_only);
512 bool bdrv_uses_whitelist(void)
514 return use_bdrv_whitelist;
517 typedef struct CreateCo {
518 BlockDriver *drv;
519 char *filename;
520 QemuOpts *opts;
521 int ret;
522 Error *err;
523 } CreateCo;
525 static void coroutine_fn bdrv_create_co_entry(void *opaque)
527 Error *local_err = NULL;
528 int ret;
530 CreateCo *cco = opaque;
531 assert(cco->drv);
533 ret = cco->drv->bdrv_co_create_opts(cco->drv,
534 cco->filename, cco->opts, &local_err);
535 error_propagate(&cco->err, local_err);
536 cco->ret = ret;
539 int bdrv_create(BlockDriver *drv, const char* filename,
540 QemuOpts *opts, Error **errp)
542 int ret;
544 GLOBAL_STATE_CODE();
546 Coroutine *co;
547 CreateCo cco = {
548 .drv = drv,
549 .filename = g_strdup(filename),
550 .opts = opts,
551 .ret = NOT_DONE,
552 .err = NULL,
555 if (!drv->bdrv_co_create_opts) {
556 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
557 ret = -ENOTSUP;
558 goto out;
561 if (qemu_in_coroutine()) {
562 /* Fast-path if already in coroutine context */
563 bdrv_create_co_entry(&cco);
564 } else {
565 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
566 qemu_coroutine_enter(co);
567 while (cco.ret == NOT_DONE) {
568 aio_poll(qemu_get_aio_context(), true);
572 ret = cco.ret;
573 if (ret < 0) {
574 if (cco.err) {
575 error_propagate(errp, cco.err);
576 } else {
577 error_setg_errno(errp, -ret, "Could not create image");
581 out:
582 g_free(cco.filename);
583 return ret;
587 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
588 * least the given @minimum_size.
590 * On success, return @blk's actual length.
591 * Otherwise, return -errno.
593 static int64_t create_file_fallback_truncate(BlockBackend *blk,
594 int64_t minimum_size, Error **errp)
596 Error *local_err = NULL;
597 int64_t size;
598 int ret;
600 GLOBAL_STATE_CODE();
602 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
603 &local_err);
604 if (ret < 0 && ret != -ENOTSUP) {
605 error_propagate(errp, local_err);
606 return ret;
609 size = blk_getlength(blk);
610 if (size < 0) {
611 error_free(local_err);
612 error_setg_errno(errp, -size,
613 "Failed to inquire the new image file's length");
614 return size;
617 if (size < minimum_size) {
618 /* Need to grow the image, but we failed to do that */
619 error_propagate(errp, local_err);
620 return -ENOTSUP;
623 error_free(local_err);
624 local_err = NULL;
626 return size;
630 * Helper function for bdrv_create_file_fallback(): Zero the first
631 * sector to remove any potentially pre-existing image header.
633 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
634 int64_t current_size,
635 Error **errp)
637 int64_t bytes_to_clear;
638 int ret;
640 GLOBAL_STATE_CODE();
642 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
643 if (bytes_to_clear) {
644 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
645 if (ret < 0) {
646 error_setg_errno(errp, -ret,
647 "Failed to clear the new image's first sector");
648 return ret;
652 return 0;
656 * Simple implementation of bdrv_co_create_opts for protocol drivers
657 * which only support creation via opening a file
658 * (usually existing raw storage device)
660 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
661 const char *filename,
662 QemuOpts *opts,
663 Error **errp)
665 BlockBackend *blk;
666 QDict *options;
667 int64_t size = 0;
668 char *buf = NULL;
669 PreallocMode prealloc;
670 Error *local_err = NULL;
671 int ret;
673 GLOBAL_STATE_CODE();
675 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
676 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
677 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
678 PREALLOC_MODE_OFF, &local_err);
679 g_free(buf);
680 if (local_err) {
681 error_propagate(errp, local_err);
682 return -EINVAL;
685 if (prealloc != PREALLOC_MODE_OFF) {
686 error_setg(errp, "Unsupported preallocation mode '%s'",
687 PreallocMode_str(prealloc));
688 return -ENOTSUP;
691 options = qdict_new();
692 qdict_put_str(options, "driver", drv->format_name);
694 blk = blk_new_open(filename, NULL, options,
695 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
696 if (!blk) {
697 error_prepend(errp, "Protocol driver '%s' does not support image "
698 "creation, and opening the image failed: ",
699 drv->format_name);
700 return -EINVAL;
703 size = create_file_fallback_truncate(blk, size, errp);
704 if (size < 0) {
705 ret = size;
706 goto out;
709 ret = create_file_fallback_zero_first_sector(blk, size, errp);
710 if (ret < 0) {
711 goto out;
714 ret = 0;
715 out:
716 blk_unref(blk);
717 return ret;
720 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
722 QemuOpts *protocol_opts;
723 BlockDriver *drv;
724 QDict *qdict;
725 int ret;
727 GLOBAL_STATE_CODE();
729 drv = bdrv_find_protocol(filename, true, errp);
730 if (drv == NULL) {
731 return -ENOENT;
734 if (!drv->create_opts) {
735 error_setg(errp, "Driver '%s' does not support image creation",
736 drv->format_name);
737 return -ENOTSUP;
741 * 'opts' contains a QemuOptsList with a combination of format and protocol
742 * default values.
744 * The format properly removes its options, but the default values remain
745 * in 'opts->list'. So if the protocol has options with the same name
746 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
747 * of the format, since for overlapping options, the format wins.
749 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
750 * only the set options, and then convert it back to QemuOpts, using the
751 * create_opts of the protocol. So the new QemuOpts, will contain only the
752 * protocol defaults.
754 qdict = qemu_opts_to_qdict(opts, NULL);
755 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
756 if (protocol_opts == NULL) {
757 ret = -EINVAL;
758 goto out;
761 ret = bdrv_create(drv, filename, protocol_opts, errp);
762 out:
763 qemu_opts_del(protocol_opts);
764 qobject_unref(qdict);
765 return ret;
768 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
770 Error *local_err = NULL;
771 int ret;
773 IO_CODE();
774 assert(bs != NULL);
776 if (!bs->drv) {
777 error_setg(errp, "Block node '%s' is not opened", bs->filename);
778 return -ENOMEDIUM;
781 if (!bs->drv->bdrv_co_delete_file) {
782 error_setg(errp, "Driver '%s' does not support image deletion",
783 bs->drv->format_name);
784 return -ENOTSUP;
787 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
788 if (ret < 0) {
789 error_propagate(errp, local_err);
792 return ret;
795 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
797 Error *local_err = NULL;
798 int ret;
799 IO_CODE();
801 if (!bs) {
802 return;
805 ret = bdrv_co_delete_file(bs, &local_err);
807 * ENOTSUP will happen if the block driver doesn't support
808 * the 'bdrv_co_delete_file' interface. This is a predictable
809 * scenario and shouldn't be reported back to the user.
811 if (ret == -ENOTSUP) {
812 error_free(local_err);
813 } else if (ret < 0) {
814 error_report_err(local_err);
819 * Try to get @bs's logical and physical block size.
820 * On success, store them in @bsz struct and return 0.
821 * On failure return -errno.
822 * @bs must not be empty.
824 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
826 BlockDriver *drv = bs->drv;
827 BlockDriverState *filtered = bdrv_filter_bs(bs);
828 GLOBAL_STATE_CODE();
830 if (drv && drv->bdrv_probe_blocksizes) {
831 return drv->bdrv_probe_blocksizes(bs, bsz);
832 } else if (filtered) {
833 return bdrv_probe_blocksizes(filtered, bsz);
836 return -ENOTSUP;
840 * Try to get @bs's geometry (cyls, heads, sectors).
841 * On success, store them in @geo struct and return 0.
842 * On failure return -errno.
843 * @bs must not be empty.
845 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
847 BlockDriver *drv = bs->drv;
848 BlockDriverState *filtered = bdrv_filter_bs(bs);
849 GLOBAL_STATE_CODE();
851 if (drv && drv->bdrv_probe_geometry) {
852 return drv->bdrv_probe_geometry(bs, geo);
853 } else if (filtered) {
854 return bdrv_probe_geometry(filtered, geo);
857 return -ENOTSUP;
861 * Create a uniquely-named empty temporary file.
862 * Return 0 upon success, otherwise a negative errno value.
864 int get_tmp_filename(char *filename, int size)
866 #ifdef _WIN32
867 char temp_dir[MAX_PATH];
868 /* GetTempFileName requires that its output buffer (4th param)
869 have length MAX_PATH or greater. */
870 assert(size >= MAX_PATH);
871 return (GetTempPath(MAX_PATH, temp_dir)
872 && GetTempFileName(temp_dir, "qem", 0, filename)
873 ? 0 : -GetLastError());
874 #else
875 int fd;
876 const char *tmpdir;
877 tmpdir = getenv("TMPDIR");
878 if (!tmpdir) {
879 tmpdir = "/var/tmp";
881 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
882 return -EOVERFLOW;
884 fd = mkstemp(filename);
885 if (fd < 0) {
886 return -errno;
888 if (close(fd) != 0) {
889 unlink(filename);
890 return -errno;
892 return 0;
893 #endif
897 * Detect host devices. By convention, /dev/cdrom[N] is always
898 * recognized as a host CDROM.
900 static BlockDriver *find_hdev_driver(const char *filename)
902 int score_max = 0, score;
903 BlockDriver *drv = NULL, *d;
904 GLOBAL_STATE_CODE();
906 QLIST_FOREACH(d, &bdrv_drivers, list) {
907 if (d->bdrv_probe_device) {
908 score = d->bdrv_probe_device(filename);
909 if (score > score_max) {
910 score_max = score;
911 drv = d;
916 return drv;
919 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
921 BlockDriver *drv1;
922 GLOBAL_STATE_CODE();
924 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
925 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
926 return drv1;
930 return NULL;
933 BlockDriver *bdrv_find_protocol(const char *filename,
934 bool allow_protocol_prefix,
935 Error **errp)
937 BlockDriver *drv1;
938 char protocol[128];
939 int len;
940 const char *p;
941 int i;
943 GLOBAL_STATE_CODE();
944 /* TODO Drivers without bdrv_file_open must be specified explicitly */
947 * XXX(hch): we really should not let host device detection
948 * override an explicit protocol specification, but moving this
949 * later breaks access to device names with colons in them.
950 * Thanks to the brain-dead persistent naming schemes on udev-
951 * based Linux systems those actually are quite common.
953 drv1 = find_hdev_driver(filename);
954 if (drv1) {
955 return drv1;
958 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
959 return &bdrv_file;
962 p = strchr(filename, ':');
963 assert(p != NULL);
964 len = p - filename;
965 if (len > sizeof(protocol) - 1)
966 len = sizeof(protocol) - 1;
967 memcpy(protocol, filename, len);
968 protocol[len] = '\0';
970 drv1 = bdrv_do_find_protocol(protocol);
971 if (drv1) {
972 return drv1;
975 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
976 if (block_driver_modules[i].protocol_name &&
977 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
978 block_module_load_one(block_driver_modules[i].library_name);
979 break;
983 drv1 = bdrv_do_find_protocol(protocol);
984 if (!drv1) {
985 error_setg(errp, "Unknown protocol '%s'", protocol);
987 return drv1;
991 * Guess image format by probing its contents.
992 * This is not a good idea when your image is raw (CVE-2008-2004), but
993 * we do it anyway for backward compatibility.
995 * @buf contains the image's first @buf_size bytes.
996 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
997 * but can be smaller if the image file is smaller)
998 * @filename is its filename.
1000 * For all block drivers, call the bdrv_probe() method to get its
1001 * probing score.
1002 * Return the first block driver with the highest probing score.
1004 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1005 const char *filename)
1007 int score_max = 0, score;
1008 BlockDriver *drv = NULL, *d;
1009 IO_CODE();
1011 QLIST_FOREACH(d, &bdrv_drivers, list) {
1012 if (d->bdrv_probe) {
1013 score = d->bdrv_probe(buf, buf_size, filename);
1014 if (score > score_max) {
1015 score_max = score;
1016 drv = d;
1021 return drv;
1024 static int find_image_format(BlockBackend *file, const char *filename,
1025 BlockDriver **pdrv, Error **errp)
1027 BlockDriver *drv;
1028 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1029 int ret = 0;
1031 GLOBAL_STATE_CODE();
1033 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1034 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1035 *pdrv = &bdrv_raw;
1036 return ret;
1039 ret = blk_pread(file, 0, buf, sizeof(buf));
1040 if (ret < 0) {
1041 error_setg_errno(errp, -ret, "Could not read image for determining its "
1042 "format");
1043 *pdrv = NULL;
1044 return ret;
1047 drv = bdrv_probe_all(buf, ret, filename);
1048 if (!drv) {
1049 error_setg(errp, "Could not determine image format: No compatible "
1050 "driver found");
1051 ret = -ENOENT;
1053 *pdrv = drv;
1054 return ret;
1058 * Set the current 'total_sectors' value
1059 * Return 0 on success, -errno on error.
1061 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1063 BlockDriver *drv = bs->drv;
1064 IO_CODE();
1066 if (!drv) {
1067 return -ENOMEDIUM;
1070 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1071 if (bdrv_is_sg(bs))
1072 return 0;
1074 /* query actual device if possible, otherwise just trust the hint */
1075 if (drv->bdrv_getlength) {
1076 int64_t length = drv->bdrv_getlength(bs);
1077 if (length < 0) {
1078 return length;
1080 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1083 bs->total_sectors = hint;
1085 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1086 return -EFBIG;
1089 return 0;
1093 * Combines a QDict of new block driver @options with any missing options taken
1094 * from @old_options, so that leaving out an option defaults to its old value.
1096 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1097 QDict *old_options)
1099 if (bs->drv && bs->drv->bdrv_join_options) {
1100 bs->drv->bdrv_join_options(options, old_options);
1101 } else {
1102 qdict_join(options, old_options, false);
1106 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1107 int open_flags,
1108 Error **errp)
1110 Error *local_err = NULL;
1111 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1112 BlockdevDetectZeroesOptions detect_zeroes =
1113 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1114 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1115 GLOBAL_STATE_CODE();
1116 g_free(value);
1117 if (local_err) {
1118 error_propagate(errp, local_err);
1119 return detect_zeroes;
1122 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1123 !(open_flags & BDRV_O_UNMAP))
1125 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1126 "without setting discard operation to unmap");
1129 return detect_zeroes;
1133 * Set open flags for aio engine
1135 * Return 0 on success, -1 if the engine specified is invalid
1137 int bdrv_parse_aio(const char *mode, int *flags)
1139 if (!strcmp(mode, "threads")) {
1140 /* do nothing, default */
1141 } else if (!strcmp(mode, "native")) {
1142 *flags |= BDRV_O_NATIVE_AIO;
1143 #ifdef CONFIG_LINUX_IO_URING
1144 } else if (!strcmp(mode, "io_uring")) {
1145 *flags |= BDRV_O_IO_URING;
1146 #endif
1147 } else {
1148 return -1;
1151 return 0;
1155 * Set open flags for a given discard mode
1157 * Return 0 on success, -1 if the discard mode was invalid.
1159 int bdrv_parse_discard_flags(const char *mode, int *flags)
1161 *flags &= ~BDRV_O_UNMAP;
1163 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1164 /* do nothing */
1165 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1166 *flags |= BDRV_O_UNMAP;
1167 } else {
1168 return -1;
1171 return 0;
1175 * Set open flags for a given cache mode
1177 * Return 0 on success, -1 if the cache mode was invalid.
1179 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1181 *flags &= ~BDRV_O_CACHE_MASK;
1183 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1184 *writethrough = false;
1185 *flags |= BDRV_O_NOCACHE;
1186 } else if (!strcmp(mode, "directsync")) {
1187 *writethrough = true;
1188 *flags |= BDRV_O_NOCACHE;
1189 } else if (!strcmp(mode, "writeback")) {
1190 *writethrough = false;
1191 } else if (!strcmp(mode, "unsafe")) {
1192 *writethrough = false;
1193 *flags |= BDRV_O_NO_FLUSH;
1194 } else if (!strcmp(mode, "writethrough")) {
1195 *writethrough = true;
1196 } else {
1197 return -1;
1200 return 0;
1203 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1205 BlockDriverState *parent = c->opaque;
1206 return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1209 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1211 BlockDriverState *bs = child->opaque;
1212 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1215 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1217 BlockDriverState *bs = child->opaque;
1218 return bdrv_drain_poll(bs, false, NULL, false);
1221 static void bdrv_child_cb_drained_end(BdrvChild *child,
1222 int *drained_end_counter)
1224 BlockDriverState *bs = child->opaque;
1225 bdrv_drained_end_no_poll(bs, drained_end_counter);
1228 static int bdrv_child_cb_inactivate(BdrvChild *child)
1230 BlockDriverState *bs = child->opaque;
1231 GLOBAL_STATE_CODE();
1232 assert(bs->open_flags & BDRV_O_INACTIVE);
1233 return 0;
1236 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1237 GSList **ignore, Error **errp)
1239 BlockDriverState *bs = child->opaque;
1240 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1243 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1244 GSList **ignore)
1246 BlockDriverState *bs = child->opaque;
1247 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1251 * Returns the options and flags that a temporary snapshot should get, based on
1252 * the originally requested flags (the originally requested image will have
1253 * flags like a backing file)
1255 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1256 int parent_flags, QDict *parent_options)
1258 GLOBAL_STATE_CODE();
1259 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1261 /* For temporary files, unconditional cache=unsafe is fine */
1262 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1263 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1265 /* Copy the read-only and discard options from the parent */
1266 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1267 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1269 /* aio=native doesn't work for cache.direct=off, so disable it for the
1270 * temporary snapshot */
1271 *child_flags &= ~BDRV_O_NATIVE_AIO;
1274 static void bdrv_backing_attach(BdrvChild *c)
1276 BlockDriverState *parent = c->opaque;
1277 BlockDriverState *backing_hd = c->bs;
1279 GLOBAL_STATE_CODE();
1280 assert(!parent->backing_blocker);
1281 error_setg(&parent->backing_blocker,
1282 "node is used as backing hd of '%s'",
1283 bdrv_get_device_or_node_name(parent));
1285 bdrv_refresh_filename(backing_hd);
1287 parent->open_flags &= ~BDRV_O_NO_BACKING;
1289 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1290 /* Otherwise we won't be able to commit or stream */
1291 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1292 parent->backing_blocker);
1293 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1294 parent->backing_blocker);
1296 * We do backup in 3 ways:
1297 * 1. drive backup
1298 * The target bs is new opened, and the source is top BDS
1299 * 2. blockdev backup
1300 * Both the source and the target are top BDSes.
1301 * 3. internal backup(used for block replication)
1302 * Both the source and the target are backing file
1304 * In case 1 and 2, neither the source nor the target is the backing file.
1305 * In case 3, we will block the top BDS, so there is only one block job
1306 * for the top BDS and its backing chain.
1308 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1309 parent->backing_blocker);
1310 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1311 parent->backing_blocker);
1314 static void bdrv_backing_detach(BdrvChild *c)
1316 BlockDriverState *parent = c->opaque;
1318 GLOBAL_STATE_CODE();
1319 assert(parent->backing_blocker);
1320 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1321 error_free(parent->backing_blocker);
1322 parent->backing_blocker = NULL;
1325 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1326 const char *filename, Error **errp)
1328 BlockDriverState *parent = c->opaque;
1329 bool read_only = bdrv_is_read_only(parent);
1330 int ret;
1331 GLOBAL_STATE_CODE();
1333 if (read_only) {
1334 ret = bdrv_reopen_set_read_only(parent, false, errp);
1335 if (ret < 0) {
1336 return ret;
1340 ret = bdrv_change_backing_file(parent, filename,
1341 base->drv ? base->drv->format_name : "",
1342 false);
1343 if (ret < 0) {
1344 error_setg_errno(errp, -ret, "Could not update backing file link");
1347 if (read_only) {
1348 bdrv_reopen_set_read_only(parent, true, NULL);
1351 return ret;
1355 * Returns the options and flags that a generic child of a BDS should
1356 * get, based on the given options and flags for the parent BDS.
1358 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1359 int *child_flags, QDict *child_options,
1360 int parent_flags, QDict *parent_options)
1362 int flags = parent_flags;
1363 GLOBAL_STATE_CODE();
1366 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1367 * Generally, the question to answer is: Should this child be
1368 * format-probed by default?
1372 * Pure and non-filtered data children of non-format nodes should
1373 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1374 * set). This only affects a very limited set of drivers (namely
1375 * quorum and blkverify when this comment was written).
1376 * Force-clear BDRV_O_PROTOCOL then.
1378 if (!parent_is_format &&
1379 (role & BDRV_CHILD_DATA) &&
1380 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1382 flags &= ~BDRV_O_PROTOCOL;
1386 * All children of format nodes (except for COW children) and all
1387 * metadata children in general should never be format-probed.
1388 * Force-set BDRV_O_PROTOCOL then.
1390 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1391 (role & BDRV_CHILD_METADATA))
1393 flags |= BDRV_O_PROTOCOL;
1397 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1398 * the parent.
1400 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1401 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1402 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1404 if (role & BDRV_CHILD_COW) {
1405 /* backing files are opened read-only by default */
1406 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1407 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1408 } else {
1409 /* Inherit the read-only option from the parent if it's not set */
1410 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1411 qdict_copy_default(child_options, parent_options,
1412 BDRV_OPT_AUTO_READ_ONLY);
1416 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1417 * can default to enable it on lower layers regardless of the
1418 * parent option.
1420 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1422 /* Clear flags that only apply to the top layer */
1423 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1425 if (role & BDRV_CHILD_METADATA) {
1426 flags &= ~BDRV_O_NO_IO;
1428 if (role & BDRV_CHILD_COW) {
1429 flags &= ~BDRV_O_TEMPORARY;
1432 *child_flags = flags;
1435 static void bdrv_child_cb_attach(BdrvChild *child)
1437 BlockDriverState *bs = child->opaque;
1439 assert_bdrv_graph_writable(bs);
1440 QLIST_INSERT_HEAD(&bs->children, child, next);
1442 if (child->role & BDRV_CHILD_COW) {
1443 bdrv_backing_attach(child);
1446 bdrv_apply_subtree_drain(child, bs);
1449 static void bdrv_child_cb_detach(BdrvChild *child)
1451 BlockDriverState *bs = child->opaque;
1453 if (child->role & BDRV_CHILD_COW) {
1454 bdrv_backing_detach(child);
1457 bdrv_unapply_subtree_drain(child, bs);
1459 assert_bdrv_graph_writable(bs);
1460 QLIST_REMOVE(child, next);
1463 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1464 const char *filename, Error **errp)
1466 if (c->role & BDRV_CHILD_COW) {
1467 return bdrv_backing_update_filename(c, base, filename, errp);
1469 return 0;
1472 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1474 BlockDriverState *bs = c->opaque;
1475 IO_CODE();
1477 return bdrv_get_aio_context(bs);
1480 const BdrvChildClass child_of_bds = {
1481 .parent_is_bds = true,
1482 .get_parent_desc = bdrv_child_get_parent_desc,
1483 .inherit_options = bdrv_inherited_options,
1484 .drained_begin = bdrv_child_cb_drained_begin,
1485 .drained_poll = bdrv_child_cb_drained_poll,
1486 .drained_end = bdrv_child_cb_drained_end,
1487 .attach = bdrv_child_cb_attach,
1488 .detach = bdrv_child_cb_detach,
1489 .inactivate = bdrv_child_cb_inactivate,
1490 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1491 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1492 .update_filename = bdrv_child_cb_update_filename,
1493 .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1496 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1498 IO_CODE();
1499 return c->klass->get_parent_aio_context(c);
1502 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1504 int open_flags = flags;
1505 GLOBAL_STATE_CODE();
1508 * Clear flags that are internal to the block layer before opening the
1509 * image.
1511 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1513 return open_flags;
1516 static void update_flags_from_options(int *flags, QemuOpts *opts)
1518 GLOBAL_STATE_CODE();
1520 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1522 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1523 *flags |= BDRV_O_NO_FLUSH;
1526 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1527 *flags |= BDRV_O_NOCACHE;
1530 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1531 *flags |= BDRV_O_RDWR;
1534 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1535 *flags |= BDRV_O_AUTO_RDONLY;
1539 static void update_options_from_flags(QDict *options, int flags)
1541 GLOBAL_STATE_CODE();
1542 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1543 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1545 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1546 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1547 flags & BDRV_O_NO_FLUSH);
1549 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1550 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1552 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1553 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1554 flags & BDRV_O_AUTO_RDONLY);
1558 static void bdrv_assign_node_name(BlockDriverState *bs,
1559 const char *node_name,
1560 Error **errp)
1562 char *gen_node_name = NULL;
1563 GLOBAL_STATE_CODE();
1565 if (!node_name) {
1566 node_name = gen_node_name = id_generate(ID_BLOCK);
1567 } else if (!id_wellformed(node_name)) {
1569 * Check for empty string or invalid characters, but not if it is
1570 * generated (generated names use characters not available to the user)
1572 error_setg(errp, "Invalid node-name: '%s'", node_name);
1573 return;
1576 /* takes care of avoiding namespaces collisions */
1577 if (blk_by_name(node_name)) {
1578 error_setg(errp, "node-name=%s is conflicting with a device id",
1579 node_name);
1580 goto out;
1583 /* takes care of avoiding duplicates node names */
1584 if (bdrv_find_node(node_name)) {
1585 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1586 goto out;
1589 /* Make sure that the node name isn't truncated */
1590 if (strlen(node_name) >= sizeof(bs->node_name)) {
1591 error_setg(errp, "Node name too long");
1592 goto out;
1595 /* copy node name into the bs and insert it into the graph list */
1596 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1597 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1598 out:
1599 g_free(gen_node_name);
1602 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1603 const char *node_name, QDict *options,
1604 int open_flags, Error **errp)
1606 Error *local_err = NULL;
1607 int i, ret;
1609 bdrv_assign_node_name(bs, node_name, &local_err);
1610 if (local_err) {
1611 error_propagate(errp, local_err);
1612 return -EINVAL;
1615 bs->drv = drv;
1616 bs->opaque = g_malloc0(drv->instance_size);
1618 if (drv->bdrv_file_open) {
1619 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1620 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1621 } else if (drv->bdrv_open) {
1622 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1623 } else {
1624 ret = 0;
1627 if (ret < 0) {
1628 if (local_err) {
1629 error_propagate(errp, local_err);
1630 } else if (bs->filename[0]) {
1631 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1632 } else {
1633 error_setg_errno(errp, -ret, "Could not open image");
1635 goto open_failed;
1638 ret = refresh_total_sectors(bs, bs->total_sectors);
1639 if (ret < 0) {
1640 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1641 return ret;
1644 bdrv_refresh_limits(bs, NULL, &local_err);
1645 if (local_err) {
1646 error_propagate(errp, local_err);
1647 return -EINVAL;
1650 assert(bdrv_opt_mem_align(bs) != 0);
1651 assert(bdrv_min_mem_align(bs) != 0);
1652 assert(is_power_of_2(bs->bl.request_alignment));
1654 for (i = 0; i < bs->quiesce_counter; i++) {
1655 if (drv->bdrv_co_drain_begin) {
1656 drv->bdrv_co_drain_begin(bs);
1660 return 0;
1661 open_failed:
1662 bs->drv = NULL;
1663 if (bs->file != NULL) {
1664 bdrv_unref_child(bs, bs->file);
1665 bs->file = NULL;
1667 g_free(bs->opaque);
1668 bs->opaque = NULL;
1669 return ret;
1673 * Create and open a block node.
1675 * @options is a QDict of options to pass to the block drivers, or NULL for an
1676 * empty set of options. The reference to the QDict belongs to the block layer
1677 * after the call (even on failure), so if the caller intends to reuse the
1678 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1680 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1681 const char *node_name,
1682 QDict *options, int flags,
1683 Error **errp)
1685 BlockDriverState *bs;
1686 int ret;
1688 GLOBAL_STATE_CODE();
1690 bs = bdrv_new();
1691 bs->open_flags = flags;
1692 bs->options = options ?: qdict_new();
1693 bs->explicit_options = qdict_clone_shallow(bs->options);
1694 bs->opaque = NULL;
1696 update_options_from_flags(bs->options, flags);
1698 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1699 if (ret < 0) {
1700 qobject_unref(bs->explicit_options);
1701 bs->explicit_options = NULL;
1702 qobject_unref(bs->options);
1703 bs->options = NULL;
1704 bdrv_unref(bs);
1705 return NULL;
1708 return bs;
1711 /* Create and open a block node. */
1712 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1713 int flags, Error **errp)
1715 GLOBAL_STATE_CODE();
1716 return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1719 QemuOptsList bdrv_runtime_opts = {
1720 .name = "bdrv_common",
1721 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1722 .desc = {
1724 .name = "node-name",
1725 .type = QEMU_OPT_STRING,
1726 .help = "Node name of the block device node",
1729 .name = "driver",
1730 .type = QEMU_OPT_STRING,
1731 .help = "Block driver to use for the node",
1734 .name = BDRV_OPT_CACHE_DIRECT,
1735 .type = QEMU_OPT_BOOL,
1736 .help = "Bypass software writeback cache on the host",
1739 .name = BDRV_OPT_CACHE_NO_FLUSH,
1740 .type = QEMU_OPT_BOOL,
1741 .help = "Ignore flush requests",
1744 .name = BDRV_OPT_READ_ONLY,
1745 .type = QEMU_OPT_BOOL,
1746 .help = "Node is opened in read-only mode",
1749 .name = BDRV_OPT_AUTO_READ_ONLY,
1750 .type = QEMU_OPT_BOOL,
1751 .help = "Node can become read-only if opening read-write fails",
1754 .name = "detect-zeroes",
1755 .type = QEMU_OPT_STRING,
1756 .help = "try to optimize zero writes (off, on, unmap)",
1759 .name = BDRV_OPT_DISCARD,
1760 .type = QEMU_OPT_STRING,
1761 .help = "discard operation (ignore/off, unmap/on)",
1764 .name = BDRV_OPT_FORCE_SHARE,
1765 .type = QEMU_OPT_BOOL,
1766 .help = "always accept other writers (default: off)",
1768 { /* end of list */ }
1772 QemuOptsList bdrv_create_opts_simple = {
1773 .name = "simple-create-opts",
1774 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1775 .desc = {
1777 .name = BLOCK_OPT_SIZE,
1778 .type = QEMU_OPT_SIZE,
1779 .help = "Virtual disk size"
1782 .name = BLOCK_OPT_PREALLOC,
1783 .type = QEMU_OPT_STRING,
1784 .help = "Preallocation mode (allowed values: off)"
1786 { /* end of list */ }
1791 * Common part for opening disk images and files
1793 * Removes all processed options from *options.
1795 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1796 QDict *options, Error **errp)
1798 int ret, open_flags;
1799 const char *filename;
1800 const char *driver_name = NULL;
1801 const char *node_name = NULL;
1802 const char *discard;
1803 QemuOpts *opts;
1804 BlockDriver *drv;
1805 Error *local_err = NULL;
1806 bool ro;
1808 assert(bs->file == NULL);
1809 assert(options != NULL && bs->options != options);
1810 GLOBAL_STATE_CODE();
1812 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1813 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1814 ret = -EINVAL;
1815 goto fail_opts;
1818 update_flags_from_options(&bs->open_flags, opts);
1820 driver_name = qemu_opt_get(opts, "driver");
1821 drv = bdrv_find_format(driver_name);
1822 assert(drv != NULL);
1824 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1826 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1827 error_setg(errp,
1828 BDRV_OPT_FORCE_SHARE
1829 "=on can only be used with read-only images");
1830 ret = -EINVAL;
1831 goto fail_opts;
1834 if (file != NULL) {
1835 bdrv_refresh_filename(blk_bs(file));
1836 filename = blk_bs(file)->filename;
1837 } else {
1839 * Caution: while qdict_get_try_str() is fine, getting
1840 * non-string types would require more care. When @options
1841 * come from -blockdev or blockdev_add, its members are typed
1842 * according to the QAPI schema, but when they come from
1843 * -drive, they're all QString.
1845 filename = qdict_get_try_str(options, "filename");
1848 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1849 error_setg(errp, "The '%s' block driver requires a file name",
1850 drv->format_name);
1851 ret = -EINVAL;
1852 goto fail_opts;
1855 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1856 drv->format_name);
1858 ro = bdrv_is_read_only(bs);
1860 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1861 if (!ro && bdrv_is_whitelisted(drv, true)) {
1862 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1863 } else {
1864 ret = -ENOTSUP;
1866 if (ret < 0) {
1867 error_setg(errp,
1868 !ro && bdrv_is_whitelisted(drv, true)
1869 ? "Driver '%s' can only be used for read-only devices"
1870 : "Driver '%s' is not whitelisted",
1871 drv->format_name);
1872 goto fail_opts;
1876 /* bdrv_new() and bdrv_close() make it so */
1877 assert(qatomic_read(&bs->copy_on_read) == 0);
1879 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1880 if (!ro) {
1881 bdrv_enable_copy_on_read(bs);
1882 } else {
1883 error_setg(errp, "Can't use copy-on-read on read-only device");
1884 ret = -EINVAL;
1885 goto fail_opts;
1889 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1890 if (discard != NULL) {
1891 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1892 error_setg(errp, "Invalid discard option");
1893 ret = -EINVAL;
1894 goto fail_opts;
1898 bs->detect_zeroes =
1899 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1900 if (local_err) {
1901 error_propagate(errp, local_err);
1902 ret = -EINVAL;
1903 goto fail_opts;
1906 if (filename != NULL) {
1907 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1908 } else {
1909 bs->filename[0] = '\0';
1911 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1913 /* Open the image, either directly or using a protocol */
1914 open_flags = bdrv_open_flags(bs, bs->open_flags);
1915 node_name = qemu_opt_get(opts, "node-name");
1917 assert(!drv->bdrv_file_open || file == NULL);
1918 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1919 if (ret < 0) {
1920 goto fail_opts;
1923 qemu_opts_del(opts);
1924 return 0;
1926 fail_opts:
1927 qemu_opts_del(opts);
1928 return ret;
1931 static QDict *parse_json_filename(const char *filename, Error **errp)
1933 QObject *options_obj;
1934 QDict *options;
1935 int ret;
1936 GLOBAL_STATE_CODE();
1938 ret = strstart(filename, "json:", &filename);
1939 assert(ret);
1941 options_obj = qobject_from_json(filename, errp);
1942 if (!options_obj) {
1943 error_prepend(errp, "Could not parse the JSON options: ");
1944 return NULL;
1947 options = qobject_to(QDict, options_obj);
1948 if (!options) {
1949 qobject_unref(options_obj);
1950 error_setg(errp, "Invalid JSON object given");
1951 return NULL;
1954 qdict_flatten(options);
1956 return options;
1959 static void parse_json_protocol(QDict *options, const char **pfilename,
1960 Error **errp)
1962 QDict *json_options;
1963 Error *local_err = NULL;
1964 GLOBAL_STATE_CODE();
1966 /* Parse json: pseudo-protocol */
1967 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1968 return;
1971 json_options = parse_json_filename(*pfilename, &local_err);
1972 if (local_err) {
1973 error_propagate(errp, local_err);
1974 return;
1977 /* Options given in the filename have lower priority than options
1978 * specified directly */
1979 qdict_join(options, json_options, false);
1980 qobject_unref(json_options);
1981 *pfilename = NULL;
1985 * Fills in default options for opening images and converts the legacy
1986 * filename/flags pair to option QDict entries.
1987 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1988 * block driver has been specified explicitly.
1990 static int bdrv_fill_options(QDict **options, const char *filename,
1991 int *flags, Error **errp)
1993 const char *drvname;
1994 bool protocol = *flags & BDRV_O_PROTOCOL;
1995 bool parse_filename = false;
1996 BlockDriver *drv = NULL;
1997 Error *local_err = NULL;
2000 * Caution: while qdict_get_try_str() is fine, getting non-string
2001 * types would require more care. When @options come from
2002 * -blockdev or blockdev_add, its members are typed according to
2003 * the QAPI schema, but when they come from -drive, they're all
2004 * QString.
2006 drvname = qdict_get_try_str(*options, "driver");
2007 if (drvname) {
2008 drv = bdrv_find_format(drvname);
2009 if (!drv) {
2010 error_setg(errp, "Unknown driver '%s'", drvname);
2011 return -ENOENT;
2013 /* If the user has explicitly specified the driver, this choice should
2014 * override the BDRV_O_PROTOCOL flag */
2015 protocol = drv->bdrv_file_open;
2018 if (protocol) {
2019 *flags |= BDRV_O_PROTOCOL;
2020 } else {
2021 *flags &= ~BDRV_O_PROTOCOL;
2024 /* Translate cache options from flags into options */
2025 update_options_from_flags(*options, *flags);
2027 /* Fetch the file name from the options QDict if necessary */
2028 if (protocol && filename) {
2029 if (!qdict_haskey(*options, "filename")) {
2030 qdict_put_str(*options, "filename", filename);
2031 parse_filename = true;
2032 } else {
2033 error_setg(errp, "Can't specify 'file' and 'filename' options at "
2034 "the same time");
2035 return -EINVAL;
2039 /* Find the right block driver */
2040 /* See cautionary note on accessing @options above */
2041 filename = qdict_get_try_str(*options, "filename");
2043 if (!drvname && protocol) {
2044 if (filename) {
2045 drv = bdrv_find_protocol(filename, parse_filename, errp);
2046 if (!drv) {
2047 return -EINVAL;
2050 drvname = drv->format_name;
2051 qdict_put_str(*options, "driver", drvname);
2052 } else {
2053 error_setg(errp, "Must specify either driver or file");
2054 return -EINVAL;
2058 assert(drv || !protocol);
2060 /* Driver-specific filename parsing */
2061 if (drv && drv->bdrv_parse_filename && parse_filename) {
2062 drv->bdrv_parse_filename(filename, *options, &local_err);
2063 if (local_err) {
2064 error_propagate(errp, local_err);
2065 return -EINVAL;
2068 if (!drv->bdrv_needs_filename) {
2069 qdict_del(*options, "filename");
2073 return 0;
2076 typedef struct BlockReopenQueueEntry {
2077 bool prepared;
2078 bool perms_checked;
2079 BDRVReopenState state;
2080 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2081 } BlockReopenQueueEntry;
2084 * Return the flags that @bs will have after the reopens in @q have
2085 * successfully completed. If @q is NULL (or @bs is not contained in @q),
2086 * return the current flags.
2088 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2090 BlockReopenQueueEntry *entry;
2092 if (q != NULL) {
2093 QTAILQ_FOREACH(entry, q, entry) {
2094 if (entry->state.bs == bs) {
2095 return entry->state.flags;
2100 return bs->open_flags;
2103 /* Returns whether the image file can be written to after the reopen queue @q
2104 * has been successfully applied, or right now if @q is NULL. */
2105 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2106 BlockReopenQueue *q)
2108 int flags = bdrv_reopen_get_flags(q, bs);
2110 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2114 * Return whether the BDS can be written to. This is not necessarily
2115 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2116 * be written to but do not count as read-only images.
2118 bool bdrv_is_writable(BlockDriverState *bs)
2120 IO_CODE();
2121 return bdrv_is_writable_after_reopen(bs, NULL);
2124 static char *bdrv_child_user_desc(BdrvChild *c)
2126 return c->klass->get_parent_desc(c);
2130 * Check that @a allows everything that @b needs. @a and @b must reference same
2131 * child node.
2133 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2135 const char *child_bs_name;
2136 g_autofree char *a_user = NULL;
2137 g_autofree char *b_user = NULL;
2138 g_autofree char *perms = NULL;
2140 assert(a->bs);
2141 assert(a->bs == b->bs);
2142 GLOBAL_STATE_CODE();
2144 if ((b->perm & a->shared_perm) == b->perm) {
2145 return true;
2148 child_bs_name = bdrv_get_node_name(b->bs);
2149 a_user = bdrv_child_user_desc(a);
2150 b_user = bdrv_child_user_desc(b);
2151 perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2153 error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2154 "both required by %s (uses node '%s' as '%s' child) and "
2155 "unshared by %s (uses node '%s' as '%s' child).",
2156 child_bs_name, perms,
2157 b_user, child_bs_name, b->name,
2158 a_user, child_bs_name, a->name);
2160 return false;
2163 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2165 BdrvChild *a, *b;
2166 GLOBAL_STATE_CODE();
2169 * During the loop we'll look at each pair twice. That's correct because
2170 * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2171 * directions.
2173 QLIST_FOREACH(a, &bs->parents, next_parent) {
2174 QLIST_FOREACH(b, &bs->parents, next_parent) {
2175 if (a == b) {
2176 continue;
2179 if (!bdrv_a_allow_b(a, b, errp)) {
2180 return true;
2185 return false;
2188 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2189 BdrvChild *c, BdrvChildRole role,
2190 BlockReopenQueue *reopen_queue,
2191 uint64_t parent_perm, uint64_t parent_shared,
2192 uint64_t *nperm, uint64_t *nshared)
2194 assert(bs->drv && bs->drv->bdrv_child_perm);
2195 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2196 parent_perm, parent_shared,
2197 nperm, nshared);
2198 /* TODO Take force_share from reopen_queue */
2199 if (child_bs && child_bs->force_share) {
2200 *nshared = BLK_PERM_ALL;
2205 * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2206 * nodes that are already in the @list, of course) so that final list is
2207 * topologically sorted. Return the result (GSList @list object is updated, so
2208 * don't use old reference after function call).
2210 * On function start @list must be already topologically sorted and for any node
2211 * in the @list the whole subtree of the node must be in the @list as well. The
2212 * simplest way to satisfy this criteria: use only result of
2213 * bdrv_topological_dfs() or NULL as @list parameter.
2215 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2216 BlockDriverState *bs)
2218 BdrvChild *child;
2219 g_autoptr(GHashTable) local_found = NULL;
2221 GLOBAL_STATE_CODE();
2223 if (!found) {
2224 assert(!list);
2225 found = local_found = g_hash_table_new(NULL, NULL);
2228 if (g_hash_table_contains(found, bs)) {
2229 return list;
2231 g_hash_table_add(found, bs);
2233 QLIST_FOREACH(child, &bs->children, next) {
2234 list = bdrv_topological_dfs(list, found, child->bs);
2237 return g_slist_prepend(list, bs);
2240 typedef struct BdrvChildSetPermState {
2241 BdrvChild *child;
2242 uint64_t old_perm;
2243 uint64_t old_shared_perm;
2244 } BdrvChildSetPermState;
2246 static void bdrv_child_set_perm_abort(void *opaque)
2248 BdrvChildSetPermState *s = opaque;
2250 GLOBAL_STATE_CODE();
2252 s->child->perm = s->old_perm;
2253 s->child->shared_perm = s->old_shared_perm;
2256 static TransactionActionDrv bdrv_child_set_pem_drv = {
2257 .abort = bdrv_child_set_perm_abort,
2258 .clean = g_free,
2261 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2262 uint64_t shared, Transaction *tran)
2264 BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2265 GLOBAL_STATE_CODE();
2267 *s = (BdrvChildSetPermState) {
2268 .child = c,
2269 .old_perm = c->perm,
2270 .old_shared_perm = c->shared_perm,
2273 c->perm = perm;
2274 c->shared_perm = shared;
2276 tran_add(tran, &bdrv_child_set_pem_drv, s);
2279 static void bdrv_drv_set_perm_commit(void *opaque)
2281 BlockDriverState *bs = opaque;
2282 uint64_t cumulative_perms, cumulative_shared_perms;
2284 if (bs->drv->bdrv_set_perm) {
2285 bdrv_get_cumulative_perm(bs, &cumulative_perms,
2286 &cumulative_shared_perms);
2287 bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2291 static void bdrv_drv_set_perm_abort(void *opaque)
2293 BlockDriverState *bs = opaque;
2295 if (bs->drv->bdrv_abort_perm_update) {
2296 bs->drv->bdrv_abort_perm_update(bs);
2300 TransactionActionDrv bdrv_drv_set_perm_drv = {
2301 .abort = bdrv_drv_set_perm_abort,
2302 .commit = bdrv_drv_set_perm_commit,
2305 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2306 uint64_t shared_perm, Transaction *tran,
2307 Error **errp)
2309 if (!bs->drv) {
2310 return 0;
2313 if (bs->drv->bdrv_check_perm) {
2314 int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2315 if (ret < 0) {
2316 return ret;
2320 if (tran) {
2321 tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2324 return 0;
2327 typedef struct BdrvReplaceChildState {
2328 BdrvChild *child;
2329 BdrvChild **childp;
2330 BlockDriverState *old_bs;
2331 bool free_empty_child;
2332 } BdrvReplaceChildState;
2334 static void bdrv_replace_child_commit(void *opaque)
2336 BdrvReplaceChildState *s = opaque;
2337 GLOBAL_STATE_CODE();
2339 if (s->free_empty_child && !s->child->bs) {
2340 bdrv_child_free(s->child);
2342 bdrv_unref(s->old_bs);
2345 static void bdrv_replace_child_abort(void *opaque)
2347 BdrvReplaceChildState *s = opaque;
2348 BlockDriverState *new_bs = s->child->bs;
2350 GLOBAL_STATE_CODE();
2352 * old_bs reference is transparently moved from @s to s->child.
2354 * Pass &s->child here instead of s->childp, because:
2355 * (1) s->old_bs must be non-NULL, so bdrv_replace_child_noperm() will not
2356 * modify the BdrvChild * pointer we indirectly pass to it, i.e. it
2357 * will not modify s->child. From that perspective, it does not matter
2358 * whether we pass s->childp or &s->child.
2359 * (2) If new_bs is not NULL, s->childp will be NULL. We then cannot use
2360 * it here.
2361 * (3) If new_bs is NULL, *s->childp will have been NULLed by
2362 * bdrv_replace_child_tran()'s bdrv_replace_child_noperm() call, and we
2363 * must not pass a NULL *s->childp here.
2365 * So whether new_bs was NULL or not, we cannot pass s->childp here; and in
2366 * any case, there is no reason to pass it anyway.
2368 bdrv_replace_child_noperm(&s->child, s->old_bs, true);
2370 * The child was pre-existing, so s->old_bs must be non-NULL, and
2371 * s->child thus must not have been freed
2373 assert(s->child != NULL);
2374 if (!new_bs) {
2375 /* As described above, *s->childp was cleared, so restore it */
2376 assert(s->childp != NULL);
2377 *s->childp = s->child;
2379 bdrv_unref(new_bs);
2382 static TransactionActionDrv bdrv_replace_child_drv = {
2383 .commit = bdrv_replace_child_commit,
2384 .abort = bdrv_replace_child_abort,
2385 .clean = g_free,
2389 * bdrv_replace_child_tran
2391 * Note: real unref of old_bs is done only on commit.
2393 * The function doesn't update permissions, caller is responsible for this.
2395 * (*childp)->bs must not be NULL.
2397 * Note that if new_bs == NULL, @childp is stored in a state object attached
2398 * to @tran, so that the old child can be reinstated in the abort handler.
2399 * Therefore, if @new_bs can be NULL, @childp must stay valid until the
2400 * transaction is committed or aborted.
2402 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2403 * freed (on commit). @free_empty_child should only be false if the
2404 * caller will free the BDrvChild themselves (which may be important
2405 * if this is in turn called in another transactional context).
2407 static void bdrv_replace_child_tran(BdrvChild **childp,
2408 BlockDriverState *new_bs,
2409 Transaction *tran,
2410 bool free_empty_child)
2412 BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2413 *s = (BdrvReplaceChildState) {
2414 .child = *childp,
2415 .childp = new_bs == NULL ? childp : NULL,
2416 .old_bs = (*childp)->bs,
2417 .free_empty_child = free_empty_child,
2419 tran_add(tran, &bdrv_replace_child_drv, s);
2421 /* The abort handler relies on this */
2422 assert(s->old_bs != NULL);
2424 if (new_bs) {
2425 bdrv_ref(new_bs);
2428 * Pass free_empty_child=false, we will free the child (if
2429 * necessary) in bdrv_replace_child_commit() (if our
2430 * @free_empty_child parameter was true).
2432 bdrv_replace_child_noperm(childp, new_bs, false);
2433 /* old_bs reference is transparently moved from *childp to @s */
2437 * Refresh permissions in @bs subtree. The function is intended to be called
2438 * after some graph modification that was done without permission update.
2440 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2441 Transaction *tran, Error **errp)
2443 BlockDriver *drv = bs->drv;
2444 BdrvChild *c;
2445 int ret;
2446 uint64_t cumulative_perms, cumulative_shared_perms;
2447 GLOBAL_STATE_CODE();
2449 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2451 /* Write permissions never work with read-only images */
2452 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2453 !bdrv_is_writable_after_reopen(bs, q))
2455 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2456 error_setg(errp, "Block node is read-only");
2457 } else {
2458 error_setg(errp, "Read-only block node '%s' cannot support "
2459 "read-write users", bdrv_get_node_name(bs));
2462 return -EPERM;
2466 * Unaligned requests will automatically be aligned to bl.request_alignment
2467 * and without RESIZE we can't extend requests to write to space beyond the
2468 * end of the image, so it's required that the image size is aligned.
2470 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2471 !(cumulative_perms & BLK_PERM_RESIZE))
2473 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2474 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2475 "Image size is not a multiple of request "
2476 "alignment");
2477 return -EPERM;
2481 /* Check this node */
2482 if (!drv) {
2483 return 0;
2486 ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2487 errp);
2488 if (ret < 0) {
2489 return ret;
2492 /* Drivers that never have children can omit .bdrv_child_perm() */
2493 if (!drv->bdrv_child_perm) {
2494 assert(QLIST_EMPTY(&bs->children));
2495 return 0;
2498 /* Check all children */
2499 QLIST_FOREACH(c, &bs->children, next) {
2500 uint64_t cur_perm, cur_shared;
2502 bdrv_child_perm(bs, c->bs, c, c->role, q,
2503 cumulative_perms, cumulative_shared_perms,
2504 &cur_perm, &cur_shared);
2505 bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2508 return 0;
2511 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2512 Transaction *tran, Error **errp)
2514 int ret;
2515 BlockDriverState *bs;
2516 GLOBAL_STATE_CODE();
2518 for ( ; list; list = list->next) {
2519 bs = list->data;
2521 if (bdrv_parent_perms_conflict(bs, errp)) {
2522 return -EINVAL;
2525 ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2526 if (ret < 0) {
2527 return ret;
2531 return 0;
2534 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2535 uint64_t *shared_perm)
2537 BdrvChild *c;
2538 uint64_t cumulative_perms = 0;
2539 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2541 GLOBAL_STATE_CODE();
2543 QLIST_FOREACH(c, &bs->parents, next_parent) {
2544 cumulative_perms |= c->perm;
2545 cumulative_shared_perms &= c->shared_perm;
2548 *perm = cumulative_perms;
2549 *shared_perm = cumulative_shared_perms;
2552 char *bdrv_perm_names(uint64_t perm)
2554 struct perm_name {
2555 uint64_t perm;
2556 const char *name;
2557 } permissions[] = {
2558 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2559 { BLK_PERM_WRITE, "write" },
2560 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2561 { BLK_PERM_RESIZE, "resize" },
2562 { 0, NULL }
2565 GString *result = g_string_sized_new(30);
2566 struct perm_name *p;
2568 for (p = permissions; p->name; p++) {
2569 if (perm & p->perm) {
2570 if (result->len > 0) {
2571 g_string_append(result, ", ");
2573 g_string_append(result, p->name);
2577 return g_string_free(result, FALSE);
2581 static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
2583 int ret;
2584 Transaction *tran = tran_new();
2585 g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2586 GLOBAL_STATE_CODE();
2588 ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2589 tran_finalize(tran, ret);
2591 return ret;
2594 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2595 Error **errp)
2597 Error *local_err = NULL;
2598 Transaction *tran = tran_new();
2599 int ret;
2601 GLOBAL_STATE_CODE();
2603 bdrv_child_set_perm(c, perm, shared, tran);
2605 ret = bdrv_refresh_perms(c->bs, &local_err);
2607 tran_finalize(tran, ret);
2609 if (ret < 0) {
2610 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2611 /* tighten permissions */
2612 error_propagate(errp, local_err);
2613 } else {
2615 * Our caller may intend to only loosen restrictions and
2616 * does not expect this function to fail. Errors are not
2617 * fatal in such a case, so we can just hide them from our
2618 * caller.
2620 error_free(local_err);
2621 ret = 0;
2625 return ret;
2628 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2630 uint64_t parent_perms, parent_shared;
2631 uint64_t perms, shared;
2633 GLOBAL_STATE_CODE();
2635 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2636 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2637 parent_perms, parent_shared, &perms, &shared);
2639 return bdrv_child_try_set_perm(c, perms, shared, errp);
2643 * Default implementation for .bdrv_child_perm() for block filters:
2644 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2645 * filtered child.
2647 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2648 BdrvChildRole role,
2649 BlockReopenQueue *reopen_queue,
2650 uint64_t perm, uint64_t shared,
2651 uint64_t *nperm, uint64_t *nshared)
2653 GLOBAL_STATE_CODE();
2654 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2655 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2658 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2659 BdrvChildRole role,
2660 BlockReopenQueue *reopen_queue,
2661 uint64_t perm, uint64_t shared,
2662 uint64_t *nperm, uint64_t *nshared)
2664 assert(role & BDRV_CHILD_COW);
2665 GLOBAL_STATE_CODE();
2668 * We want consistent read from backing files if the parent needs it.
2669 * No other operations are performed on backing files.
2671 perm &= BLK_PERM_CONSISTENT_READ;
2674 * If the parent can deal with changing data, we're okay with a
2675 * writable and resizable backing file.
2676 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2678 if (shared & BLK_PERM_WRITE) {
2679 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2680 } else {
2681 shared = 0;
2684 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2686 if (bs->open_flags & BDRV_O_INACTIVE) {
2687 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2690 *nperm = perm;
2691 *nshared = shared;
2694 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2695 BdrvChildRole role,
2696 BlockReopenQueue *reopen_queue,
2697 uint64_t perm, uint64_t shared,
2698 uint64_t *nperm, uint64_t *nshared)
2700 int flags;
2702 GLOBAL_STATE_CODE();
2703 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2705 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2708 * Apart from the modifications below, the same permissions are
2709 * forwarded and left alone as for filters
2711 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2712 perm, shared, &perm, &shared);
2714 if (role & BDRV_CHILD_METADATA) {
2715 /* Format drivers may touch metadata even if the guest doesn't write */
2716 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2717 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2721 * bs->file always needs to be consistent because of the
2722 * metadata. We can never allow other users to resize or write
2723 * to it.
2725 if (!(flags & BDRV_O_NO_IO)) {
2726 perm |= BLK_PERM_CONSISTENT_READ;
2728 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2731 if (role & BDRV_CHILD_DATA) {
2733 * Technically, everything in this block is a subset of the
2734 * BDRV_CHILD_METADATA path taken above, and so this could
2735 * be an "else if" branch. However, that is not obvious, and
2736 * this function is not performance critical, therefore we let
2737 * this be an independent "if".
2741 * We cannot allow other users to resize the file because the
2742 * format driver might have some assumptions about the size
2743 * (e.g. because it is stored in metadata, or because the file
2744 * is split into fixed-size data files).
2746 shared &= ~BLK_PERM_RESIZE;
2749 * WRITE_UNCHANGED often cannot be performed as such on the
2750 * data file. For example, the qcow2 driver may still need to
2751 * write copied clusters on copy-on-read.
2753 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2754 perm |= BLK_PERM_WRITE;
2758 * If the data file is written to, the format driver may
2759 * expect to be able to resize it by writing beyond the EOF.
2761 if (perm & BLK_PERM_WRITE) {
2762 perm |= BLK_PERM_RESIZE;
2766 if (bs->open_flags & BDRV_O_INACTIVE) {
2767 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2770 *nperm = perm;
2771 *nshared = shared;
2774 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2775 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2776 uint64_t perm, uint64_t shared,
2777 uint64_t *nperm, uint64_t *nshared)
2779 GLOBAL_STATE_CODE();
2780 if (role & BDRV_CHILD_FILTERED) {
2781 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2782 BDRV_CHILD_COW)));
2783 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2784 perm, shared, nperm, nshared);
2785 } else if (role & BDRV_CHILD_COW) {
2786 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2787 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2788 perm, shared, nperm, nshared);
2789 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2790 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2791 perm, shared, nperm, nshared);
2792 } else {
2793 g_assert_not_reached();
2797 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2799 static const uint64_t permissions[] = {
2800 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2801 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2802 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2803 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2806 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2807 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2809 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2811 return permissions[qapi_perm];
2815 * Replace (*childp)->bs by @new_bs.
2817 * If @new_bs is NULL, *childp will be set to NULL, too: BDS parents
2818 * generally cannot handle a BdrvChild with .bs == NULL, so clearing
2819 * BdrvChild.bs should generally immediately be followed by the
2820 * BdrvChild pointer being cleared as well.
2822 * If @free_empty_child is true and @new_bs is NULL, the BdrvChild is
2823 * freed. @free_empty_child should only be false if the caller will
2824 * free the BdrvChild themselves (this may be important in a
2825 * transactional context, where it may only be freed on commit).
2827 static void bdrv_replace_child_noperm(BdrvChild **childp,
2828 BlockDriverState *new_bs,
2829 bool free_empty_child)
2831 BdrvChild *child = *childp;
2832 BlockDriverState *old_bs = child->bs;
2833 int new_bs_quiesce_counter;
2834 int drain_saldo;
2836 assert(!child->frozen);
2837 assert(old_bs != new_bs);
2839 if (old_bs && new_bs) {
2840 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2843 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2844 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2847 * If the new child node is drained but the old one was not, flush
2848 * all outstanding requests to the old child node.
2850 while (drain_saldo > 0 && child->klass->drained_begin) {
2851 bdrv_parent_drained_begin_single(child, true);
2852 drain_saldo--;
2855 if (old_bs) {
2856 /* Detach first so that the recursive drain sections coming from @child
2857 * are already gone and we only end the drain sections that came from
2858 * elsewhere. */
2859 if (child->klass->detach) {
2860 child->klass->detach(child);
2862 assert_bdrv_graph_writable(old_bs);
2863 QLIST_REMOVE(child, next_parent);
2866 child->bs = new_bs;
2867 if (!new_bs) {
2868 *childp = NULL;
2871 if (new_bs) {
2872 assert_bdrv_graph_writable(new_bs);
2873 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2876 * Detaching the old node may have led to the new node's
2877 * quiesce_counter having been decreased. Not a problem, we
2878 * just need to recognize this here and then invoke
2879 * drained_end appropriately more often.
2881 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2882 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2884 /* Attach only after starting new drained sections, so that recursive
2885 * drain sections coming from @child don't get an extra .drained_begin
2886 * callback. */
2887 if (child->klass->attach) {
2888 child->klass->attach(child);
2893 * If the old child node was drained but the new one is not, allow
2894 * requests to come in only after the new node has been attached.
2896 while (drain_saldo < 0 && child->klass->drained_end) {
2897 bdrv_parent_drained_end_single(child);
2898 drain_saldo++;
2901 if (free_empty_child && !child->bs) {
2902 bdrv_child_free(child);
2907 * Free the given @child.
2909 * The child must be empty (i.e. `child->bs == NULL`) and it must be
2910 * unused (i.e. not in a children list).
2912 static void bdrv_child_free(BdrvChild *child)
2914 assert(!child->bs);
2915 GLOBAL_STATE_CODE();
2916 assert(!child->next.le_prev); /* not in children list */
2918 g_free(child->name);
2919 g_free(child);
2922 typedef struct BdrvAttachChildCommonState {
2923 BdrvChild **child;
2924 AioContext *old_parent_ctx;
2925 AioContext *old_child_ctx;
2926 } BdrvAttachChildCommonState;
2928 static void bdrv_attach_child_common_abort(void *opaque)
2930 BdrvAttachChildCommonState *s = opaque;
2931 BdrvChild *child = *s->child;
2932 BlockDriverState *bs = child->bs;
2935 * Pass free_empty_child=false, because we still need the child
2936 * for the AioContext operations on the parent below; those
2937 * BdrvChildClass methods all work on a BdrvChild object, so we
2938 * need to keep it as an empty shell (after this function, it will
2939 * not be attached to any parent, and it will not have a .bs).
2941 bdrv_replace_child_noperm(s->child, NULL, false);
2943 if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2944 bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2947 if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2948 GSList *ignore;
2950 /* No need to ignore `child`, because it has been detached already */
2951 ignore = NULL;
2952 child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2953 &error_abort);
2954 g_slist_free(ignore);
2956 ignore = NULL;
2957 child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2958 g_slist_free(ignore);
2961 bdrv_unref(bs);
2962 bdrv_child_free(child);
2965 static TransactionActionDrv bdrv_attach_child_common_drv = {
2966 .abort = bdrv_attach_child_common_abort,
2967 .clean = g_free,
2971 * Common part of attaching bdrv child to bs or to blk or to job
2973 * Resulting new child is returned through @child.
2974 * At start *@child must be NULL.
2975 * @child is saved to a new entry of @tran, so that *@child could be reverted to
2976 * NULL on abort(). So referenced variable must live at least until transaction
2977 * end.
2979 * Function doesn't update permissions, caller is responsible for this.
2981 static int bdrv_attach_child_common(BlockDriverState *child_bs,
2982 const char *child_name,
2983 const BdrvChildClass *child_class,
2984 BdrvChildRole child_role,
2985 uint64_t perm, uint64_t shared_perm,
2986 void *opaque, BdrvChild **child,
2987 Transaction *tran, Error **errp)
2989 BdrvChild *new_child;
2990 AioContext *parent_ctx;
2991 AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2993 assert(child);
2994 assert(*child == NULL);
2995 assert(child_class->get_parent_desc);
2996 GLOBAL_STATE_CODE();
2998 new_child = g_new(BdrvChild, 1);
2999 *new_child = (BdrvChild) {
3000 .bs = NULL,
3001 .name = g_strdup(child_name),
3002 .klass = child_class,
3003 .role = child_role,
3004 .perm = perm,
3005 .shared_perm = shared_perm,
3006 .opaque = opaque,
3010 * If the AioContexts don't match, first try to move the subtree of
3011 * child_bs into the AioContext of the new parent. If this doesn't work,
3012 * try moving the parent into the AioContext of child_bs instead.
3014 parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3015 if (child_ctx != parent_ctx) {
3016 Error *local_err = NULL;
3017 int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
3019 if (ret < 0 && child_class->can_set_aio_ctx) {
3020 GSList *ignore = g_slist_prepend(NULL, new_child);
3021 if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
3022 NULL))
3024 error_free(local_err);
3025 ret = 0;
3026 g_slist_free(ignore);
3027 ignore = g_slist_prepend(NULL, new_child);
3028 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
3030 g_slist_free(ignore);
3033 if (ret < 0) {
3034 error_propagate(errp, local_err);
3035 bdrv_child_free(new_child);
3036 return ret;
3040 bdrv_ref(child_bs);
3041 bdrv_replace_child_noperm(&new_child, child_bs, true);
3042 /* child_bs was non-NULL, so new_child must not have been freed */
3043 assert(new_child != NULL);
3045 *child = new_child;
3047 BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3048 *s = (BdrvAttachChildCommonState) {
3049 .child = child,
3050 .old_parent_ctx = parent_ctx,
3051 .old_child_ctx = child_ctx,
3053 tran_add(tran, &bdrv_attach_child_common_drv, s);
3055 return 0;
3059 * Variable referenced by @child must live at least until transaction end.
3060 * (see bdrv_attach_child_common() doc for details)
3062 * Function doesn't update permissions, caller is responsible for this.
3064 static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3065 BlockDriverState *child_bs,
3066 const char *child_name,
3067 const BdrvChildClass *child_class,
3068 BdrvChildRole child_role,
3069 BdrvChild **child,
3070 Transaction *tran,
3071 Error **errp)
3073 int ret;
3074 uint64_t perm, shared_perm;
3076 assert(parent_bs->drv);
3077 GLOBAL_STATE_CODE();
3079 if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3080 error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3081 child_bs->node_name, child_name, parent_bs->node_name);
3082 return -EINVAL;
3085 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3086 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3087 perm, shared_perm, &perm, &shared_perm);
3089 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3090 child_role, perm, shared_perm, parent_bs,
3091 child, tran, errp);
3092 if (ret < 0) {
3093 return ret;
3096 return 0;
3099 static void bdrv_detach_child(BdrvChild **childp)
3101 BlockDriverState *old_bs = (*childp)->bs;
3103 GLOBAL_STATE_CODE();
3104 bdrv_replace_child_noperm(childp, NULL, true);
3106 if (old_bs) {
3108 * Update permissions for old node. We're just taking a parent away, so
3109 * we're loosening restrictions. Errors of permission update are not
3110 * fatal in this case, ignore them.
3112 bdrv_refresh_perms(old_bs, NULL);
3115 * When the parent requiring a non-default AioContext is removed, the
3116 * node moves back to the main AioContext
3118 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3123 * This function steals the reference to child_bs from the caller.
3124 * That reference is later dropped by bdrv_root_unref_child().
3126 * On failure NULL is returned, errp is set and the reference to
3127 * child_bs is also dropped.
3129 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3130 * (unless @child_bs is already in @ctx).
3132 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3133 const char *child_name,
3134 const BdrvChildClass *child_class,
3135 BdrvChildRole child_role,
3136 uint64_t perm, uint64_t shared_perm,
3137 void *opaque, Error **errp)
3139 int ret;
3140 BdrvChild *child = NULL;
3141 Transaction *tran = tran_new();
3143 GLOBAL_STATE_CODE();
3145 ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3146 child_role, perm, shared_perm, opaque,
3147 &child, tran, errp);
3148 if (ret < 0) {
3149 goto out;
3152 ret = bdrv_refresh_perms(child_bs, errp);
3154 out:
3155 tran_finalize(tran, ret);
3156 /* child is unset on failure by bdrv_attach_child_common_abort() */
3157 assert((ret < 0) == !child);
3159 bdrv_unref(child_bs);
3160 return child;
3164 * This function transfers the reference to child_bs from the caller
3165 * to parent_bs. That reference is later dropped by parent_bs on
3166 * bdrv_close() or if someone calls bdrv_unref_child().
3168 * On failure NULL is returned, errp is set and the reference to
3169 * child_bs is also dropped.
3171 * If @parent_bs and @child_bs are in different AioContexts, the caller must
3172 * hold the AioContext lock for @child_bs, but not for @parent_bs.
3174 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3175 BlockDriverState *child_bs,
3176 const char *child_name,
3177 const BdrvChildClass *child_class,
3178 BdrvChildRole child_role,
3179 Error **errp)
3181 int ret;
3182 BdrvChild *child = NULL;
3183 Transaction *tran = tran_new();
3185 GLOBAL_STATE_CODE();
3187 ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3188 child_role, &child, tran, errp);
3189 if (ret < 0) {
3190 goto out;
3193 ret = bdrv_refresh_perms(parent_bs, errp);
3194 if (ret < 0) {
3195 goto out;
3198 out:
3199 tran_finalize(tran, ret);
3200 /* child is unset on failure by bdrv_attach_child_common_abort() */
3201 assert((ret < 0) == !child);
3203 bdrv_unref(child_bs);
3205 return child;
3208 /* Callers must ensure that child->frozen is false. */
3209 void bdrv_root_unref_child(BdrvChild *child)
3211 BlockDriverState *child_bs;
3213 GLOBAL_STATE_CODE();
3215 child_bs = child->bs;
3216 bdrv_detach_child(&child);
3217 bdrv_unref(child_bs);
3220 typedef struct BdrvSetInheritsFrom {
3221 BlockDriverState *bs;
3222 BlockDriverState *old_inherits_from;
3223 } BdrvSetInheritsFrom;
3225 static void bdrv_set_inherits_from_abort(void *opaque)
3227 BdrvSetInheritsFrom *s = opaque;
3229 s->bs->inherits_from = s->old_inherits_from;
3232 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3233 .abort = bdrv_set_inherits_from_abort,
3234 .clean = g_free,
3237 /* @tran is allowed to be NULL. In this case no rollback is possible */
3238 static void bdrv_set_inherits_from(BlockDriverState *bs,
3239 BlockDriverState *new_inherits_from,
3240 Transaction *tran)
3242 if (tran) {
3243 BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3245 *s = (BdrvSetInheritsFrom) {
3246 .bs = bs,
3247 .old_inherits_from = bs->inherits_from,
3250 tran_add(tran, &bdrv_set_inherits_from_drv, s);
3253 bs->inherits_from = new_inherits_from;
3257 * Clear all inherits_from pointers from children and grandchildren of
3258 * @root that point to @root, where necessary.
3259 * @tran is allowed to be NULL. In this case no rollback is possible
3261 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3262 Transaction *tran)
3264 BdrvChild *c;
3266 if (child->bs->inherits_from == root) {
3268 * Remove inherits_from only when the last reference between root and
3269 * child->bs goes away.
3271 QLIST_FOREACH(c, &root->children, next) {
3272 if (c != child && c->bs == child->bs) {
3273 break;
3276 if (c == NULL) {
3277 bdrv_set_inherits_from(child->bs, NULL, tran);
3281 QLIST_FOREACH(c, &child->bs->children, next) {
3282 bdrv_unset_inherits_from(root, c, tran);
3286 /* Callers must ensure that child->frozen is false. */
3287 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3289 GLOBAL_STATE_CODE();
3290 if (child == NULL) {
3291 return;
3294 bdrv_unset_inherits_from(parent, child, NULL);
3295 bdrv_root_unref_child(child);
3299 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3301 BdrvChild *c;
3302 QLIST_FOREACH(c, &bs->parents, next_parent) {
3303 if (c->klass->change_media) {
3304 c->klass->change_media(c, load);
3309 /* Return true if you can reach parent going through child->inherits_from
3310 * recursively. If parent or child are NULL, return false */
3311 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3312 BlockDriverState *parent)
3314 while (child && child != parent) {
3315 child = child->inherits_from;
3318 return child != NULL;
3322 * Return the BdrvChildRole for @bs's backing child. bs->backing is
3323 * mostly used for COW backing children (role = COW), but also for
3324 * filtered children (role = FILTERED | PRIMARY).
3326 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3328 if (bs->drv && bs->drv->is_filter) {
3329 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3330 } else {
3331 return BDRV_CHILD_COW;
3336 * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3337 * callers which don't need their own reference any more must call bdrv_unref().
3339 * Function doesn't update permissions, caller is responsible for this.
3341 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3342 BlockDriverState *child_bs,
3343 bool is_backing,
3344 Transaction *tran, Error **errp)
3346 int ret = 0;
3347 bool update_inherits_from =
3348 bdrv_inherits_from_recursive(child_bs, parent_bs);
3349 BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3350 BdrvChildRole role;
3352 GLOBAL_STATE_CODE();
3354 if (!parent_bs->drv) {
3356 * Node without drv is an object without a class :/. TODO: finally fix
3357 * qcow2 driver to never clear bs->drv and implement format corruption
3358 * handling in other way.
3360 error_setg(errp, "Node corrupted");
3361 return -EINVAL;
3364 if (child && child->frozen) {
3365 error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3366 child->name, parent_bs->node_name, child->bs->node_name);
3367 return -EPERM;
3370 if (is_backing && !parent_bs->drv->is_filter &&
3371 !parent_bs->drv->supports_backing)
3373 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3374 "files", parent_bs->drv->format_name, parent_bs->node_name);
3375 return -EINVAL;
3378 if (parent_bs->drv->is_filter) {
3379 role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3380 } else if (is_backing) {
3381 role = BDRV_CHILD_COW;
3382 } else {
3384 * We only can use same role as it is in existing child. We don't have
3385 * infrastructure to determine role of file child in generic way
3387 if (!child) {
3388 error_setg(errp, "Cannot set file child to format node without "
3389 "file child");
3390 return -EINVAL;
3392 role = child->role;
3395 if (child) {
3396 bdrv_unset_inherits_from(parent_bs, child, tran);
3397 bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3400 if (!child_bs) {
3401 goto out;
3404 ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3405 is_backing ? "backing" : "file",
3406 &child_of_bds, role,
3407 is_backing ? &parent_bs->backing :
3408 &parent_bs->file,
3409 tran, errp);
3410 if (ret < 0) {
3411 return ret;
3416 * If inherits_from pointed recursively to bs then let's update it to
3417 * point directly to bs (else it will become NULL).
3419 if (update_inherits_from) {
3420 bdrv_set_inherits_from(child_bs, parent_bs, tran);
3423 out:
3424 bdrv_refresh_limits(parent_bs, tran, NULL);
3426 return 0;
3429 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3430 BlockDriverState *backing_hd,
3431 Transaction *tran, Error **errp)
3433 GLOBAL_STATE_CODE();
3434 return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3437 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3438 Error **errp)
3440 int ret;
3441 Transaction *tran = tran_new();
3443 GLOBAL_STATE_CODE();
3444 bdrv_drained_begin(bs);
3446 ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3447 if (ret < 0) {
3448 goto out;
3451 ret = bdrv_refresh_perms(bs, errp);
3452 out:
3453 tran_finalize(tran, ret);
3455 bdrv_drained_end(bs);
3457 return ret;
3461 * Opens the backing file for a BlockDriverState if not yet open
3463 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3464 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3465 * itself, all options starting with "${bdref_key}." are considered part of the
3466 * BlockdevRef.
3468 * TODO Can this be unified with bdrv_open_image()?
3470 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3471 const char *bdref_key, Error **errp)
3473 char *backing_filename = NULL;
3474 char *bdref_key_dot;
3475 const char *reference = NULL;
3476 int ret = 0;
3477 bool implicit_backing = false;
3478 BlockDriverState *backing_hd;
3479 QDict *options;
3480 QDict *tmp_parent_options = NULL;
3481 Error *local_err = NULL;
3483 GLOBAL_STATE_CODE();
3485 if (bs->backing != NULL) {
3486 goto free_exit;
3489 /* NULL means an empty set of options */
3490 if (parent_options == NULL) {
3491 tmp_parent_options = qdict_new();
3492 parent_options = tmp_parent_options;
3495 bs->open_flags &= ~BDRV_O_NO_BACKING;
3497 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3498 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3499 g_free(bdref_key_dot);
3502 * Caution: while qdict_get_try_str() is fine, getting non-string
3503 * types would require more care. When @parent_options come from
3504 * -blockdev or blockdev_add, its members are typed according to
3505 * the QAPI schema, but when they come from -drive, they're all
3506 * QString.
3508 reference = qdict_get_try_str(parent_options, bdref_key);
3509 if (reference || qdict_haskey(options, "file.filename")) {
3510 /* keep backing_filename NULL */
3511 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3512 qobject_unref(options);
3513 goto free_exit;
3514 } else {
3515 if (qdict_size(options) == 0) {
3516 /* If the user specifies options that do not modify the
3517 * backing file's behavior, we might still consider it the
3518 * implicit backing file. But it's easier this way, and
3519 * just specifying some of the backing BDS's options is
3520 * only possible with -drive anyway (otherwise the QAPI
3521 * schema forces the user to specify everything). */
3522 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3525 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3526 if (local_err) {
3527 ret = -EINVAL;
3528 error_propagate(errp, local_err);
3529 qobject_unref(options);
3530 goto free_exit;
3534 if (!bs->drv || !bs->drv->supports_backing) {
3535 ret = -EINVAL;
3536 error_setg(errp, "Driver doesn't support backing files");
3537 qobject_unref(options);
3538 goto free_exit;
3541 if (!reference &&
3542 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3543 qdict_put_str(options, "driver", bs->backing_format);
3546 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3547 &child_of_bds, bdrv_backing_role(bs), errp);
3548 if (!backing_hd) {
3549 bs->open_flags |= BDRV_O_NO_BACKING;
3550 error_prepend(errp, "Could not open backing file: ");
3551 ret = -EINVAL;
3552 goto free_exit;
3555 if (implicit_backing) {
3556 bdrv_refresh_filename(backing_hd);
3557 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3558 backing_hd->filename);
3561 /* Hook up the backing file link; drop our reference, bs owns the
3562 * backing_hd reference now */
3563 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3564 bdrv_unref(backing_hd);
3565 if (ret < 0) {
3566 goto free_exit;
3569 qdict_del(parent_options, bdref_key);
3571 free_exit:
3572 g_free(backing_filename);
3573 qobject_unref(tmp_parent_options);
3574 return ret;
3577 static BlockDriverState *
3578 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3579 BlockDriverState *parent, const BdrvChildClass *child_class,
3580 BdrvChildRole child_role, bool allow_none, Error **errp)
3582 BlockDriverState *bs = NULL;
3583 QDict *image_options;
3584 char *bdref_key_dot;
3585 const char *reference;
3587 assert(child_class != NULL);
3589 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3590 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3591 g_free(bdref_key_dot);
3594 * Caution: while qdict_get_try_str() is fine, getting non-string
3595 * types would require more care. When @options come from
3596 * -blockdev or blockdev_add, its members are typed according to
3597 * the QAPI schema, but when they come from -drive, they're all
3598 * QString.
3600 reference = qdict_get_try_str(options, bdref_key);
3601 if (!filename && !reference && !qdict_size(image_options)) {
3602 if (!allow_none) {
3603 error_setg(errp, "A block device must be specified for \"%s\"",
3604 bdref_key);
3606 qobject_unref(image_options);
3607 goto done;
3610 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3611 parent, child_class, child_role, errp);
3612 if (!bs) {
3613 goto done;
3616 done:
3617 qdict_del(options, bdref_key);
3618 return bs;
3622 * Opens a disk image whose options are given as BlockdevRef in another block
3623 * device's options.
3625 * If allow_none is true, no image will be opened if filename is false and no
3626 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3628 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3629 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3630 * itself, all options starting with "${bdref_key}." are considered part of the
3631 * BlockdevRef.
3633 * The BlockdevRef will be removed from the options QDict.
3635 BdrvChild *bdrv_open_child(const char *filename,
3636 QDict *options, const char *bdref_key,
3637 BlockDriverState *parent,
3638 const BdrvChildClass *child_class,
3639 BdrvChildRole child_role,
3640 bool allow_none, Error **errp)
3642 BlockDriverState *bs;
3644 GLOBAL_STATE_CODE();
3646 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3647 child_role, allow_none, errp);
3648 if (bs == NULL) {
3649 return NULL;
3652 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3653 errp);
3657 * TODO Future callers may need to specify parent/child_class in order for
3658 * option inheritance to work. Existing callers use it for the root node.
3660 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3662 BlockDriverState *bs = NULL;
3663 QObject *obj = NULL;
3664 QDict *qdict = NULL;
3665 const char *reference = NULL;
3666 Visitor *v = NULL;
3668 GLOBAL_STATE_CODE();
3670 if (ref->type == QTYPE_QSTRING) {
3671 reference = ref->u.reference;
3672 } else {
3673 BlockdevOptions *options = &ref->u.definition;
3674 assert(ref->type == QTYPE_QDICT);
3676 v = qobject_output_visitor_new(&obj);
3677 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3678 visit_complete(v, &obj);
3680 qdict = qobject_to(QDict, obj);
3681 qdict_flatten(qdict);
3683 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3684 * compatibility with other callers) rather than what we want as the
3685 * real defaults. Apply the defaults here instead. */
3686 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3687 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3688 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3689 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3693 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3694 obj = NULL;
3695 qobject_unref(obj);
3696 visit_free(v);
3697 return bs;
3700 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3701 int flags,
3702 QDict *snapshot_options,
3703 Error **errp)
3705 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3706 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3707 int64_t total_size;
3708 QemuOpts *opts = NULL;
3709 BlockDriverState *bs_snapshot = NULL;
3710 int ret;
3712 GLOBAL_STATE_CODE();
3714 /* if snapshot, we create a temporary backing file and open it
3715 instead of opening 'filename' directly */
3717 /* Get the required size from the image */
3718 total_size = bdrv_getlength(bs);
3719 if (total_size < 0) {
3720 error_setg_errno(errp, -total_size, "Could not get image size");
3721 goto out;
3724 /* Create the temporary image */
3725 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3726 if (ret < 0) {
3727 error_setg_errno(errp, -ret, "Could not get temporary filename");
3728 goto out;
3731 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3732 &error_abort);
3733 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3734 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3735 qemu_opts_del(opts);
3736 if (ret < 0) {
3737 error_prepend(errp, "Could not create temporary overlay '%s': ",
3738 tmp_filename);
3739 goto out;
3742 /* Prepare options QDict for the temporary file */
3743 qdict_put_str(snapshot_options, "file.driver", "file");
3744 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3745 qdict_put_str(snapshot_options, "driver", "qcow2");
3747 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3748 snapshot_options = NULL;
3749 if (!bs_snapshot) {
3750 goto out;
3753 ret = bdrv_append(bs_snapshot, bs, errp);
3754 if (ret < 0) {
3755 bs_snapshot = NULL;
3756 goto out;
3759 out:
3760 qobject_unref(snapshot_options);
3761 g_free(tmp_filename);
3762 return bs_snapshot;
3766 * Opens a disk image (raw, qcow2, vmdk, ...)
3768 * options is a QDict of options to pass to the block drivers, or NULL for an
3769 * empty set of options. The reference to the QDict belongs to the block layer
3770 * after the call (even on failure), so if the caller intends to reuse the
3771 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3773 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3774 * If it is not NULL, the referenced BDS will be reused.
3776 * The reference parameter may be used to specify an existing block device which
3777 * should be opened. If specified, neither options nor a filename may be given,
3778 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3780 static BlockDriverState *bdrv_open_inherit(const char *filename,
3781 const char *reference,
3782 QDict *options, int flags,
3783 BlockDriverState *parent,
3784 const BdrvChildClass *child_class,
3785 BdrvChildRole child_role,
3786 Error **errp)
3788 int ret;
3789 BlockBackend *file = NULL;
3790 BlockDriverState *bs;
3791 BlockDriver *drv = NULL;
3792 BdrvChild *child;
3793 const char *drvname;
3794 const char *backing;
3795 Error *local_err = NULL;
3796 QDict *snapshot_options = NULL;
3797 int snapshot_flags = 0;
3799 assert(!child_class || !flags);
3800 assert(!child_class == !parent);
3802 if (reference) {
3803 bool options_non_empty = options ? qdict_size(options) : false;
3804 qobject_unref(options);
3806 if (filename || options_non_empty) {
3807 error_setg(errp, "Cannot reference an existing block device with "
3808 "additional options or a new filename");
3809 return NULL;
3812 bs = bdrv_lookup_bs(reference, reference, errp);
3813 if (!bs) {
3814 return NULL;
3817 bdrv_ref(bs);
3818 return bs;
3821 bs = bdrv_new();
3823 /* NULL means an empty set of options */
3824 if (options == NULL) {
3825 options = qdict_new();
3828 /* json: syntax counts as explicit options, as if in the QDict */
3829 parse_json_protocol(options, &filename, &local_err);
3830 if (local_err) {
3831 goto fail;
3834 bs->explicit_options = qdict_clone_shallow(options);
3836 if (child_class) {
3837 bool parent_is_format;
3839 if (parent->drv) {
3840 parent_is_format = parent->drv->is_format;
3841 } else {
3843 * parent->drv is not set yet because this node is opened for
3844 * (potential) format probing. That means that @parent is going
3845 * to be a format node.
3847 parent_is_format = true;
3850 bs->inherits_from = parent;
3851 child_class->inherit_options(child_role, parent_is_format,
3852 &flags, options,
3853 parent->open_flags, parent->options);
3856 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3857 if (ret < 0) {
3858 goto fail;
3862 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3863 * Caution: getting a boolean member of @options requires care.
3864 * When @options come from -blockdev or blockdev_add, members are
3865 * typed according to the QAPI schema, but when they come from
3866 * -drive, they're all QString.
3868 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3869 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3870 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3871 } else {
3872 flags &= ~BDRV_O_RDWR;
3875 if (flags & BDRV_O_SNAPSHOT) {
3876 snapshot_options = qdict_new();
3877 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3878 flags, options);
3879 /* Let bdrv_backing_options() override "read-only" */
3880 qdict_del(options, BDRV_OPT_READ_ONLY);
3881 bdrv_inherited_options(BDRV_CHILD_COW, true,
3882 &flags, options, flags, options);
3885 bs->open_flags = flags;
3886 bs->options = options;
3887 options = qdict_clone_shallow(options);
3889 /* Find the right image format driver */
3890 /* See cautionary note on accessing @options above */
3891 drvname = qdict_get_try_str(options, "driver");
3892 if (drvname) {
3893 drv = bdrv_find_format(drvname);
3894 if (!drv) {
3895 error_setg(errp, "Unknown driver: '%s'", drvname);
3896 goto fail;
3900 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3902 /* See cautionary note on accessing @options above */
3903 backing = qdict_get_try_str(options, "backing");
3904 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3905 (backing && *backing == '\0'))
3907 if (backing) {
3908 warn_report("Use of \"backing\": \"\" is deprecated; "
3909 "use \"backing\": null instead");
3911 flags |= BDRV_O_NO_BACKING;
3912 qdict_del(bs->explicit_options, "backing");
3913 qdict_del(bs->options, "backing");
3914 qdict_del(options, "backing");
3917 /* Open image file without format layer. This BlockBackend is only used for
3918 * probing, the block drivers will do their own bdrv_open_child() for the
3919 * same BDS, which is why we put the node name back into options. */
3920 if ((flags & BDRV_O_PROTOCOL) == 0) {
3921 BlockDriverState *file_bs;
3923 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3924 &child_of_bds, BDRV_CHILD_IMAGE,
3925 true, &local_err);
3926 if (local_err) {
3927 goto fail;
3929 if (file_bs != NULL) {
3930 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3931 * looking at the header to guess the image format. This works even
3932 * in cases where a guest would not see a consistent state. */
3933 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3934 blk_insert_bs(file, file_bs, &local_err);
3935 bdrv_unref(file_bs);
3936 if (local_err) {
3937 goto fail;
3940 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3944 /* Image format probing */
3945 bs->probed = !drv;
3946 if (!drv && file) {
3947 ret = find_image_format(file, filename, &drv, &local_err);
3948 if (ret < 0) {
3949 goto fail;
3952 * This option update would logically belong in bdrv_fill_options(),
3953 * but we first need to open bs->file for the probing to work, while
3954 * opening bs->file already requires the (mostly) final set of options
3955 * so that cache mode etc. can be inherited.
3957 * Adding the driver later is somewhat ugly, but it's not an option
3958 * that would ever be inherited, so it's correct. We just need to make
3959 * sure to update both bs->options (which has the full effective
3960 * options for bs) and options (which has file.* already removed).
3962 qdict_put_str(bs->options, "driver", drv->format_name);
3963 qdict_put_str(options, "driver", drv->format_name);
3964 } else if (!drv) {
3965 error_setg(errp, "Must specify either driver or file");
3966 goto fail;
3969 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3970 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3971 /* file must be NULL if a protocol BDS is about to be created
3972 * (the inverse results in an error message from bdrv_open_common()) */
3973 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3975 /* Open the image */
3976 ret = bdrv_open_common(bs, file, options, &local_err);
3977 if (ret < 0) {
3978 goto fail;
3981 if (file) {
3982 blk_unref(file);
3983 file = NULL;
3986 /* If there is a backing file, use it */
3987 if ((flags & BDRV_O_NO_BACKING) == 0) {
3988 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3989 if (ret < 0) {
3990 goto close_and_fail;
3994 /* Remove all children options and references
3995 * from bs->options and bs->explicit_options */
3996 QLIST_FOREACH(child, &bs->children, next) {
3997 char *child_key_dot;
3998 child_key_dot = g_strdup_printf("%s.", child->name);
3999 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4000 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4001 qdict_del(bs->explicit_options, child->name);
4002 qdict_del(bs->options, child->name);
4003 g_free(child_key_dot);
4006 /* Check if any unknown options were used */
4007 if (qdict_size(options) != 0) {
4008 const QDictEntry *entry = qdict_first(options);
4009 if (flags & BDRV_O_PROTOCOL) {
4010 error_setg(errp, "Block protocol '%s' doesn't support the option "
4011 "'%s'", drv->format_name, entry->key);
4012 } else {
4013 error_setg(errp,
4014 "Block format '%s' does not support the option '%s'",
4015 drv->format_name, entry->key);
4018 goto close_and_fail;
4021 bdrv_parent_cb_change_media(bs, true);
4023 qobject_unref(options);
4024 options = NULL;
4026 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4027 * temporary snapshot afterwards. */
4028 if (snapshot_flags) {
4029 BlockDriverState *snapshot_bs;
4030 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4031 snapshot_options, &local_err);
4032 snapshot_options = NULL;
4033 if (local_err) {
4034 goto close_and_fail;
4036 /* We are not going to return bs but the overlay on top of it
4037 * (snapshot_bs); thus, we have to drop the strong reference to bs
4038 * (which we obtained by calling bdrv_new()). bs will not be deleted,
4039 * though, because the overlay still has a reference to it. */
4040 bdrv_unref(bs);
4041 bs = snapshot_bs;
4044 return bs;
4046 fail:
4047 blk_unref(file);
4048 qobject_unref(snapshot_options);
4049 qobject_unref(bs->explicit_options);
4050 qobject_unref(bs->options);
4051 qobject_unref(options);
4052 bs->options = NULL;
4053 bs->explicit_options = NULL;
4054 bdrv_unref(bs);
4055 error_propagate(errp, local_err);
4056 return NULL;
4058 close_and_fail:
4059 bdrv_unref(bs);
4060 qobject_unref(snapshot_options);
4061 qobject_unref(options);
4062 error_propagate(errp, local_err);
4063 return NULL;
4066 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4067 QDict *options, int flags, Error **errp)
4069 GLOBAL_STATE_CODE();
4071 return bdrv_open_inherit(filename, reference, options, flags, NULL,
4072 NULL, 0, errp);
4075 /* Return true if the NULL-terminated @list contains @str */
4076 static bool is_str_in_list(const char *str, const char *const *list)
4078 if (str && list) {
4079 int i;
4080 for (i = 0; list[i] != NULL; i++) {
4081 if (!strcmp(str, list[i])) {
4082 return true;
4086 return false;
4090 * Check that every option set in @bs->options is also set in
4091 * @new_opts.
4093 * Options listed in the common_options list and in
4094 * @bs->drv->mutable_opts are skipped.
4096 * Return 0 on success, otherwise return -EINVAL and set @errp.
4098 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4099 const QDict *new_opts, Error **errp)
4101 const QDictEntry *e;
4102 /* These options are common to all block drivers and are handled
4103 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4104 const char *const common_options[] = {
4105 "node-name", "discard", "cache.direct", "cache.no-flush",
4106 "read-only", "auto-read-only", "detect-zeroes", NULL
4109 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4110 if (!qdict_haskey(new_opts, e->key) &&
4111 !is_str_in_list(e->key, common_options) &&
4112 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4113 error_setg(errp, "Option '%s' cannot be reset "
4114 "to its default value", e->key);
4115 return -EINVAL;
4119 return 0;
4123 * Returns true if @child can be reached recursively from @bs
4125 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4126 BlockDriverState *child)
4128 BdrvChild *c;
4130 if (bs == child) {
4131 return true;
4134 QLIST_FOREACH(c, &bs->children, next) {
4135 if (bdrv_recurse_has_child(c->bs, child)) {
4136 return true;
4140 return false;
4144 * Adds a BlockDriverState to a simple queue for an atomic, transactional
4145 * reopen of multiple devices.
4147 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4148 * already performed, or alternatively may be NULL a new BlockReopenQueue will
4149 * be created and initialized. This newly created BlockReopenQueue should be
4150 * passed back in for subsequent calls that are intended to be of the same
4151 * atomic 'set'.
4153 * bs is the BlockDriverState to add to the reopen queue.
4155 * options contains the changed options for the associated bs
4156 * (the BlockReopenQueue takes ownership)
4158 * flags contains the open flags for the associated bs
4160 * returns a pointer to bs_queue, which is either the newly allocated
4161 * bs_queue, or the existing bs_queue being used.
4163 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4165 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4166 BlockDriverState *bs,
4167 QDict *options,
4168 const BdrvChildClass *klass,
4169 BdrvChildRole role,
4170 bool parent_is_format,
4171 QDict *parent_options,
4172 int parent_flags,
4173 bool keep_old_opts)
4175 assert(bs != NULL);
4177 BlockReopenQueueEntry *bs_entry;
4178 BdrvChild *child;
4179 QDict *old_options, *explicit_options, *options_copy;
4180 int flags;
4181 QemuOpts *opts;
4183 /* Make sure that the caller remembered to use a drained section. This is
4184 * important to avoid graph changes between the recursive queuing here and
4185 * bdrv_reopen_multiple(). */
4186 assert(bs->quiesce_counter > 0);
4188 if (bs_queue == NULL) {
4189 bs_queue = g_new0(BlockReopenQueue, 1);
4190 QTAILQ_INIT(bs_queue);
4193 if (!options) {
4194 options = qdict_new();
4197 /* Check if this BlockDriverState is already in the queue */
4198 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4199 if (bs == bs_entry->state.bs) {
4200 break;
4205 * Precedence of options:
4206 * 1. Explicitly passed in options (highest)
4207 * 2. Retained from explicitly set options of bs
4208 * 3. Inherited from parent node
4209 * 4. Retained from effective options of bs
4212 /* Old explicitly set values (don't overwrite by inherited value) */
4213 if (bs_entry || keep_old_opts) {
4214 old_options = qdict_clone_shallow(bs_entry ?
4215 bs_entry->state.explicit_options :
4216 bs->explicit_options);
4217 bdrv_join_options(bs, options, old_options);
4218 qobject_unref(old_options);
4221 explicit_options = qdict_clone_shallow(options);
4223 /* Inherit from parent node */
4224 if (parent_options) {
4225 flags = 0;
4226 klass->inherit_options(role, parent_is_format, &flags, options,
4227 parent_flags, parent_options);
4228 } else {
4229 flags = bdrv_get_flags(bs);
4232 if (keep_old_opts) {
4233 /* Old values are used for options that aren't set yet */
4234 old_options = qdict_clone_shallow(bs->options);
4235 bdrv_join_options(bs, options, old_options);
4236 qobject_unref(old_options);
4239 /* We have the final set of options so let's update the flags */
4240 options_copy = qdict_clone_shallow(options);
4241 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4242 qemu_opts_absorb_qdict(opts, options_copy, NULL);
4243 update_flags_from_options(&flags, opts);
4244 qemu_opts_del(opts);
4245 qobject_unref(options_copy);
4247 /* bdrv_open_inherit() sets and clears some additional flags internally */
4248 flags &= ~BDRV_O_PROTOCOL;
4249 if (flags & BDRV_O_RDWR) {
4250 flags |= BDRV_O_ALLOW_RDWR;
4253 if (!bs_entry) {
4254 bs_entry = g_new0(BlockReopenQueueEntry, 1);
4255 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4256 } else {
4257 qobject_unref(bs_entry->state.options);
4258 qobject_unref(bs_entry->state.explicit_options);
4261 bs_entry->state.bs = bs;
4262 bs_entry->state.options = options;
4263 bs_entry->state.explicit_options = explicit_options;
4264 bs_entry->state.flags = flags;
4267 * If keep_old_opts is false then it means that unspecified
4268 * options must be reset to their original value. We don't allow
4269 * resetting 'backing' but we need to know if the option is
4270 * missing in order to decide if we have to return an error.
4272 if (!keep_old_opts) {
4273 bs_entry->state.backing_missing =
4274 !qdict_haskey(options, "backing") &&
4275 !qdict_haskey(options, "backing.driver");
4278 QLIST_FOREACH(child, &bs->children, next) {
4279 QDict *new_child_options = NULL;
4280 bool child_keep_old = keep_old_opts;
4282 /* reopen can only change the options of block devices that were
4283 * implicitly created and inherited options. For other (referenced)
4284 * block devices, a syntax like "backing.foo" results in an error. */
4285 if (child->bs->inherits_from != bs) {
4286 continue;
4289 /* Check if the options contain a child reference */
4290 if (qdict_haskey(options, child->name)) {
4291 const char *childref = qdict_get_try_str(options, child->name);
4293 * The current child must not be reopened if the child
4294 * reference is null or points to a different node.
4296 if (g_strcmp0(childref, child->bs->node_name)) {
4297 continue;
4300 * If the child reference points to the current child then
4301 * reopen it with its existing set of options (note that
4302 * it can still inherit new options from the parent).
4304 child_keep_old = true;
4305 } else {
4306 /* Extract child options ("child-name.*") */
4307 char *child_key_dot = g_strdup_printf("%s.", child->name);
4308 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4309 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4310 g_free(child_key_dot);
4313 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4314 child->klass, child->role, bs->drv->is_format,
4315 options, flags, child_keep_old);
4318 return bs_queue;
4321 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4322 BlockDriverState *bs,
4323 QDict *options, bool keep_old_opts)
4325 GLOBAL_STATE_CODE();
4327 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4328 NULL, 0, keep_old_opts);
4331 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4333 GLOBAL_STATE_CODE();
4334 if (bs_queue) {
4335 BlockReopenQueueEntry *bs_entry, *next;
4336 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4337 qobject_unref(bs_entry->state.explicit_options);
4338 qobject_unref(bs_entry->state.options);
4339 g_free(bs_entry);
4341 g_free(bs_queue);
4346 * Reopen multiple BlockDriverStates atomically & transactionally.
4348 * The queue passed in (bs_queue) must have been built up previous
4349 * via bdrv_reopen_queue().
4351 * Reopens all BDS specified in the queue, with the appropriate
4352 * flags. All devices are prepared for reopen, and failure of any
4353 * device will cause all device changes to be abandoned, and intermediate
4354 * data cleaned up.
4356 * If all devices prepare successfully, then the changes are committed
4357 * to all devices.
4359 * All affected nodes must be drained between bdrv_reopen_queue() and
4360 * bdrv_reopen_multiple().
4362 * To be called from the main thread, with all other AioContexts unlocked.
4364 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4366 int ret = -1;
4367 BlockReopenQueueEntry *bs_entry, *next;
4368 AioContext *ctx;
4369 Transaction *tran = tran_new();
4370 g_autoptr(GHashTable) found = NULL;
4371 g_autoptr(GSList) refresh_list = NULL;
4373 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4374 assert(bs_queue != NULL);
4376 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4377 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4378 aio_context_acquire(ctx);
4379 ret = bdrv_flush(bs_entry->state.bs);
4380 aio_context_release(ctx);
4381 if (ret < 0) {
4382 error_setg_errno(errp, -ret, "Error flushing drive");
4383 goto abort;
4387 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4388 assert(bs_entry->state.bs->quiesce_counter > 0);
4389 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4390 aio_context_acquire(ctx);
4391 ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4392 aio_context_release(ctx);
4393 if (ret < 0) {
4394 goto abort;
4396 bs_entry->prepared = true;
4399 found = g_hash_table_new(NULL, NULL);
4400 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4401 BDRVReopenState *state = &bs_entry->state;
4403 refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4404 if (state->old_backing_bs) {
4405 refresh_list = bdrv_topological_dfs(refresh_list, found,
4406 state->old_backing_bs);
4408 if (state->old_file_bs) {
4409 refresh_list = bdrv_topological_dfs(refresh_list, found,
4410 state->old_file_bs);
4415 * Note that file-posix driver rely on permission update done during reopen
4416 * (even if no permission changed), because it wants "new" permissions for
4417 * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4418 * in raw_reopen_prepare() which is called with "old" permissions.
4420 ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4421 if (ret < 0) {
4422 goto abort;
4426 * If we reach this point, we have success and just need to apply the
4427 * changes.
4429 * Reverse order is used to comfort qcow2 driver: on commit it need to write
4430 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4431 * children are usually goes after parents in reopen-queue, so go from last
4432 * to first element.
4434 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4435 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4436 aio_context_acquire(ctx);
4437 bdrv_reopen_commit(&bs_entry->state);
4438 aio_context_release(ctx);
4441 tran_commit(tran);
4443 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4444 BlockDriverState *bs = bs_entry->state.bs;
4446 if (bs->drv->bdrv_reopen_commit_post) {
4447 ctx = bdrv_get_aio_context(bs);
4448 aio_context_acquire(ctx);
4449 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4450 aio_context_release(ctx);
4454 ret = 0;
4455 goto cleanup;
4457 abort:
4458 tran_abort(tran);
4459 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4460 if (bs_entry->prepared) {
4461 ctx = bdrv_get_aio_context(bs_entry->state.bs);
4462 aio_context_acquire(ctx);
4463 bdrv_reopen_abort(&bs_entry->state);
4464 aio_context_release(ctx);
4468 cleanup:
4469 bdrv_reopen_queue_free(bs_queue);
4471 return ret;
4474 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4475 Error **errp)
4477 AioContext *ctx = bdrv_get_aio_context(bs);
4478 BlockReopenQueue *queue;
4479 int ret;
4481 GLOBAL_STATE_CODE();
4483 bdrv_subtree_drained_begin(bs);
4484 if (ctx != qemu_get_aio_context()) {
4485 aio_context_release(ctx);
4488 queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4489 ret = bdrv_reopen_multiple(queue, errp);
4491 if (ctx != qemu_get_aio_context()) {
4492 aio_context_acquire(ctx);
4494 bdrv_subtree_drained_end(bs);
4496 return ret;
4499 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4500 Error **errp)
4502 QDict *opts = qdict_new();
4504 GLOBAL_STATE_CODE();
4506 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4508 return bdrv_reopen(bs, opts, true, errp);
4512 * Take a BDRVReopenState and check if the value of 'backing' in the
4513 * reopen_state->options QDict is valid or not.
4515 * If 'backing' is missing from the QDict then return 0.
4517 * If 'backing' contains the node name of the backing file of
4518 * reopen_state->bs then return 0.
4520 * If 'backing' contains a different node name (or is null) then check
4521 * whether the current backing file can be replaced with the new one.
4522 * If that's the case then reopen_state->replace_backing_bs is set to
4523 * true and reopen_state->new_backing_bs contains a pointer to the new
4524 * backing BlockDriverState (or NULL).
4526 * Return 0 on success, otherwise return < 0 and set @errp.
4528 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4529 bool is_backing, Transaction *tran,
4530 Error **errp)
4532 BlockDriverState *bs = reopen_state->bs;
4533 BlockDriverState *new_child_bs;
4534 BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4535 child_bs(bs->file);
4536 const char *child_name = is_backing ? "backing" : "file";
4537 QObject *value;
4538 const char *str;
4540 GLOBAL_STATE_CODE();
4542 value = qdict_get(reopen_state->options, child_name);
4543 if (value == NULL) {
4544 return 0;
4547 switch (qobject_type(value)) {
4548 case QTYPE_QNULL:
4549 assert(is_backing); /* The 'file' option does not allow a null value */
4550 new_child_bs = NULL;
4551 break;
4552 case QTYPE_QSTRING:
4553 str = qstring_get_str(qobject_to(QString, value));
4554 new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4555 if (new_child_bs == NULL) {
4556 return -EINVAL;
4557 } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4558 error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4559 "cycle", str, child_name, bs->node_name);
4560 return -EINVAL;
4562 break;
4563 default:
4565 * The options QDict has been flattened, so 'backing' and 'file'
4566 * do not allow any other data type here.
4568 g_assert_not_reached();
4571 if (old_child_bs == new_child_bs) {
4572 return 0;
4575 if (old_child_bs) {
4576 if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4577 return 0;
4580 if (old_child_bs->implicit) {
4581 error_setg(errp, "Cannot replace implicit %s child of %s",
4582 child_name, bs->node_name);
4583 return -EPERM;
4587 if (bs->drv->is_filter && !old_child_bs) {
4589 * Filters always have a file or a backing child, so we are trying to
4590 * change wrong child
4592 error_setg(errp, "'%s' is a %s filter node that does not support a "
4593 "%s child", bs->node_name, bs->drv->format_name, child_name);
4594 return -EINVAL;
4597 if (is_backing) {
4598 reopen_state->old_backing_bs = old_child_bs;
4599 } else {
4600 reopen_state->old_file_bs = old_child_bs;
4603 return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4604 tran, errp);
4608 * Prepares a BlockDriverState for reopen. All changes are staged in the
4609 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4610 * the block driver layer .bdrv_reopen_prepare()
4612 * bs is the BlockDriverState to reopen
4613 * flags are the new open flags
4614 * queue is the reopen queue
4616 * Returns 0 on success, non-zero on error. On error errp will be set
4617 * as well.
4619 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4620 * It is the responsibility of the caller to then call the abort() or
4621 * commit() for any other BDS that have been left in a prepare() state
4624 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4625 BlockReopenQueue *queue,
4626 Transaction *change_child_tran, Error **errp)
4628 int ret = -1;
4629 int old_flags;
4630 Error *local_err = NULL;
4631 BlockDriver *drv;
4632 QemuOpts *opts;
4633 QDict *orig_reopen_opts;
4634 char *discard = NULL;
4635 bool read_only;
4636 bool drv_prepared = false;
4638 assert(reopen_state != NULL);
4639 assert(reopen_state->bs->drv != NULL);
4640 drv = reopen_state->bs->drv;
4642 /* This function and each driver's bdrv_reopen_prepare() remove
4643 * entries from reopen_state->options as they are processed, so
4644 * we need to make a copy of the original QDict. */
4645 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4647 /* Process generic block layer options */
4648 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4649 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4650 ret = -EINVAL;
4651 goto error;
4654 /* This was already called in bdrv_reopen_queue_child() so the flags
4655 * are up-to-date. This time we simply want to remove the options from
4656 * QemuOpts in order to indicate that they have been processed. */
4657 old_flags = reopen_state->flags;
4658 update_flags_from_options(&reopen_state->flags, opts);
4659 assert(old_flags == reopen_state->flags);
4661 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4662 if (discard != NULL) {
4663 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4664 error_setg(errp, "Invalid discard option");
4665 ret = -EINVAL;
4666 goto error;
4670 reopen_state->detect_zeroes =
4671 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4672 if (local_err) {
4673 error_propagate(errp, local_err);
4674 ret = -EINVAL;
4675 goto error;
4678 /* All other options (including node-name and driver) must be unchanged.
4679 * Put them back into the QDict, so that they are checked at the end
4680 * of this function. */
4681 qemu_opts_to_qdict(opts, reopen_state->options);
4683 /* If we are to stay read-only, do not allow permission change
4684 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4685 * not set, or if the BDS still has copy_on_read enabled */
4686 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4687 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4688 if (local_err) {
4689 error_propagate(errp, local_err);
4690 goto error;
4693 if (drv->bdrv_reopen_prepare) {
4695 * If a driver-specific option is missing, it means that we
4696 * should reset it to its default value.
4697 * But not all options allow that, so we need to check it first.
4699 ret = bdrv_reset_options_allowed(reopen_state->bs,
4700 reopen_state->options, errp);
4701 if (ret) {
4702 goto error;
4705 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4706 if (ret) {
4707 if (local_err != NULL) {
4708 error_propagate(errp, local_err);
4709 } else {
4710 bdrv_refresh_filename(reopen_state->bs);
4711 error_setg(errp, "failed while preparing to reopen image '%s'",
4712 reopen_state->bs->filename);
4714 goto error;
4716 } else {
4717 /* It is currently mandatory to have a bdrv_reopen_prepare()
4718 * handler for each supported drv. */
4719 error_setg(errp, "Block format '%s' used by node '%s' "
4720 "does not support reopening files", drv->format_name,
4721 bdrv_get_device_or_node_name(reopen_state->bs));
4722 ret = -1;
4723 goto error;
4726 drv_prepared = true;
4729 * We must provide the 'backing' option if the BDS has a backing
4730 * file or if the image file has a backing file name as part of
4731 * its metadata. Otherwise the 'backing' option can be omitted.
4733 if (drv->supports_backing && reopen_state->backing_missing &&
4734 (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4735 error_setg(errp, "backing is missing for '%s'",
4736 reopen_state->bs->node_name);
4737 ret = -EINVAL;
4738 goto error;
4742 * Allow changing the 'backing' option. The new value can be
4743 * either a reference to an existing node (using its node name)
4744 * or NULL to simply detach the current backing file.
4746 ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4747 change_child_tran, errp);
4748 if (ret < 0) {
4749 goto error;
4751 qdict_del(reopen_state->options, "backing");
4753 /* Allow changing the 'file' option. In this case NULL is not allowed */
4754 ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4755 change_child_tran, errp);
4756 if (ret < 0) {
4757 goto error;
4759 qdict_del(reopen_state->options, "file");
4761 /* Options that are not handled are only okay if they are unchanged
4762 * compared to the old state. It is expected that some options are only
4763 * used for the initial open, but not reopen (e.g. filename) */
4764 if (qdict_size(reopen_state->options)) {
4765 const QDictEntry *entry = qdict_first(reopen_state->options);
4767 do {
4768 QObject *new = entry->value;
4769 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4771 /* Allow child references (child_name=node_name) as long as they
4772 * point to the current child (i.e. everything stays the same). */
4773 if (qobject_type(new) == QTYPE_QSTRING) {
4774 BdrvChild *child;
4775 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4776 if (!strcmp(child->name, entry->key)) {
4777 break;
4781 if (child) {
4782 if (!strcmp(child->bs->node_name,
4783 qstring_get_str(qobject_to(QString, new)))) {
4784 continue; /* Found child with this name, skip option */
4790 * TODO: When using -drive to specify blockdev options, all values
4791 * will be strings; however, when using -blockdev, blockdev-add or
4792 * filenames using the json:{} pseudo-protocol, they will be
4793 * correctly typed.
4794 * In contrast, reopening options are (currently) always strings
4795 * (because you can only specify them through qemu-io; all other
4796 * callers do not specify any options).
4797 * Therefore, when using anything other than -drive to create a BDS,
4798 * this cannot detect non-string options as unchanged, because
4799 * qobject_is_equal() always returns false for objects of different
4800 * type. In the future, this should be remedied by correctly typing
4801 * all options. For now, this is not too big of an issue because
4802 * the user can simply omit options which cannot be changed anyway,
4803 * so they will stay unchanged.
4805 if (!qobject_is_equal(new, old)) {
4806 error_setg(errp, "Cannot change the option '%s'", entry->key);
4807 ret = -EINVAL;
4808 goto error;
4810 } while ((entry = qdict_next(reopen_state->options, entry)));
4813 ret = 0;
4815 /* Restore the original reopen_state->options QDict */
4816 qobject_unref(reopen_state->options);
4817 reopen_state->options = qobject_ref(orig_reopen_opts);
4819 error:
4820 if (ret < 0 && drv_prepared) {
4821 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4822 * call drv->bdrv_reopen_abort() before signaling an error
4823 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4824 * when the respective bdrv_reopen_prepare() has failed) */
4825 if (drv->bdrv_reopen_abort) {
4826 drv->bdrv_reopen_abort(reopen_state);
4829 qemu_opts_del(opts);
4830 qobject_unref(orig_reopen_opts);
4831 g_free(discard);
4832 return ret;
4836 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4837 * makes them final by swapping the staging BlockDriverState contents into
4838 * the active BlockDriverState contents.
4840 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4842 BlockDriver *drv;
4843 BlockDriverState *bs;
4844 BdrvChild *child;
4846 assert(reopen_state != NULL);
4847 bs = reopen_state->bs;
4848 drv = bs->drv;
4849 assert(drv != NULL);
4851 /* If there are any driver level actions to take */
4852 if (drv->bdrv_reopen_commit) {
4853 drv->bdrv_reopen_commit(reopen_state);
4856 /* set BDS specific flags now */
4857 qobject_unref(bs->explicit_options);
4858 qobject_unref(bs->options);
4859 qobject_ref(reopen_state->explicit_options);
4860 qobject_ref(reopen_state->options);
4862 bs->explicit_options = reopen_state->explicit_options;
4863 bs->options = reopen_state->options;
4864 bs->open_flags = reopen_state->flags;
4865 bs->detect_zeroes = reopen_state->detect_zeroes;
4867 /* Remove child references from bs->options and bs->explicit_options.
4868 * Child options were already removed in bdrv_reopen_queue_child() */
4869 QLIST_FOREACH(child, &bs->children, next) {
4870 qdict_del(bs->explicit_options, child->name);
4871 qdict_del(bs->options, child->name);
4873 /* backing is probably removed, so it's not handled by previous loop */
4874 qdict_del(bs->explicit_options, "backing");
4875 qdict_del(bs->options, "backing");
4877 bdrv_refresh_limits(bs, NULL, NULL);
4881 * Abort the reopen, and delete and free the staged changes in
4882 * reopen_state
4884 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4886 BlockDriver *drv;
4888 assert(reopen_state != NULL);
4889 drv = reopen_state->bs->drv;
4890 assert(drv != NULL);
4892 if (drv->bdrv_reopen_abort) {
4893 drv->bdrv_reopen_abort(reopen_state);
4898 static void bdrv_close(BlockDriverState *bs)
4900 BdrvAioNotifier *ban, *ban_next;
4901 BdrvChild *child, *next;
4903 GLOBAL_STATE_CODE();
4904 assert(!bs->refcnt);
4906 bdrv_drained_begin(bs); /* complete I/O */
4907 bdrv_flush(bs);
4908 bdrv_drain(bs); /* in case flush left pending I/O */
4910 if (bs->drv) {
4911 if (bs->drv->bdrv_close) {
4912 /* Must unfreeze all children, so bdrv_unref_child() works */
4913 bs->drv->bdrv_close(bs);
4915 bs->drv = NULL;
4918 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4919 bdrv_unref_child(bs, child);
4922 bs->backing = NULL;
4923 bs->file = NULL;
4924 g_free(bs->opaque);
4925 bs->opaque = NULL;
4926 qatomic_set(&bs->copy_on_read, 0);
4927 bs->backing_file[0] = '\0';
4928 bs->backing_format[0] = '\0';
4929 bs->total_sectors = 0;
4930 bs->encrypted = false;
4931 bs->sg = false;
4932 qobject_unref(bs->options);
4933 qobject_unref(bs->explicit_options);
4934 bs->options = NULL;
4935 bs->explicit_options = NULL;
4936 qobject_unref(bs->full_open_options);
4937 bs->full_open_options = NULL;
4938 g_free(bs->block_status_cache);
4939 bs->block_status_cache = NULL;
4941 bdrv_release_named_dirty_bitmaps(bs);
4942 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4944 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4945 g_free(ban);
4947 QLIST_INIT(&bs->aio_notifiers);
4948 bdrv_drained_end(bs);
4951 * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4952 * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4953 * gets called.
4955 if (bs->quiesce_counter) {
4956 bdrv_drain_all_end_quiesce(bs);
4960 void bdrv_close_all(void)
4962 assert(job_next(NULL) == NULL);
4963 GLOBAL_STATE_CODE();
4965 /* Drop references from requests still in flight, such as canceled block
4966 * jobs whose AIO context has not been polled yet */
4967 bdrv_drain_all();
4969 blk_remove_all_bs();
4970 blockdev_close_all_bdrv_states();
4972 assert(QTAILQ_EMPTY(&all_bdrv_states));
4975 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4977 GQueue *queue;
4978 GHashTable *found;
4979 bool ret;
4981 if (c->klass->stay_at_node) {
4982 return false;
4985 /* If the child @c belongs to the BDS @to, replacing the current
4986 * c->bs by @to would mean to create a loop.
4988 * Such a case occurs when appending a BDS to a backing chain.
4989 * For instance, imagine the following chain:
4991 * guest device -> node A -> further backing chain...
4993 * Now we create a new BDS B which we want to put on top of this
4994 * chain, so we first attach A as its backing node:
4996 * node B
4999 * guest device -> node A -> further backing chain...
5001 * Finally we want to replace A by B. When doing that, we want to
5002 * replace all pointers to A by pointers to B -- except for the
5003 * pointer from B because (1) that would create a loop, and (2)
5004 * that pointer should simply stay intact:
5006 * guest device -> node B
5009 * node A -> further backing chain...
5011 * In general, when replacing a node A (c->bs) by a node B (@to),
5012 * if A is a child of B, that means we cannot replace A by B there
5013 * because that would create a loop. Silently detaching A from B
5014 * is also not really an option. So overall just leaving A in
5015 * place there is the most sensible choice.
5017 * We would also create a loop in any cases where @c is only
5018 * indirectly referenced by @to. Prevent this by returning false
5019 * if @c is found (by breadth-first search) anywhere in the whole
5020 * subtree of @to.
5023 ret = true;
5024 found = g_hash_table_new(NULL, NULL);
5025 g_hash_table_add(found, to);
5026 queue = g_queue_new();
5027 g_queue_push_tail(queue, to);
5029 while (!g_queue_is_empty(queue)) {
5030 BlockDriverState *v = g_queue_pop_head(queue);
5031 BdrvChild *c2;
5033 QLIST_FOREACH(c2, &v->children, next) {
5034 if (c2 == c) {
5035 ret = false;
5036 break;
5039 if (g_hash_table_contains(found, c2->bs)) {
5040 continue;
5043 g_queue_push_tail(queue, c2->bs);
5044 g_hash_table_add(found, c2->bs);
5048 g_queue_free(queue);
5049 g_hash_table_destroy(found);
5051 return ret;
5054 typedef struct BdrvRemoveFilterOrCowChild {
5055 BdrvChild *child;
5056 BlockDriverState *bs;
5057 bool is_backing;
5058 } BdrvRemoveFilterOrCowChild;
5060 static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
5062 BdrvRemoveFilterOrCowChild *s = opaque;
5063 BlockDriverState *parent_bs = s->child->opaque;
5065 if (s->is_backing) {
5066 parent_bs->backing = s->child;
5067 } else {
5068 parent_bs->file = s->child;
5072 * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
5073 * because that function is transactionable and it registered own completion
5074 * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5075 * called automatically.
5079 static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
5081 BdrvRemoveFilterOrCowChild *s = opaque;
5082 GLOBAL_STATE_CODE();
5083 bdrv_child_free(s->child);
5086 static void bdrv_remove_filter_or_cow_child_clean(void *opaque)
5088 BdrvRemoveFilterOrCowChild *s = opaque;
5090 /* Drop the bs reference after the transaction is done */
5091 bdrv_unref(s->bs);
5092 g_free(s);
5095 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
5096 .abort = bdrv_remove_filter_or_cow_child_abort,
5097 .commit = bdrv_remove_filter_or_cow_child_commit,
5098 .clean = bdrv_remove_filter_or_cow_child_clean,
5102 * A function to remove backing or file child of @bs.
5103 * Function doesn't update permissions, caller is responsible for this.
5105 static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
5106 BdrvChild *child,
5107 Transaction *tran)
5109 BdrvChild **childp;
5110 BdrvRemoveFilterOrCowChild *s;
5112 if (!child) {
5113 return;
5117 * Keep a reference to @bs so @childp will stay valid throughout the
5118 * transaction (required by bdrv_replace_child_tran())
5120 bdrv_ref(bs);
5121 if (child == bs->backing) {
5122 childp = &bs->backing;
5123 } else if (child == bs->file) {
5124 childp = &bs->file;
5125 } else {
5126 g_assert_not_reached();
5129 if (child->bs) {
5131 * Pass free_empty_child=false, we will free the child in
5132 * bdrv_remove_filter_or_cow_child_commit()
5134 bdrv_replace_child_tran(childp, NULL, tran, false);
5137 s = g_new(BdrvRemoveFilterOrCowChild, 1);
5138 *s = (BdrvRemoveFilterOrCowChild) {
5139 .child = child,
5140 .bs = bs,
5141 .is_backing = (childp == &bs->backing),
5143 tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
5147 * A function to remove backing-chain child of @bs if exists: cow child for
5148 * format nodes (always .backing) and filter child for filters (may be .file or
5149 * .backing)
5151 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5152 Transaction *tran)
5154 bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5157 static int bdrv_replace_node_noperm(BlockDriverState *from,
5158 BlockDriverState *to,
5159 bool auto_skip, Transaction *tran,
5160 Error **errp)
5162 BdrvChild *c, *next;
5164 assert(to != NULL);
5165 GLOBAL_STATE_CODE();
5167 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5168 assert(c->bs == from);
5169 if (!should_update_child(c, to)) {
5170 if (auto_skip) {
5171 continue;
5173 error_setg(errp, "Should not change '%s' link to '%s'",
5174 c->name, from->node_name);
5175 return -EINVAL;
5177 if (c->frozen) {
5178 error_setg(errp, "Cannot change '%s' link to '%s'",
5179 c->name, from->node_name);
5180 return -EPERM;
5184 * Passing a pointer to the local variable @c is fine here, because
5185 * @to is not NULL, and so &c will not be attached to the transaction.
5187 bdrv_replace_child_tran(&c, to, tran, true);
5190 return 0;
5194 * With auto_skip=true bdrv_replace_node_common skips updating from parents
5195 * if it creates a parent-child relation loop or if parent is block-job.
5197 * With auto_skip=false the error is returned if from has a parent which should
5198 * not be updated.
5200 * With @detach_subchain=true @to must be in a backing chain of @from. In this
5201 * case backing link of the cow-parent of @to is removed.
5203 * @to must not be NULL.
5205 static int bdrv_replace_node_common(BlockDriverState *from,
5206 BlockDriverState *to,
5207 bool auto_skip, bool detach_subchain,
5208 Error **errp)
5210 Transaction *tran = tran_new();
5211 g_autoptr(GHashTable) found = NULL;
5212 g_autoptr(GSList) refresh_list = NULL;
5213 BlockDriverState *to_cow_parent = NULL;
5214 int ret;
5216 GLOBAL_STATE_CODE();
5217 assert(to != NULL);
5219 if (detach_subchain) {
5220 assert(bdrv_chain_contains(from, to));
5221 assert(from != to);
5222 for (to_cow_parent = from;
5223 bdrv_filter_or_cow_bs(to_cow_parent) != to;
5224 to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5230 /* Make sure that @from doesn't go away until we have successfully attached
5231 * all of its parents to @to. */
5232 bdrv_ref(from);
5234 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5235 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5236 bdrv_drained_begin(from);
5239 * Do the replacement without permission update.
5240 * Replacement may influence the permissions, we should calculate new
5241 * permissions based on new graph. If we fail, we'll roll-back the
5242 * replacement.
5244 ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5245 if (ret < 0) {
5246 goto out;
5249 if (detach_subchain) {
5250 bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5253 found = g_hash_table_new(NULL, NULL);
5255 refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5256 refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5258 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5259 if (ret < 0) {
5260 goto out;
5263 ret = 0;
5265 out:
5266 tran_finalize(tran, ret);
5268 bdrv_drained_end(from);
5269 bdrv_unref(from);
5271 return ret;
5275 * Replace node @from by @to (where neither may be NULL).
5277 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5278 Error **errp)
5280 GLOBAL_STATE_CODE();
5282 return bdrv_replace_node_common(from, to, true, false, errp);
5285 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5287 GLOBAL_STATE_CODE();
5289 return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5290 errp);
5294 * Add new bs contents at the top of an image chain while the chain is
5295 * live, while keeping required fields on the top layer.
5297 * This will modify the BlockDriverState fields, and swap contents
5298 * between bs_new and bs_top. Both bs_new and bs_top are modified.
5300 * bs_new must not be attached to a BlockBackend and must not have backing
5301 * child.
5303 * This function does not create any image files.
5305 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5306 Error **errp)
5308 int ret;
5309 Transaction *tran = tran_new();
5311 GLOBAL_STATE_CODE();
5313 assert(!bs_new->backing);
5315 ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5316 &child_of_bds, bdrv_backing_role(bs_new),
5317 &bs_new->backing, tran, errp);
5318 if (ret < 0) {
5319 goto out;
5322 ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5323 if (ret < 0) {
5324 goto out;
5327 ret = bdrv_refresh_perms(bs_new, errp);
5328 out:
5329 tran_finalize(tran, ret);
5331 bdrv_refresh_limits(bs_top, NULL, NULL);
5333 return ret;
5336 /* Not for empty child */
5337 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5338 Error **errp)
5340 int ret;
5341 Transaction *tran = tran_new();
5342 g_autoptr(GHashTable) found = NULL;
5343 g_autoptr(GSList) refresh_list = NULL;
5344 BlockDriverState *old_bs = child->bs;
5346 GLOBAL_STATE_CODE();
5348 bdrv_ref(old_bs);
5349 bdrv_drained_begin(old_bs);
5350 bdrv_drained_begin(new_bs);
5352 bdrv_replace_child_tran(&child, new_bs, tran, true);
5353 /* @new_bs must have been non-NULL, so @child must not have been freed */
5354 assert(child != NULL);
5356 found = g_hash_table_new(NULL, NULL);
5357 refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5358 refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5360 ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5362 tran_finalize(tran, ret);
5364 bdrv_drained_end(old_bs);
5365 bdrv_drained_end(new_bs);
5366 bdrv_unref(old_bs);
5368 return ret;
5371 static void bdrv_delete(BlockDriverState *bs)
5373 assert(bdrv_op_blocker_is_empty(bs));
5374 assert(!bs->refcnt);
5375 GLOBAL_STATE_CODE();
5377 /* remove from list, if necessary */
5378 if (bs->node_name[0] != '\0') {
5379 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5381 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5383 bdrv_close(bs);
5385 g_free(bs);
5390 * Replace @bs by newly created block node.
5392 * @options is a QDict of options to pass to the block drivers, or NULL for an
5393 * empty set of options. The reference to the QDict belongs to the block layer
5394 * after the call (even on failure), so if the caller intends to reuse the
5395 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5397 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5398 int flags, Error **errp)
5400 ERRP_GUARD();
5401 int ret;
5402 BlockDriverState *new_node_bs = NULL;
5403 const char *drvname, *node_name;
5404 BlockDriver *drv;
5406 drvname = qdict_get_try_str(options, "driver");
5407 if (!drvname) {
5408 error_setg(errp, "driver is not specified");
5409 goto fail;
5412 drv = bdrv_find_format(drvname);
5413 if (!drv) {
5414 error_setg(errp, "Unknown driver: '%s'", drvname);
5415 goto fail;
5418 node_name = qdict_get_try_str(options, "node-name");
5420 GLOBAL_STATE_CODE();
5422 new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5423 errp);
5424 options = NULL; /* bdrv_new_open_driver() eats options */
5425 if (!new_node_bs) {
5426 error_prepend(errp, "Could not create node: ");
5427 goto fail;
5430 bdrv_drained_begin(bs);
5431 ret = bdrv_replace_node(bs, new_node_bs, errp);
5432 bdrv_drained_end(bs);
5434 if (ret < 0) {
5435 error_prepend(errp, "Could not replace node: ");
5436 goto fail;
5439 return new_node_bs;
5441 fail:
5442 qobject_unref(options);
5443 bdrv_unref(new_node_bs);
5444 return NULL;
5448 * Run consistency checks on an image
5450 * Returns 0 if the check could be completed (it doesn't mean that the image is
5451 * free of errors) or -errno when an internal error occurred. The results of the
5452 * check are stored in res.
5454 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5455 BdrvCheckResult *res, BdrvCheckMode fix)
5457 if (bs->drv == NULL) {
5458 return -ENOMEDIUM;
5460 if (bs->drv->bdrv_co_check == NULL) {
5461 return -ENOTSUP;
5464 memset(res, 0, sizeof(*res));
5465 return bs->drv->bdrv_co_check(bs, res, fix);
5469 * Return values:
5470 * 0 - success
5471 * -EINVAL - backing format specified, but no file
5472 * -ENOSPC - can't update the backing file because no space is left in the
5473 * image file header
5474 * -ENOTSUP - format driver doesn't support changing the backing file
5476 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5477 const char *backing_fmt, bool require)
5479 BlockDriver *drv = bs->drv;
5480 int ret;
5482 GLOBAL_STATE_CODE();
5484 if (!drv) {
5485 return -ENOMEDIUM;
5488 /* Backing file format doesn't make sense without a backing file */
5489 if (backing_fmt && !backing_file) {
5490 return -EINVAL;
5493 if (require && backing_file && !backing_fmt) {
5494 return -EINVAL;
5497 if (drv->bdrv_change_backing_file != NULL) {
5498 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5499 } else {
5500 ret = -ENOTSUP;
5503 if (ret == 0) {
5504 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5505 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5506 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5507 backing_file ?: "");
5509 return ret;
5513 * Finds the first non-filter node above bs in the chain between
5514 * active and bs. The returned node is either an immediate parent of
5515 * bs, or there are only filter nodes between the two.
5517 * Returns NULL if bs is not found in active's image chain,
5518 * or if active == bs.
5520 * Returns the bottommost base image if bs == NULL.
5522 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5523 BlockDriverState *bs)
5526 GLOBAL_STATE_CODE();
5528 bs = bdrv_skip_filters(bs);
5529 active = bdrv_skip_filters(active);
5531 while (active) {
5532 BlockDriverState *next = bdrv_backing_chain_next(active);
5533 if (bs == next) {
5534 return active;
5536 active = next;
5539 return NULL;
5542 /* Given a BDS, searches for the base layer. */
5543 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5545 GLOBAL_STATE_CODE();
5547 return bdrv_find_overlay(bs, NULL);
5551 * Return true if at least one of the COW (backing) and filter links
5552 * between @bs and @base is frozen. @errp is set if that's the case.
5553 * @base must be reachable from @bs, or NULL.
5555 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5556 Error **errp)
5558 BlockDriverState *i;
5559 BdrvChild *child;
5561 GLOBAL_STATE_CODE();
5563 for (i = bs; i != base; i = child_bs(child)) {
5564 child = bdrv_filter_or_cow_child(i);
5566 if (child && child->frozen) {
5567 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5568 child->name, i->node_name, child->bs->node_name);
5569 return true;
5573 return false;
5577 * Freeze all COW (backing) and filter links between @bs and @base.
5578 * If any of the links is already frozen the operation is aborted and
5579 * none of the links are modified.
5580 * @base must be reachable from @bs, or NULL.
5581 * Returns 0 on success. On failure returns < 0 and sets @errp.
5583 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5584 Error **errp)
5586 BlockDriverState *i;
5587 BdrvChild *child;
5589 GLOBAL_STATE_CODE();
5591 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5592 return -EPERM;
5595 for (i = bs; i != base; i = child_bs(child)) {
5596 child = bdrv_filter_or_cow_child(i);
5597 if (child && child->bs->never_freeze) {
5598 error_setg(errp, "Cannot freeze '%s' link to '%s'",
5599 child->name, child->bs->node_name);
5600 return -EPERM;
5604 for (i = bs; i != base; i = child_bs(child)) {
5605 child = bdrv_filter_or_cow_child(i);
5606 if (child) {
5607 child->frozen = true;
5611 return 0;
5615 * Unfreeze all COW (backing) and filter links between @bs and @base.
5616 * The caller must ensure that all links are frozen before using this
5617 * function.
5618 * @base must be reachable from @bs, or NULL.
5620 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5622 BlockDriverState *i;
5623 BdrvChild *child;
5625 GLOBAL_STATE_CODE();
5627 for (i = bs; i != base; i = child_bs(child)) {
5628 child = bdrv_filter_or_cow_child(i);
5629 if (child) {
5630 assert(child->frozen);
5631 child->frozen = false;
5637 * Drops images above 'base' up to and including 'top', and sets the image
5638 * above 'top' to have base as its backing file.
5640 * Requires that the overlay to 'top' is opened r/w, so that the backing file
5641 * information in 'bs' can be properly updated.
5643 * E.g., this will convert the following chain:
5644 * bottom <- base <- intermediate <- top <- active
5646 * to
5648 * bottom <- base <- active
5650 * It is allowed for bottom==base, in which case it converts:
5652 * base <- intermediate <- top <- active
5654 * to
5656 * base <- active
5658 * If backing_file_str is non-NULL, it will be used when modifying top's
5659 * overlay image metadata.
5661 * Error conditions:
5662 * if active == top, that is considered an error
5665 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5666 const char *backing_file_str)
5668 BlockDriverState *explicit_top = top;
5669 bool update_inherits_from;
5670 BdrvChild *c;
5671 Error *local_err = NULL;
5672 int ret = -EIO;
5673 g_autoptr(GSList) updated_children = NULL;
5674 GSList *p;
5676 GLOBAL_STATE_CODE();
5678 bdrv_ref(top);
5679 bdrv_subtree_drained_begin(top);
5681 if (!top->drv || !base->drv) {
5682 goto exit;
5685 /* Make sure that base is in the backing chain of top */
5686 if (!bdrv_chain_contains(top, base)) {
5687 goto exit;
5690 /* If 'base' recursively inherits from 'top' then we should set
5691 * base->inherits_from to top->inherits_from after 'top' and all
5692 * other intermediate nodes have been dropped.
5693 * If 'top' is an implicit node (e.g. "commit_top") we should skip
5694 * it because no one inherits from it. We use explicit_top for that. */
5695 explicit_top = bdrv_skip_implicit_filters(explicit_top);
5696 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5698 /* success - we can delete the intermediate states, and link top->base */
5699 if (!backing_file_str) {
5700 bdrv_refresh_filename(base);
5701 backing_file_str = base->filename;
5704 QLIST_FOREACH(c, &top->parents, next_parent) {
5705 updated_children = g_slist_prepend(updated_children, c);
5709 * It seems correct to pass detach_subchain=true here, but it triggers
5710 * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5711 * another drained section, which modify the graph (for example, removing
5712 * the child, which we keep in updated_children list). So, it's a TODO.
5714 * Note, bug triggered if pass detach_subchain=true here and run
5715 * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5716 * That's a FIXME.
5718 bdrv_replace_node_common(top, base, false, false, &local_err);
5719 if (local_err) {
5720 error_report_err(local_err);
5721 goto exit;
5724 for (p = updated_children; p; p = p->next) {
5725 c = p->data;
5727 if (c->klass->update_filename) {
5728 ret = c->klass->update_filename(c, base, backing_file_str,
5729 &local_err);
5730 if (ret < 0) {
5732 * TODO: Actually, we want to rollback all previous iterations
5733 * of this loop, and (which is almost impossible) previous
5734 * bdrv_replace_node()...
5736 * Note, that c->klass->update_filename may lead to permission
5737 * update, so it's a bad idea to call it inside permission
5738 * update transaction of bdrv_replace_node.
5740 error_report_err(local_err);
5741 goto exit;
5746 if (update_inherits_from) {
5747 base->inherits_from = explicit_top->inherits_from;
5750 ret = 0;
5751 exit:
5752 bdrv_subtree_drained_end(top);
5753 bdrv_unref(top);
5754 return ret;
5758 * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5759 * sums the size of all data-bearing children. (This excludes backing
5760 * children.)
5762 static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5764 BdrvChild *child;
5765 int64_t child_size, sum = 0;
5767 QLIST_FOREACH(child, &bs->children, next) {
5768 if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5769 BDRV_CHILD_FILTERED))
5771 child_size = bdrv_get_allocated_file_size(child->bs);
5772 if (child_size < 0) {
5773 return child_size;
5775 sum += child_size;
5779 return sum;
5783 * Length of a allocated file in bytes. Sparse files are counted by actual
5784 * allocated space. Return < 0 if error or unknown.
5786 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5788 BlockDriver *drv = bs->drv;
5789 IO_CODE();
5791 if (!drv) {
5792 return -ENOMEDIUM;
5794 if (drv->bdrv_get_allocated_file_size) {
5795 return drv->bdrv_get_allocated_file_size(bs);
5798 if (drv->bdrv_file_open) {
5800 * Protocol drivers default to -ENOTSUP (most of their data is
5801 * not stored in any of their children (if they even have any),
5802 * so there is no generic way to figure it out).
5804 return -ENOTSUP;
5805 } else if (drv->is_filter) {
5806 /* Filter drivers default to the size of their filtered child */
5807 return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5808 } else {
5809 /* Other drivers default to summing their children's sizes */
5810 return bdrv_sum_allocated_file_size(bs);
5815 * bdrv_measure:
5816 * @drv: Format driver
5817 * @opts: Creation options for new image
5818 * @in_bs: Existing image containing data for new image (may be NULL)
5819 * @errp: Error object
5820 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5821 * or NULL on error
5823 * Calculate file size required to create a new image.
5825 * If @in_bs is given then space for allocated clusters and zero clusters
5826 * from that image are included in the calculation. If @opts contains a
5827 * backing file that is shared by @in_bs then backing clusters may be omitted
5828 * from the calculation.
5830 * If @in_bs is NULL then the calculation includes no allocated clusters
5831 * unless a preallocation option is given in @opts.
5833 * Note that @in_bs may use a different BlockDriver from @drv.
5835 * If an error occurs the @errp pointer is set.
5837 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5838 BlockDriverState *in_bs, Error **errp)
5840 IO_CODE();
5841 if (!drv->bdrv_measure) {
5842 error_setg(errp, "Block driver '%s' does not support size measurement",
5843 drv->format_name);
5844 return NULL;
5847 return drv->bdrv_measure(opts, in_bs, errp);
5851 * Return number of sectors on success, -errno on error.
5853 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5855 BlockDriver *drv = bs->drv;
5856 IO_CODE();
5858 if (!drv)
5859 return -ENOMEDIUM;
5861 if (drv->has_variable_length) {
5862 int ret = refresh_total_sectors(bs, bs->total_sectors);
5863 if (ret < 0) {
5864 return ret;
5867 return bs->total_sectors;
5871 * Return length in bytes on success, -errno on error.
5872 * The length is always a multiple of BDRV_SECTOR_SIZE.
5874 int64_t bdrv_getlength(BlockDriverState *bs)
5876 int64_t ret = bdrv_nb_sectors(bs);
5877 IO_CODE();
5879 if (ret < 0) {
5880 return ret;
5882 if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5883 return -EFBIG;
5885 return ret * BDRV_SECTOR_SIZE;
5888 /* return 0 as number of sectors if no device present or error */
5889 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5891 int64_t nb_sectors = bdrv_nb_sectors(bs);
5892 IO_CODE();
5894 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5897 bool bdrv_is_sg(BlockDriverState *bs)
5899 IO_CODE();
5900 return bs->sg;
5904 * Return whether the given node supports compressed writes.
5906 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5908 BlockDriverState *filtered;
5909 IO_CODE();
5911 if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5912 return false;
5915 filtered = bdrv_filter_bs(bs);
5916 if (filtered) {
5918 * Filters can only forward compressed writes, so we have to
5919 * check the child.
5921 return bdrv_supports_compressed_writes(filtered);
5924 return true;
5927 const char *bdrv_get_format_name(BlockDriverState *bs)
5929 IO_CODE();
5930 return bs->drv ? bs->drv->format_name : NULL;
5933 static int qsort_strcmp(const void *a, const void *b)
5935 return strcmp(*(char *const *)a, *(char *const *)b);
5938 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5939 void *opaque, bool read_only)
5941 BlockDriver *drv;
5942 int count = 0;
5943 int i;
5944 const char **formats = NULL;
5946 GLOBAL_STATE_CODE();
5948 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5949 if (drv->format_name) {
5950 bool found = false;
5951 int i = count;
5953 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5954 continue;
5957 while (formats && i && !found) {
5958 found = !strcmp(formats[--i], drv->format_name);
5961 if (!found) {
5962 formats = g_renew(const char *, formats, count + 1);
5963 formats[count++] = drv->format_name;
5968 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5969 const char *format_name = block_driver_modules[i].format_name;
5971 if (format_name) {
5972 bool found = false;
5973 int j = count;
5975 if (use_bdrv_whitelist &&
5976 !bdrv_format_is_whitelisted(format_name, read_only)) {
5977 continue;
5980 while (formats && j && !found) {
5981 found = !strcmp(formats[--j], format_name);
5984 if (!found) {
5985 formats = g_renew(const char *, formats, count + 1);
5986 formats[count++] = format_name;
5991 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5993 for (i = 0; i < count; i++) {
5994 it(opaque, formats[i]);
5997 g_free(formats);
6000 /* This function is to find a node in the bs graph */
6001 BlockDriverState *bdrv_find_node(const char *node_name)
6003 BlockDriverState *bs;
6005 assert(node_name);
6006 GLOBAL_STATE_CODE();
6008 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6009 if (!strcmp(node_name, bs->node_name)) {
6010 return bs;
6013 return NULL;
6016 /* Put this QMP function here so it can access the static graph_bdrv_states. */
6017 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6018 Error **errp)
6020 BlockDeviceInfoList *list;
6021 BlockDriverState *bs;
6023 GLOBAL_STATE_CODE();
6025 list = NULL;
6026 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6027 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6028 if (!info) {
6029 qapi_free_BlockDeviceInfoList(list);
6030 return NULL;
6032 QAPI_LIST_PREPEND(list, info);
6035 return list;
6038 typedef struct XDbgBlockGraphConstructor {
6039 XDbgBlockGraph *graph;
6040 GHashTable *graph_nodes;
6041 } XDbgBlockGraphConstructor;
6043 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
6045 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
6047 gr->graph = g_new0(XDbgBlockGraph, 1);
6048 gr->graph_nodes = g_hash_table_new(NULL, NULL);
6050 return gr;
6053 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
6055 XDbgBlockGraph *graph = gr->graph;
6057 g_hash_table_destroy(gr->graph_nodes);
6058 g_free(gr);
6060 return graph;
6063 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
6065 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
6067 if (ret != 0) {
6068 return ret;
6072 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
6073 * answer of g_hash_table_lookup.
6075 ret = g_hash_table_size(gr->graph_nodes) + 1;
6076 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6078 return ret;
6081 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6082 XDbgBlockGraphNodeType type, const char *name)
6084 XDbgBlockGraphNode *n;
6086 n = g_new0(XDbgBlockGraphNode, 1);
6088 n->id = xdbg_graph_node_num(gr, node);
6089 n->type = type;
6090 n->name = g_strdup(name);
6092 QAPI_LIST_PREPEND(gr->graph->nodes, n);
6095 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6096 const BdrvChild *child)
6098 BlockPermission qapi_perm;
6099 XDbgBlockGraphEdge *edge;
6100 GLOBAL_STATE_CODE();
6102 edge = g_new0(XDbgBlockGraphEdge, 1);
6104 edge->parent = xdbg_graph_node_num(gr, parent);
6105 edge->child = xdbg_graph_node_num(gr, child->bs);
6106 edge->name = g_strdup(child->name);
6108 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6109 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6111 if (flag & child->perm) {
6112 QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6114 if (flag & child->shared_perm) {
6115 QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6119 QAPI_LIST_PREPEND(gr->graph->edges, edge);
6123 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6125 BlockBackend *blk;
6126 BlockJob *job;
6127 BlockDriverState *bs;
6128 BdrvChild *child;
6129 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6131 GLOBAL_STATE_CODE();
6133 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6134 char *allocated_name = NULL;
6135 const char *name = blk_name(blk);
6137 if (!*name) {
6138 name = allocated_name = blk_get_attached_dev_id(blk);
6140 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6141 name);
6142 g_free(allocated_name);
6143 if (blk_root(blk)) {
6144 xdbg_graph_add_edge(gr, blk, blk_root(blk));
6148 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
6149 GSList *el;
6151 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6152 job->job.id);
6153 for (el = job->nodes; el; el = el->next) {
6154 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6158 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6159 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6160 bs->node_name);
6161 QLIST_FOREACH(child, &bs->children, next) {
6162 xdbg_graph_add_edge(gr, bs, child);
6166 return xdbg_graph_finalize(gr);
6169 BlockDriverState *bdrv_lookup_bs(const char *device,
6170 const char *node_name,
6171 Error **errp)
6173 BlockBackend *blk;
6174 BlockDriverState *bs;
6176 GLOBAL_STATE_CODE();
6178 if (device) {
6179 blk = blk_by_name(device);
6181 if (blk) {
6182 bs = blk_bs(blk);
6183 if (!bs) {
6184 error_setg(errp, "Device '%s' has no medium", device);
6187 return bs;
6191 if (node_name) {
6192 bs = bdrv_find_node(node_name);
6194 if (bs) {
6195 return bs;
6199 error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6200 device ? device : "",
6201 node_name ? node_name : "");
6202 return NULL;
6205 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6206 * return false. If either argument is NULL, return false. */
6207 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6210 GLOBAL_STATE_CODE();
6212 while (top && top != base) {
6213 top = bdrv_filter_or_cow_bs(top);
6216 return top != NULL;
6219 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6221 GLOBAL_STATE_CODE();
6222 if (!bs) {
6223 return QTAILQ_FIRST(&graph_bdrv_states);
6225 return QTAILQ_NEXT(bs, node_list);
6228 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6230 GLOBAL_STATE_CODE();
6231 if (!bs) {
6232 return QTAILQ_FIRST(&all_bdrv_states);
6234 return QTAILQ_NEXT(bs, bs_list);
6237 const char *bdrv_get_node_name(const BlockDriverState *bs)
6239 IO_CODE();
6240 return bs->node_name;
6243 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6245 BdrvChild *c;
6246 const char *name;
6247 IO_CODE();
6249 /* If multiple parents have a name, just pick the first one. */
6250 QLIST_FOREACH(c, &bs->parents, next_parent) {
6251 if (c->klass->get_name) {
6252 name = c->klass->get_name(c);
6253 if (name && *name) {
6254 return name;
6259 return NULL;
6262 /* TODO check what callers really want: bs->node_name or blk_name() */
6263 const char *bdrv_get_device_name(const BlockDriverState *bs)
6265 IO_CODE();
6266 return bdrv_get_parent_name(bs) ?: "";
6269 /* This can be used to identify nodes that might not have a device
6270 * name associated. Since node and device names live in the same
6271 * namespace, the result is unambiguous. The exception is if both are
6272 * absent, then this returns an empty (non-null) string. */
6273 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6275 IO_CODE();
6276 return bdrv_get_parent_name(bs) ?: bs->node_name;
6279 int bdrv_get_flags(BlockDriverState *bs)
6281 GLOBAL_STATE_CODE();
6282 return bs->open_flags;
6285 int bdrv_has_zero_init_1(BlockDriverState *bs)
6287 GLOBAL_STATE_CODE();
6288 return 1;
6291 int bdrv_has_zero_init(BlockDriverState *bs)
6293 BlockDriverState *filtered;
6294 GLOBAL_STATE_CODE();
6296 if (!bs->drv) {
6297 return 0;
6300 /* If BS is a copy on write image, it is initialized to
6301 the contents of the base image, which may not be zeroes. */
6302 if (bdrv_cow_child(bs)) {
6303 return 0;
6305 if (bs->drv->bdrv_has_zero_init) {
6306 return bs->drv->bdrv_has_zero_init(bs);
6309 filtered = bdrv_filter_bs(bs);
6310 if (filtered) {
6311 return bdrv_has_zero_init(filtered);
6314 /* safe default */
6315 return 0;
6318 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6320 IO_CODE();
6321 if (!(bs->open_flags & BDRV_O_UNMAP)) {
6322 return false;
6325 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6328 void bdrv_get_backing_filename(BlockDriverState *bs,
6329 char *filename, int filename_size)
6331 IO_CODE();
6332 pstrcpy(filename, filename_size, bs->backing_file);
6335 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6337 int ret;
6338 BlockDriver *drv = bs->drv;
6339 IO_CODE();
6340 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6341 if (!drv) {
6342 return -ENOMEDIUM;
6344 if (!drv->bdrv_get_info) {
6345 BlockDriverState *filtered = bdrv_filter_bs(bs);
6346 if (filtered) {
6347 return bdrv_get_info(filtered, bdi);
6349 return -ENOTSUP;
6351 memset(bdi, 0, sizeof(*bdi));
6352 ret = drv->bdrv_get_info(bs, bdi);
6353 if (ret < 0) {
6354 return ret;
6357 if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6358 return -EINVAL;
6361 return 0;
6364 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6365 Error **errp)
6367 BlockDriver *drv = bs->drv;
6368 IO_CODE();
6369 if (drv && drv->bdrv_get_specific_info) {
6370 return drv->bdrv_get_specific_info(bs, errp);
6372 return NULL;
6375 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6377 BlockDriver *drv = bs->drv;
6378 IO_CODE();
6379 if (!drv || !drv->bdrv_get_specific_stats) {
6380 return NULL;
6382 return drv->bdrv_get_specific_stats(bs);
6385 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6387 IO_CODE();
6388 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6389 return;
6392 bs->drv->bdrv_debug_event(bs, event);
6395 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
6397 GLOBAL_STATE_CODE();
6398 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6399 bs = bdrv_primary_bs(bs);
6402 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6403 assert(bs->drv->bdrv_debug_remove_breakpoint);
6404 return bs;
6407 return NULL;
6410 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6411 const char *tag)
6413 GLOBAL_STATE_CODE();
6414 bs = bdrv_find_debug_node(bs);
6415 if (bs) {
6416 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6419 return -ENOTSUP;
6422 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6424 GLOBAL_STATE_CODE();
6425 bs = bdrv_find_debug_node(bs);
6426 if (bs) {
6427 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6430 return -ENOTSUP;
6433 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6435 GLOBAL_STATE_CODE();
6436 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6437 bs = bdrv_primary_bs(bs);
6440 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6441 return bs->drv->bdrv_debug_resume(bs, tag);
6444 return -ENOTSUP;
6447 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6449 GLOBAL_STATE_CODE();
6450 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6451 bs = bdrv_primary_bs(bs);
6454 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6455 return bs->drv->bdrv_debug_is_suspended(bs, tag);
6458 return false;
6461 /* backing_file can either be relative, or absolute, or a protocol. If it is
6462 * relative, it must be relative to the chain. So, passing in bs->filename
6463 * from a BDS as backing_file should not be done, as that may be relative to
6464 * the CWD rather than the chain. */
6465 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6466 const char *backing_file)
6468 char *filename_full = NULL;
6469 char *backing_file_full = NULL;
6470 char *filename_tmp = NULL;
6471 int is_protocol = 0;
6472 bool filenames_refreshed = false;
6473 BlockDriverState *curr_bs = NULL;
6474 BlockDriverState *retval = NULL;
6475 BlockDriverState *bs_below;
6477 GLOBAL_STATE_CODE();
6479 if (!bs || !bs->drv || !backing_file) {
6480 return NULL;
6483 filename_full = g_malloc(PATH_MAX);
6484 backing_file_full = g_malloc(PATH_MAX);
6486 is_protocol = path_has_protocol(backing_file);
6489 * Being largely a legacy function, skip any filters here
6490 * (because filters do not have normal filenames, so they cannot
6491 * match anyway; and allowing json:{} filenames is a bit out of
6492 * scope).
6494 for (curr_bs = bdrv_skip_filters(bs);
6495 bdrv_cow_child(curr_bs) != NULL;
6496 curr_bs = bs_below)
6498 bs_below = bdrv_backing_chain_next(curr_bs);
6500 if (bdrv_backing_overridden(curr_bs)) {
6502 * If the backing file was overridden, we can only compare
6503 * directly against the backing node's filename.
6506 if (!filenames_refreshed) {
6508 * This will automatically refresh all of the
6509 * filenames in the rest of the backing chain, so we
6510 * only need to do this once.
6512 bdrv_refresh_filename(bs_below);
6513 filenames_refreshed = true;
6516 if (strcmp(backing_file, bs_below->filename) == 0) {
6517 retval = bs_below;
6518 break;
6520 } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6522 * If either of the filename paths is actually a protocol, then
6523 * compare unmodified paths; otherwise make paths relative.
6525 char *backing_file_full_ret;
6527 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6528 retval = bs_below;
6529 break;
6531 /* Also check against the full backing filename for the image */
6532 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6533 NULL);
6534 if (backing_file_full_ret) {
6535 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6536 g_free(backing_file_full_ret);
6537 if (equal) {
6538 retval = bs_below;
6539 break;
6542 } else {
6543 /* If not an absolute filename path, make it relative to the current
6544 * image's filename path */
6545 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6546 NULL);
6547 /* We are going to compare canonicalized absolute pathnames */
6548 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6549 g_free(filename_tmp);
6550 continue;
6552 g_free(filename_tmp);
6554 /* We need to make sure the backing filename we are comparing against
6555 * is relative to the current image filename (or absolute) */
6556 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6557 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6558 g_free(filename_tmp);
6559 continue;
6561 g_free(filename_tmp);
6563 if (strcmp(backing_file_full, filename_full) == 0) {
6564 retval = bs_below;
6565 break;
6570 g_free(filename_full);
6571 g_free(backing_file_full);
6572 return retval;
6575 void bdrv_init(void)
6577 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6578 use_bdrv_whitelist = 1;
6579 #endif
6580 module_call_init(MODULE_INIT_BLOCK);
6583 void bdrv_init_with_whitelist(void)
6585 use_bdrv_whitelist = 1;
6586 bdrv_init();
6589 int bdrv_activate(BlockDriverState *bs, Error **errp)
6591 BdrvChild *child, *parent;
6592 Error *local_err = NULL;
6593 int ret;
6594 BdrvDirtyBitmap *bm;
6596 GLOBAL_STATE_CODE();
6598 if (!bs->drv) {
6599 return -ENOMEDIUM;
6602 QLIST_FOREACH(child, &bs->children, next) {
6603 bdrv_activate(child->bs, &local_err);
6604 if (local_err) {
6605 error_propagate(errp, local_err);
6606 return -EINVAL;
6611 * Update permissions, they may differ for inactive nodes.
6613 * Note that the required permissions of inactive images are always a
6614 * subset of the permissions required after activating the image. This
6615 * allows us to just get the permissions upfront without restricting
6616 * bdrv_co_invalidate_cache().
6618 * It also means that in error cases, we don't have to try and revert to
6619 * the old permissions (which is an operation that could fail, too). We can
6620 * just keep the extended permissions for the next time that an activation
6621 * of the image is tried.
6623 if (bs->open_flags & BDRV_O_INACTIVE) {
6624 bs->open_flags &= ~BDRV_O_INACTIVE;
6625 ret = bdrv_refresh_perms(bs, errp);
6626 if (ret < 0) {
6627 bs->open_flags |= BDRV_O_INACTIVE;
6628 return ret;
6631 ret = bdrv_invalidate_cache(bs, errp);
6632 if (ret < 0) {
6633 bs->open_flags |= BDRV_O_INACTIVE;
6634 return ret;
6637 FOR_EACH_DIRTY_BITMAP(bs, bm) {
6638 bdrv_dirty_bitmap_skip_store(bm, false);
6641 ret = refresh_total_sectors(bs, bs->total_sectors);
6642 if (ret < 0) {
6643 bs->open_flags |= BDRV_O_INACTIVE;
6644 error_setg_errno(errp, -ret, "Could not refresh total sector count");
6645 return ret;
6649 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6650 if (parent->klass->activate) {
6651 parent->klass->activate(parent, &local_err);
6652 if (local_err) {
6653 bs->open_flags |= BDRV_O_INACTIVE;
6654 error_propagate(errp, local_err);
6655 return -EINVAL;
6660 return 0;
6663 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6665 Error *local_err = NULL;
6667 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6669 if (bs->drv->bdrv_co_invalidate_cache) {
6670 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6671 if (local_err) {
6672 error_propagate(errp, local_err);
6673 return -EINVAL;
6677 return 0;
6680 void bdrv_activate_all(Error **errp)
6682 BlockDriverState *bs;
6683 BdrvNextIterator it;
6685 GLOBAL_STATE_CODE();
6687 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6688 AioContext *aio_context = bdrv_get_aio_context(bs);
6689 int ret;
6691 aio_context_acquire(aio_context);
6692 ret = bdrv_activate(bs, errp);
6693 aio_context_release(aio_context);
6694 if (ret < 0) {
6695 bdrv_next_cleanup(&it);
6696 return;
6701 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6703 BdrvChild *parent;
6704 GLOBAL_STATE_CODE();
6706 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6707 if (parent->klass->parent_is_bds) {
6708 BlockDriverState *parent_bs = parent->opaque;
6709 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6710 return true;
6715 return false;
6718 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6720 BdrvChild *child, *parent;
6721 int ret;
6722 uint64_t cumulative_perms, cumulative_shared_perms;
6724 if (!bs->drv) {
6725 return -ENOMEDIUM;
6728 /* Make sure that we don't inactivate a child before its parent.
6729 * It will be covered by recursion from the yet active parent. */
6730 if (bdrv_has_bds_parent(bs, true)) {
6731 return 0;
6734 assert(!(bs->open_flags & BDRV_O_INACTIVE));
6736 /* Inactivate this node */
6737 if (bs->drv->bdrv_inactivate) {
6738 ret = bs->drv->bdrv_inactivate(bs);
6739 if (ret < 0) {
6740 return ret;
6744 QLIST_FOREACH(parent, &bs->parents, next_parent) {
6745 if (parent->klass->inactivate) {
6746 ret = parent->klass->inactivate(parent);
6747 if (ret < 0) {
6748 return ret;
6753 bdrv_get_cumulative_perm(bs, &cumulative_perms,
6754 &cumulative_shared_perms);
6755 if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6756 /* Our inactive parents still need write access. Inactivation failed. */
6757 return -EPERM;
6760 bs->open_flags |= BDRV_O_INACTIVE;
6763 * Update permissions, they may differ for inactive nodes.
6764 * We only tried to loosen restrictions, so errors are not fatal, ignore
6765 * them.
6767 bdrv_refresh_perms(bs, NULL);
6769 /* Recursively inactivate children */
6770 QLIST_FOREACH(child, &bs->children, next) {
6771 ret = bdrv_inactivate_recurse(child->bs);
6772 if (ret < 0) {
6773 return ret;
6777 return 0;
6780 int bdrv_inactivate_all(void)
6782 BlockDriverState *bs = NULL;
6783 BdrvNextIterator it;
6784 int ret = 0;
6785 GSList *aio_ctxs = NULL, *ctx;
6787 GLOBAL_STATE_CODE();
6789 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6790 AioContext *aio_context = bdrv_get_aio_context(bs);
6792 if (!g_slist_find(aio_ctxs, aio_context)) {
6793 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6794 aio_context_acquire(aio_context);
6798 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6799 /* Nodes with BDS parents are covered by recursion from the last
6800 * parent that gets inactivated. Don't inactivate them a second
6801 * time if that has already happened. */
6802 if (bdrv_has_bds_parent(bs, false)) {
6803 continue;
6805 ret = bdrv_inactivate_recurse(bs);
6806 if (ret < 0) {
6807 bdrv_next_cleanup(&it);
6808 goto out;
6812 out:
6813 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6814 AioContext *aio_context = ctx->data;
6815 aio_context_release(aio_context);
6817 g_slist_free(aio_ctxs);
6819 return ret;
6822 /**************************************************************/
6823 /* removable device support */
6826 * Return TRUE if the media is present
6828 bool bdrv_is_inserted(BlockDriverState *bs)
6830 BlockDriver *drv = bs->drv;
6831 BdrvChild *child;
6832 IO_CODE();
6834 if (!drv) {
6835 return false;
6837 if (drv->bdrv_is_inserted) {
6838 return drv->bdrv_is_inserted(bs);
6840 QLIST_FOREACH(child, &bs->children, next) {
6841 if (!bdrv_is_inserted(child->bs)) {
6842 return false;
6845 return true;
6849 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6851 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6853 BlockDriver *drv = bs->drv;
6854 IO_CODE();
6856 if (drv && drv->bdrv_eject) {
6857 drv->bdrv_eject(bs, eject_flag);
6862 * Lock or unlock the media (if it is locked, the user won't be able
6863 * to eject it manually).
6865 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6867 BlockDriver *drv = bs->drv;
6868 IO_CODE();
6869 trace_bdrv_lock_medium(bs, locked);
6871 if (drv && drv->bdrv_lock_medium) {
6872 drv->bdrv_lock_medium(bs, locked);
6876 /* Get a reference to bs */
6877 void bdrv_ref(BlockDriverState *bs)
6879 GLOBAL_STATE_CODE();
6880 bs->refcnt++;
6883 /* Release a previously grabbed reference to bs.
6884 * If after releasing, reference count is zero, the BlockDriverState is
6885 * deleted. */
6886 void bdrv_unref(BlockDriverState *bs)
6888 GLOBAL_STATE_CODE();
6889 if (!bs) {
6890 return;
6892 assert(bs->refcnt > 0);
6893 if (--bs->refcnt == 0) {
6894 bdrv_delete(bs);
6898 struct BdrvOpBlocker {
6899 Error *reason;
6900 QLIST_ENTRY(BdrvOpBlocker) list;
6903 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6905 BdrvOpBlocker *blocker;
6906 GLOBAL_STATE_CODE();
6907 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6908 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6909 blocker = QLIST_FIRST(&bs->op_blockers[op]);
6910 error_propagate_prepend(errp, error_copy(blocker->reason),
6911 "Node '%s' is busy: ",
6912 bdrv_get_device_or_node_name(bs));
6913 return true;
6915 return false;
6918 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6920 BdrvOpBlocker *blocker;
6921 GLOBAL_STATE_CODE();
6922 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6924 blocker = g_new0(BdrvOpBlocker, 1);
6925 blocker->reason = reason;
6926 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6929 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6931 BdrvOpBlocker *blocker, *next;
6932 GLOBAL_STATE_CODE();
6933 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6934 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6935 if (blocker->reason == reason) {
6936 QLIST_REMOVE(blocker, list);
6937 g_free(blocker);
6942 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6944 int i;
6945 GLOBAL_STATE_CODE();
6946 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6947 bdrv_op_block(bs, i, reason);
6951 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6953 int i;
6954 GLOBAL_STATE_CODE();
6955 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6956 bdrv_op_unblock(bs, i, reason);
6960 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6962 int i;
6963 GLOBAL_STATE_CODE();
6964 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6965 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6966 return false;
6969 return true;
6972 void bdrv_img_create(const char *filename, const char *fmt,
6973 const char *base_filename, const char *base_fmt,
6974 char *options, uint64_t img_size, int flags, bool quiet,
6975 Error **errp)
6977 QemuOptsList *create_opts = NULL;
6978 QemuOpts *opts = NULL;
6979 const char *backing_fmt, *backing_file;
6980 int64_t size;
6981 BlockDriver *drv, *proto_drv;
6982 Error *local_err = NULL;
6983 int ret = 0;
6985 GLOBAL_STATE_CODE();
6987 /* Find driver and parse its options */
6988 drv = bdrv_find_format(fmt);
6989 if (!drv) {
6990 error_setg(errp, "Unknown file format '%s'", fmt);
6991 return;
6994 proto_drv = bdrv_find_protocol(filename, true, errp);
6995 if (!proto_drv) {
6996 return;
6999 if (!drv->create_opts) {
7000 error_setg(errp, "Format driver '%s' does not support image creation",
7001 drv->format_name);
7002 return;
7005 if (!proto_drv->create_opts) {
7006 error_setg(errp, "Protocol driver '%s' does not support image creation",
7007 proto_drv->format_name);
7008 return;
7011 /* Create parameter list */
7012 create_opts = qemu_opts_append(create_opts, drv->create_opts);
7013 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7015 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7017 /* Parse -o options */
7018 if (options) {
7019 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7020 goto out;
7024 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7025 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7026 } else if (img_size != UINT64_C(-1)) {
7027 error_setg(errp, "The image size must be specified only once");
7028 goto out;
7031 if (base_filename) {
7032 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
7033 NULL)) {
7034 error_setg(errp, "Backing file not supported for file format '%s'",
7035 fmt);
7036 goto out;
7040 if (base_fmt) {
7041 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
7042 error_setg(errp, "Backing file format not supported for file "
7043 "format '%s'", fmt);
7044 goto out;
7048 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
7049 if (backing_file) {
7050 if (!strcmp(filename, backing_file)) {
7051 error_setg(errp, "Error: Trying to create an image with the "
7052 "same filename as the backing file");
7053 goto out;
7055 if (backing_file[0] == '\0') {
7056 error_setg(errp, "Expected backing file name, got empty string");
7057 goto out;
7061 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7063 /* The size for the image must always be specified, unless we have a backing
7064 * file and we have not been forbidden from opening it. */
7065 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
7066 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
7067 BlockDriverState *bs;
7068 char *full_backing;
7069 int back_flags;
7070 QDict *backing_options = NULL;
7072 full_backing =
7073 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7074 &local_err);
7075 if (local_err) {
7076 goto out;
7078 assert(full_backing);
7081 * No need to do I/O here, which allows us to open encrypted
7082 * backing images without needing the secret
7084 back_flags = flags;
7085 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7086 back_flags |= BDRV_O_NO_IO;
7088 backing_options = qdict_new();
7089 if (backing_fmt) {
7090 qdict_put_str(backing_options, "driver", backing_fmt);
7092 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7094 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7095 &local_err);
7096 g_free(full_backing);
7097 if (!bs) {
7098 error_append_hint(&local_err, "Could not open backing image.\n");
7099 goto out;
7100 } else {
7101 if (!backing_fmt) {
7102 error_setg(&local_err,
7103 "Backing file specified without backing format");
7104 error_append_hint(&local_err, "Detected format of %s.",
7105 bs->drv->format_name);
7106 goto out;
7108 if (size == -1) {
7109 /* Opened BS, have no size */
7110 size = bdrv_getlength(bs);
7111 if (size < 0) {
7112 error_setg_errno(errp, -size, "Could not get size of '%s'",
7113 backing_file);
7114 bdrv_unref(bs);
7115 goto out;
7117 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7119 bdrv_unref(bs);
7121 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7122 } else if (backing_file && !backing_fmt) {
7123 error_setg(&local_err,
7124 "Backing file specified without backing format");
7125 goto out;
7128 if (size == -1) {
7129 error_setg(errp, "Image creation needs a size parameter");
7130 goto out;
7133 if (!quiet) {
7134 printf("Formatting '%s', fmt=%s ", filename, fmt);
7135 qemu_opts_print(opts, " ");
7136 puts("");
7137 fflush(stdout);
7140 ret = bdrv_create(drv, filename, opts, &local_err);
7142 if (ret == -EFBIG) {
7143 /* This is generally a better message than whatever the driver would
7144 * deliver (especially because of the cluster_size_hint), since that
7145 * is most probably not much different from "image too large". */
7146 const char *cluster_size_hint = "";
7147 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7148 cluster_size_hint = " (try using a larger cluster size)";
7150 error_setg(errp, "The image size is too large for file format '%s'"
7151 "%s", fmt, cluster_size_hint);
7152 error_free(local_err);
7153 local_err = NULL;
7156 out:
7157 qemu_opts_del(opts);
7158 qemu_opts_free(create_opts);
7159 error_propagate(errp, local_err);
7162 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7164 IO_CODE();
7165 return bs ? bs->aio_context : qemu_get_aio_context();
7168 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7170 Coroutine *self = qemu_coroutine_self();
7171 AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7172 AioContext *new_ctx;
7173 IO_CODE();
7176 * Increase bs->in_flight to ensure that this operation is completed before
7177 * moving the node to a different AioContext. Read new_ctx only afterwards.
7179 bdrv_inc_in_flight(bs);
7181 new_ctx = bdrv_get_aio_context(bs);
7182 aio_co_reschedule_self(new_ctx);
7183 return old_ctx;
7186 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7188 IO_CODE();
7189 aio_co_reschedule_self(old_ctx);
7190 bdrv_dec_in_flight(bs);
7193 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7195 AioContext *ctx = bdrv_get_aio_context(bs);
7197 /* In the main thread, bs->aio_context won't change concurrently */
7198 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7201 * We're in coroutine context, so we already hold the lock of the main
7202 * loop AioContext. Don't lock it twice to avoid deadlocks.
7204 assert(qemu_in_coroutine());
7205 if (ctx != qemu_get_aio_context()) {
7206 aio_context_acquire(ctx);
7210 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7212 AioContext *ctx = bdrv_get_aio_context(bs);
7214 assert(qemu_in_coroutine());
7215 if (ctx != qemu_get_aio_context()) {
7216 aio_context_release(ctx);
7220 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7222 IO_CODE();
7223 aio_co_enter(bdrv_get_aio_context(bs), co);
7226 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7228 GLOBAL_STATE_CODE();
7229 QLIST_REMOVE(ban, list);
7230 g_free(ban);
7233 static void bdrv_detach_aio_context(BlockDriverState *bs)
7235 BdrvAioNotifier *baf, *baf_tmp;
7237 assert(!bs->walking_aio_notifiers);
7238 bs->walking_aio_notifiers = true;
7239 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7240 if (baf->deleted) {
7241 bdrv_do_remove_aio_context_notifier(baf);
7242 } else {
7243 baf->detach_aio_context(baf->opaque);
7246 /* Never mind iterating again to check for ->deleted. bdrv_close() will
7247 * remove remaining aio notifiers if we aren't called again.
7249 bs->walking_aio_notifiers = false;
7251 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7252 bs->drv->bdrv_detach_aio_context(bs);
7255 if (bs->quiesce_counter) {
7256 aio_enable_external(bs->aio_context);
7258 bs->aio_context = NULL;
7261 static void bdrv_attach_aio_context(BlockDriverState *bs,
7262 AioContext *new_context)
7264 BdrvAioNotifier *ban, *ban_tmp;
7266 if (bs->quiesce_counter) {
7267 aio_disable_external(new_context);
7270 bs->aio_context = new_context;
7272 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7273 bs->drv->bdrv_attach_aio_context(bs, new_context);
7276 assert(!bs->walking_aio_notifiers);
7277 bs->walking_aio_notifiers = true;
7278 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7279 if (ban->deleted) {
7280 bdrv_do_remove_aio_context_notifier(ban);
7281 } else {
7282 ban->attached_aio_context(new_context, ban->opaque);
7285 bs->walking_aio_notifiers = false;
7289 * Changes the AioContext used for fd handlers, timers, and BHs by this
7290 * BlockDriverState and all its children and parents.
7292 * Must be called from the main AioContext.
7294 * The caller must own the AioContext lock for the old AioContext of bs, but it
7295 * must not own the AioContext lock for new_context (unless new_context is the
7296 * same as the current context of bs).
7298 * @ignore will accumulate all visited BdrvChild object. The caller is
7299 * responsible for freeing the list afterwards.
7301 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7302 AioContext *new_context, GSList **ignore)
7304 AioContext *old_context = bdrv_get_aio_context(bs);
7305 GSList *children_to_process = NULL;
7306 GSList *parents_to_process = NULL;
7307 GSList *entry;
7308 BdrvChild *child, *parent;
7310 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7312 if (old_context == new_context) {
7313 return;
7316 bdrv_drained_begin(bs);
7318 QLIST_FOREACH(child, &bs->children, next) {
7319 if (g_slist_find(*ignore, child)) {
7320 continue;
7322 *ignore = g_slist_prepend(*ignore, child);
7323 children_to_process = g_slist_prepend(children_to_process, child);
7326 QLIST_FOREACH(parent, &bs->parents, next_parent) {
7327 if (g_slist_find(*ignore, parent)) {
7328 continue;
7330 *ignore = g_slist_prepend(*ignore, parent);
7331 parents_to_process = g_slist_prepend(parents_to_process, parent);
7334 for (entry = children_to_process;
7335 entry != NULL;
7336 entry = g_slist_next(entry)) {
7337 child = entry->data;
7338 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7340 g_slist_free(children_to_process);
7342 for (entry = parents_to_process;
7343 entry != NULL;
7344 entry = g_slist_next(entry)) {
7345 parent = entry->data;
7346 assert(parent->klass->set_aio_ctx);
7347 parent->klass->set_aio_ctx(parent, new_context, ignore);
7349 g_slist_free(parents_to_process);
7351 bdrv_detach_aio_context(bs);
7353 /* Acquire the new context, if necessary */
7354 if (qemu_get_aio_context() != new_context) {
7355 aio_context_acquire(new_context);
7358 bdrv_attach_aio_context(bs, new_context);
7361 * If this function was recursively called from
7362 * bdrv_set_aio_context_ignore(), there may be nodes in the
7363 * subtree that have not yet been moved to the new AioContext.
7364 * Release the old one so bdrv_drained_end() can poll them.
7366 if (qemu_get_aio_context() != old_context) {
7367 aio_context_release(old_context);
7370 bdrv_drained_end(bs);
7372 if (qemu_get_aio_context() != old_context) {
7373 aio_context_acquire(old_context);
7375 if (qemu_get_aio_context() != new_context) {
7376 aio_context_release(new_context);
7380 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7381 GSList **ignore, Error **errp)
7383 if (g_slist_find(*ignore, c)) {
7384 return true;
7386 *ignore = g_slist_prepend(*ignore, c);
7389 * A BdrvChildClass that doesn't handle AioContext changes cannot
7390 * tolerate any AioContext changes
7392 if (!c->klass->can_set_aio_ctx) {
7393 char *user = bdrv_child_user_desc(c);
7394 error_setg(errp, "Changing iothreads is not supported by %s", user);
7395 g_free(user);
7396 return false;
7398 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
7399 assert(!errp || *errp);
7400 return false;
7402 return true;
7405 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7406 GSList **ignore, Error **errp)
7408 GLOBAL_STATE_CODE();
7409 if (g_slist_find(*ignore, c)) {
7410 return true;
7412 *ignore = g_slist_prepend(*ignore, c);
7413 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7416 /* @ignore will accumulate all visited BdrvChild object. The caller is
7417 * responsible for freeing the list afterwards. */
7418 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7419 GSList **ignore, Error **errp)
7421 BdrvChild *c;
7423 if (bdrv_get_aio_context(bs) == ctx) {
7424 return true;
7427 GLOBAL_STATE_CODE();
7429 QLIST_FOREACH(c, &bs->parents, next_parent) {
7430 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7431 return false;
7434 QLIST_FOREACH(c, &bs->children, next) {
7435 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7436 return false;
7440 return true;
7443 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7444 BdrvChild *ignore_child, Error **errp)
7446 GSList *ignore;
7447 bool ret;
7449 GLOBAL_STATE_CODE();
7451 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7452 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7453 g_slist_free(ignore);
7455 if (!ret) {
7456 return -EPERM;
7459 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7460 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7461 g_slist_free(ignore);
7463 return 0;
7466 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7467 Error **errp)
7469 GLOBAL_STATE_CODE();
7470 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7473 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7474 void (*attached_aio_context)(AioContext *new_context, void *opaque),
7475 void (*detach_aio_context)(void *opaque), void *opaque)
7477 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7478 *ban = (BdrvAioNotifier){
7479 .attached_aio_context = attached_aio_context,
7480 .detach_aio_context = detach_aio_context,
7481 .opaque = opaque
7483 GLOBAL_STATE_CODE();
7485 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7488 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7489 void (*attached_aio_context)(AioContext *,
7490 void *),
7491 void (*detach_aio_context)(void *),
7492 void *opaque)
7494 BdrvAioNotifier *ban, *ban_next;
7495 GLOBAL_STATE_CODE();
7497 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7498 if (ban->attached_aio_context == attached_aio_context &&
7499 ban->detach_aio_context == detach_aio_context &&
7500 ban->opaque == opaque &&
7501 ban->deleted == false)
7503 if (bs->walking_aio_notifiers) {
7504 ban->deleted = true;
7505 } else {
7506 bdrv_do_remove_aio_context_notifier(ban);
7508 return;
7512 abort();
7515 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7516 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7517 bool force,
7518 Error **errp)
7520 GLOBAL_STATE_CODE();
7521 if (!bs->drv) {
7522 error_setg(errp, "Node is ejected");
7523 return -ENOMEDIUM;
7525 if (!bs->drv->bdrv_amend_options) {
7526 error_setg(errp, "Block driver '%s' does not support option amendment",
7527 bs->drv->format_name);
7528 return -ENOTSUP;
7530 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7531 cb_opaque, force, errp);
7535 * This function checks whether the given @to_replace is allowed to be
7536 * replaced by a node that always shows the same data as @bs. This is
7537 * used for example to verify whether the mirror job can replace
7538 * @to_replace by the target mirrored from @bs.
7539 * To be replaceable, @bs and @to_replace may either be guaranteed to
7540 * always show the same data (because they are only connected through
7541 * filters), or some driver may allow replacing one of its children
7542 * because it can guarantee that this child's data is not visible at
7543 * all (for example, for dissenting quorum children that have no other
7544 * parents).
7546 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7547 BlockDriverState *to_replace)
7549 BlockDriverState *filtered;
7551 GLOBAL_STATE_CODE();
7553 if (!bs || !bs->drv) {
7554 return false;
7557 if (bs == to_replace) {
7558 return true;
7561 /* See what the driver can do */
7562 if (bs->drv->bdrv_recurse_can_replace) {
7563 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7566 /* For filters without an own implementation, we can recurse on our own */
7567 filtered = bdrv_filter_bs(bs);
7568 if (filtered) {
7569 return bdrv_recurse_can_replace(filtered, to_replace);
7572 /* Safe default */
7573 return false;
7577 * Check whether the given @node_name can be replaced by a node that
7578 * has the same data as @parent_bs. If so, return @node_name's BDS;
7579 * NULL otherwise.
7581 * @node_name must be a (recursive) *child of @parent_bs (or this
7582 * function will return NULL).
7584 * The result (whether the node can be replaced or not) is only valid
7585 * for as long as no graph or permission changes occur.
7587 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7588 const char *node_name, Error **errp)
7590 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7591 AioContext *aio_context;
7593 GLOBAL_STATE_CODE();
7595 if (!to_replace_bs) {
7596 error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7597 return NULL;
7600 aio_context = bdrv_get_aio_context(to_replace_bs);
7601 aio_context_acquire(aio_context);
7603 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7604 to_replace_bs = NULL;
7605 goto out;
7608 /* We don't want arbitrary node of the BDS chain to be replaced only the top
7609 * most non filter in order to prevent data corruption.
7610 * Another benefit is that this tests exclude backing files which are
7611 * blocked by the backing blockers.
7613 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7614 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7615 "because it cannot be guaranteed that doing so would not "
7616 "lead to an abrupt change of visible data",
7617 node_name, parent_bs->node_name);
7618 to_replace_bs = NULL;
7619 goto out;
7622 out:
7623 aio_context_release(aio_context);
7624 return to_replace_bs;
7628 * Iterates through the list of runtime option keys that are said to
7629 * be "strong" for a BDS. An option is called "strong" if it changes
7630 * a BDS's data. For example, the null block driver's "size" and
7631 * "read-zeroes" options are strong, but its "latency-ns" option is
7632 * not.
7634 * If a key returned by this function ends with a dot, all options
7635 * starting with that prefix are strong.
7637 static const char *const *strong_options(BlockDriverState *bs,
7638 const char *const *curopt)
7640 static const char *const global_options[] = {
7641 "driver", "filename", NULL
7644 if (!curopt) {
7645 return &global_options[0];
7648 curopt++;
7649 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7650 curopt = bs->drv->strong_runtime_opts;
7653 return (curopt && *curopt) ? curopt : NULL;
7657 * Copies all strong runtime options from bs->options to the given
7658 * QDict. The set of strong option keys is determined by invoking
7659 * strong_options().
7661 * Returns true iff any strong option was present in bs->options (and
7662 * thus copied to the target QDict) with the exception of "filename"
7663 * and "driver". The caller is expected to use this value to decide
7664 * whether the existence of strong options prevents the generation of
7665 * a plain filename.
7667 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7669 bool found_any = false;
7670 const char *const *option_name = NULL;
7672 if (!bs->drv) {
7673 return false;
7676 while ((option_name = strong_options(bs, option_name))) {
7677 bool option_given = false;
7679 assert(strlen(*option_name) > 0);
7680 if ((*option_name)[strlen(*option_name) - 1] != '.') {
7681 QObject *entry = qdict_get(bs->options, *option_name);
7682 if (!entry) {
7683 continue;
7686 qdict_put_obj(d, *option_name, qobject_ref(entry));
7687 option_given = true;
7688 } else {
7689 const QDictEntry *entry;
7690 for (entry = qdict_first(bs->options); entry;
7691 entry = qdict_next(bs->options, entry))
7693 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7694 qdict_put_obj(d, qdict_entry_key(entry),
7695 qobject_ref(qdict_entry_value(entry)));
7696 option_given = true;
7701 /* While "driver" and "filename" need to be included in a JSON filename,
7702 * their existence does not prohibit generation of a plain filename. */
7703 if (!found_any && option_given &&
7704 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7706 found_any = true;
7710 if (!qdict_haskey(d, "driver")) {
7711 /* Drivers created with bdrv_new_open_driver() may not have a
7712 * @driver option. Add it here. */
7713 qdict_put_str(d, "driver", bs->drv->format_name);
7716 return found_any;
7719 /* Note: This function may return false positives; it may return true
7720 * even if opening the backing file specified by bs's image header
7721 * would result in exactly bs->backing. */
7722 static bool bdrv_backing_overridden(BlockDriverState *bs)
7724 GLOBAL_STATE_CODE();
7725 if (bs->backing) {
7726 return strcmp(bs->auto_backing_file,
7727 bs->backing->bs->filename);
7728 } else {
7729 /* No backing BDS, so if the image header reports any backing
7730 * file, it must have been suppressed */
7731 return bs->auto_backing_file[0] != '\0';
7735 /* Updates the following BDS fields:
7736 * - exact_filename: A filename which may be used for opening a block device
7737 * which (mostly) equals the given BDS (even without any
7738 * other options; so reading and writing must return the same
7739 * results, but caching etc. may be different)
7740 * - full_open_options: Options which, when given when opening a block device
7741 * (without a filename), result in a BDS (mostly)
7742 * equalling the given one
7743 * - filename: If exact_filename is set, it is copied here. Otherwise,
7744 * full_open_options is converted to a JSON object, prefixed with
7745 * "json:" (for use through the JSON pseudo protocol) and put here.
7747 void bdrv_refresh_filename(BlockDriverState *bs)
7749 BlockDriver *drv = bs->drv;
7750 BdrvChild *child;
7751 BlockDriverState *primary_child_bs;
7752 QDict *opts;
7753 bool backing_overridden;
7754 bool generate_json_filename; /* Whether our default implementation should
7755 fill exact_filename (false) or not (true) */
7757 GLOBAL_STATE_CODE();
7759 if (!drv) {
7760 return;
7763 /* This BDS's file name may depend on any of its children's file names, so
7764 * refresh those first */
7765 QLIST_FOREACH(child, &bs->children, next) {
7766 bdrv_refresh_filename(child->bs);
7769 if (bs->implicit) {
7770 /* For implicit nodes, just copy everything from the single child */
7771 child = QLIST_FIRST(&bs->children);
7772 assert(QLIST_NEXT(child, next) == NULL);
7774 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7775 child->bs->exact_filename);
7776 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7778 qobject_unref(bs->full_open_options);
7779 bs->full_open_options = qobject_ref(child->bs->full_open_options);
7781 return;
7784 backing_overridden = bdrv_backing_overridden(bs);
7786 if (bs->open_flags & BDRV_O_NO_IO) {
7787 /* Without I/O, the backing file does not change anything.
7788 * Therefore, in such a case (primarily qemu-img), we can
7789 * pretend the backing file has not been overridden even if
7790 * it technically has been. */
7791 backing_overridden = false;
7794 /* Gather the options QDict */
7795 opts = qdict_new();
7796 generate_json_filename = append_strong_runtime_options(opts, bs);
7797 generate_json_filename |= backing_overridden;
7799 if (drv->bdrv_gather_child_options) {
7800 /* Some block drivers may not want to present all of their children's
7801 * options, or name them differently from BdrvChild.name */
7802 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7803 } else {
7804 QLIST_FOREACH(child, &bs->children, next) {
7805 if (child == bs->backing && !backing_overridden) {
7806 /* We can skip the backing BDS if it has not been overridden */
7807 continue;
7810 qdict_put(opts, child->name,
7811 qobject_ref(child->bs->full_open_options));
7814 if (backing_overridden && !bs->backing) {
7815 /* Force no backing file */
7816 qdict_put_null(opts, "backing");
7820 qobject_unref(bs->full_open_options);
7821 bs->full_open_options = opts;
7823 primary_child_bs = bdrv_primary_bs(bs);
7825 if (drv->bdrv_refresh_filename) {
7826 /* Obsolete information is of no use here, so drop the old file name
7827 * information before refreshing it */
7828 bs->exact_filename[0] = '\0';
7830 drv->bdrv_refresh_filename(bs);
7831 } else if (primary_child_bs) {
7833 * Try to reconstruct valid information from the underlying
7834 * file -- this only works for format nodes (filter nodes
7835 * cannot be probed and as such must be selected by the user
7836 * either through an options dict, or through a special
7837 * filename which the filter driver must construct in its
7838 * .bdrv_refresh_filename() implementation).
7841 bs->exact_filename[0] = '\0';
7844 * We can use the underlying file's filename if:
7845 * - it has a filename,
7846 * - the current BDS is not a filter,
7847 * - the file is a protocol BDS, and
7848 * - opening that file (as this BDS's format) will automatically create
7849 * the BDS tree we have right now, that is:
7850 * - the user did not significantly change this BDS's behavior with
7851 * some explicit (strong) options
7852 * - no non-file child of this BDS has been overridden by the user
7853 * Both of these conditions are represented by generate_json_filename.
7855 if (primary_child_bs->exact_filename[0] &&
7856 primary_child_bs->drv->bdrv_file_open &&
7857 !drv->is_filter && !generate_json_filename)
7859 strcpy(bs->exact_filename, primary_child_bs->exact_filename);
7863 if (bs->exact_filename[0]) {
7864 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
7865 } else {
7866 GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
7867 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
7868 json->str) >= sizeof(bs->filename)) {
7869 /* Give user a hint if we truncated things. */
7870 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7872 g_string_free(json, true);
7876 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7878 BlockDriver *drv = bs->drv;
7879 BlockDriverState *child_bs;
7881 GLOBAL_STATE_CODE();
7883 if (!drv) {
7884 error_setg(errp, "Node '%s' is ejected", bs->node_name);
7885 return NULL;
7888 if (drv->bdrv_dirname) {
7889 return drv->bdrv_dirname(bs, errp);
7892 child_bs = bdrv_primary_bs(bs);
7893 if (child_bs) {
7894 return bdrv_dirname(child_bs, errp);
7897 bdrv_refresh_filename(bs);
7898 if (bs->exact_filename[0] != '\0') {
7899 return path_combine(bs->exact_filename, "");
7902 error_setg(errp, "Cannot generate a base directory for %s nodes",
7903 drv->format_name);
7904 return NULL;
7908 * Hot add/remove a BDS's child. So the user can take a child offline when
7909 * it is broken and take a new child online
7911 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7912 Error **errp)
7914 GLOBAL_STATE_CODE();
7915 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7916 error_setg(errp, "The node %s does not support adding a child",
7917 bdrv_get_device_or_node_name(parent_bs));
7918 return;
7921 if (!QLIST_EMPTY(&child_bs->parents)) {
7922 error_setg(errp, "The node %s already has a parent",
7923 child_bs->node_name);
7924 return;
7927 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7930 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7932 BdrvChild *tmp;
7934 GLOBAL_STATE_CODE();
7935 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7936 error_setg(errp, "The node %s does not support removing a child",
7937 bdrv_get_device_or_node_name(parent_bs));
7938 return;
7941 QLIST_FOREACH(tmp, &parent_bs->children, next) {
7942 if (tmp == child) {
7943 break;
7947 if (!tmp) {
7948 error_setg(errp, "The node %s does not have a child named %s",
7949 bdrv_get_device_or_node_name(parent_bs),
7950 bdrv_get_device_or_node_name(child->bs));
7951 return;
7954 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7957 int bdrv_make_empty(BdrvChild *c, Error **errp)
7959 BlockDriver *drv = c->bs->drv;
7960 int ret;
7962 GLOBAL_STATE_CODE();
7963 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7965 if (!drv->bdrv_make_empty) {
7966 error_setg(errp, "%s does not support emptying nodes",
7967 drv->format_name);
7968 return -ENOTSUP;
7971 ret = drv->bdrv_make_empty(c->bs);
7972 if (ret < 0) {
7973 error_setg_errno(errp, -ret, "Failed to empty %s",
7974 c->bs->filename);
7975 return ret;
7978 return 0;
7982 * Return the child that @bs acts as an overlay for, and from which data may be
7983 * copied in COW or COR operations. Usually this is the backing file.
7985 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7987 IO_CODE();
7989 if (!bs || !bs->drv) {
7990 return NULL;
7993 if (bs->drv->is_filter) {
7994 return NULL;
7997 if (!bs->backing) {
7998 return NULL;
8001 assert(bs->backing->role & BDRV_CHILD_COW);
8002 return bs->backing;
8006 * If @bs acts as a filter for exactly one of its children, return
8007 * that child.
8009 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8011 BdrvChild *c;
8012 IO_CODE();
8014 if (!bs || !bs->drv) {
8015 return NULL;
8018 if (!bs->drv->is_filter) {
8019 return NULL;
8022 /* Only one of @backing or @file may be used */
8023 assert(!(bs->backing && bs->file));
8025 c = bs->backing ?: bs->file;
8026 if (!c) {
8027 return NULL;
8030 assert(c->role & BDRV_CHILD_FILTERED);
8031 return c;
8035 * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8036 * whichever is non-NULL.
8038 * Return NULL if both are NULL.
8040 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8042 BdrvChild *cow_child = bdrv_cow_child(bs);
8043 BdrvChild *filter_child = bdrv_filter_child(bs);
8044 IO_CODE();
8046 /* Filter nodes cannot have COW backing files */
8047 assert(!(cow_child && filter_child));
8049 return cow_child ?: filter_child;
8053 * Return the primary child of this node: For filters, that is the
8054 * filtered child. For other nodes, that is usually the child storing
8055 * metadata.
8056 * (A generally more helpful description is that this is (usually) the
8057 * child that has the same filename as @bs.)
8059 * Drivers do not necessarily have a primary child; for example quorum
8060 * does not.
8062 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8064 BdrvChild *c, *found = NULL;
8065 IO_CODE();
8067 QLIST_FOREACH(c, &bs->children, next) {
8068 if (c->role & BDRV_CHILD_PRIMARY) {
8069 assert(!found);
8070 found = c;
8074 return found;
8077 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8078 bool stop_on_explicit_filter)
8080 BdrvChild *c;
8082 if (!bs) {
8083 return NULL;
8086 while (!(stop_on_explicit_filter && !bs->implicit)) {
8087 c = bdrv_filter_child(bs);
8088 if (!c) {
8090 * A filter that is embedded in a working block graph must
8091 * have a child. Assert this here so this function does
8092 * not return a filter node that is not expected by the
8093 * caller.
8095 assert(!bs->drv || !bs->drv->is_filter);
8096 break;
8098 bs = c->bs;
8101 * Note that this treats nodes with bs->drv == NULL as not being
8102 * filters (bs->drv == NULL should be replaced by something else
8103 * anyway).
8104 * The advantage of this behavior is that this function will thus
8105 * always return a non-NULL value (given a non-NULL @bs).
8108 return bs;
8112 * Return the first BDS that has not been added implicitly or that
8113 * does not have a filtered child down the chain starting from @bs
8114 * (including @bs itself).
8116 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8118 GLOBAL_STATE_CODE();
8119 return bdrv_do_skip_filters(bs, true);
8123 * Return the first BDS that does not have a filtered child down the
8124 * chain starting from @bs (including @bs itself).
8126 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8128 IO_CODE();
8129 return bdrv_do_skip_filters(bs, false);
8133 * For a backing chain, return the first non-filter backing image of
8134 * the first non-filter image.
8136 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8138 IO_CODE();
8139 return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8143 * Check whether [offset, offset + bytes) overlaps with the cached
8144 * block-status data region.
8146 * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8147 * which is what bdrv_bsc_is_data()'s interface needs.
8148 * Otherwise, *pnum is not touched.
8150 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8151 int64_t offset, int64_t bytes,
8152 int64_t *pnum)
8154 BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8155 bool overlaps;
8157 overlaps =
8158 qatomic_read(&bsc->valid) &&
8159 ranges_overlap(offset, bytes, bsc->data_start,
8160 bsc->data_end - bsc->data_start);
8162 if (overlaps && pnum) {
8163 *pnum = bsc->data_end - offset;
8166 return overlaps;
8170 * See block_int.h for this function's documentation.
8172 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8174 IO_CODE();
8175 RCU_READ_LOCK_GUARD();
8176 return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8180 * See block_int.h for this function's documentation.
8182 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8183 int64_t offset, int64_t bytes)
8185 IO_CODE();
8186 RCU_READ_LOCK_GUARD();
8188 if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8189 qatomic_set(&bs->block_status_cache->valid, false);
8194 * See block_int.h for this function's documentation.
8196 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8198 BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8199 BdrvBlockStatusCache *old_bsc;
8200 IO_CODE();
8202 *new_bsc = (BdrvBlockStatusCache) {
8203 .valid = true,
8204 .data_start = offset,
8205 .data_end = offset + bytes,
8208 QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8210 old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8211 qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8212 if (old_bsc) {
8213 g_free_rcu(old_bsc, rcu);