block: Drop child_format
[qemu.git] / block.c
blob85b4f947babdd653505387afe0fb3ccbaaf038fa
1 /*
2 * QEMU System Emulator block driver
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
25 #include "qemu/osdep.h"
26 #include "block/trace.h"
27 #include "block/block_int.h"
28 #include "block/blockjob.h"
29 #include "block/nbd.h"
30 #include "block/qdict.h"
31 #include "qemu/error-report.h"
32 #include "module_block.h"
33 #include "qemu/main-loop.h"
34 #include "qemu/module.h"
35 #include "qapi/error.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qapi/qmp/qjson.h"
38 #include "qapi/qmp/qnull.h"
39 #include "qapi/qmp/qstring.h"
40 #include "qapi/qobject-output-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "sysemu/block-backend.h"
43 #include "sysemu/sysemu.h"
44 #include "qemu/notify.h"
45 #include "qemu/option.h"
46 #include "qemu/coroutine.h"
47 #include "block/qapi.h"
48 #include "qemu/timer.h"
49 #include "qemu/cutils.h"
50 #include "qemu/id.h"
52 #ifdef CONFIG_BSD
53 #include <sys/ioctl.h>
54 #include <sys/queue.h>
55 #ifndef __DragonFly__
56 #include <sys/disk.h>
57 #endif
58 #endif
60 #ifdef _WIN32
61 #include <windows.h>
62 #endif
64 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
66 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
67 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
69 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
70 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
72 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
73 QLIST_HEAD_INITIALIZER(bdrv_drivers);
75 static BlockDriverState *bdrv_open_inherit(const char *filename,
76 const char *reference,
77 QDict *options, int flags,
78 BlockDriverState *parent,
79 const BdrvChildClass *child_class,
80 BdrvChildRole child_role,
81 Error **errp);
83 /* TODO: Remove when no longer needed */
84 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
85 int *child_flags, QDict *child_options,
86 int parent_flags, QDict *parent_options);
87 static void bdrv_child_cb_attach(BdrvChild *child);
88 static void bdrv_child_cb_detach(BdrvChild *child);
90 /* If non-zero, use only whitelisted block drivers */
91 static int use_bdrv_whitelist;
93 #ifdef _WIN32
94 static int is_windows_drive_prefix(const char *filename)
96 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
97 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
98 filename[1] == ':');
101 int is_windows_drive(const char *filename)
103 if (is_windows_drive_prefix(filename) &&
104 filename[2] == '\0')
105 return 1;
106 if (strstart(filename, "\\\\.\\", NULL) ||
107 strstart(filename, "//./", NULL))
108 return 1;
109 return 0;
111 #endif
113 size_t bdrv_opt_mem_align(BlockDriverState *bs)
115 if (!bs || !bs->drv) {
116 /* page size or 4k (hdd sector size) should be on the safe side */
117 return MAX(4096, qemu_real_host_page_size);
120 return bs->bl.opt_mem_alignment;
123 size_t bdrv_min_mem_align(BlockDriverState *bs)
125 if (!bs || !bs->drv) {
126 /* page size or 4k (hdd sector size) should be on the safe side */
127 return MAX(4096, qemu_real_host_page_size);
130 return bs->bl.min_mem_alignment;
133 /* check if the path starts with "<protocol>:" */
134 int path_has_protocol(const char *path)
136 const char *p;
138 #ifdef _WIN32
139 if (is_windows_drive(path) ||
140 is_windows_drive_prefix(path)) {
141 return 0;
143 p = path + strcspn(path, ":/\\");
144 #else
145 p = path + strcspn(path, ":/");
146 #endif
148 return *p == ':';
151 int path_is_absolute(const char *path)
153 #ifdef _WIN32
154 /* specific case for names like: "\\.\d:" */
155 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
156 return 1;
158 return (*path == '/' || *path == '\\');
159 #else
160 return (*path == '/');
161 #endif
164 /* if filename is absolute, just return its duplicate. Otherwise, build a
165 path to it by considering it is relative to base_path. URL are
166 supported. */
167 char *path_combine(const char *base_path, const char *filename)
169 const char *protocol_stripped = NULL;
170 const char *p, *p1;
171 char *result;
172 int len;
174 if (path_is_absolute(filename)) {
175 return g_strdup(filename);
178 if (path_has_protocol(base_path)) {
179 protocol_stripped = strchr(base_path, ':');
180 if (protocol_stripped) {
181 protocol_stripped++;
184 p = protocol_stripped ?: base_path;
186 p1 = strrchr(base_path, '/');
187 #ifdef _WIN32
189 const char *p2;
190 p2 = strrchr(base_path, '\\');
191 if (!p1 || p2 > p1) {
192 p1 = p2;
195 #endif
196 if (p1) {
197 p1++;
198 } else {
199 p1 = base_path;
201 if (p1 > p) {
202 p = p1;
204 len = p - base_path;
206 result = g_malloc(len + strlen(filename) + 1);
207 memcpy(result, base_path, len);
208 strcpy(result + len, filename);
210 return result;
214 * Helper function for bdrv_parse_filename() implementations to remove optional
215 * protocol prefixes (especially "file:") from a filename and for putting the
216 * stripped filename into the options QDict if there is such a prefix.
218 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
219 QDict *options)
221 if (strstart(filename, prefix, &filename)) {
222 /* Stripping the explicit protocol prefix may result in a protocol
223 * prefix being (wrongly) detected (if the filename contains a colon) */
224 if (path_has_protocol(filename)) {
225 QString *fat_filename;
227 /* This means there is some colon before the first slash; therefore,
228 * this cannot be an absolute path */
229 assert(!path_is_absolute(filename));
231 /* And we can thus fix the protocol detection issue by prefixing it
232 * by "./" */
233 fat_filename = qstring_from_str("./");
234 qstring_append(fat_filename, filename);
236 assert(!path_has_protocol(qstring_get_str(fat_filename)));
238 qdict_put(options, "filename", fat_filename);
239 } else {
240 /* If no protocol prefix was detected, we can use the shortened
241 * filename as-is */
242 qdict_put_str(options, "filename", filename);
248 /* Returns whether the image file is opened as read-only. Note that this can
249 * return false and writing to the image file is still not possible because the
250 * image is inactivated. */
251 bool bdrv_is_read_only(BlockDriverState *bs)
253 return bs->read_only;
256 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
257 bool ignore_allow_rdw, Error **errp)
259 /* Do not set read_only if copy_on_read is enabled */
260 if (bs->copy_on_read && read_only) {
261 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
262 bdrv_get_device_or_node_name(bs));
263 return -EINVAL;
266 /* Do not clear read_only if it is prohibited */
267 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
268 !ignore_allow_rdw)
270 error_setg(errp, "Node '%s' is read only",
271 bdrv_get_device_or_node_name(bs));
272 return -EPERM;
275 return 0;
279 * Called by a driver that can only provide a read-only image.
281 * Returns 0 if the node is already read-only or it could switch the node to
282 * read-only because BDRV_O_AUTO_RDONLY is set.
284 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
285 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
286 * is not NULL, it is used as the error message for the Error object.
288 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
289 Error **errp)
291 int ret = 0;
293 if (!(bs->open_flags & BDRV_O_RDWR)) {
294 return 0;
296 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
297 goto fail;
300 ret = bdrv_can_set_read_only(bs, true, false, NULL);
301 if (ret < 0) {
302 goto fail;
305 bs->read_only = true;
306 bs->open_flags &= ~BDRV_O_RDWR;
308 return 0;
310 fail:
311 error_setg(errp, "%s", errmsg ?: "Image is read-only");
312 return -EACCES;
316 * If @backing is empty, this function returns NULL without setting
317 * @errp. In all other cases, NULL will only be returned with @errp
318 * set.
320 * Therefore, a return value of NULL without @errp set means that
321 * there is no backing file; if @errp is set, there is one but its
322 * absolute filename cannot be generated.
324 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
325 const char *backing,
326 Error **errp)
328 if (backing[0] == '\0') {
329 return NULL;
330 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
331 return g_strdup(backing);
332 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
333 error_setg(errp, "Cannot use relative backing file names for '%s'",
334 backed);
335 return NULL;
336 } else {
337 return path_combine(backed, backing);
342 * If @filename is empty or NULL, this function returns NULL without
343 * setting @errp. In all other cases, NULL will only be returned with
344 * @errp set.
346 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
347 const char *filename, Error **errp)
349 char *dir, *full_name;
351 if (!filename || filename[0] == '\0') {
352 return NULL;
353 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
354 return g_strdup(filename);
357 dir = bdrv_dirname(relative_to, errp);
358 if (!dir) {
359 return NULL;
362 full_name = g_strconcat(dir, filename, NULL);
363 g_free(dir);
364 return full_name;
367 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
369 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
372 void bdrv_register(BlockDriver *bdrv)
374 assert(bdrv->format_name);
375 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
378 BlockDriverState *bdrv_new(void)
380 BlockDriverState *bs;
381 int i;
383 bs = g_new0(BlockDriverState, 1);
384 QLIST_INIT(&bs->dirty_bitmaps);
385 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
386 QLIST_INIT(&bs->op_blockers[i]);
388 notifier_with_return_list_init(&bs->before_write_notifiers);
389 qemu_co_mutex_init(&bs->reqs_lock);
390 qemu_mutex_init(&bs->dirty_bitmap_mutex);
391 bs->refcnt = 1;
392 bs->aio_context = qemu_get_aio_context();
394 qemu_co_queue_init(&bs->flush_queue);
396 for (i = 0; i < bdrv_drain_all_count; i++) {
397 bdrv_drained_begin(bs);
400 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
402 return bs;
405 static BlockDriver *bdrv_do_find_format(const char *format_name)
407 BlockDriver *drv1;
409 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
410 if (!strcmp(drv1->format_name, format_name)) {
411 return drv1;
415 return NULL;
418 BlockDriver *bdrv_find_format(const char *format_name)
420 BlockDriver *drv1;
421 int i;
423 drv1 = bdrv_do_find_format(format_name);
424 if (drv1) {
425 return drv1;
428 /* The driver isn't registered, maybe we need to load a module */
429 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
430 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
431 block_module_load_one(block_driver_modules[i].library_name);
432 break;
436 return bdrv_do_find_format(format_name);
439 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
441 static const char *whitelist_rw[] = {
442 CONFIG_BDRV_RW_WHITELIST
444 static const char *whitelist_ro[] = {
445 CONFIG_BDRV_RO_WHITELIST
447 const char **p;
449 if (!whitelist_rw[0] && !whitelist_ro[0]) {
450 return 1; /* no whitelist, anything goes */
453 for (p = whitelist_rw; *p; p++) {
454 if (!strcmp(format_name, *p)) {
455 return 1;
458 if (read_only) {
459 for (p = whitelist_ro; *p; p++) {
460 if (!strcmp(format_name, *p)) {
461 return 1;
465 return 0;
468 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
470 return bdrv_format_is_whitelisted(drv->format_name, read_only);
473 bool bdrv_uses_whitelist(void)
475 return use_bdrv_whitelist;
478 typedef struct CreateCo {
479 BlockDriver *drv;
480 char *filename;
481 QemuOpts *opts;
482 int ret;
483 Error *err;
484 } CreateCo;
486 static void coroutine_fn bdrv_create_co_entry(void *opaque)
488 Error *local_err = NULL;
489 int ret;
491 CreateCo *cco = opaque;
492 assert(cco->drv);
494 ret = cco->drv->bdrv_co_create_opts(cco->drv,
495 cco->filename, cco->opts, &local_err);
496 error_propagate(&cco->err, local_err);
497 cco->ret = ret;
500 int bdrv_create(BlockDriver *drv, const char* filename,
501 QemuOpts *opts, Error **errp)
503 int ret;
505 Coroutine *co;
506 CreateCo cco = {
507 .drv = drv,
508 .filename = g_strdup(filename),
509 .opts = opts,
510 .ret = NOT_DONE,
511 .err = NULL,
514 if (!drv->bdrv_co_create_opts) {
515 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
516 ret = -ENOTSUP;
517 goto out;
520 if (qemu_in_coroutine()) {
521 /* Fast-path if already in coroutine context */
522 bdrv_create_co_entry(&cco);
523 } else {
524 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
525 qemu_coroutine_enter(co);
526 while (cco.ret == NOT_DONE) {
527 aio_poll(qemu_get_aio_context(), true);
531 ret = cco.ret;
532 if (ret < 0) {
533 if (cco.err) {
534 error_propagate(errp, cco.err);
535 } else {
536 error_setg_errno(errp, -ret, "Could not create image");
540 out:
541 g_free(cco.filename);
542 return ret;
546 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
547 * least the given @minimum_size.
549 * On success, return @blk's actual length.
550 * Otherwise, return -errno.
552 static int64_t create_file_fallback_truncate(BlockBackend *blk,
553 int64_t minimum_size, Error **errp)
555 Error *local_err = NULL;
556 int64_t size;
557 int ret;
559 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
560 &local_err);
561 if (ret < 0 && ret != -ENOTSUP) {
562 error_propagate(errp, local_err);
563 return ret;
566 size = blk_getlength(blk);
567 if (size < 0) {
568 error_free(local_err);
569 error_setg_errno(errp, -size,
570 "Failed to inquire the new image file's length");
571 return size;
574 if (size < minimum_size) {
575 /* Need to grow the image, but we failed to do that */
576 error_propagate(errp, local_err);
577 return -ENOTSUP;
580 error_free(local_err);
581 local_err = NULL;
583 return size;
587 * Helper function for bdrv_create_file_fallback(): Zero the first
588 * sector to remove any potentially pre-existing image header.
590 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
591 int64_t current_size,
592 Error **errp)
594 int64_t bytes_to_clear;
595 int ret;
597 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
598 if (bytes_to_clear) {
599 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
600 if (ret < 0) {
601 error_setg_errno(errp, -ret,
602 "Failed to clear the new image's first sector");
603 return ret;
607 return 0;
611 * Simple implementation of bdrv_co_create_opts for protocol drivers
612 * which only support creation via opening a file
613 * (usually existing raw storage device)
615 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
616 const char *filename,
617 QemuOpts *opts,
618 Error **errp)
620 BlockBackend *blk;
621 QDict *options;
622 int64_t size = 0;
623 char *buf = NULL;
624 PreallocMode prealloc;
625 Error *local_err = NULL;
626 int ret;
628 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
629 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
630 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
631 PREALLOC_MODE_OFF, &local_err);
632 g_free(buf);
633 if (local_err) {
634 error_propagate(errp, local_err);
635 return -EINVAL;
638 if (prealloc != PREALLOC_MODE_OFF) {
639 error_setg(errp, "Unsupported preallocation mode '%s'",
640 PreallocMode_str(prealloc));
641 return -ENOTSUP;
644 options = qdict_new();
645 qdict_put_str(options, "driver", drv->format_name);
647 blk = blk_new_open(filename, NULL, options,
648 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
649 if (!blk) {
650 error_prepend(errp, "Protocol driver '%s' does not support image "
651 "creation, and opening the image failed: ",
652 drv->format_name);
653 return -EINVAL;
656 size = create_file_fallback_truncate(blk, size, errp);
657 if (size < 0) {
658 ret = size;
659 goto out;
662 ret = create_file_fallback_zero_first_sector(blk, size, errp);
663 if (ret < 0) {
664 goto out;
667 ret = 0;
668 out:
669 blk_unref(blk);
670 return ret;
673 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
675 BlockDriver *drv;
677 drv = bdrv_find_protocol(filename, true, errp);
678 if (drv == NULL) {
679 return -ENOENT;
682 return bdrv_create(drv, filename, opts, errp);
685 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
687 Error *local_err = NULL;
688 int ret;
690 assert(bs != NULL);
692 if (!bs->drv) {
693 error_setg(errp, "Block node '%s' is not opened", bs->filename);
694 return -ENOMEDIUM;
697 if (!bs->drv->bdrv_co_delete_file) {
698 error_setg(errp, "Driver '%s' does not support image deletion",
699 bs->drv->format_name);
700 return -ENOTSUP;
703 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
704 if (ret < 0) {
705 error_propagate(errp, local_err);
708 return ret;
712 * Try to get @bs's logical and physical block size.
713 * On success, store them in @bsz struct and return 0.
714 * On failure return -errno.
715 * @bs must not be empty.
717 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
719 BlockDriver *drv = bs->drv;
721 if (drv && drv->bdrv_probe_blocksizes) {
722 return drv->bdrv_probe_blocksizes(bs, bsz);
723 } else if (drv && drv->is_filter && bs->file) {
724 return bdrv_probe_blocksizes(bs->file->bs, bsz);
727 return -ENOTSUP;
731 * Try to get @bs's geometry (cyls, heads, sectors).
732 * On success, store them in @geo struct and return 0.
733 * On failure return -errno.
734 * @bs must not be empty.
736 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
738 BlockDriver *drv = bs->drv;
740 if (drv && drv->bdrv_probe_geometry) {
741 return drv->bdrv_probe_geometry(bs, geo);
742 } else if (drv && drv->is_filter && bs->file) {
743 return bdrv_probe_geometry(bs->file->bs, geo);
746 return -ENOTSUP;
750 * Create a uniquely-named empty temporary file.
751 * Return 0 upon success, otherwise a negative errno value.
753 int get_tmp_filename(char *filename, int size)
755 #ifdef _WIN32
756 char temp_dir[MAX_PATH];
757 /* GetTempFileName requires that its output buffer (4th param)
758 have length MAX_PATH or greater. */
759 assert(size >= MAX_PATH);
760 return (GetTempPath(MAX_PATH, temp_dir)
761 && GetTempFileName(temp_dir, "qem", 0, filename)
762 ? 0 : -GetLastError());
763 #else
764 int fd;
765 const char *tmpdir;
766 tmpdir = getenv("TMPDIR");
767 if (!tmpdir) {
768 tmpdir = "/var/tmp";
770 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
771 return -EOVERFLOW;
773 fd = mkstemp(filename);
774 if (fd < 0) {
775 return -errno;
777 if (close(fd) != 0) {
778 unlink(filename);
779 return -errno;
781 return 0;
782 #endif
786 * Detect host devices. By convention, /dev/cdrom[N] is always
787 * recognized as a host CDROM.
789 static BlockDriver *find_hdev_driver(const char *filename)
791 int score_max = 0, score;
792 BlockDriver *drv = NULL, *d;
794 QLIST_FOREACH(d, &bdrv_drivers, list) {
795 if (d->bdrv_probe_device) {
796 score = d->bdrv_probe_device(filename);
797 if (score > score_max) {
798 score_max = score;
799 drv = d;
804 return drv;
807 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
809 BlockDriver *drv1;
811 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
812 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
813 return drv1;
817 return NULL;
820 BlockDriver *bdrv_find_protocol(const char *filename,
821 bool allow_protocol_prefix,
822 Error **errp)
824 BlockDriver *drv1;
825 char protocol[128];
826 int len;
827 const char *p;
828 int i;
830 /* TODO Drivers without bdrv_file_open must be specified explicitly */
833 * XXX(hch): we really should not let host device detection
834 * override an explicit protocol specification, but moving this
835 * later breaks access to device names with colons in them.
836 * Thanks to the brain-dead persistent naming schemes on udev-
837 * based Linux systems those actually are quite common.
839 drv1 = find_hdev_driver(filename);
840 if (drv1) {
841 return drv1;
844 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
845 return &bdrv_file;
848 p = strchr(filename, ':');
849 assert(p != NULL);
850 len = p - filename;
851 if (len > sizeof(protocol) - 1)
852 len = sizeof(protocol) - 1;
853 memcpy(protocol, filename, len);
854 protocol[len] = '\0';
856 drv1 = bdrv_do_find_protocol(protocol);
857 if (drv1) {
858 return drv1;
861 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
862 if (block_driver_modules[i].protocol_name &&
863 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
864 block_module_load_one(block_driver_modules[i].library_name);
865 break;
869 drv1 = bdrv_do_find_protocol(protocol);
870 if (!drv1) {
871 error_setg(errp, "Unknown protocol '%s'", protocol);
873 return drv1;
877 * Guess image format by probing its contents.
878 * This is not a good idea when your image is raw (CVE-2008-2004), but
879 * we do it anyway for backward compatibility.
881 * @buf contains the image's first @buf_size bytes.
882 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
883 * but can be smaller if the image file is smaller)
884 * @filename is its filename.
886 * For all block drivers, call the bdrv_probe() method to get its
887 * probing score.
888 * Return the first block driver with the highest probing score.
890 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
891 const char *filename)
893 int score_max = 0, score;
894 BlockDriver *drv = NULL, *d;
896 QLIST_FOREACH(d, &bdrv_drivers, list) {
897 if (d->bdrv_probe) {
898 score = d->bdrv_probe(buf, buf_size, filename);
899 if (score > score_max) {
900 score_max = score;
901 drv = d;
906 return drv;
909 static int find_image_format(BlockBackend *file, const char *filename,
910 BlockDriver **pdrv, Error **errp)
912 BlockDriver *drv;
913 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
914 int ret = 0;
916 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
917 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
918 *pdrv = &bdrv_raw;
919 return ret;
922 ret = blk_pread(file, 0, buf, sizeof(buf));
923 if (ret < 0) {
924 error_setg_errno(errp, -ret, "Could not read image for determining its "
925 "format");
926 *pdrv = NULL;
927 return ret;
930 drv = bdrv_probe_all(buf, ret, filename);
931 if (!drv) {
932 error_setg(errp, "Could not determine image format: No compatible "
933 "driver found");
934 ret = -ENOENT;
936 *pdrv = drv;
937 return ret;
941 * Set the current 'total_sectors' value
942 * Return 0 on success, -errno on error.
944 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
946 BlockDriver *drv = bs->drv;
948 if (!drv) {
949 return -ENOMEDIUM;
952 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
953 if (bdrv_is_sg(bs))
954 return 0;
956 /* query actual device if possible, otherwise just trust the hint */
957 if (drv->bdrv_getlength) {
958 int64_t length = drv->bdrv_getlength(bs);
959 if (length < 0) {
960 return length;
962 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
965 bs->total_sectors = hint;
966 return 0;
970 * Combines a QDict of new block driver @options with any missing options taken
971 * from @old_options, so that leaving out an option defaults to its old value.
973 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
974 QDict *old_options)
976 if (bs->drv && bs->drv->bdrv_join_options) {
977 bs->drv->bdrv_join_options(options, old_options);
978 } else {
979 qdict_join(options, old_options, false);
983 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
984 int open_flags,
985 Error **errp)
987 Error *local_err = NULL;
988 char *value = qemu_opt_get_del(opts, "detect-zeroes");
989 BlockdevDetectZeroesOptions detect_zeroes =
990 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
991 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
992 g_free(value);
993 if (local_err) {
994 error_propagate(errp, local_err);
995 return detect_zeroes;
998 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
999 !(open_flags & BDRV_O_UNMAP))
1001 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1002 "without setting discard operation to unmap");
1005 return detect_zeroes;
1009 * Set open flags for aio engine
1011 * Return 0 on success, -1 if the engine specified is invalid
1013 int bdrv_parse_aio(const char *mode, int *flags)
1015 if (!strcmp(mode, "threads")) {
1016 /* do nothing, default */
1017 } else if (!strcmp(mode, "native")) {
1018 *flags |= BDRV_O_NATIVE_AIO;
1019 #ifdef CONFIG_LINUX_IO_URING
1020 } else if (!strcmp(mode, "io_uring")) {
1021 *flags |= BDRV_O_IO_URING;
1022 #endif
1023 } else {
1024 return -1;
1027 return 0;
1031 * Set open flags for a given discard mode
1033 * Return 0 on success, -1 if the discard mode was invalid.
1035 int bdrv_parse_discard_flags(const char *mode, int *flags)
1037 *flags &= ~BDRV_O_UNMAP;
1039 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1040 /* do nothing */
1041 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1042 *flags |= BDRV_O_UNMAP;
1043 } else {
1044 return -1;
1047 return 0;
1051 * Set open flags for a given cache mode
1053 * Return 0 on success, -1 if the cache mode was invalid.
1055 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1057 *flags &= ~BDRV_O_CACHE_MASK;
1059 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1060 *writethrough = false;
1061 *flags |= BDRV_O_NOCACHE;
1062 } else if (!strcmp(mode, "directsync")) {
1063 *writethrough = true;
1064 *flags |= BDRV_O_NOCACHE;
1065 } else if (!strcmp(mode, "writeback")) {
1066 *writethrough = false;
1067 } else if (!strcmp(mode, "unsafe")) {
1068 *writethrough = false;
1069 *flags |= BDRV_O_NO_FLUSH;
1070 } else if (!strcmp(mode, "writethrough")) {
1071 *writethrough = true;
1072 } else {
1073 return -1;
1076 return 0;
1079 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1081 BlockDriverState *parent = c->opaque;
1082 return g_strdup(bdrv_get_device_or_node_name(parent));
1085 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1087 BlockDriverState *bs = child->opaque;
1088 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1091 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1093 BlockDriverState *bs = child->opaque;
1094 return bdrv_drain_poll(bs, false, NULL, false);
1097 static void bdrv_child_cb_drained_end(BdrvChild *child,
1098 int *drained_end_counter)
1100 BlockDriverState *bs = child->opaque;
1101 bdrv_drained_end_no_poll(bs, drained_end_counter);
1104 static int bdrv_child_cb_inactivate(BdrvChild *child)
1106 BlockDriverState *bs = child->opaque;
1107 assert(bs->open_flags & BDRV_O_INACTIVE);
1108 return 0;
1111 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1112 GSList **ignore, Error **errp)
1114 BlockDriverState *bs = child->opaque;
1115 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1118 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1119 GSList **ignore)
1121 BlockDriverState *bs = child->opaque;
1122 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1126 * Returns the options and flags that a temporary snapshot should get, based on
1127 * the originally requested flags (the originally requested image will have
1128 * flags like a backing file)
1130 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1131 int parent_flags, QDict *parent_options)
1133 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1135 /* For temporary files, unconditional cache=unsafe is fine */
1136 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1137 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1139 /* Copy the read-only and discard options from the parent */
1140 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1141 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1143 /* aio=native doesn't work for cache.direct=off, so disable it for the
1144 * temporary snapshot */
1145 *child_flags &= ~BDRV_O_NATIVE_AIO;
1149 * Returns the options and flags that bs->file should get if a protocol driver
1150 * is expected, based on the given options and flags for the parent BDS
1152 static void bdrv_protocol_options(BdrvChildRole role, bool parent_is_format,
1153 int *child_flags, QDict *child_options,
1154 int parent_flags, QDict *parent_options)
1156 bdrv_inherited_options(BDRV_CHILD_IMAGE, true,
1157 child_flags, child_options,
1158 parent_flags, parent_options);
1161 const BdrvChildClass child_file = {
1162 .parent_is_bds = true,
1163 .get_parent_desc = bdrv_child_get_parent_desc,
1164 .inherit_options = bdrv_protocol_options,
1165 .drained_begin = bdrv_child_cb_drained_begin,
1166 .drained_poll = bdrv_child_cb_drained_poll,
1167 .drained_end = bdrv_child_cb_drained_end,
1168 .attach = bdrv_child_cb_attach,
1169 .detach = bdrv_child_cb_detach,
1170 .inactivate = bdrv_child_cb_inactivate,
1171 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1172 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1175 static void bdrv_backing_attach(BdrvChild *c)
1177 BlockDriverState *parent = c->opaque;
1178 BlockDriverState *backing_hd = c->bs;
1180 assert(!parent->backing_blocker);
1181 error_setg(&parent->backing_blocker,
1182 "node is used as backing hd of '%s'",
1183 bdrv_get_device_or_node_name(parent));
1185 bdrv_refresh_filename(backing_hd);
1187 parent->open_flags &= ~BDRV_O_NO_BACKING;
1188 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1189 backing_hd->filename);
1190 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1191 backing_hd->drv ? backing_hd->drv->format_name : "");
1193 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1194 /* Otherwise we won't be able to commit or stream */
1195 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1196 parent->backing_blocker);
1197 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1198 parent->backing_blocker);
1200 * We do backup in 3 ways:
1201 * 1. drive backup
1202 * The target bs is new opened, and the source is top BDS
1203 * 2. blockdev backup
1204 * Both the source and the target are top BDSes.
1205 * 3. internal backup(used for block replication)
1206 * Both the source and the target are backing file
1208 * In case 1 and 2, neither the source nor the target is the backing file.
1209 * In case 3, we will block the top BDS, so there is only one block job
1210 * for the top BDS and its backing chain.
1212 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1213 parent->backing_blocker);
1214 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1215 parent->backing_blocker);
1218 /* XXX: Will be removed along with child_backing */
1219 static void bdrv_child_cb_attach_backing(BdrvChild *c)
1221 if (!(c->role & BDRV_CHILD_COW)) {
1222 bdrv_backing_attach(c);
1224 bdrv_child_cb_attach(c);
1227 static void bdrv_backing_detach(BdrvChild *c)
1229 BlockDriverState *parent = c->opaque;
1231 assert(parent->backing_blocker);
1232 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1233 error_free(parent->backing_blocker);
1234 parent->backing_blocker = NULL;
1237 /* XXX: Will be removed along with child_backing */
1238 static void bdrv_child_cb_detach_backing(BdrvChild *c)
1240 if (!(c->role & BDRV_CHILD_COW)) {
1241 bdrv_backing_detach(c);
1243 bdrv_child_cb_detach(c);
1247 * Returns the options and flags that bs->backing should get, based on the
1248 * given options and flags for the parent BDS
1250 static void bdrv_backing_options(BdrvChildRole role, bool parent_is_format,
1251 int *child_flags, QDict *child_options,
1252 int parent_flags, QDict *parent_options)
1254 bdrv_inherited_options(BDRV_CHILD_COW, true,
1255 child_flags, child_options,
1256 parent_flags, parent_options);
1259 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1260 const char *filename, Error **errp)
1262 BlockDriverState *parent = c->opaque;
1263 bool read_only = bdrv_is_read_only(parent);
1264 int ret;
1266 if (read_only) {
1267 ret = bdrv_reopen_set_read_only(parent, false, errp);
1268 if (ret < 0) {
1269 return ret;
1273 ret = bdrv_change_backing_file(parent, filename,
1274 base->drv ? base->drv->format_name : "");
1275 if (ret < 0) {
1276 error_setg_errno(errp, -ret, "Could not update backing file link");
1279 if (read_only) {
1280 bdrv_reopen_set_read_only(parent, true, NULL);
1283 return ret;
1286 const BdrvChildClass child_backing = {
1287 .parent_is_bds = true,
1288 .get_parent_desc = bdrv_child_get_parent_desc,
1289 .attach = bdrv_child_cb_attach_backing,
1290 .detach = bdrv_child_cb_detach_backing,
1291 .inherit_options = bdrv_backing_options,
1292 .drained_begin = bdrv_child_cb_drained_begin,
1293 .drained_poll = bdrv_child_cb_drained_poll,
1294 .drained_end = bdrv_child_cb_drained_end,
1295 .inactivate = bdrv_child_cb_inactivate,
1296 .update_filename = bdrv_backing_update_filename,
1297 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1298 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1302 * Returns the options and flags that a generic child of a BDS should
1303 * get, based on the given options and flags for the parent BDS.
1305 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1306 int *child_flags, QDict *child_options,
1307 int parent_flags, QDict *parent_options)
1309 int flags = parent_flags;
1312 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1313 * Generally, the question to answer is: Should this child be
1314 * format-probed by default?
1318 * Pure and non-filtered data children of non-format nodes should
1319 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1320 * set). This only affects a very limited set of drivers (namely
1321 * quorum and blkverify when this comment was written).
1322 * Force-clear BDRV_O_PROTOCOL then.
1324 if (!parent_is_format &&
1325 (role & BDRV_CHILD_DATA) &&
1326 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1328 flags &= ~BDRV_O_PROTOCOL;
1332 * All children of format nodes (except for COW children) and all
1333 * metadata children in general should never be format-probed.
1334 * Force-set BDRV_O_PROTOCOL then.
1336 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1337 (role & BDRV_CHILD_METADATA))
1339 flags |= BDRV_O_PROTOCOL;
1343 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1344 * the parent.
1346 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1347 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1348 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1350 if (role & BDRV_CHILD_COW) {
1351 /* backing files are opened read-only by default */
1352 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1353 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1354 } else {
1355 /* Inherit the read-only option from the parent if it's not set */
1356 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1357 qdict_copy_default(child_options, parent_options,
1358 BDRV_OPT_AUTO_READ_ONLY);
1362 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1363 * can default to enable it on lower layers regardless of the
1364 * parent option.
1366 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1368 /* Clear flags that only apply to the top layer */
1369 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1371 if (role & BDRV_CHILD_METADATA) {
1372 flags &= ~BDRV_O_NO_IO;
1374 if (role & BDRV_CHILD_COW) {
1375 flags &= ~BDRV_O_TEMPORARY;
1378 *child_flags = flags;
1381 static void bdrv_child_cb_attach(BdrvChild *child)
1383 BlockDriverState *bs = child->opaque;
1385 if (child->role & BDRV_CHILD_COW) {
1386 bdrv_backing_attach(child);
1389 bdrv_apply_subtree_drain(child, bs);
1392 static void bdrv_child_cb_detach(BdrvChild *child)
1394 BlockDriverState *bs = child->opaque;
1396 if (child->role & BDRV_CHILD_COW) {
1397 bdrv_backing_detach(child);
1400 bdrv_unapply_subtree_drain(child, bs);
1403 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1404 const char *filename, Error **errp)
1406 if (c->role & BDRV_CHILD_COW) {
1407 return bdrv_backing_update_filename(c, base, filename, errp);
1409 return 0;
1412 const BdrvChildClass child_of_bds = {
1413 .parent_is_bds = true,
1414 .get_parent_desc = bdrv_child_get_parent_desc,
1415 .inherit_options = bdrv_inherited_options,
1416 .drained_begin = bdrv_child_cb_drained_begin,
1417 .drained_poll = bdrv_child_cb_drained_poll,
1418 .drained_end = bdrv_child_cb_drained_end,
1419 .attach = bdrv_child_cb_attach,
1420 .detach = bdrv_child_cb_detach,
1421 .inactivate = bdrv_child_cb_inactivate,
1422 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1423 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1424 .update_filename = bdrv_child_cb_update_filename,
1427 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1429 int open_flags = flags;
1432 * Clear flags that are internal to the block layer before opening the
1433 * image.
1435 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1437 return open_flags;
1440 static void update_flags_from_options(int *flags, QemuOpts *opts)
1442 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1444 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1445 *flags |= BDRV_O_NO_FLUSH;
1448 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1449 *flags |= BDRV_O_NOCACHE;
1452 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1453 *flags |= BDRV_O_RDWR;
1456 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1457 *flags |= BDRV_O_AUTO_RDONLY;
1461 static void update_options_from_flags(QDict *options, int flags)
1463 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1464 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1466 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1467 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1468 flags & BDRV_O_NO_FLUSH);
1470 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1471 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1473 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1474 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1475 flags & BDRV_O_AUTO_RDONLY);
1479 static void bdrv_assign_node_name(BlockDriverState *bs,
1480 const char *node_name,
1481 Error **errp)
1483 char *gen_node_name = NULL;
1485 if (!node_name) {
1486 node_name = gen_node_name = id_generate(ID_BLOCK);
1487 } else if (!id_wellformed(node_name)) {
1489 * Check for empty string or invalid characters, but not if it is
1490 * generated (generated names use characters not available to the user)
1492 error_setg(errp, "Invalid node name");
1493 return;
1496 /* takes care of avoiding namespaces collisions */
1497 if (blk_by_name(node_name)) {
1498 error_setg(errp, "node-name=%s is conflicting with a device id",
1499 node_name);
1500 goto out;
1503 /* takes care of avoiding duplicates node names */
1504 if (bdrv_find_node(node_name)) {
1505 error_setg(errp, "Duplicate node name");
1506 goto out;
1509 /* Make sure that the node name isn't truncated */
1510 if (strlen(node_name) >= sizeof(bs->node_name)) {
1511 error_setg(errp, "Node name too long");
1512 goto out;
1515 /* copy node name into the bs and insert it into the graph list */
1516 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1517 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1518 out:
1519 g_free(gen_node_name);
1522 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1523 const char *node_name, QDict *options,
1524 int open_flags, Error **errp)
1526 Error *local_err = NULL;
1527 int i, ret;
1529 bdrv_assign_node_name(bs, node_name, &local_err);
1530 if (local_err) {
1531 error_propagate(errp, local_err);
1532 return -EINVAL;
1535 bs->drv = drv;
1536 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1537 bs->opaque = g_malloc0(drv->instance_size);
1539 if (drv->bdrv_file_open) {
1540 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1541 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1542 } else if (drv->bdrv_open) {
1543 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1544 } else {
1545 ret = 0;
1548 if (ret < 0) {
1549 if (local_err) {
1550 error_propagate(errp, local_err);
1551 } else if (bs->filename[0]) {
1552 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1553 } else {
1554 error_setg_errno(errp, -ret, "Could not open image");
1556 goto open_failed;
1559 ret = refresh_total_sectors(bs, bs->total_sectors);
1560 if (ret < 0) {
1561 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1562 return ret;
1565 bdrv_refresh_limits(bs, &local_err);
1566 if (local_err) {
1567 error_propagate(errp, local_err);
1568 return -EINVAL;
1571 assert(bdrv_opt_mem_align(bs) != 0);
1572 assert(bdrv_min_mem_align(bs) != 0);
1573 assert(is_power_of_2(bs->bl.request_alignment));
1575 for (i = 0; i < bs->quiesce_counter; i++) {
1576 if (drv->bdrv_co_drain_begin) {
1577 drv->bdrv_co_drain_begin(bs);
1581 return 0;
1582 open_failed:
1583 bs->drv = NULL;
1584 if (bs->file != NULL) {
1585 bdrv_unref_child(bs, bs->file);
1586 bs->file = NULL;
1588 g_free(bs->opaque);
1589 bs->opaque = NULL;
1590 return ret;
1593 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1594 int flags, Error **errp)
1596 BlockDriverState *bs;
1597 int ret;
1599 bs = bdrv_new();
1600 bs->open_flags = flags;
1601 bs->explicit_options = qdict_new();
1602 bs->options = qdict_new();
1603 bs->opaque = NULL;
1605 update_options_from_flags(bs->options, flags);
1607 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1608 if (ret < 0) {
1609 qobject_unref(bs->explicit_options);
1610 bs->explicit_options = NULL;
1611 qobject_unref(bs->options);
1612 bs->options = NULL;
1613 bdrv_unref(bs);
1614 return NULL;
1617 return bs;
1620 QemuOptsList bdrv_runtime_opts = {
1621 .name = "bdrv_common",
1622 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1623 .desc = {
1625 .name = "node-name",
1626 .type = QEMU_OPT_STRING,
1627 .help = "Node name of the block device node",
1630 .name = "driver",
1631 .type = QEMU_OPT_STRING,
1632 .help = "Block driver to use for the node",
1635 .name = BDRV_OPT_CACHE_DIRECT,
1636 .type = QEMU_OPT_BOOL,
1637 .help = "Bypass software writeback cache on the host",
1640 .name = BDRV_OPT_CACHE_NO_FLUSH,
1641 .type = QEMU_OPT_BOOL,
1642 .help = "Ignore flush requests",
1645 .name = BDRV_OPT_READ_ONLY,
1646 .type = QEMU_OPT_BOOL,
1647 .help = "Node is opened in read-only mode",
1650 .name = BDRV_OPT_AUTO_READ_ONLY,
1651 .type = QEMU_OPT_BOOL,
1652 .help = "Node can become read-only if opening read-write fails",
1655 .name = "detect-zeroes",
1656 .type = QEMU_OPT_STRING,
1657 .help = "try to optimize zero writes (off, on, unmap)",
1660 .name = BDRV_OPT_DISCARD,
1661 .type = QEMU_OPT_STRING,
1662 .help = "discard operation (ignore/off, unmap/on)",
1665 .name = BDRV_OPT_FORCE_SHARE,
1666 .type = QEMU_OPT_BOOL,
1667 .help = "always accept other writers (default: off)",
1669 { /* end of list */ }
1673 QemuOptsList bdrv_create_opts_simple = {
1674 .name = "simple-create-opts",
1675 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1676 .desc = {
1678 .name = BLOCK_OPT_SIZE,
1679 .type = QEMU_OPT_SIZE,
1680 .help = "Virtual disk size"
1683 .name = BLOCK_OPT_PREALLOC,
1684 .type = QEMU_OPT_STRING,
1685 .help = "Preallocation mode (allowed values: off)"
1687 { /* end of list */ }
1692 * Common part for opening disk images and files
1694 * Removes all processed options from *options.
1696 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1697 QDict *options, Error **errp)
1699 int ret, open_flags;
1700 const char *filename;
1701 const char *driver_name = NULL;
1702 const char *node_name = NULL;
1703 const char *discard;
1704 QemuOpts *opts;
1705 BlockDriver *drv;
1706 Error *local_err = NULL;
1708 assert(bs->file == NULL);
1709 assert(options != NULL && bs->options != options);
1711 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1712 qemu_opts_absorb_qdict(opts, options, &local_err);
1713 if (local_err) {
1714 error_propagate(errp, local_err);
1715 ret = -EINVAL;
1716 goto fail_opts;
1719 update_flags_from_options(&bs->open_flags, opts);
1721 driver_name = qemu_opt_get(opts, "driver");
1722 drv = bdrv_find_format(driver_name);
1723 assert(drv != NULL);
1725 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1727 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1728 error_setg(errp,
1729 BDRV_OPT_FORCE_SHARE
1730 "=on can only be used with read-only images");
1731 ret = -EINVAL;
1732 goto fail_opts;
1735 if (file != NULL) {
1736 bdrv_refresh_filename(blk_bs(file));
1737 filename = blk_bs(file)->filename;
1738 } else {
1740 * Caution: while qdict_get_try_str() is fine, getting
1741 * non-string types would require more care. When @options
1742 * come from -blockdev or blockdev_add, its members are typed
1743 * according to the QAPI schema, but when they come from
1744 * -drive, they're all QString.
1746 filename = qdict_get_try_str(options, "filename");
1749 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1750 error_setg(errp, "The '%s' block driver requires a file name",
1751 drv->format_name);
1752 ret = -EINVAL;
1753 goto fail_opts;
1756 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1757 drv->format_name);
1759 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1761 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1762 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1763 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1764 } else {
1765 ret = -ENOTSUP;
1767 if (ret < 0) {
1768 error_setg(errp,
1769 !bs->read_only && bdrv_is_whitelisted(drv, true)
1770 ? "Driver '%s' can only be used for read-only devices"
1771 : "Driver '%s' is not whitelisted",
1772 drv->format_name);
1773 goto fail_opts;
1777 /* bdrv_new() and bdrv_close() make it so */
1778 assert(atomic_read(&bs->copy_on_read) == 0);
1780 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1781 if (!bs->read_only) {
1782 bdrv_enable_copy_on_read(bs);
1783 } else {
1784 error_setg(errp, "Can't use copy-on-read on read-only device");
1785 ret = -EINVAL;
1786 goto fail_opts;
1790 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1791 if (discard != NULL) {
1792 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1793 error_setg(errp, "Invalid discard option");
1794 ret = -EINVAL;
1795 goto fail_opts;
1799 bs->detect_zeroes =
1800 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1801 if (local_err) {
1802 error_propagate(errp, local_err);
1803 ret = -EINVAL;
1804 goto fail_opts;
1807 if (filename != NULL) {
1808 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1809 } else {
1810 bs->filename[0] = '\0';
1812 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1814 /* Open the image, either directly or using a protocol */
1815 open_flags = bdrv_open_flags(bs, bs->open_flags);
1816 node_name = qemu_opt_get(opts, "node-name");
1818 assert(!drv->bdrv_file_open || file == NULL);
1819 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1820 if (ret < 0) {
1821 goto fail_opts;
1824 qemu_opts_del(opts);
1825 return 0;
1827 fail_opts:
1828 qemu_opts_del(opts);
1829 return ret;
1832 static QDict *parse_json_filename(const char *filename, Error **errp)
1834 QObject *options_obj;
1835 QDict *options;
1836 int ret;
1838 ret = strstart(filename, "json:", &filename);
1839 assert(ret);
1841 options_obj = qobject_from_json(filename, errp);
1842 if (!options_obj) {
1843 error_prepend(errp, "Could not parse the JSON options: ");
1844 return NULL;
1847 options = qobject_to(QDict, options_obj);
1848 if (!options) {
1849 qobject_unref(options_obj);
1850 error_setg(errp, "Invalid JSON object given");
1851 return NULL;
1854 qdict_flatten(options);
1856 return options;
1859 static void parse_json_protocol(QDict *options, const char **pfilename,
1860 Error **errp)
1862 QDict *json_options;
1863 Error *local_err = NULL;
1865 /* Parse json: pseudo-protocol */
1866 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1867 return;
1870 json_options = parse_json_filename(*pfilename, &local_err);
1871 if (local_err) {
1872 error_propagate(errp, local_err);
1873 return;
1876 /* Options given in the filename have lower priority than options
1877 * specified directly */
1878 qdict_join(options, json_options, false);
1879 qobject_unref(json_options);
1880 *pfilename = NULL;
1884 * Fills in default options for opening images and converts the legacy
1885 * filename/flags pair to option QDict entries.
1886 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1887 * block driver has been specified explicitly.
1889 static int bdrv_fill_options(QDict **options, const char *filename,
1890 int *flags, Error **errp)
1892 const char *drvname;
1893 bool protocol = *flags & BDRV_O_PROTOCOL;
1894 bool parse_filename = false;
1895 BlockDriver *drv = NULL;
1896 Error *local_err = NULL;
1899 * Caution: while qdict_get_try_str() is fine, getting non-string
1900 * types would require more care. When @options come from
1901 * -blockdev or blockdev_add, its members are typed according to
1902 * the QAPI schema, but when they come from -drive, they're all
1903 * QString.
1905 drvname = qdict_get_try_str(*options, "driver");
1906 if (drvname) {
1907 drv = bdrv_find_format(drvname);
1908 if (!drv) {
1909 error_setg(errp, "Unknown driver '%s'", drvname);
1910 return -ENOENT;
1912 /* If the user has explicitly specified the driver, this choice should
1913 * override the BDRV_O_PROTOCOL flag */
1914 protocol = drv->bdrv_file_open;
1917 if (protocol) {
1918 *flags |= BDRV_O_PROTOCOL;
1919 } else {
1920 *flags &= ~BDRV_O_PROTOCOL;
1923 /* Translate cache options from flags into options */
1924 update_options_from_flags(*options, *flags);
1926 /* Fetch the file name from the options QDict if necessary */
1927 if (protocol && filename) {
1928 if (!qdict_haskey(*options, "filename")) {
1929 qdict_put_str(*options, "filename", filename);
1930 parse_filename = true;
1931 } else {
1932 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1933 "the same time");
1934 return -EINVAL;
1938 /* Find the right block driver */
1939 /* See cautionary note on accessing @options above */
1940 filename = qdict_get_try_str(*options, "filename");
1942 if (!drvname && protocol) {
1943 if (filename) {
1944 drv = bdrv_find_protocol(filename, parse_filename, errp);
1945 if (!drv) {
1946 return -EINVAL;
1949 drvname = drv->format_name;
1950 qdict_put_str(*options, "driver", drvname);
1951 } else {
1952 error_setg(errp, "Must specify either driver or file");
1953 return -EINVAL;
1957 assert(drv || !protocol);
1959 /* Driver-specific filename parsing */
1960 if (drv && drv->bdrv_parse_filename && parse_filename) {
1961 drv->bdrv_parse_filename(filename, *options, &local_err);
1962 if (local_err) {
1963 error_propagate(errp, local_err);
1964 return -EINVAL;
1967 if (!drv->bdrv_needs_filename) {
1968 qdict_del(*options, "filename");
1972 return 0;
1975 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1976 uint64_t perm, uint64_t shared,
1977 GSList *ignore_children,
1978 bool *tighten_restrictions, Error **errp);
1979 static void bdrv_child_abort_perm_update(BdrvChild *c);
1980 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1982 typedef struct BlockReopenQueueEntry {
1983 bool prepared;
1984 bool perms_checked;
1985 BDRVReopenState state;
1986 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1987 } BlockReopenQueueEntry;
1990 * Return the flags that @bs will have after the reopens in @q have
1991 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1992 * return the current flags.
1994 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1996 BlockReopenQueueEntry *entry;
1998 if (q != NULL) {
1999 QTAILQ_FOREACH(entry, q, entry) {
2000 if (entry->state.bs == bs) {
2001 return entry->state.flags;
2006 return bs->open_flags;
2009 /* Returns whether the image file can be written to after the reopen queue @q
2010 * has been successfully applied, or right now if @q is NULL. */
2011 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2012 BlockReopenQueue *q)
2014 int flags = bdrv_reopen_get_flags(q, bs);
2016 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2020 * Return whether the BDS can be written to. This is not necessarily
2021 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2022 * be written to but do not count as read-only images.
2024 bool bdrv_is_writable(BlockDriverState *bs)
2026 return bdrv_is_writable_after_reopen(bs, NULL);
2029 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2030 BdrvChild *c, const BdrvChildClass *child_class,
2031 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2032 uint64_t parent_perm, uint64_t parent_shared,
2033 uint64_t *nperm, uint64_t *nshared)
2035 assert(bs->drv && bs->drv->bdrv_child_perm);
2036 bs->drv->bdrv_child_perm(bs, c, child_class, role, reopen_queue,
2037 parent_perm, parent_shared,
2038 nperm, nshared);
2039 /* TODO Take force_share from reopen_queue */
2040 if (child_bs && child_bs->force_share) {
2041 *nshared = BLK_PERM_ALL;
2046 * Check whether permissions on this node can be changed in a way that
2047 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2048 * permissions of all its parents. This involves checking whether all necessary
2049 * permission changes to child nodes can be performed.
2051 * Will set *tighten_restrictions to true if and only if new permissions have to
2052 * be taken or currently shared permissions are to be unshared. Otherwise,
2053 * errors are not fatal as long as the caller accepts that the restrictions
2054 * remain tighter than they need to be. The caller still has to abort the
2055 * transaction.
2056 * @tighten_restrictions cannot be used together with @q: When reopening, we may
2057 * encounter fatal errors even though no restrictions are to be tightened. For
2058 * example, changing a node from RW to RO will fail if the WRITE permission is
2059 * to be kept.
2061 * A call to this function must always be followed by a call to bdrv_set_perm()
2062 * or bdrv_abort_perm_update().
2064 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2065 uint64_t cumulative_perms,
2066 uint64_t cumulative_shared_perms,
2067 GSList *ignore_children,
2068 bool *tighten_restrictions, Error **errp)
2070 BlockDriver *drv = bs->drv;
2071 BdrvChild *c;
2072 int ret;
2074 assert(!q || !tighten_restrictions);
2076 if (tighten_restrictions) {
2077 uint64_t current_perms, current_shared;
2078 uint64_t added_perms, removed_shared_perms;
2080 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2082 added_perms = cumulative_perms & ~current_perms;
2083 removed_shared_perms = current_shared & ~cumulative_shared_perms;
2085 *tighten_restrictions = added_perms || removed_shared_perms;
2088 /* Write permissions never work with read-only images */
2089 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2090 !bdrv_is_writable_after_reopen(bs, q))
2092 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2093 error_setg(errp, "Block node is read-only");
2094 } else {
2095 uint64_t current_perms, current_shared;
2096 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2097 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2098 error_setg(errp, "Cannot make block node read-only, there is "
2099 "a writer on it");
2100 } else {
2101 error_setg(errp, "Cannot make block node read-only and create "
2102 "a writer on it");
2106 return -EPERM;
2109 /* Check this node */
2110 if (!drv) {
2111 return 0;
2114 if (drv->bdrv_check_perm) {
2115 return drv->bdrv_check_perm(bs, cumulative_perms,
2116 cumulative_shared_perms, errp);
2119 /* Drivers that never have children can omit .bdrv_child_perm() */
2120 if (!drv->bdrv_child_perm) {
2121 assert(QLIST_EMPTY(&bs->children));
2122 return 0;
2125 /* Check all children */
2126 QLIST_FOREACH(c, &bs->children, next) {
2127 uint64_t cur_perm, cur_shared;
2128 bool child_tighten_restr;
2130 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, q,
2131 cumulative_perms, cumulative_shared_perms,
2132 &cur_perm, &cur_shared);
2133 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
2134 tighten_restrictions ? &child_tighten_restr
2135 : NULL,
2136 errp);
2137 if (tighten_restrictions) {
2138 *tighten_restrictions |= child_tighten_restr;
2140 if (ret < 0) {
2141 return ret;
2145 return 0;
2149 * Notifies drivers that after a previous bdrv_check_perm() call, the
2150 * permission update is not performed and any preparations made for it (e.g.
2151 * taken file locks) need to be undone.
2153 * This function recursively notifies all child nodes.
2155 static void bdrv_abort_perm_update(BlockDriverState *bs)
2157 BlockDriver *drv = bs->drv;
2158 BdrvChild *c;
2160 if (!drv) {
2161 return;
2164 if (drv->bdrv_abort_perm_update) {
2165 drv->bdrv_abort_perm_update(bs);
2168 QLIST_FOREACH(c, &bs->children, next) {
2169 bdrv_child_abort_perm_update(c);
2173 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
2174 uint64_t cumulative_shared_perms)
2176 BlockDriver *drv = bs->drv;
2177 BdrvChild *c;
2179 if (!drv) {
2180 return;
2183 /* Update this node */
2184 if (drv->bdrv_set_perm) {
2185 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2188 /* Drivers that never have children can omit .bdrv_child_perm() */
2189 if (!drv->bdrv_child_perm) {
2190 assert(QLIST_EMPTY(&bs->children));
2191 return;
2194 /* Update all children */
2195 QLIST_FOREACH(c, &bs->children, next) {
2196 uint64_t cur_perm, cur_shared;
2197 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, NULL,
2198 cumulative_perms, cumulative_shared_perms,
2199 &cur_perm, &cur_shared);
2200 bdrv_child_set_perm(c, cur_perm, cur_shared);
2204 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2205 uint64_t *shared_perm)
2207 BdrvChild *c;
2208 uint64_t cumulative_perms = 0;
2209 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2211 QLIST_FOREACH(c, &bs->parents, next_parent) {
2212 cumulative_perms |= c->perm;
2213 cumulative_shared_perms &= c->shared_perm;
2216 *perm = cumulative_perms;
2217 *shared_perm = cumulative_shared_perms;
2220 static char *bdrv_child_user_desc(BdrvChild *c)
2222 if (c->klass->get_parent_desc) {
2223 return c->klass->get_parent_desc(c);
2226 return g_strdup("another user");
2229 char *bdrv_perm_names(uint64_t perm)
2231 struct perm_name {
2232 uint64_t perm;
2233 const char *name;
2234 } permissions[] = {
2235 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2236 { BLK_PERM_WRITE, "write" },
2237 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2238 { BLK_PERM_RESIZE, "resize" },
2239 { BLK_PERM_GRAPH_MOD, "change children" },
2240 { 0, NULL }
2243 GString *result = g_string_sized_new(30);
2244 struct perm_name *p;
2246 for (p = permissions; p->name; p++) {
2247 if (perm & p->perm) {
2248 if (result->len > 0) {
2249 g_string_append(result, ", ");
2251 g_string_append(result, p->name);
2255 return g_string_free(result, FALSE);
2259 * Checks whether a new reference to @bs can be added if the new user requires
2260 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2261 * set, the BdrvChild objects in this list are ignored in the calculations;
2262 * this allows checking permission updates for an existing reference.
2264 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2266 * Needs to be followed by a call to either bdrv_set_perm() or
2267 * bdrv_abort_perm_update(). */
2268 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2269 uint64_t new_used_perm,
2270 uint64_t new_shared_perm,
2271 GSList *ignore_children,
2272 bool *tighten_restrictions,
2273 Error **errp)
2275 BdrvChild *c;
2276 uint64_t cumulative_perms = new_used_perm;
2277 uint64_t cumulative_shared_perms = new_shared_perm;
2279 assert(!q || !tighten_restrictions);
2281 /* There is no reason why anyone couldn't tolerate write_unchanged */
2282 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2284 QLIST_FOREACH(c, &bs->parents, next_parent) {
2285 if (g_slist_find(ignore_children, c)) {
2286 continue;
2289 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2290 char *user = bdrv_child_user_desc(c);
2291 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
2293 if (tighten_restrictions) {
2294 *tighten_restrictions = true;
2297 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2298 "allow '%s' on %s",
2299 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2300 g_free(user);
2301 g_free(perm_names);
2302 return -EPERM;
2305 if ((c->perm & new_shared_perm) != c->perm) {
2306 char *user = bdrv_child_user_desc(c);
2307 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
2309 if (tighten_restrictions) {
2310 *tighten_restrictions = true;
2313 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2314 "'%s' on %s",
2315 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2316 g_free(user);
2317 g_free(perm_names);
2318 return -EPERM;
2321 cumulative_perms |= c->perm;
2322 cumulative_shared_perms &= c->shared_perm;
2325 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
2326 ignore_children, tighten_restrictions, errp);
2329 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2330 * bdrv_child_abort_perm_update(). */
2331 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2332 uint64_t perm, uint64_t shared,
2333 GSList *ignore_children,
2334 bool *tighten_restrictions, Error **errp)
2336 int ret;
2338 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
2339 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2340 tighten_restrictions, errp);
2341 g_slist_free(ignore_children);
2343 if (ret < 0) {
2344 return ret;
2347 if (!c->has_backup_perm) {
2348 c->has_backup_perm = true;
2349 c->backup_perm = c->perm;
2350 c->backup_shared_perm = c->shared_perm;
2353 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2354 * same child twice during check_perm procedure
2357 c->perm = perm;
2358 c->shared_perm = shared;
2360 return 0;
2363 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
2365 uint64_t cumulative_perms, cumulative_shared_perms;
2367 c->has_backup_perm = false;
2369 c->perm = perm;
2370 c->shared_perm = shared;
2372 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2373 &cumulative_shared_perms);
2374 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2377 static void bdrv_child_abort_perm_update(BdrvChild *c)
2379 if (c->has_backup_perm) {
2380 c->perm = c->backup_perm;
2381 c->shared_perm = c->backup_shared_perm;
2382 c->has_backup_perm = false;
2385 bdrv_abort_perm_update(c->bs);
2388 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2389 Error **errp)
2391 Error *local_err = NULL;
2392 int ret;
2393 bool tighten_restrictions;
2395 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2396 &tighten_restrictions, &local_err);
2397 if (ret < 0) {
2398 bdrv_child_abort_perm_update(c);
2399 if (tighten_restrictions) {
2400 error_propagate(errp, local_err);
2401 } else {
2403 * Our caller may intend to only loosen restrictions and
2404 * does not expect this function to fail. Errors are not
2405 * fatal in such a case, so we can just hide them from our
2406 * caller.
2408 error_free(local_err);
2409 ret = 0;
2411 return ret;
2414 bdrv_child_set_perm(c, perm, shared);
2416 return 0;
2419 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2421 uint64_t parent_perms, parent_shared;
2422 uint64_t perms, shared;
2424 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2425 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, NULL,
2426 parent_perms, parent_shared, &perms, &shared);
2428 return bdrv_child_try_set_perm(c, perms, shared, errp);
2431 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2432 const BdrvChildClass *child_class,
2433 BdrvChildRole role,
2434 BlockReopenQueue *reopen_queue,
2435 uint64_t perm, uint64_t shared,
2436 uint64_t *nperm, uint64_t *nshared)
2438 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2439 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2442 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2443 const BdrvChildClass *child_class,
2444 BdrvChildRole role,
2445 BlockReopenQueue *reopen_queue,
2446 uint64_t perm, uint64_t shared,
2447 uint64_t *nperm, uint64_t *nshared)
2449 assert(child_class == &child_backing ||
2450 (child_class == &child_of_bds && (role & BDRV_CHILD_COW)));
2453 * We want consistent read from backing files if the parent needs it.
2454 * No other operations are performed on backing files.
2456 perm &= BLK_PERM_CONSISTENT_READ;
2459 * If the parent can deal with changing data, we're okay with a
2460 * writable and resizable backing file.
2461 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2463 if (shared & BLK_PERM_WRITE) {
2464 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2465 } else {
2466 shared = 0;
2469 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2470 BLK_PERM_WRITE_UNCHANGED;
2472 if (bs->open_flags & BDRV_O_INACTIVE) {
2473 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2476 *nperm = perm;
2477 *nshared = shared;
2480 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2481 const BdrvChildClass *child_class,
2482 BdrvChildRole role,
2483 BlockReopenQueue *reopen_queue,
2484 uint64_t perm, uint64_t shared,
2485 uint64_t *nperm, uint64_t *nshared)
2487 int flags;
2489 assert(child_class == &child_file ||
2490 (child_class == &child_of_bds &&
2491 (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA))));
2493 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2496 * Apart from the modifications below, the same permissions are
2497 * forwarded and left alone as for filters
2499 bdrv_filter_default_perms(bs, c, child_class, role, reopen_queue,
2500 perm, shared, &perm, &shared);
2502 if (role & BDRV_CHILD_METADATA) {
2503 /* Format drivers may touch metadata even if the guest doesn't write */
2504 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2505 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2509 * bs->file always needs to be consistent because of the
2510 * metadata. We can never allow other users to resize or write
2511 * to it.
2513 if (!(flags & BDRV_O_NO_IO)) {
2514 perm |= BLK_PERM_CONSISTENT_READ;
2516 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2519 if (role & BDRV_CHILD_DATA) {
2521 * Technically, everything in this block is a subset of the
2522 * BDRV_CHILD_METADATA path taken above, and so this could
2523 * be an "else if" branch. However, that is not obvious, and
2524 * this function is not performance critical, therefore we let
2525 * this be an independent "if".
2529 * We cannot allow other users to resize the file because the
2530 * format driver might have some assumptions about the size
2531 * (e.g. because it is stored in metadata, or because the file
2532 * is split into fixed-size data files).
2534 shared &= ~BLK_PERM_RESIZE;
2537 * WRITE_UNCHANGED often cannot be performed as such on the
2538 * data file. For example, the qcow2 driver may still need to
2539 * write copied clusters on copy-on-read.
2541 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2542 perm |= BLK_PERM_WRITE;
2546 * If the data file is written to, the format driver may
2547 * expect to be able to resize it by writing beyond the EOF.
2549 if (perm & BLK_PERM_WRITE) {
2550 perm |= BLK_PERM_RESIZE;
2554 if (bs->open_flags & BDRV_O_INACTIVE) {
2555 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2558 *nperm = perm;
2559 *nshared = shared;
2562 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
2563 const BdrvChildClass *child_class,
2564 BdrvChildRole role,
2565 BlockReopenQueue *reopen_queue,
2566 uint64_t perm, uint64_t shared,
2567 uint64_t *nperm, uint64_t *nshared)
2569 bool backing = (child_class == &child_backing);
2571 if (child_class == &child_of_bds) {
2572 bdrv_default_perms(bs, c, child_class, role, reopen_queue,
2573 perm, shared, nperm, nshared);
2574 return;
2577 assert(child_class == &child_backing || child_class == &child_file);
2579 if (!backing) {
2580 bdrv_default_perms_for_storage(bs, c, child_class, role, reopen_queue,
2581 perm, shared, nperm, nshared);
2582 } else {
2583 bdrv_default_perms_for_cow(bs, c, child_class, role, reopen_queue,
2584 perm, shared, nperm, nshared);
2588 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2589 const BdrvChildClass *child_class, BdrvChildRole role,
2590 BlockReopenQueue *reopen_queue,
2591 uint64_t perm, uint64_t shared,
2592 uint64_t *nperm, uint64_t *nshared)
2594 assert(child_class == &child_of_bds);
2596 if (role & BDRV_CHILD_FILTERED) {
2597 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2598 BDRV_CHILD_COW)));
2599 bdrv_filter_default_perms(bs, c, child_class, role, reopen_queue,
2600 perm, shared, nperm, nshared);
2601 } else if (role & BDRV_CHILD_COW) {
2602 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2603 bdrv_default_perms_for_cow(bs, c, child_class, role, reopen_queue,
2604 perm, shared, nperm, nshared);
2605 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2606 bdrv_default_perms_for_storage(bs, c, child_class, role, reopen_queue,
2607 perm, shared, nperm, nshared);
2608 } else {
2609 g_assert_not_reached();
2613 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2615 static const uint64_t permissions[] = {
2616 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2617 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2618 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2619 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2620 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2623 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2624 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2626 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2628 return permissions[qapi_perm];
2631 static void bdrv_replace_child_noperm(BdrvChild *child,
2632 BlockDriverState *new_bs)
2634 BlockDriverState *old_bs = child->bs;
2635 int new_bs_quiesce_counter;
2636 int drain_saldo;
2638 assert(!child->frozen);
2640 if (old_bs && new_bs) {
2641 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2644 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2645 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2648 * If the new child node is drained but the old one was not, flush
2649 * all outstanding requests to the old child node.
2651 while (drain_saldo > 0 && child->klass->drained_begin) {
2652 bdrv_parent_drained_begin_single(child, true);
2653 drain_saldo--;
2656 if (old_bs) {
2657 /* Detach first so that the recursive drain sections coming from @child
2658 * are already gone and we only end the drain sections that came from
2659 * elsewhere. */
2660 if (child->klass->detach) {
2661 child->klass->detach(child);
2663 QLIST_REMOVE(child, next_parent);
2666 child->bs = new_bs;
2668 if (new_bs) {
2669 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2672 * Detaching the old node may have led to the new node's
2673 * quiesce_counter having been decreased. Not a problem, we
2674 * just need to recognize this here and then invoke
2675 * drained_end appropriately more often.
2677 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2678 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2680 /* Attach only after starting new drained sections, so that recursive
2681 * drain sections coming from @child don't get an extra .drained_begin
2682 * callback. */
2683 if (child->klass->attach) {
2684 child->klass->attach(child);
2689 * If the old child node was drained but the new one is not, allow
2690 * requests to come in only after the new node has been attached.
2692 while (drain_saldo < 0 && child->klass->drained_end) {
2693 bdrv_parent_drained_end_single(child);
2694 drain_saldo++;
2699 * Updates @child to change its reference to point to @new_bs, including
2700 * checking and applying the necessary permisson updates both to the old node
2701 * and to @new_bs.
2703 * NULL is passed as @new_bs for removing the reference before freeing @child.
2705 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2706 * function uses bdrv_set_perm() to update the permissions according to the new
2707 * reference that @new_bs gets.
2709 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2711 BlockDriverState *old_bs = child->bs;
2712 uint64_t perm, shared_perm;
2714 bdrv_replace_child_noperm(child, new_bs);
2717 * Start with the new node's permissions. If @new_bs is a (direct
2718 * or indirect) child of @old_bs, we must complete the permission
2719 * update on @new_bs before we loosen the restrictions on @old_bs.
2720 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2721 * updating the permissions of @new_bs, and thus not purely loosen
2722 * restrictions.
2724 if (new_bs) {
2725 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2726 bdrv_set_perm(new_bs, perm, shared_perm);
2729 if (old_bs) {
2730 /* Update permissions for old node. This is guaranteed to succeed
2731 * because we're just taking a parent away, so we're loosening
2732 * restrictions. */
2733 bool tighten_restrictions;
2734 int ret;
2736 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
2737 ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2738 &tighten_restrictions, NULL);
2739 assert(tighten_restrictions == false);
2740 if (ret < 0) {
2741 /* We only tried to loosen restrictions, so errors are not fatal */
2742 bdrv_abort_perm_update(old_bs);
2743 } else {
2744 bdrv_set_perm(old_bs, perm, shared_perm);
2747 /* When the parent requiring a non-default AioContext is removed, the
2748 * node moves back to the main AioContext */
2749 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2754 * This function steals the reference to child_bs from the caller.
2755 * That reference is later dropped by bdrv_root_unref_child().
2757 * On failure NULL is returned, errp is set and the reference to
2758 * child_bs is also dropped.
2760 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2761 * (unless @child_bs is already in @ctx).
2763 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2764 const char *child_name,
2765 const BdrvChildClass *child_class,
2766 BdrvChildRole child_role,
2767 AioContext *ctx,
2768 uint64_t perm, uint64_t shared_perm,
2769 void *opaque, Error **errp)
2771 BdrvChild *child;
2772 Error *local_err = NULL;
2773 int ret;
2775 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2776 errp);
2777 if (ret < 0) {
2778 bdrv_abort_perm_update(child_bs);
2779 bdrv_unref(child_bs);
2780 return NULL;
2783 child = g_new(BdrvChild, 1);
2784 *child = (BdrvChild) {
2785 .bs = NULL,
2786 .name = g_strdup(child_name),
2787 .klass = child_class,
2788 .role = child_role,
2789 .perm = perm,
2790 .shared_perm = shared_perm,
2791 .opaque = opaque,
2794 /* If the AioContexts don't match, first try to move the subtree of
2795 * child_bs into the AioContext of the new parent. If this doesn't work,
2796 * try moving the parent into the AioContext of child_bs instead. */
2797 if (bdrv_get_aio_context(child_bs) != ctx) {
2798 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2799 if (ret < 0 && child_class->can_set_aio_ctx) {
2800 GSList *ignore = g_slist_prepend(NULL, child);
2801 ctx = bdrv_get_aio_context(child_bs);
2802 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2803 error_free(local_err);
2804 ret = 0;
2805 g_slist_free(ignore);
2806 ignore = g_slist_prepend(NULL, child);
2807 child_class->set_aio_ctx(child, ctx, &ignore);
2809 g_slist_free(ignore);
2811 if (ret < 0) {
2812 error_propagate(errp, local_err);
2813 g_free(child);
2814 bdrv_abort_perm_update(child_bs);
2815 bdrv_unref(child_bs);
2816 return NULL;
2820 /* This performs the matching bdrv_set_perm() for the above check. */
2821 bdrv_replace_child(child, child_bs);
2823 return child;
2827 * This function transfers the reference to child_bs from the caller
2828 * to parent_bs. That reference is later dropped by parent_bs on
2829 * bdrv_close() or if someone calls bdrv_unref_child().
2831 * On failure NULL is returned, errp is set and the reference to
2832 * child_bs is also dropped.
2834 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2835 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2837 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2838 BlockDriverState *child_bs,
2839 const char *child_name,
2840 const BdrvChildClass *child_class,
2841 BdrvChildRole child_role,
2842 Error **errp)
2844 BdrvChild *child;
2845 uint64_t perm, shared_perm;
2847 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2849 assert(parent_bs->drv);
2850 bdrv_child_perm(parent_bs, child_bs, NULL, child_class, child_role, NULL,
2851 perm, shared_perm, &perm, &shared_perm);
2853 child = bdrv_root_attach_child(child_bs, child_name, child_class,
2854 child_role, bdrv_get_aio_context(parent_bs),
2855 perm, shared_perm, parent_bs, errp);
2856 if (child == NULL) {
2857 return NULL;
2860 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2861 return child;
2864 static void bdrv_detach_child(BdrvChild *child)
2866 QLIST_SAFE_REMOVE(child, next);
2868 bdrv_replace_child(child, NULL);
2870 g_free(child->name);
2871 g_free(child);
2874 void bdrv_root_unref_child(BdrvChild *child)
2876 BlockDriverState *child_bs;
2878 child_bs = child->bs;
2879 bdrv_detach_child(child);
2880 bdrv_unref(child_bs);
2884 * Clear all inherits_from pointers from children and grandchildren of
2885 * @root that point to @root, where necessary.
2887 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
2889 BdrvChild *c;
2891 if (child->bs->inherits_from == root) {
2893 * Remove inherits_from only when the last reference between root and
2894 * child->bs goes away.
2896 QLIST_FOREACH(c, &root->children, next) {
2897 if (c != child && c->bs == child->bs) {
2898 break;
2901 if (c == NULL) {
2902 child->bs->inherits_from = NULL;
2906 QLIST_FOREACH(c, &child->bs->children, next) {
2907 bdrv_unset_inherits_from(root, c);
2911 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2913 if (child == NULL) {
2914 return;
2917 bdrv_unset_inherits_from(parent, child);
2918 bdrv_root_unref_child(child);
2922 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2924 BdrvChild *c;
2925 QLIST_FOREACH(c, &bs->parents, next_parent) {
2926 if (c->klass->change_media) {
2927 c->klass->change_media(c, load);
2932 /* Return true if you can reach parent going through child->inherits_from
2933 * recursively. If parent or child are NULL, return false */
2934 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2935 BlockDriverState *parent)
2937 while (child && child != parent) {
2938 child = child->inherits_from;
2941 return child != NULL;
2945 * Sets the backing file link of a BDS. A new reference is created; callers
2946 * which don't need their own reference any more must call bdrv_unref().
2948 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2949 Error **errp)
2951 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2952 bdrv_inherits_from_recursive(backing_hd, bs);
2954 if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2955 return;
2958 if (backing_hd) {
2959 bdrv_ref(backing_hd);
2962 if (bs->backing) {
2963 bdrv_unref_child(bs, bs->backing);
2964 bs->backing = NULL;
2967 if (!backing_hd) {
2968 goto out;
2971 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
2972 0, errp);
2973 /* If backing_hd was already part of bs's backing chain, and
2974 * inherits_from pointed recursively to bs then let's update it to
2975 * point directly to bs (else it will become NULL). */
2976 if (bs->backing && update_inherits_from) {
2977 backing_hd->inherits_from = bs;
2980 out:
2981 bdrv_refresh_limits(bs, NULL);
2985 * Opens the backing file for a BlockDriverState if not yet open
2987 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2988 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2989 * itself, all options starting with "${bdref_key}." are considered part of the
2990 * BlockdevRef.
2992 * TODO Can this be unified with bdrv_open_image()?
2994 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2995 const char *bdref_key, Error **errp)
2997 char *backing_filename = NULL;
2998 char *bdref_key_dot;
2999 const char *reference = NULL;
3000 int ret = 0;
3001 bool implicit_backing = false;
3002 BlockDriverState *backing_hd;
3003 QDict *options;
3004 QDict *tmp_parent_options = NULL;
3005 Error *local_err = NULL;
3007 if (bs->backing != NULL) {
3008 goto free_exit;
3011 /* NULL means an empty set of options */
3012 if (parent_options == NULL) {
3013 tmp_parent_options = qdict_new();
3014 parent_options = tmp_parent_options;
3017 bs->open_flags &= ~BDRV_O_NO_BACKING;
3019 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3020 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3021 g_free(bdref_key_dot);
3024 * Caution: while qdict_get_try_str() is fine, getting non-string
3025 * types would require more care. When @parent_options come from
3026 * -blockdev or blockdev_add, its members are typed according to
3027 * the QAPI schema, but when they come from -drive, they're all
3028 * QString.
3030 reference = qdict_get_try_str(parent_options, bdref_key);
3031 if (reference || qdict_haskey(options, "file.filename")) {
3032 /* keep backing_filename NULL */
3033 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3034 qobject_unref(options);
3035 goto free_exit;
3036 } else {
3037 if (qdict_size(options) == 0) {
3038 /* If the user specifies options that do not modify the
3039 * backing file's behavior, we might still consider it the
3040 * implicit backing file. But it's easier this way, and
3041 * just specifying some of the backing BDS's options is
3042 * only possible with -drive anyway (otherwise the QAPI
3043 * schema forces the user to specify everything). */
3044 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3047 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3048 if (local_err) {
3049 ret = -EINVAL;
3050 error_propagate(errp, local_err);
3051 qobject_unref(options);
3052 goto free_exit;
3056 if (!bs->drv || !bs->drv->supports_backing) {
3057 ret = -EINVAL;
3058 error_setg(errp, "Driver doesn't support backing files");
3059 qobject_unref(options);
3060 goto free_exit;
3063 if (!reference &&
3064 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3065 qdict_put_str(options, "driver", bs->backing_format);
3068 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3069 &child_backing, 0, errp);
3070 if (!backing_hd) {
3071 bs->open_flags |= BDRV_O_NO_BACKING;
3072 error_prepend(errp, "Could not open backing file: ");
3073 ret = -EINVAL;
3074 goto free_exit;
3077 if (implicit_backing) {
3078 bdrv_refresh_filename(backing_hd);
3079 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3080 backing_hd->filename);
3083 /* Hook up the backing file link; drop our reference, bs owns the
3084 * backing_hd reference now */
3085 bdrv_set_backing_hd(bs, backing_hd, &local_err);
3086 bdrv_unref(backing_hd);
3087 if (local_err) {
3088 error_propagate(errp, local_err);
3089 ret = -EINVAL;
3090 goto free_exit;
3093 qdict_del(parent_options, bdref_key);
3095 free_exit:
3096 g_free(backing_filename);
3097 qobject_unref(tmp_parent_options);
3098 return ret;
3101 static BlockDriverState *
3102 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3103 BlockDriverState *parent, const BdrvChildClass *child_class,
3104 BdrvChildRole child_role, bool allow_none, Error **errp)
3106 BlockDriverState *bs = NULL;
3107 QDict *image_options;
3108 char *bdref_key_dot;
3109 const char *reference;
3111 assert(child_class != NULL);
3113 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3114 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3115 g_free(bdref_key_dot);
3118 * Caution: while qdict_get_try_str() is fine, getting non-string
3119 * types would require more care. When @options come from
3120 * -blockdev or blockdev_add, its members are typed according to
3121 * the QAPI schema, but when they come from -drive, they're all
3122 * QString.
3124 reference = qdict_get_try_str(options, bdref_key);
3125 if (!filename && !reference && !qdict_size(image_options)) {
3126 if (!allow_none) {
3127 error_setg(errp, "A block device must be specified for \"%s\"",
3128 bdref_key);
3130 qobject_unref(image_options);
3131 goto done;
3134 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3135 parent, child_class, child_role, errp);
3136 if (!bs) {
3137 goto done;
3140 done:
3141 qdict_del(options, bdref_key);
3142 return bs;
3146 * Opens a disk image whose options are given as BlockdevRef in another block
3147 * device's options.
3149 * If allow_none is true, no image will be opened if filename is false and no
3150 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3152 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3153 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3154 * itself, all options starting with "${bdref_key}." are considered part of the
3155 * BlockdevRef.
3157 * The BlockdevRef will be removed from the options QDict.
3159 BdrvChild *bdrv_open_child(const char *filename,
3160 QDict *options, const char *bdref_key,
3161 BlockDriverState *parent,
3162 const BdrvChildClass *child_class,
3163 BdrvChildRole child_role,
3164 bool allow_none, Error **errp)
3166 BlockDriverState *bs;
3168 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3169 child_role, allow_none, errp);
3170 if (bs == NULL) {
3171 return NULL;
3174 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3175 errp);
3179 * TODO Future callers may need to specify parent/child_class in order for
3180 * option inheritance to work. Existing callers use it for the root node.
3182 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3184 BlockDriverState *bs = NULL;
3185 QObject *obj = NULL;
3186 QDict *qdict = NULL;
3187 const char *reference = NULL;
3188 Visitor *v = NULL;
3190 if (ref->type == QTYPE_QSTRING) {
3191 reference = ref->u.reference;
3192 } else {
3193 BlockdevOptions *options = &ref->u.definition;
3194 assert(ref->type == QTYPE_QDICT);
3196 v = qobject_output_visitor_new(&obj);
3197 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3198 visit_complete(v, &obj);
3200 qdict = qobject_to(QDict, obj);
3201 qdict_flatten(qdict);
3203 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3204 * compatibility with other callers) rather than what we want as the
3205 * real defaults. Apply the defaults here instead. */
3206 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3207 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3208 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3209 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3213 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3214 obj = NULL;
3215 qobject_unref(obj);
3216 visit_free(v);
3217 return bs;
3220 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3221 int flags,
3222 QDict *snapshot_options,
3223 Error **errp)
3225 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3226 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3227 int64_t total_size;
3228 QemuOpts *opts = NULL;
3229 BlockDriverState *bs_snapshot = NULL;
3230 Error *local_err = NULL;
3231 int ret;
3233 /* if snapshot, we create a temporary backing file and open it
3234 instead of opening 'filename' directly */
3236 /* Get the required size from the image */
3237 total_size = bdrv_getlength(bs);
3238 if (total_size < 0) {
3239 error_setg_errno(errp, -total_size, "Could not get image size");
3240 goto out;
3243 /* Create the temporary image */
3244 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3245 if (ret < 0) {
3246 error_setg_errno(errp, -ret, "Could not get temporary filename");
3247 goto out;
3250 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3251 &error_abort);
3252 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3253 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3254 qemu_opts_del(opts);
3255 if (ret < 0) {
3256 error_prepend(errp, "Could not create temporary overlay '%s': ",
3257 tmp_filename);
3258 goto out;
3261 /* Prepare options QDict for the temporary file */
3262 qdict_put_str(snapshot_options, "file.driver", "file");
3263 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3264 qdict_put_str(snapshot_options, "driver", "qcow2");
3266 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3267 snapshot_options = NULL;
3268 if (!bs_snapshot) {
3269 goto out;
3272 /* bdrv_append() consumes a strong reference to bs_snapshot
3273 * (i.e. it will call bdrv_unref() on it) even on error, so in
3274 * order to be able to return one, we have to increase
3275 * bs_snapshot's refcount here */
3276 bdrv_ref(bs_snapshot);
3277 bdrv_append(bs_snapshot, bs, &local_err);
3278 if (local_err) {
3279 error_propagate(errp, local_err);
3280 bs_snapshot = NULL;
3281 goto out;
3284 out:
3285 qobject_unref(snapshot_options);
3286 g_free(tmp_filename);
3287 return bs_snapshot;
3291 * Opens a disk image (raw, qcow2, vmdk, ...)
3293 * options is a QDict of options to pass to the block drivers, or NULL for an
3294 * empty set of options. The reference to the QDict belongs to the block layer
3295 * after the call (even on failure), so if the caller intends to reuse the
3296 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3298 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3299 * If it is not NULL, the referenced BDS will be reused.
3301 * The reference parameter may be used to specify an existing block device which
3302 * should be opened. If specified, neither options nor a filename may be given,
3303 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3305 static BlockDriverState *bdrv_open_inherit(const char *filename,
3306 const char *reference,
3307 QDict *options, int flags,
3308 BlockDriverState *parent,
3309 const BdrvChildClass *child_class,
3310 BdrvChildRole child_role,
3311 Error **errp)
3313 int ret;
3314 BlockBackend *file = NULL;
3315 BlockDriverState *bs;
3316 BlockDriver *drv = NULL;
3317 BdrvChild *child;
3318 const char *drvname;
3319 const char *backing;
3320 Error *local_err = NULL;
3321 QDict *snapshot_options = NULL;
3322 int snapshot_flags = 0;
3324 assert(!child_class || !flags);
3325 assert(!child_class == !parent);
3327 if (reference) {
3328 bool options_non_empty = options ? qdict_size(options) : false;
3329 qobject_unref(options);
3331 if (filename || options_non_empty) {
3332 error_setg(errp, "Cannot reference an existing block device with "
3333 "additional options or a new filename");
3334 return NULL;
3337 bs = bdrv_lookup_bs(reference, reference, errp);
3338 if (!bs) {
3339 return NULL;
3342 bdrv_ref(bs);
3343 return bs;
3346 bs = bdrv_new();
3348 /* NULL means an empty set of options */
3349 if (options == NULL) {
3350 options = qdict_new();
3353 /* json: syntax counts as explicit options, as if in the QDict */
3354 parse_json_protocol(options, &filename, &local_err);
3355 if (local_err) {
3356 goto fail;
3359 bs->explicit_options = qdict_clone_shallow(options);
3361 if (child_class) {
3362 bool parent_is_format;
3364 if (parent->drv) {
3365 parent_is_format = parent->drv->is_format;
3366 } else {
3368 * parent->drv is not set yet because this node is opened for
3369 * (potential) format probing. That means that @parent is going
3370 * to be a format node.
3372 parent_is_format = true;
3375 bs->inherits_from = parent;
3376 child_class->inherit_options(child_role, parent_is_format,
3377 &flags, options,
3378 parent->open_flags, parent->options);
3381 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3382 if (ret < 0) {
3383 goto fail;
3387 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3388 * Caution: getting a boolean member of @options requires care.
3389 * When @options come from -blockdev or blockdev_add, members are
3390 * typed according to the QAPI schema, but when they come from
3391 * -drive, they're all QString.
3393 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3394 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3395 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3396 } else {
3397 flags &= ~BDRV_O_RDWR;
3400 if (flags & BDRV_O_SNAPSHOT) {
3401 snapshot_options = qdict_new();
3402 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3403 flags, options);
3404 /* Let bdrv_backing_options() override "read-only" */
3405 qdict_del(options, BDRV_OPT_READ_ONLY);
3406 bdrv_inherited_options(BDRV_CHILD_COW, true,
3407 &flags, options, flags, options);
3410 bs->open_flags = flags;
3411 bs->options = options;
3412 options = qdict_clone_shallow(options);
3414 /* Find the right image format driver */
3415 /* See cautionary note on accessing @options above */
3416 drvname = qdict_get_try_str(options, "driver");
3417 if (drvname) {
3418 drv = bdrv_find_format(drvname);
3419 if (!drv) {
3420 error_setg(errp, "Unknown driver: '%s'", drvname);
3421 goto fail;
3425 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3427 /* See cautionary note on accessing @options above */
3428 backing = qdict_get_try_str(options, "backing");
3429 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3430 (backing && *backing == '\0'))
3432 if (backing) {
3433 warn_report("Use of \"backing\": \"\" is deprecated; "
3434 "use \"backing\": null instead");
3436 flags |= BDRV_O_NO_BACKING;
3437 qdict_del(bs->explicit_options, "backing");
3438 qdict_del(bs->options, "backing");
3439 qdict_del(options, "backing");
3442 /* Open image file without format layer. This BlockBackend is only used for
3443 * probing, the block drivers will do their own bdrv_open_child() for the
3444 * same BDS, which is why we put the node name back into options. */
3445 if ((flags & BDRV_O_PROTOCOL) == 0) {
3446 BlockDriverState *file_bs;
3448 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3449 &child_file, 0, true, &local_err);
3450 if (local_err) {
3451 goto fail;
3453 if (file_bs != NULL) {
3454 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3455 * looking at the header to guess the image format. This works even
3456 * in cases where a guest would not see a consistent state. */
3457 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3458 blk_insert_bs(file, file_bs, &local_err);
3459 bdrv_unref(file_bs);
3460 if (local_err) {
3461 goto fail;
3464 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3468 /* Image format probing */
3469 bs->probed = !drv;
3470 if (!drv && file) {
3471 ret = find_image_format(file, filename, &drv, &local_err);
3472 if (ret < 0) {
3473 goto fail;
3476 * This option update would logically belong in bdrv_fill_options(),
3477 * but we first need to open bs->file for the probing to work, while
3478 * opening bs->file already requires the (mostly) final set of options
3479 * so that cache mode etc. can be inherited.
3481 * Adding the driver later is somewhat ugly, but it's not an option
3482 * that would ever be inherited, so it's correct. We just need to make
3483 * sure to update both bs->options (which has the full effective
3484 * options for bs) and options (which has file.* already removed).
3486 qdict_put_str(bs->options, "driver", drv->format_name);
3487 qdict_put_str(options, "driver", drv->format_name);
3488 } else if (!drv) {
3489 error_setg(errp, "Must specify either driver or file");
3490 goto fail;
3493 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3494 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3495 /* file must be NULL if a protocol BDS is about to be created
3496 * (the inverse results in an error message from bdrv_open_common()) */
3497 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3499 /* Open the image */
3500 ret = bdrv_open_common(bs, file, options, &local_err);
3501 if (ret < 0) {
3502 goto fail;
3505 if (file) {
3506 blk_unref(file);
3507 file = NULL;
3510 /* If there is a backing file, use it */
3511 if ((flags & BDRV_O_NO_BACKING) == 0) {
3512 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3513 if (ret < 0) {
3514 goto close_and_fail;
3518 /* Remove all children options and references
3519 * from bs->options and bs->explicit_options */
3520 QLIST_FOREACH(child, &bs->children, next) {
3521 char *child_key_dot;
3522 child_key_dot = g_strdup_printf("%s.", child->name);
3523 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3524 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3525 qdict_del(bs->explicit_options, child->name);
3526 qdict_del(bs->options, child->name);
3527 g_free(child_key_dot);
3530 /* Check if any unknown options were used */
3531 if (qdict_size(options) != 0) {
3532 const QDictEntry *entry = qdict_first(options);
3533 if (flags & BDRV_O_PROTOCOL) {
3534 error_setg(errp, "Block protocol '%s' doesn't support the option "
3535 "'%s'", drv->format_name, entry->key);
3536 } else {
3537 error_setg(errp,
3538 "Block format '%s' does not support the option '%s'",
3539 drv->format_name, entry->key);
3542 goto close_and_fail;
3545 bdrv_parent_cb_change_media(bs, true);
3547 qobject_unref(options);
3548 options = NULL;
3550 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3551 * temporary snapshot afterwards. */
3552 if (snapshot_flags) {
3553 BlockDriverState *snapshot_bs;
3554 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3555 snapshot_options, &local_err);
3556 snapshot_options = NULL;
3557 if (local_err) {
3558 goto close_and_fail;
3560 /* We are not going to return bs but the overlay on top of it
3561 * (snapshot_bs); thus, we have to drop the strong reference to bs
3562 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3563 * though, because the overlay still has a reference to it. */
3564 bdrv_unref(bs);
3565 bs = snapshot_bs;
3568 return bs;
3570 fail:
3571 blk_unref(file);
3572 qobject_unref(snapshot_options);
3573 qobject_unref(bs->explicit_options);
3574 qobject_unref(bs->options);
3575 qobject_unref(options);
3576 bs->options = NULL;
3577 bs->explicit_options = NULL;
3578 bdrv_unref(bs);
3579 error_propagate(errp, local_err);
3580 return NULL;
3582 close_and_fail:
3583 bdrv_unref(bs);
3584 qobject_unref(snapshot_options);
3585 qobject_unref(options);
3586 error_propagate(errp, local_err);
3587 return NULL;
3590 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3591 QDict *options, int flags, Error **errp)
3593 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3594 NULL, 0, errp);
3597 /* Return true if the NULL-terminated @list contains @str */
3598 static bool is_str_in_list(const char *str, const char *const *list)
3600 if (str && list) {
3601 int i;
3602 for (i = 0; list[i] != NULL; i++) {
3603 if (!strcmp(str, list[i])) {
3604 return true;
3608 return false;
3612 * Check that every option set in @bs->options is also set in
3613 * @new_opts.
3615 * Options listed in the common_options list and in
3616 * @bs->drv->mutable_opts are skipped.
3618 * Return 0 on success, otherwise return -EINVAL and set @errp.
3620 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3621 const QDict *new_opts, Error **errp)
3623 const QDictEntry *e;
3624 /* These options are common to all block drivers and are handled
3625 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3626 const char *const common_options[] = {
3627 "node-name", "discard", "cache.direct", "cache.no-flush",
3628 "read-only", "auto-read-only", "detect-zeroes", NULL
3631 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3632 if (!qdict_haskey(new_opts, e->key) &&
3633 !is_str_in_list(e->key, common_options) &&
3634 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3635 error_setg(errp, "Option '%s' cannot be reset "
3636 "to its default value", e->key);
3637 return -EINVAL;
3641 return 0;
3645 * Returns true if @child can be reached recursively from @bs
3647 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3648 BlockDriverState *child)
3650 BdrvChild *c;
3652 if (bs == child) {
3653 return true;
3656 QLIST_FOREACH(c, &bs->children, next) {
3657 if (bdrv_recurse_has_child(c->bs, child)) {
3658 return true;
3662 return false;
3666 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3667 * reopen of multiple devices.
3669 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3670 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3671 * be created and initialized. This newly created BlockReopenQueue should be
3672 * passed back in for subsequent calls that are intended to be of the same
3673 * atomic 'set'.
3675 * bs is the BlockDriverState to add to the reopen queue.
3677 * options contains the changed options for the associated bs
3678 * (the BlockReopenQueue takes ownership)
3680 * flags contains the open flags for the associated bs
3682 * returns a pointer to bs_queue, which is either the newly allocated
3683 * bs_queue, or the existing bs_queue being used.
3685 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3687 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3688 BlockDriverState *bs,
3689 QDict *options,
3690 const BdrvChildClass *klass,
3691 BdrvChildRole role,
3692 bool parent_is_format,
3693 QDict *parent_options,
3694 int parent_flags,
3695 bool keep_old_opts)
3697 assert(bs != NULL);
3699 BlockReopenQueueEntry *bs_entry;
3700 BdrvChild *child;
3701 QDict *old_options, *explicit_options, *options_copy;
3702 int flags;
3703 QemuOpts *opts;
3705 /* Make sure that the caller remembered to use a drained section. This is
3706 * important to avoid graph changes between the recursive queuing here and
3707 * bdrv_reopen_multiple(). */
3708 assert(bs->quiesce_counter > 0);
3710 if (bs_queue == NULL) {
3711 bs_queue = g_new0(BlockReopenQueue, 1);
3712 QTAILQ_INIT(bs_queue);
3715 if (!options) {
3716 options = qdict_new();
3719 /* Check if this BlockDriverState is already in the queue */
3720 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3721 if (bs == bs_entry->state.bs) {
3722 break;
3727 * Precedence of options:
3728 * 1. Explicitly passed in options (highest)
3729 * 2. Retained from explicitly set options of bs
3730 * 3. Inherited from parent node
3731 * 4. Retained from effective options of bs
3734 /* Old explicitly set values (don't overwrite by inherited value) */
3735 if (bs_entry || keep_old_opts) {
3736 old_options = qdict_clone_shallow(bs_entry ?
3737 bs_entry->state.explicit_options :
3738 bs->explicit_options);
3739 bdrv_join_options(bs, options, old_options);
3740 qobject_unref(old_options);
3743 explicit_options = qdict_clone_shallow(options);
3745 /* Inherit from parent node */
3746 if (parent_options) {
3747 flags = 0;
3748 klass->inherit_options(role, parent_is_format, &flags, options,
3749 parent_flags, parent_options);
3750 } else {
3751 flags = bdrv_get_flags(bs);
3754 if (keep_old_opts) {
3755 /* Old values are used for options that aren't set yet */
3756 old_options = qdict_clone_shallow(bs->options);
3757 bdrv_join_options(bs, options, old_options);
3758 qobject_unref(old_options);
3761 /* We have the final set of options so let's update the flags */
3762 options_copy = qdict_clone_shallow(options);
3763 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3764 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3765 update_flags_from_options(&flags, opts);
3766 qemu_opts_del(opts);
3767 qobject_unref(options_copy);
3769 /* bdrv_open_inherit() sets and clears some additional flags internally */
3770 flags &= ~BDRV_O_PROTOCOL;
3771 if (flags & BDRV_O_RDWR) {
3772 flags |= BDRV_O_ALLOW_RDWR;
3775 if (!bs_entry) {
3776 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3777 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3778 } else {
3779 qobject_unref(bs_entry->state.options);
3780 qobject_unref(bs_entry->state.explicit_options);
3783 bs_entry->state.bs = bs;
3784 bs_entry->state.options = options;
3785 bs_entry->state.explicit_options = explicit_options;
3786 bs_entry->state.flags = flags;
3788 /* This needs to be overwritten in bdrv_reopen_prepare() */
3789 bs_entry->state.perm = UINT64_MAX;
3790 bs_entry->state.shared_perm = 0;
3793 * If keep_old_opts is false then it means that unspecified
3794 * options must be reset to their original value. We don't allow
3795 * resetting 'backing' but we need to know if the option is
3796 * missing in order to decide if we have to return an error.
3798 if (!keep_old_opts) {
3799 bs_entry->state.backing_missing =
3800 !qdict_haskey(options, "backing") &&
3801 !qdict_haskey(options, "backing.driver");
3804 QLIST_FOREACH(child, &bs->children, next) {
3805 QDict *new_child_options = NULL;
3806 bool child_keep_old = keep_old_opts;
3808 /* reopen can only change the options of block devices that were
3809 * implicitly created and inherited options. For other (referenced)
3810 * block devices, a syntax like "backing.foo" results in an error. */
3811 if (child->bs->inherits_from != bs) {
3812 continue;
3815 /* Check if the options contain a child reference */
3816 if (qdict_haskey(options, child->name)) {
3817 const char *childref = qdict_get_try_str(options, child->name);
3819 * The current child must not be reopened if the child
3820 * reference is null or points to a different node.
3822 if (g_strcmp0(childref, child->bs->node_name)) {
3823 continue;
3826 * If the child reference points to the current child then
3827 * reopen it with its existing set of options (note that
3828 * it can still inherit new options from the parent).
3830 child_keep_old = true;
3831 } else {
3832 /* Extract child options ("child-name.*") */
3833 char *child_key_dot = g_strdup_printf("%s.", child->name);
3834 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3835 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3836 g_free(child_key_dot);
3839 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3840 child->klass, child->role, bs->drv->is_format,
3841 options, flags, child_keep_old);
3844 return bs_queue;
3847 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3848 BlockDriverState *bs,
3849 QDict *options, bool keep_old_opts)
3851 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3852 NULL, 0, keep_old_opts);
3856 * Reopen multiple BlockDriverStates atomically & transactionally.
3858 * The queue passed in (bs_queue) must have been built up previous
3859 * via bdrv_reopen_queue().
3861 * Reopens all BDS specified in the queue, with the appropriate
3862 * flags. All devices are prepared for reopen, and failure of any
3863 * device will cause all device changes to be abandoned, and intermediate
3864 * data cleaned up.
3866 * If all devices prepare successfully, then the changes are committed
3867 * to all devices.
3869 * All affected nodes must be drained between bdrv_reopen_queue() and
3870 * bdrv_reopen_multiple().
3872 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3874 int ret = -1;
3875 BlockReopenQueueEntry *bs_entry, *next;
3877 assert(bs_queue != NULL);
3879 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3880 assert(bs_entry->state.bs->quiesce_counter > 0);
3881 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3882 goto cleanup;
3884 bs_entry->prepared = true;
3887 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3888 BDRVReopenState *state = &bs_entry->state;
3889 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3890 state->shared_perm, NULL, NULL, errp);
3891 if (ret < 0) {
3892 goto cleanup_perm;
3894 /* Check if new_backing_bs would accept the new permissions */
3895 if (state->replace_backing_bs && state->new_backing_bs) {
3896 uint64_t nperm, nshared;
3897 bdrv_child_perm(state->bs, state->new_backing_bs,
3898 NULL, &child_backing, 0, bs_queue,
3899 state->perm, state->shared_perm,
3900 &nperm, &nshared);
3901 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3902 nperm, nshared, NULL, NULL, errp);
3903 if (ret < 0) {
3904 goto cleanup_perm;
3907 bs_entry->perms_checked = true;
3911 * If we reach this point, we have success and just need to apply the
3912 * changes.
3914 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3915 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3916 * children are usually goes after parents in reopen-queue, so go from last
3917 * to first element.
3919 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3920 bdrv_reopen_commit(&bs_entry->state);
3923 ret = 0;
3924 cleanup_perm:
3925 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3926 BDRVReopenState *state = &bs_entry->state;
3928 if (!bs_entry->perms_checked) {
3929 continue;
3932 if (ret == 0) {
3933 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3934 } else {
3935 bdrv_abort_perm_update(state->bs);
3936 if (state->replace_backing_bs && state->new_backing_bs) {
3937 bdrv_abort_perm_update(state->new_backing_bs);
3942 if (ret == 0) {
3943 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3944 BlockDriverState *bs = bs_entry->state.bs;
3946 if (bs->drv->bdrv_reopen_commit_post)
3947 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3950 cleanup:
3951 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3952 if (ret) {
3953 if (bs_entry->prepared) {
3954 bdrv_reopen_abort(&bs_entry->state);
3956 qobject_unref(bs_entry->state.explicit_options);
3957 qobject_unref(bs_entry->state.options);
3959 if (bs_entry->state.new_backing_bs) {
3960 bdrv_unref(bs_entry->state.new_backing_bs);
3962 g_free(bs_entry);
3964 g_free(bs_queue);
3966 return ret;
3969 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3970 Error **errp)
3972 int ret;
3973 BlockReopenQueue *queue;
3974 QDict *opts = qdict_new();
3976 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3978 bdrv_subtree_drained_begin(bs);
3979 queue = bdrv_reopen_queue(NULL, bs, opts, true);
3980 ret = bdrv_reopen_multiple(queue, errp);
3981 bdrv_subtree_drained_end(bs);
3983 return ret;
3986 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3987 BdrvChild *c)
3989 BlockReopenQueueEntry *entry;
3991 QTAILQ_FOREACH(entry, q, entry) {
3992 BlockDriverState *bs = entry->state.bs;
3993 BdrvChild *child;
3995 QLIST_FOREACH(child, &bs->children, next) {
3996 if (child == c) {
3997 return entry;
4002 return NULL;
4005 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
4006 uint64_t *perm, uint64_t *shared)
4008 BdrvChild *c;
4009 BlockReopenQueueEntry *parent;
4010 uint64_t cumulative_perms = 0;
4011 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
4013 QLIST_FOREACH(c, &bs->parents, next_parent) {
4014 parent = find_parent_in_reopen_queue(q, c);
4015 if (!parent) {
4016 cumulative_perms |= c->perm;
4017 cumulative_shared_perms &= c->shared_perm;
4018 } else {
4019 uint64_t nperm, nshared;
4021 bdrv_child_perm(parent->state.bs, bs, c, c->klass, c->role, q,
4022 parent->state.perm, parent->state.shared_perm,
4023 &nperm, &nshared);
4025 cumulative_perms |= nperm;
4026 cumulative_shared_perms &= nshared;
4029 *perm = cumulative_perms;
4030 *shared = cumulative_shared_perms;
4033 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4034 BdrvChild *child,
4035 BlockDriverState *new_child,
4036 Error **errp)
4038 AioContext *parent_ctx = bdrv_get_aio_context(parent);
4039 AioContext *child_ctx = bdrv_get_aio_context(new_child);
4040 GSList *ignore;
4041 bool ret;
4043 ignore = g_slist_prepend(NULL, child);
4044 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4045 g_slist_free(ignore);
4046 if (ret) {
4047 return ret;
4050 ignore = g_slist_prepend(NULL, child);
4051 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4052 g_slist_free(ignore);
4053 return ret;
4057 * Take a BDRVReopenState and check if the value of 'backing' in the
4058 * reopen_state->options QDict is valid or not.
4060 * If 'backing' is missing from the QDict then return 0.
4062 * If 'backing' contains the node name of the backing file of
4063 * reopen_state->bs then return 0.
4065 * If 'backing' contains a different node name (or is null) then check
4066 * whether the current backing file can be replaced with the new one.
4067 * If that's the case then reopen_state->replace_backing_bs is set to
4068 * true and reopen_state->new_backing_bs contains a pointer to the new
4069 * backing BlockDriverState (or NULL).
4071 * Return 0 on success, otherwise return < 0 and set @errp.
4073 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4074 Error **errp)
4076 BlockDriverState *bs = reopen_state->bs;
4077 BlockDriverState *overlay_bs, *new_backing_bs;
4078 QObject *value;
4079 const char *str;
4081 value = qdict_get(reopen_state->options, "backing");
4082 if (value == NULL) {
4083 return 0;
4086 switch (qobject_type(value)) {
4087 case QTYPE_QNULL:
4088 new_backing_bs = NULL;
4089 break;
4090 case QTYPE_QSTRING:
4091 str = qobject_get_try_str(value);
4092 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4093 if (new_backing_bs == NULL) {
4094 return -EINVAL;
4095 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4096 error_setg(errp, "Making '%s' a backing file of '%s' "
4097 "would create a cycle", str, bs->node_name);
4098 return -EINVAL;
4100 break;
4101 default:
4102 /* 'backing' does not allow any other data type */
4103 g_assert_not_reached();
4107 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4108 * bdrv_reopen_commit() won't fail.
4110 if (new_backing_bs) {
4111 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4112 return -EINVAL;
4117 * Find the "actual" backing file by skipping all links that point
4118 * to an implicit node, if any (e.g. a commit filter node).
4120 overlay_bs = bs;
4121 while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
4122 overlay_bs = backing_bs(overlay_bs);
4125 /* If we want to replace the backing file we need some extra checks */
4126 if (new_backing_bs != backing_bs(overlay_bs)) {
4127 /* Check for implicit nodes between bs and its backing file */
4128 if (bs != overlay_bs) {
4129 error_setg(errp, "Cannot change backing link if '%s' has "
4130 "an implicit backing file", bs->node_name);
4131 return -EPERM;
4133 /* Check if the backing link that we want to replace is frozen */
4134 if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
4135 errp)) {
4136 return -EPERM;
4138 reopen_state->replace_backing_bs = true;
4139 if (new_backing_bs) {
4140 bdrv_ref(new_backing_bs);
4141 reopen_state->new_backing_bs = new_backing_bs;
4145 return 0;
4149 * Prepares a BlockDriverState for reopen. All changes are staged in the
4150 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4151 * the block driver layer .bdrv_reopen_prepare()
4153 * bs is the BlockDriverState to reopen
4154 * flags are the new open flags
4155 * queue is the reopen queue
4157 * Returns 0 on success, non-zero on error. On error errp will be set
4158 * as well.
4160 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4161 * It is the responsibility of the caller to then call the abort() or
4162 * commit() for any other BDS that have been left in a prepare() state
4165 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4166 Error **errp)
4168 int ret = -1;
4169 int old_flags;
4170 Error *local_err = NULL;
4171 BlockDriver *drv;
4172 QemuOpts *opts;
4173 QDict *orig_reopen_opts;
4174 char *discard = NULL;
4175 bool read_only;
4176 bool drv_prepared = false;
4178 assert(reopen_state != NULL);
4179 assert(reopen_state->bs->drv != NULL);
4180 drv = reopen_state->bs->drv;
4182 /* This function and each driver's bdrv_reopen_prepare() remove
4183 * entries from reopen_state->options as they are processed, so
4184 * we need to make a copy of the original QDict. */
4185 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4187 /* Process generic block layer options */
4188 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4189 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
4190 if (local_err) {
4191 error_propagate(errp, local_err);
4192 ret = -EINVAL;
4193 goto error;
4196 /* This was already called in bdrv_reopen_queue_child() so the flags
4197 * are up-to-date. This time we simply want to remove the options from
4198 * QemuOpts in order to indicate that they have been processed. */
4199 old_flags = reopen_state->flags;
4200 update_flags_from_options(&reopen_state->flags, opts);
4201 assert(old_flags == reopen_state->flags);
4203 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4204 if (discard != NULL) {
4205 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4206 error_setg(errp, "Invalid discard option");
4207 ret = -EINVAL;
4208 goto error;
4212 reopen_state->detect_zeroes =
4213 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4214 if (local_err) {
4215 error_propagate(errp, local_err);
4216 ret = -EINVAL;
4217 goto error;
4220 /* All other options (including node-name and driver) must be unchanged.
4221 * Put them back into the QDict, so that they are checked at the end
4222 * of this function. */
4223 qemu_opts_to_qdict(opts, reopen_state->options);
4225 /* If we are to stay read-only, do not allow permission change
4226 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4227 * not set, or if the BDS still has copy_on_read enabled */
4228 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4229 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4230 if (local_err) {
4231 error_propagate(errp, local_err);
4232 goto error;
4235 /* Calculate required permissions after reopening */
4236 bdrv_reopen_perm(queue, reopen_state->bs,
4237 &reopen_state->perm, &reopen_state->shared_perm);
4239 ret = bdrv_flush(reopen_state->bs);
4240 if (ret) {
4241 error_setg_errno(errp, -ret, "Error flushing drive");
4242 goto error;
4245 if (drv->bdrv_reopen_prepare) {
4247 * If a driver-specific option is missing, it means that we
4248 * should reset it to its default value.
4249 * But not all options allow that, so we need to check it first.
4251 ret = bdrv_reset_options_allowed(reopen_state->bs,
4252 reopen_state->options, errp);
4253 if (ret) {
4254 goto error;
4257 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4258 if (ret) {
4259 if (local_err != NULL) {
4260 error_propagate(errp, local_err);
4261 } else {
4262 bdrv_refresh_filename(reopen_state->bs);
4263 error_setg(errp, "failed while preparing to reopen image '%s'",
4264 reopen_state->bs->filename);
4266 goto error;
4268 } else {
4269 /* It is currently mandatory to have a bdrv_reopen_prepare()
4270 * handler for each supported drv. */
4271 error_setg(errp, "Block format '%s' used by node '%s' "
4272 "does not support reopening files", drv->format_name,
4273 bdrv_get_device_or_node_name(reopen_state->bs));
4274 ret = -1;
4275 goto error;
4278 drv_prepared = true;
4281 * We must provide the 'backing' option if the BDS has a backing
4282 * file or if the image file has a backing file name as part of
4283 * its metadata. Otherwise the 'backing' option can be omitted.
4285 if (drv->supports_backing && reopen_state->backing_missing &&
4286 (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
4287 error_setg(errp, "backing is missing for '%s'",
4288 reopen_state->bs->node_name);
4289 ret = -EINVAL;
4290 goto error;
4294 * Allow changing the 'backing' option. The new value can be
4295 * either a reference to an existing node (using its node name)
4296 * or NULL to simply detach the current backing file.
4298 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4299 if (ret < 0) {
4300 goto error;
4302 qdict_del(reopen_state->options, "backing");
4304 /* Options that are not handled are only okay if they are unchanged
4305 * compared to the old state. It is expected that some options are only
4306 * used for the initial open, but not reopen (e.g. filename) */
4307 if (qdict_size(reopen_state->options)) {
4308 const QDictEntry *entry = qdict_first(reopen_state->options);
4310 do {
4311 QObject *new = entry->value;
4312 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4314 /* Allow child references (child_name=node_name) as long as they
4315 * point to the current child (i.e. everything stays the same). */
4316 if (qobject_type(new) == QTYPE_QSTRING) {
4317 BdrvChild *child;
4318 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4319 if (!strcmp(child->name, entry->key)) {
4320 break;
4324 if (child) {
4325 const char *str = qobject_get_try_str(new);
4326 if (!strcmp(child->bs->node_name, str)) {
4327 continue; /* Found child with this name, skip option */
4333 * TODO: When using -drive to specify blockdev options, all values
4334 * will be strings; however, when using -blockdev, blockdev-add or
4335 * filenames using the json:{} pseudo-protocol, they will be
4336 * correctly typed.
4337 * In contrast, reopening options are (currently) always strings
4338 * (because you can only specify them through qemu-io; all other
4339 * callers do not specify any options).
4340 * Therefore, when using anything other than -drive to create a BDS,
4341 * this cannot detect non-string options as unchanged, because
4342 * qobject_is_equal() always returns false for objects of different
4343 * type. In the future, this should be remedied by correctly typing
4344 * all options. For now, this is not too big of an issue because
4345 * the user can simply omit options which cannot be changed anyway,
4346 * so they will stay unchanged.
4348 if (!qobject_is_equal(new, old)) {
4349 error_setg(errp, "Cannot change the option '%s'", entry->key);
4350 ret = -EINVAL;
4351 goto error;
4353 } while ((entry = qdict_next(reopen_state->options, entry)));
4356 ret = 0;
4358 /* Restore the original reopen_state->options QDict */
4359 qobject_unref(reopen_state->options);
4360 reopen_state->options = qobject_ref(orig_reopen_opts);
4362 error:
4363 if (ret < 0 && drv_prepared) {
4364 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4365 * call drv->bdrv_reopen_abort() before signaling an error
4366 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4367 * when the respective bdrv_reopen_prepare() has failed) */
4368 if (drv->bdrv_reopen_abort) {
4369 drv->bdrv_reopen_abort(reopen_state);
4372 qemu_opts_del(opts);
4373 qobject_unref(orig_reopen_opts);
4374 g_free(discard);
4375 return ret;
4379 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4380 * makes them final by swapping the staging BlockDriverState contents into
4381 * the active BlockDriverState contents.
4383 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4385 BlockDriver *drv;
4386 BlockDriverState *bs;
4387 BdrvChild *child;
4389 assert(reopen_state != NULL);
4390 bs = reopen_state->bs;
4391 drv = bs->drv;
4392 assert(drv != NULL);
4394 /* If there are any driver level actions to take */
4395 if (drv->bdrv_reopen_commit) {
4396 drv->bdrv_reopen_commit(reopen_state);
4399 /* set BDS specific flags now */
4400 qobject_unref(bs->explicit_options);
4401 qobject_unref(bs->options);
4403 bs->explicit_options = reopen_state->explicit_options;
4404 bs->options = reopen_state->options;
4405 bs->open_flags = reopen_state->flags;
4406 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
4407 bs->detect_zeroes = reopen_state->detect_zeroes;
4409 if (reopen_state->replace_backing_bs) {
4410 qdict_del(bs->explicit_options, "backing");
4411 qdict_del(bs->options, "backing");
4414 /* Remove child references from bs->options and bs->explicit_options.
4415 * Child options were already removed in bdrv_reopen_queue_child() */
4416 QLIST_FOREACH(child, &bs->children, next) {
4417 qdict_del(bs->explicit_options, child->name);
4418 qdict_del(bs->options, child->name);
4422 * Change the backing file if a new one was specified. We do this
4423 * after updating bs->options, so bdrv_refresh_filename() (called
4424 * from bdrv_set_backing_hd()) has the new values.
4426 if (reopen_state->replace_backing_bs) {
4427 BlockDriverState *old_backing_bs = backing_bs(bs);
4428 assert(!old_backing_bs || !old_backing_bs->implicit);
4429 /* Abort the permission update on the backing bs we're detaching */
4430 if (old_backing_bs) {
4431 bdrv_abort_perm_update(old_backing_bs);
4433 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4436 bdrv_refresh_limits(bs, NULL);
4440 * Abort the reopen, and delete and free the staged changes in
4441 * reopen_state
4443 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4445 BlockDriver *drv;
4447 assert(reopen_state != NULL);
4448 drv = reopen_state->bs->drv;
4449 assert(drv != NULL);
4451 if (drv->bdrv_reopen_abort) {
4452 drv->bdrv_reopen_abort(reopen_state);
4457 static void bdrv_close(BlockDriverState *bs)
4459 BdrvAioNotifier *ban, *ban_next;
4460 BdrvChild *child, *next;
4462 assert(!bs->refcnt);
4464 bdrv_drained_begin(bs); /* complete I/O */
4465 bdrv_flush(bs);
4466 bdrv_drain(bs); /* in case flush left pending I/O */
4468 if (bs->drv) {
4469 if (bs->drv->bdrv_close) {
4470 bs->drv->bdrv_close(bs);
4472 bs->drv = NULL;
4475 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4476 bdrv_unref_child(bs, child);
4479 bs->backing = NULL;
4480 bs->file = NULL;
4481 g_free(bs->opaque);
4482 bs->opaque = NULL;
4483 atomic_set(&bs->copy_on_read, 0);
4484 bs->backing_file[0] = '\0';
4485 bs->backing_format[0] = '\0';
4486 bs->total_sectors = 0;
4487 bs->encrypted = false;
4488 bs->sg = false;
4489 qobject_unref(bs->options);
4490 qobject_unref(bs->explicit_options);
4491 bs->options = NULL;
4492 bs->explicit_options = NULL;
4493 qobject_unref(bs->full_open_options);
4494 bs->full_open_options = NULL;
4496 bdrv_release_named_dirty_bitmaps(bs);
4497 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4499 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4500 g_free(ban);
4502 QLIST_INIT(&bs->aio_notifiers);
4503 bdrv_drained_end(bs);
4506 void bdrv_close_all(void)
4508 assert(job_next(NULL) == NULL);
4509 nbd_export_close_all();
4511 /* Drop references from requests still in flight, such as canceled block
4512 * jobs whose AIO context has not been polled yet */
4513 bdrv_drain_all();
4515 blk_remove_all_bs();
4516 blockdev_close_all_bdrv_states();
4518 assert(QTAILQ_EMPTY(&all_bdrv_states));
4521 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4523 GQueue *queue;
4524 GHashTable *found;
4525 bool ret;
4527 if (c->klass->stay_at_node) {
4528 return false;
4531 /* If the child @c belongs to the BDS @to, replacing the current
4532 * c->bs by @to would mean to create a loop.
4534 * Such a case occurs when appending a BDS to a backing chain.
4535 * For instance, imagine the following chain:
4537 * guest device -> node A -> further backing chain...
4539 * Now we create a new BDS B which we want to put on top of this
4540 * chain, so we first attach A as its backing node:
4542 * node B
4545 * guest device -> node A -> further backing chain...
4547 * Finally we want to replace A by B. When doing that, we want to
4548 * replace all pointers to A by pointers to B -- except for the
4549 * pointer from B because (1) that would create a loop, and (2)
4550 * that pointer should simply stay intact:
4552 * guest device -> node B
4555 * node A -> further backing chain...
4557 * In general, when replacing a node A (c->bs) by a node B (@to),
4558 * if A is a child of B, that means we cannot replace A by B there
4559 * because that would create a loop. Silently detaching A from B
4560 * is also not really an option. So overall just leaving A in
4561 * place there is the most sensible choice.
4563 * We would also create a loop in any cases where @c is only
4564 * indirectly referenced by @to. Prevent this by returning false
4565 * if @c is found (by breadth-first search) anywhere in the whole
4566 * subtree of @to.
4569 ret = true;
4570 found = g_hash_table_new(NULL, NULL);
4571 g_hash_table_add(found, to);
4572 queue = g_queue_new();
4573 g_queue_push_tail(queue, to);
4575 while (!g_queue_is_empty(queue)) {
4576 BlockDriverState *v = g_queue_pop_head(queue);
4577 BdrvChild *c2;
4579 QLIST_FOREACH(c2, &v->children, next) {
4580 if (c2 == c) {
4581 ret = false;
4582 break;
4585 if (g_hash_table_contains(found, c2->bs)) {
4586 continue;
4589 g_queue_push_tail(queue, c2->bs);
4590 g_hash_table_add(found, c2->bs);
4594 g_queue_free(queue);
4595 g_hash_table_destroy(found);
4597 return ret;
4600 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4601 Error **errp)
4603 BdrvChild *c, *next;
4604 GSList *list = NULL, *p;
4605 uint64_t perm = 0, shared = BLK_PERM_ALL;
4606 int ret;
4608 /* Make sure that @from doesn't go away until we have successfully attached
4609 * all of its parents to @to. */
4610 bdrv_ref(from);
4612 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4613 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
4614 bdrv_drained_begin(from);
4616 /* Put all parents into @list and calculate their cumulative permissions */
4617 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4618 assert(c->bs == from);
4619 if (!should_update_child(c, to)) {
4620 continue;
4622 if (c->frozen) {
4623 error_setg(errp, "Cannot change '%s' link to '%s'",
4624 c->name, from->node_name);
4625 goto out;
4627 list = g_slist_prepend(list, c);
4628 perm |= c->perm;
4629 shared &= c->shared_perm;
4632 /* Check whether the required permissions can be granted on @to, ignoring
4633 * all BdrvChild in @list so that they can't block themselves. */
4634 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
4635 if (ret < 0) {
4636 bdrv_abort_perm_update(to);
4637 goto out;
4640 /* Now actually perform the change. We performed the permission check for
4641 * all elements of @list at once, so set the permissions all at once at the
4642 * very end. */
4643 for (p = list; p != NULL; p = p->next) {
4644 c = p->data;
4646 bdrv_ref(to);
4647 bdrv_replace_child_noperm(c, to);
4648 bdrv_unref(from);
4651 bdrv_get_cumulative_perm(to, &perm, &shared);
4652 bdrv_set_perm(to, perm, shared);
4654 out:
4655 g_slist_free(list);
4656 bdrv_drained_end(from);
4657 bdrv_unref(from);
4661 * Add new bs contents at the top of an image chain while the chain is
4662 * live, while keeping required fields on the top layer.
4664 * This will modify the BlockDriverState fields, and swap contents
4665 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4667 * bs_new must not be attached to a BlockBackend.
4669 * This function does not create any image files.
4671 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4672 * that's what the callers commonly need. bs_new will be referenced by the old
4673 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4674 * reference of its own, it must call bdrv_ref().
4676 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4677 Error **errp)
4679 Error *local_err = NULL;
4681 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4682 if (local_err) {
4683 error_propagate(errp, local_err);
4684 goto out;
4687 bdrv_replace_node(bs_top, bs_new, &local_err);
4688 if (local_err) {
4689 error_propagate(errp, local_err);
4690 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4691 goto out;
4694 /* bs_new is now referenced by its new parents, we don't need the
4695 * additional reference any more. */
4696 out:
4697 bdrv_unref(bs_new);
4700 static void bdrv_delete(BlockDriverState *bs)
4702 assert(bdrv_op_blocker_is_empty(bs));
4703 assert(!bs->refcnt);
4705 /* remove from list, if necessary */
4706 if (bs->node_name[0] != '\0') {
4707 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4709 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4711 bdrv_close(bs);
4713 g_free(bs);
4717 * Run consistency checks on an image
4719 * Returns 0 if the check could be completed (it doesn't mean that the image is
4720 * free of errors) or -errno when an internal error occurred. The results of the
4721 * check are stored in res.
4723 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4724 BdrvCheckResult *res, BdrvCheckMode fix)
4726 if (bs->drv == NULL) {
4727 return -ENOMEDIUM;
4729 if (bs->drv->bdrv_co_check == NULL) {
4730 return -ENOTSUP;
4733 memset(res, 0, sizeof(*res));
4734 return bs->drv->bdrv_co_check(bs, res, fix);
4737 typedef struct CheckCo {
4738 BlockDriverState *bs;
4739 BdrvCheckResult *res;
4740 BdrvCheckMode fix;
4741 int ret;
4742 } CheckCo;
4744 static void coroutine_fn bdrv_check_co_entry(void *opaque)
4746 CheckCo *cco = opaque;
4747 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4748 aio_wait_kick();
4751 int bdrv_check(BlockDriverState *bs,
4752 BdrvCheckResult *res, BdrvCheckMode fix)
4754 Coroutine *co;
4755 CheckCo cco = {
4756 .bs = bs,
4757 .res = res,
4758 .ret = -EINPROGRESS,
4759 .fix = fix,
4762 if (qemu_in_coroutine()) {
4763 /* Fast-path if already in coroutine context */
4764 bdrv_check_co_entry(&cco);
4765 } else {
4766 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4767 bdrv_coroutine_enter(bs, co);
4768 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4771 return cco.ret;
4775 * Return values:
4776 * 0 - success
4777 * -EINVAL - backing format specified, but no file
4778 * -ENOSPC - can't update the backing file because no space is left in the
4779 * image file header
4780 * -ENOTSUP - format driver doesn't support changing the backing file
4782 int bdrv_change_backing_file(BlockDriverState *bs,
4783 const char *backing_file, const char *backing_fmt)
4785 BlockDriver *drv = bs->drv;
4786 int ret;
4788 if (!drv) {
4789 return -ENOMEDIUM;
4792 /* Backing file format doesn't make sense without a backing file */
4793 if (backing_fmt && !backing_file) {
4794 return -EINVAL;
4797 if (drv->bdrv_change_backing_file != NULL) {
4798 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
4799 } else {
4800 ret = -ENOTSUP;
4803 if (ret == 0) {
4804 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4805 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
4806 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4807 backing_file ?: "");
4809 return ret;
4813 * Finds the image layer in the chain that has 'bs' as its backing file.
4815 * active is the current topmost image.
4817 * Returns NULL if bs is not found in active's image chain,
4818 * or if active == bs.
4820 * Returns the bottommost base image if bs == NULL.
4822 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4823 BlockDriverState *bs)
4825 while (active && bs != backing_bs(active)) {
4826 active = backing_bs(active);
4829 return active;
4832 /* Given a BDS, searches for the base layer. */
4833 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4835 return bdrv_find_overlay(bs, NULL);
4839 * Return true if at least one of the backing links between @bs and
4840 * @base is frozen. @errp is set if that's the case.
4841 * @base must be reachable from @bs, or NULL.
4843 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4844 Error **errp)
4846 BlockDriverState *i;
4848 for (i = bs; i != base; i = backing_bs(i)) {
4849 if (i->backing && i->backing->frozen) {
4850 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4851 i->backing->name, i->node_name,
4852 backing_bs(i)->node_name);
4853 return true;
4857 return false;
4861 * Freeze all backing links between @bs and @base.
4862 * If any of the links is already frozen the operation is aborted and
4863 * none of the links are modified.
4864 * @base must be reachable from @bs, or NULL.
4865 * Returns 0 on success. On failure returns < 0 and sets @errp.
4867 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4868 Error **errp)
4870 BlockDriverState *i;
4872 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4873 return -EPERM;
4876 for (i = bs; i != base; i = backing_bs(i)) {
4877 if (i->backing && backing_bs(i)->never_freeze) {
4878 error_setg(errp, "Cannot freeze '%s' link to '%s'",
4879 i->backing->name, backing_bs(i)->node_name);
4880 return -EPERM;
4884 for (i = bs; i != base; i = backing_bs(i)) {
4885 if (i->backing) {
4886 i->backing->frozen = true;
4890 return 0;
4894 * Unfreeze all backing links between @bs and @base. The caller must
4895 * ensure that all links are frozen before using this function.
4896 * @base must be reachable from @bs, or NULL.
4898 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4900 BlockDriverState *i;
4902 for (i = bs; i != base; i = backing_bs(i)) {
4903 if (i->backing) {
4904 assert(i->backing->frozen);
4905 i->backing->frozen = false;
4911 * Drops images above 'base' up to and including 'top', and sets the image
4912 * above 'top' to have base as its backing file.
4914 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4915 * information in 'bs' can be properly updated.
4917 * E.g., this will convert the following chain:
4918 * bottom <- base <- intermediate <- top <- active
4920 * to
4922 * bottom <- base <- active
4924 * It is allowed for bottom==base, in which case it converts:
4926 * base <- intermediate <- top <- active
4928 * to
4930 * base <- active
4932 * If backing_file_str is non-NULL, it will be used when modifying top's
4933 * overlay image metadata.
4935 * Error conditions:
4936 * if active == top, that is considered an error
4939 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4940 const char *backing_file_str)
4942 BlockDriverState *explicit_top = top;
4943 bool update_inherits_from;
4944 BdrvChild *c, *next;
4945 Error *local_err = NULL;
4946 int ret = -EIO;
4948 bdrv_ref(top);
4949 bdrv_subtree_drained_begin(top);
4951 if (!top->drv || !base->drv) {
4952 goto exit;
4955 /* Make sure that base is in the backing chain of top */
4956 if (!bdrv_chain_contains(top, base)) {
4957 goto exit;
4960 /* This function changes all links that point to top and makes
4961 * them point to base. Check that none of them is frozen. */
4962 QLIST_FOREACH(c, &top->parents, next_parent) {
4963 if (c->frozen) {
4964 goto exit;
4968 /* If 'base' recursively inherits from 'top' then we should set
4969 * base->inherits_from to top->inherits_from after 'top' and all
4970 * other intermediate nodes have been dropped.
4971 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4972 * it because no one inherits from it. We use explicit_top for that. */
4973 while (explicit_top && explicit_top->implicit) {
4974 explicit_top = backing_bs(explicit_top);
4976 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4978 /* success - we can delete the intermediate states, and link top->base */
4979 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4980 * we've figured out how they should work. */
4981 if (!backing_file_str) {
4982 bdrv_refresh_filename(base);
4983 backing_file_str = base->filename;
4986 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
4987 /* Check whether we are allowed to switch c from top to base */
4988 GSList *ignore_children = g_slist_prepend(NULL, c);
4989 ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
4990 ignore_children, NULL, &local_err);
4991 g_slist_free(ignore_children);
4992 if (ret < 0) {
4993 error_report_err(local_err);
4994 goto exit;
4997 /* If so, update the backing file path in the image file */
4998 if (c->klass->update_filename) {
4999 ret = c->klass->update_filename(c, base, backing_file_str,
5000 &local_err);
5001 if (ret < 0) {
5002 bdrv_abort_perm_update(base);
5003 error_report_err(local_err);
5004 goto exit;
5008 /* Do the actual switch in the in-memory graph.
5009 * Completes bdrv_check_update_perm() transaction internally. */
5010 bdrv_ref(base);
5011 bdrv_replace_child(c, base);
5012 bdrv_unref(top);
5015 if (update_inherits_from) {
5016 base->inherits_from = explicit_top->inherits_from;
5019 ret = 0;
5020 exit:
5021 bdrv_subtree_drained_end(top);
5022 bdrv_unref(top);
5023 return ret;
5027 * Length of a allocated file in bytes. Sparse files are counted by actual
5028 * allocated space. Return < 0 if error or unknown.
5030 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5032 BlockDriver *drv = bs->drv;
5033 if (!drv) {
5034 return -ENOMEDIUM;
5036 if (drv->bdrv_get_allocated_file_size) {
5037 return drv->bdrv_get_allocated_file_size(bs);
5039 if (bs->file) {
5040 return bdrv_get_allocated_file_size(bs->file->bs);
5042 return -ENOTSUP;
5046 * bdrv_measure:
5047 * @drv: Format driver
5048 * @opts: Creation options for new image
5049 * @in_bs: Existing image containing data for new image (may be NULL)
5050 * @errp: Error object
5051 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5052 * or NULL on error
5054 * Calculate file size required to create a new image.
5056 * If @in_bs is given then space for allocated clusters and zero clusters
5057 * from that image are included in the calculation. If @opts contains a
5058 * backing file that is shared by @in_bs then backing clusters may be omitted
5059 * from the calculation.
5061 * If @in_bs is NULL then the calculation includes no allocated clusters
5062 * unless a preallocation option is given in @opts.
5064 * Note that @in_bs may use a different BlockDriver from @drv.
5066 * If an error occurs the @errp pointer is set.
5068 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5069 BlockDriverState *in_bs, Error **errp)
5071 if (!drv->bdrv_measure) {
5072 error_setg(errp, "Block driver '%s' does not support size measurement",
5073 drv->format_name);
5074 return NULL;
5077 return drv->bdrv_measure(opts, in_bs, errp);
5081 * Return number of sectors on success, -errno on error.
5083 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5085 BlockDriver *drv = bs->drv;
5087 if (!drv)
5088 return -ENOMEDIUM;
5090 if (drv->has_variable_length) {
5091 int ret = refresh_total_sectors(bs, bs->total_sectors);
5092 if (ret < 0) {
5093 return ret;
5096 return bs->total_sectors;
5100 * Return length in bytes on success, -errno on error.
5101 * The length is always a multiple of BDRV_SECTOR_SIZE.
5103 int64_t bdrv_getlength(BlockDriverState *bs)
5105 int64_t ret = bdrv_nb_sectors(bs);
5107 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
5108 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
5111 /* return 0 as number of sectors if no device present or error */
5112 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5114 int64_t nb_sectors = bdrv_nb_sectors(bs);
5116 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5119 bool bdrv_is_sg(BlockDriverState *bs)
5121 return bs->sg;
5124 bool bdrv_is_encrypted(BlockDriverState *bs)
5126 if (bs->backing && bs->backing->bs->encrypted) {
5127 return true;
5129 return bs->encrypted;
5132 const char *bdrv_get_format_name(BlockDriverState *bs)
5134 return bs->drv ? bs->drv->format_name : NULL;
5137 static int qsort_strcmp(const void *a, const void *b)
5139 return strcmp(*(char *const *)a, *(char *const *)b);
5142 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5143 void *opaque, bool read_only)
5145 BlockDriver *drv;
5146 int count = 0;
5147 int i;
5148 const char **formats = NULL;
5150 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5151 if (drv->format_name) {
5152 bool found = false;
5153 int i = count;
5155 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5156 continue;
5159 while (formats && i && !found) {
5160 found = !strcmp(formats[--i], drv->format_name);
5163 if (!found) {
5164 formats = g_renew(const char *, formats, count + 1);
5165 formats[count++] = drv->format_name;
5170 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5171 const char *format_name = block_driver_modules[i].format_name;
5173 if (format_name) {
5174 bool found = false;
5175 int j = count;
5177 if (use_bdrv_whitelist &&
5178 !bdrv_format_is_whitelisted(format_name, read_only)) {
5179 continue;
5182 while (formats && j && !found) {
5183 found = !strcmp(formats[--j], format_name);
5186 if (!found) {
5187 formats = g_renew(const char *, formats, count + 1);
5188 formats[count++] = format_name;
5193 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5195 for (i = 0; i < count; i++) {
5196 it(opaque, formats[i]);
5199 g_free(formats);
5202 /* This function is to find a node in the bs graph */
5203 BlockDriverState *bdrv_find_node(const char *node_name)
5205 BlockDriverState *bs;
5207 assert(node_name);
5209 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5210 if (!strcmp(node_name, bs->node_name)) {
5211 return bs;
5214 return NULL;
5217 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5218 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5219 Error **errp)
5221 BlockDeviceInfoList *list, *entry;
5222 BlockDriverState *bs;
5224 list = NULL;
5225 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5226 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5227 if (!info) {
5228 qapi_free_BlockDeviceInfoList(list);
5229 return NULL;
5231 entry = g_malloc0(sizeof(*entry));
5232 entry->value = info;
5233 entry->next = list;
5234 list = entry;
5237 return list;
5240 #define QAPI_LIST_ADD(list, element) do { \
5241 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
5242 _tmp->value = (element); \
5243 _tmp->next = (list); \
5244 (list) = _tmp; \
5245 } while (0)
5247 typedef struct XDbgBlockGraphConstructor {
5248 XDbgBlockGraph *graph;
5249 GHashTable *graph_nodes;
5250 } XDbgBlockGraphConstructor;
5252 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5254 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5256 gr->graph = g_new0(XDbgBlockGraph, 1);
5257 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5259 return gr;
5262 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5264 XDbgBlockGraph *graph = gr->graph;
5266 g_hash_table_destroy(gr->graph_nodes);
5267 g_free(gr);
5269 return graph;
5272 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5274 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5276 if (ret != 0) {
5277 return ret;
5281 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5282 * answer of g_hash_table_lookup.
5284 ret = g_hash_table_size(gr->graph_nodes) + 1;
5285 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5287 return ret;
5290 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5291 XDbgBlockGraphNodeType type, const char *name)
5293 XDbgBlockGraphNode *n;
5295 n = g_new0(XDbgBlockGraphNode, 1);
5297 n->id = xdbg_graph_node_num(gr, node);
5298 n->type = type;
5299 n->name = g_strdup(name);
5301 QAPI_LIST_ADD(gr->graph->nodes, n);
5304 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5305 const BdrvChild *child)
5307 BlockPermission qapi_perm;
5308 XDbgBlockGraphEdge *edge;
5310 edge = g_new0(XDbgBlockGraphEdge, 1);
5312 edge->parent = xdbg_graph_node_num(gr, parent);
5313 edge->child = xdbg_graph_node_num(gr, child->bs);
5314 edge->name = g_strdup(child->name);
5316 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5317 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5319 if (flag & child->perm) {
5320 QAPI_LIST_ADD(edge->perm, qapi_perm);
5322 if (flag & child->shared_perm) {
5323 QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
5327 QAPI_LIST_ADD(gr->graph->edges, edge);
5331 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5333 BlockBackend *blk;
5334 BlockJob *job;
5335 BlockDriverState *bs;
5336 BdrvChild *child;
5337 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5339 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5340 char *allocated_name = NULL;
5341 const char *name = blk_name(blk);
5343 if (!*name) {
5344 name = allocated_name = blk_get_attached_dev_id(blk);
5346 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5347 name);
5348 g_free(allocated_name);
5349 if (blk_root(blk)) {
5350 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5354 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5355 GSList *el;
5357 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5358 job->job.id);
5359 for (el = job->nodes; el; el = el->next) {
5360 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5364 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5365 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5366 bs->node_name);
5367 QLIST_FOREACH(child, &bs->children, next) {
5368 xdbg_graph_add_edge(gr, bs, child);
5372 return xdbg_graph_finalize(gr);
5375 BlockDriverState *bdrv_lookup_bs(const char *device,
5376 const char *node_name,
5377 Error **errp)
5379 BlockBackend *blk;
5380 BlockDriverState *bs;
5382 if (device) {
5383 blk = blk_by_name(device);
5385 if (blk) {
5386 bs = blk_bs(blk);
5387 if (!bs) {
5388 error_setg(errp, "Device '%s' has no medium", device);
5391 return bs;
5395 if (node_name) {
5396 bs = bdrv_find_node(node_name);
5398 if (bs) {
5399 return bs;
5403 error_setg(errp, "Cannot find device=%s nor node_name=%s",
5404 device ? device : "",
5405 node_name ? node_name : "");
5406 return NULL;
5409 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5410 * return false. If either argument is NULL, return false. */
5411 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5413 while (top && top != base) {
5414 top = backing_bs(top);
5417 return top != NULL;
5420 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5422 if (!bs) {
5423 return QTAILQ_FIRST(&graph_bdrv_states);
5425 return QTAILQ_NEXT(bs, node_list);
5428 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5430 if (!bs) {
5431 return QTAILQ_FIRST(&all_bdrv_states);
5433 return QTAILQ_NEXT(bs, bs_list);
5436 const char *bdrv_get_node_name(const BlockDriverState *bs)
5438 return bs->node_name;
5441 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5443 BdrvChild *c;
5444 const char *name;
5446 /* If multiple parents have a name, just pick the first one. */
5447 QLIST_FOREACH(c, &bs->parents, next_parent) {
5448 if (c->klass->get_name) {
5449 name = c->klass->get_name(c);
5450 if (name && *name) {
5451 return name;
5456 return NULL;
5459 /* TODO check what callers really want: bs->node_name or blk_name() */
5460 const char *bdrv_get_device_name(const BlockDriverState *bs)
5462 return bdrv_get_parent_name(bs) ?: "";
5465 /* This can be used to identify nodes that might not have a device
5466 * name associated. Since node and device names live in the same
5467 * namespace, the result is unambiguous. The exception is if both are
5468 * absent, then this returns an empty (non-null) string. */
5469 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5471 return bdrv_get_parent_name(bs) ?: bs->node_name;
5474 int bdrv_get_flags(BlockDriverState *bs)
5476 return bs->open_flags;
5479 int bdrv_has_zero_init_1(BlockDriverState *bs)
5481 return 1;
5484 int bdrv_has_zero_init(BlockDriverState *bs)
5486 if (!bs->drv) {
5487 return 0;
5490 /* If BS is a copy on write image, it is initialized to
5491 the contents of the base image, which may not be zeroes. */
5492 if (bs->backing) {
5493 return 0;
5495 if (bs->drv->bdrv_has_zero_init) {
5496 return bs->drv->bdrv_has_zero_init(bs);
5498 if (bs->file && bs->drv->is_filter) {
5499 return bdrv_has_zero_init(bs->file->bs);
5502 /* safe default */
5503 return 0;
5506 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
5508 BlockDriverInfo bdi;
5510 if (bs->backing) {
5511 return false;
5514 if (bdrv_get_info(bs, &bdi) == 0) {
5515 return bdi.unallocated_blocks_are_zero;
5518 return false;
5521 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5523 if (!(bs->open_flags & BDRV_O_UNMAP)) {
5524 return false;
5527 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5530 void bdrv_get_backing_filename(BlockDriverState *bs,
5531 char *filename, int filename_size)
5533 pstrcpy(filename, filename_size, bs->backing_file);
5536 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5538 BlockDriver *drv = bs->drv;
5539 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5540 if (!drv) {
5541 return -ENOMEDIUM;
5543 if (!drv->bdrv_get_info) {
5544 if (bs->file && drv->is_filter) {
5545 return bdrv_get_info(bs->file->bs, bdi);
5547 return -ENOTSUP;
5549 memset(bdi, 0, sizeof(*bdi));
5550 return drv->bdrv_get_info(bs, bdi);
5553 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5554 Error **errp)
5556 BlockDriver *drv = bs->drv;
5557 if (drv && drv->bdrv_get_specific_info) {
5558 return drv->bdrv_get_specific_info(bs, errp);
5560 return NULL;
5563 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5565 BlockDriver *drv = bs->drv;
5566 if (!drv || !drv->bdrv_get_specific_stats) {
5567 return NULL;
5569 return drv->bdrv_get_specific_stats(bs);
5572 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5574 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5575 return;
5578 bs->drv->bdrv_debug_event(bs, event);
5581 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5583 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5584 if (bs->file) {
5585 bs = bs->file->bs;
5586 continue;
5589 if (bs->drv->is_filter && bs->backing) {
5590 bs = bs->backing->bs;
5591 continue;
5594 break;
5597 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5598 assert(bs->drv->bdrv_debug_remove_breakpoint);
5599 return bs;
5602 return NULL;
5605 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5606 const char *tag)
5608 bs = bdrv_find_debug_node(bs);
5609 if (bs) {
5610 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5613 return -ENOTSUP;
5616 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5618 bs = bdrv_find_debug_node(bs);
5619 if (bs) {
5620 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5623 return -ENOTSUP;
5626 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5628 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5629 bs = bs->file ? bs->file->bs : NULL;
5632 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5633 return bs->drv->bdrv_debug_resume(bs, tag);
5636 return -ENOTSUP;
5639 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5641 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5642 bs = bs->file ? bs->file->bs : NULL;
5645 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5646 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5649 return false;
5652 /* backing_file can either be relative, or absolute, or a protocol. If it is
5653 * relative, it must be relative to the chain. So, passing in bs->filename
5654 * from a BDS as backing_file should not be done, as that may be relative to
5655 * the CWD rather than the chain. */
5656 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5657 const char *backing_file)
5659 char *filename_full = NULL;
5660 char *backing_file_full = NULL;
5661 char *filename_tmp = NULL;
5662 int is_protocol = 0;
5663 BlockDriverState *curr_bs = NULL;
5664 BlockDriverState *retval = NULL;
5666 if (!bs || !bs->drv || !backing_file) {
5667 return NULL;
5670 filename_full = g_malloc(PATH_MAX);
5671 backing_file_full = g_malloc(PATH_MAX);
5673 is_protocol = path_has_protocol(backing_file);
5675 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
5677 /* If either of the filename paths is actually a protocol, then
5678 * compare unmodified paths; otherwise make paths relative */
5679 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5680 char *backing_file_full_ret;
5682 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
5683 retval = curr_bs->backing->bs;
5684 break;
5686 /* Also check against the full backing filename for the image */
5687 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5688 NULL);
5689 if (backing_file_full_ret) {
5690 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5691 g_free(backing_file_full_ret);
5692 if (equal) {
5693 retval = curr_bs->backing->bs;
5694 break;
5697 } else {
5698 /* If not an absolute filename path, make it relative to the current
5699 * image's filename path */
5700 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5701 NULL);
5702 /* We are going to compare canonicalized absolute pathnames */
5703 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5704 g_free(filename_tmp);
5705 continue;
5707 g_free(filename_tmp);
5709 /* We need to make sure the backing filename we are comparing against
5710 * is relative to the current image filename (or absolute) */
5711 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5712 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5713 g_free(filename_tmp);
5714 continue;
5716 g_free(filename_tmp);
5718 if (strcmp(backing_file_full, filename_full) == 0) {
5719 retval = curr_bs->backing->bs;
5720 break;
5725 g_free(filename_full);
5726 g_free(backing_file_full);
5727 return retval;
5730 void bdrv_init(void)
5732 module_call_init(MODULE_INIT_BLOCK);
5735 void bdrv_init_with_whitelist(void)
5737 use_bdrv_whitelist = 1;
5738 bdrv_init();
5741 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5742 Error **errp)
5744 BdrvChild *child, *parent;
5745 uint64_t perm, shared_perm;
5746 Error *local_err = NULL;
5747 int ret;
5748 BdrvDirtyBitmap *bm;
5750 if (!bs->drv) {
5751 return;
5754 QLIST_FOREACH(child, &bs->children, next) {
5755 bdrv_co_invalidate_cache(child->bs, &local_err);
5756 if (local_err) {
5757 error_propagate(errp, local_err);
5758 return;
5763 * Update permissions, they may differ for inactive nodes.
5765 * Note that the required permissions of inactive images are always a
5766 * subset of the permissions required after activating the image. This
5767 * allows us to just get the permissions upfront without restricting
5768 * drv->bdrv_invalidate_cache().
5770 * It also means that in error cases, we don't have to try and revert to
5771 * the old permissions (which is an operation that could fail, too). We can
5772 * just keep the extended permissions for the next time that an activation
5773 * of the image is tried.
5775 if (bs->open_flags & BDRV_O_INACTIVE) {
5776 bs->open_flags &= ~BDRV_O_INACTIVE;
5777 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5778 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, &local_err);
5779 if (ret < 0) {
5780 bs->open_flags |= BDRV_O_INACTIVE;
5781 error_propagate(errp, local_err);
5782 return;
5784 bdrv_set_perm(bs, perm, shared_perm);
5786 if (bs->drv->bdrv_co_invalidate_cache) {
5787 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5788 if (local_err) {
5789 bs->open_flags |= BDRV_O_INACTIVE;
5790 error_propagate(errp, local_err);
5791 return;
5795 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5796 bdrv_dirty_bitmap_skip_store(bm, false);
5799 ret = refresh_total_sectors(bs, bs->total_sectors);
5800 if (ret < 0) {
5801 bs->open_flags |= BDRV_O_INACTIVE;
5802 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5803 return;
5807 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5808 if (parent->klass->activate) {
5809 parent->klass->activate(parent, &local_err);
5810 if (local_err) {
5811 bs->open_flags |= BDRV_O_INACTIVE;
5812 error_propagate(errp, local_err);
5813 return;
5819 typedef struct InvalidateCacheCo {
5820 BlockDriverState *bs;
5821 Error **errp;
5822 bool done;
5823 } InvalidateCacheCo;
5825 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5827 InvalidateCacheCo *ico = opaque;
5828 bdrv_co_invalidate_cache(ico->bs, ico->errp);
5829 ico->done = true;
5830 aio_wait_kick();
5833 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5835 Coroutine *co;
5836 InvalidateCacheCo ico = {
5837 .bs = bs,
5838 .done = false,
5839 .errp = errp
5842 if (qemu_in_coroutine()) {
5843 /* Fast-path if already in coroutine context */
5844 bdrv_invalidate_cache_co_entry(&ico);
5845 } else {
5846 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
5847 bdrv_coroutine_enter(bs, co);
5848 BDRV_POLL_WHILE(bs, !ico.done);
5852 void bdrv_invalidate_cache_all(Error **errp)
5854 BlockDriverState *bs;
5855 Error *local_err = NULL;
5856 BdrvNextIterator it;
5858 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5859 AioContext *aio_context = bdrv_get_aio_context(bs);
5861 aio_context_acquire(aio_context);
5862 bdrv_invalidate_cache(bs, &local_err);
5863 aio_context_release(aio_context);
5864 if (local_err) {
5865 error_propagate(errp, local_err);
5866 bdrv_next_cleanup(&it);
5867 return;
5872 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5874 BdrvChild *parent;
5876 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5877 if (parent->klass->parent_is_bds) {
5878 BlockDriverState *parent_bs = parent->opaque;
5879 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5880 return true;
5885 return false;
5888 static int bdrv_inactivate_recurse(BlockDriverState *bs)
5890 BdrvChild *child, *parent;
5891 bool tighten_restrictions;
5892 uint64_t perm, shared_perm;
5893 int ret;
5895 if (!bs->drv) {
5896 return -ENOMEDIUM;
5899 /* Make sure that we don't inactivate a child before its parent.
5900 * It will be covered by recursion from the yet active parent. */
5901 if (bdrv_has_bds_parent(bs, true)) {
5902 return 0;
5905 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5907 /* Inactivate this node */
5908 if (bs->drv->bdrv_inactivate) {
5909 ret = bs->drv->bdrv_inactivate(bs);
5910 if (ret < 0) {
5911 return ret;
5915 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5916 if (parent->klass->inactivate) {
5917 ret = parent->klass->inactivate(parent);
5918 if (ret < 0) {
5919 return ret;
5924 bs->open_flags |= BDRV_O_INACTIVE;
5926 /* Update permissions, they may differ for inactive nodes */
5927 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5928 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5929 &tighten_restrictions, NULL);
5930 assert(tighten_restrictions == false);
5931 if (ret < 0) {
5932 /* We only tried to loosen restrictions, so errors are not fatal */
5933 bdrv_abort_perm_update(bs);
5934 } else {
5935 bdrv_set_perm(bs, perm, shared_perm);
5939 /* Recursively inactivate children */
5940 QLIST_FOREACH(child, &bs->children, next) {
5941 ret = bdrv_inactivate_recurse(child->bs);
5942 if (ret < 0) {
5943 return ret;
5947 return 0;
5950 int bdrv_inactivate_all(void)
5952 BlockDriverState *bs = NULL;
5953 BdrvNextIterator it;
5954 int ret = 0;
5955 GSList *aio_ctxs = NULL, *ctx;
5957 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5958 AioContext *aio_context = bdrv_get_aio_context(bs);
5960 if (!g_slist_find(aio_ctxs, aio_context)) {
5961 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5962 aio_context_acquire(aio_context);
5966 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5967 /* Nodes with BDS parents are covered by recursion from the last
5968 * parent that gets inactivated. Don't inactivate them a second
5969 * time if that has already happened. */
5970 if (bdrv_has_bds_parent(bs, false)) {
5971 continue;
5973 ret = bdrv_inactivate_recurse(bs);
5974 if (ret < 0) {
5975 bdrv_next_cleanup(&it);
5976 goto out;
5980 out:
5981 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5982 AioContext *aio_context = ctx->data;
5983 aio_context_release(aio_context);
5985 g_slist_free(aio_ctxs);
5987 return ret;
5990 /**************************************************************/
5991 /* removable device support */
5994 * Return TRUE if the media is present
5996 bool bdrv_is_inserted(BlockDriverState *bs)
5998 BlockDriver *drv = bs->drv;
5999 BdrvChild *child;
6001 if (!drv) {
6002 return false;
6004 if (drv->bdrv_is_inserted) {
6005 return drv->bdrv_is_inserted(bs);
6007 QLIST_FOREACH(child, &bs->children, next) {
6008 if (!bdrv_is_inserted(child->bs)) {
6009 return false;
6012 return true;
6016 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6018 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6020 BlockDriver *drv = bs->drv;
6022 if (drv && drv->bdrv_eject) {
6023 drv->bdrv_eject(bs, eject_flag);
6028 * Lock or unlock the media (if it is locked, the user won't be able
6029 * to eject it manually).
6031 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6033 BlockDriver *drv = bs->drv;
6035 trace_bdrv_lock_medium(bs, locked);
6037 if (drv && drv->bdrv_lock_medium) {
6038 drv->bdrv_lock_medium(bs, locked);
6042 /* Get a reference to bs */
6043 void bdrv_ref(BlockDriverState *bs)
6045 bs->refcnt++;
6048 /* Release a previously grabbed reference to bs.
6049 * If after releasing, reference count is zero, the BlockDriverState is
6050 * deleted. */
6051 void bdrv_unref(BlockDriverState *bs)
6053 if (!bs) {
6054 return;
6056 assert(bs->refcnt > 0);
6057 if (--bs->refcnt == 0) {
6058 bdrv_delete(bs);
6062 struct BdrvOpBlocker {
6063 Error *reason;
6064 QLIST_ENTRY(BdrvOpBlocker) list;
6067 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6069 BdrvOpBlocker *blocker;
6070 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6071 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6072 blocker = QLIST_FIRST(&bs->op_blockers[op]);
6073 error_propagate_prepend(errp, error_copy(blocker->reason),
6074 "Node '%s' is busy: ",
6075 bdrv_get_device_or_node_name(bs));
6076 return true;
6078 return false;
6081 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6083 BdrvOpBlocker *blocker;
6084 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6086 blocker = g_new0(BdrvOpBlocker, 1);
6087 blocker->reason = reason;
6088 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6091 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6093 BdrvOpBlocker *blocker, *next;
6094 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6095 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6096 if (blocker->reason == reason) {
6097 QLIST_REMOVE(blocker, list);
6098 g_free(blocker);
6103 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6105 int i;
6106 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6107 bdrv_op_block(bs, i, reason);
6111 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6113 int i;
6114 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6115 bdrv_op_unblock(bs, i, reason);
6119 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6121 int i;
6123 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6124 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6125 return false;
6128 return true;
6131 void bdrv_img_create(const char *filename, const char *fmt,
6132 const char *base_filename, const char *base_fmt,
6133 char *options, uint64_t img_size, int flags, bool quiet,
6134 Error **errp)
6136 QemuOptsList *create_opts = NULL;
6137 QemuOpts *opts = NULL;
6138 const char *backing_fmt, *backing_file;
6139 int64_t size;
6140 BlockDriver *drv, *proto_drv;
6141 Error *local_err = NULL;
6142 int ret = 0;
6144 /* Find driver and parse its options */
6145 drv = bdrv_find_format(fmt);
6146 if (!drv) {
6147 error_setg(errp, "Unknown file format '%s'", fmt);
6148 return;
6151 proto_drv = bdrv_find_protocol(filename, true, errp);
6152 if (!proto_drv) {
6153 return;
6156 if (!drv->create_opts) {
6157 error_setg(errp, "Format driver '%s' does not support image creation",
6158 drv->format_name);
6159 return;
6162 if (!proto_drv->create_opts) {
6163 error_setg(errp, "Protocol driver '%s' does not support image creation",
6164 proto_drv->format_name);
6165 return;
6168 /* Create parameter list */
6169 create_opts = qemu_opts_append(create_opts, drv->create_opts);
6170 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6172 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6174 /* Parse -o options */
6175 if (options) {
6176 qemu_opts_do_parse(opts, options, NULL, &local_err);
6177 if (local_err) {
6178 goto out;
6182 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6183 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6184 } else if (img_size != UINT64_C(-1)) {
6185 error_setg(errp, "The image size must be specified only once");
6186 goto out;
6189 if (base_filename) {
6190 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
6191 if (local_err) {
6192 error_setg(errp, "Backing file not supported for file format '%s'",
6193 fmt);
6194 goto out;
6198 if (base_fmt) {
6199 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
6200 if (local_err) {
6201 error_setg(errp, "Backing file format not supported for file "
6202 "format '%s'", fmt);
6203 goto out;
6207 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6208 if (backing_file) {
6209 if (!strcmp(filename, backing_file)) {
6210 error_setg(errp, "Error: Trying to create an image with the "
6211 "same filename as the backing file");
6212 goto out;
6216 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6218 /* The size for the image must always be specified, unless we have a backing
6219 * file and we have not been forbidden from opening it. */
6220 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6221 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6222 BlockDriverState *bs;
6223 char *full_backing;
6224 int back_flags;
6225 QDict *backing_options = NULL;
6227 full_backing =
6228 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6229 &local_err);
6230 if (local_err) {
6231 goto out;
6233 assert(full_backing);
6235 /* backing files always opened read-only */
6236 back_flags = flags;
6237 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6239 backing_options = qdict_new();
6240 if (backing_fmt) {
6241 qdict_put_str(backing_options, "driver", backing_fmt);
6243 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
6245 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6246 &local_err);
6247 g_free(full_backing);
6248 if (!bs && size != -1) {
6249 /* Couldn't open BS, but we have a size, so it's nonfatal */
6250 warn_reportf_err(local_err,
6251 "Could not verify backing image. "
6252 "This may become an error in future versions.\n");
6253 local_err = NULL;
6254 } else if (!bs) {
6255 /* Couldn't open bs, do not have size */
6256 error_append_hint(&local_err,
6257 "Could not open backing image to determine size.\n");
6258 goto out;
6259 } else {
6260 if (size == -1) {
6261 /* Opened BS, have no size */
6262 size = bdrv_getlength(bs);
6263 if (size < 0) {
6264 error_setg_errno(errp, -size, "Could not get size of '%s'",
6265 backing_file);
6266 bdrv_unref(bs);
6267 goto out;
6269 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6271 bdrv_unref(bs);
6273 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6275 if (size == -1) {
6276 error_setg(errp, "Image creation needs a size parameter");
6277 goto out;
6280 if (!quiet) {
6281 printf("Formatting '%s', fmt=%s ", filename, fmt);
6282 qemu_opts_print(opts, " ");
6283 puts("");
6286 ret = bdrv_create(drv, filename, opts, &local_err);
6288 if (ret == -EFBIG) {
6289 /* This is generally a better message than whatever the driver would
6290 * deliver (especially because of the cluster_size_hint), since that
6291 * is most probably not much different from "image too large". */
6292 const char *cluster_size_hint = "";
6293 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
6294 cluster_size_hint = " (try using a larger cluster size)";
6296 error_setg(errp, "The image size is too large for file format '%s'"
6297 "%s", fmt, cluster_size_hint);
6298 error_free(local_err);
6299 local_err = NULL;
6302 out:
6303 qemu_opts_del(opts);
6304 qemu_opts_free(create_opts);
6305 error_propagate(errp, local_err);
6308 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6310 return bs ? bs->aio_context : qemu_get_aio_context();
6313 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6315 aio_co_enter(bdrv_get_aio_context(bs), co);
6318 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6320 QLIST_REMOVE(ban, list);
6321 g_free(ban);
6324 static void bdrv_detach_aio_context(BlockDriverState *bs)
6326 BdrvAioNotifier *baf, *baf_tmp;
6328 assert(!bs->walking_aio_notifiers);
6329 bs->walking_aio_notifiers = true;
6330 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6331 if (baf->deleted) {
6332 bdrv_do_remove_aio_context_notifier(baf);
6333 } else {
6334 baf->detach_aio_context(baf->opaque);
6337 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6338 * remove remaining aio notifiers if we aren't called again.
6340 bs->walking_aio_notifiers = false;
6342 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
6343 bs->drv->bdrv_detach_aio_context(bs);
6346 if (bs->quiesce_counter) {
6347 aio_enable_external(bs->aio_context);
6349 bs->aio_context = NULL;
6352 static void bdrv_attach_aio_context(BlockDriverState *bs,
6353 AioContext *new_context)
6355 BdrvAioNotifier *ban, *ban_tmp;
6357 if (bs->quiesce_counter) {
6358 aio_disable_external(new_context);
6361 bs->aio_context = new_context;
6363 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
6364 bs->drv->bdrv_attach_aio_context(bs, new_context);
6367 assert(!bs->walking_aio_notifiers);
6368 bs->walking_aio_notifiers = true;
6369 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6370 if (ban->deleted) {
6371 bdrv_do_remove_aio_context_notifier(ban);
6372 } else {
6373 ban->attached_aio_context(new_context, ban->opaque);
6376 bs->walking_aio_notifiers = false;
6380 * Changes the AioContext used for fd handlers, timers, and BHs by this
6381 * BlockDriverState and all its children and parents.
6383 * Must be called from the main AioContext.
6385 * The caller must own the AioContext lock for the old AioContext of bs, but it
6386 * must not own the AioContext lock for new_context (unless new_context is the
6387 * same as the current context of bs).
6389 * @ignore will accumulate all visited BdrvChild object. The caller is
6390 * responsible for freeing the list afterwards.
6392 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6393 AioContext *new_context, GSList **ignore)
6395 AioContext *old_context = bdrv_get_aio_context(bs);
6396 BdrvChild *child;
6398 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6400 if (old_context == new_context) {
6401 return;
6404 bdrv_drained_begin(bs);
6406 QLIST_FOREACH(child, &bs->children, next) {
6407 if (g_slist_find(*ignore, child)) {
6408 continue;
6410 *ignore = g_slist_prepend(*ignore, child);
6411 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6413 QLIST_FOREACH(child, &bs->parents, next_parent) {
6414 if (g_slist_find(*ignore, child)) {
6415 continue;
6417 assert(child->klass->set_aio_ctx);
6418 *ignore = g_slist_prepend(*ignore, child);
6419 child->klass->set_aio_ctx(child, new_context, ignore);
6422 bdrv_detach_aio_context(bs);
6424 /* Acquire the new context, if necessary */
6425 if (qemu_get_aio_context() != new_context) {
6426 aio_context_acquire(new_context);
6429 bdrv_attach_aio_context(bs, new_context);
6432 * If this function was recursively called from
6433 * bdrv_set_aio_context_ignore(), there may be nodes in the
6434 * subtree that have not yet been moved to the new AioContext.
6435 * Release the old one so bdrv_drained_end() can poll them.
6437 if (qemu_get_aio_context() != old_context) {
6438 aio_context_release(old_context);
6441 bdrv_drained_end(bs);
6443 if (qemu_get_aio_context() != old_context) {
6444 aio_context_acquire(old_context);
6446 if (qemu_get_aio_context() != new_context) {
6447 aio_context_release(new_context);
6451 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6452 GSList **ignore, Error **errp)
6454 if (g_slist_find(*ignore, c)) {
6455 return true;
6457 *ignore = g_slist_prepend(*ignore, c);
6460 * A BdrvChildClass that doesn't handle AioContext changes cannot
6461 * tolerate any AioContext changes
6463 if (!c->klass->can_set_aio_ctx) {
6464 char *user = bdrv_child_user_desc(c);
6465 error_setg(errp, "Changing iothreads is not supported by %s", user);
6466 g_free(user);
6467 return false;
6469 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
6470 assert(!errp || *errp);
6471 return false;
6473 return true;
6476 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6477 GSList **ignore, Error **errp)
6479 if (g_slist_find(*ignore, c)) {
6480 return true;
6482 *ignore = g_slist_prepend(*ignore, c);
6483 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6486 /* @ignore will accumulate all visited BdrvChild object. The caller is
6487 * responsible for freeing the list afterwards. */
6488 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6489 GSList **ignore, Error **errp)
6491 BdrvChild *c;
6493 if (bdrv_get_aio_context(bs) == ctx) {
6494 return true;
6497 QLIST_FOREACH(c, &bs->parents, next_parent) {
6498 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6499 return false;
6502 QLIST_FOREACH(c, &bs->children, next) {
6503 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6504 return false;
6508 return true;
6511 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6512 BdrvChild *ignore_child, Error **errp)
6514 GSList *ignore;
6515 bool ret;
6517 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6518 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6519 g_slist_free(ignore);
6521 if (!ret) {
6522 return -EPERM;
6525 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6526 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6527 g_slist_free(ignore);
6529 return 0;
6532 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6533 Error **errp)
6535 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6538 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6539 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6540 void (*detach_aio_context)(void *opaque), void *opaque)
6542 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6543 *ban = (BdrvAioNotifier){
6544 .attached_aio_context = attached_aio_context,
6545 .detach_aio_context = detach_aio_context,
6546 .opaque = opaque
6549 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6552 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6553 void (*attached_aio_context)(AioContext *,
6554 void *),
6555 void (*detach_aio_context)(void *),
6556 void *opaque)
6558 BdrvAioNotifier *ban, *ban_next;
6560 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6561 if (ban->attached_aio_context == attached_aio_context &&
6562 ban->detach_aio_context == detach_aio_context &&
6563 ban->opaque == opaque &&
6564 ban->deleted == false)
6566 if (bs->walking_aio_notifiers) {
6567 ban->deleted = true;
6568 } else {
6569 bdrv_do_remove_aio_context_notifier(ban);
6571 return;
6575 abort();
6578 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6579 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6580 Error **errp)
6582 if (!bs->drv) {
6583 error_setg(errp, "Node is ejected");
6584 return -ENOMEDIUM;
6586 if (!bs->drv->bdrv_amend_options) {
6587 error_setg(errp, "Block driver '%s' does not support option amendment",
6588 bs->drv->format_name);
6589 return -ENOTSUP;
6591 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6595 * This function checks whether the given @to_replace is allowed to be
6596 * replaced by a node that always shows the same data as @bs. This is
6597 * used for example to verify whether the mirror job can replace
6598 * @to_replace by the target mirrored from @bs.
6599 * To be replaceable, @bs and @to_replace may either be guaranteed to
6600 * always show the same data (because they are only connected through
6601 * filters), or some driver may allow replacing one of its children
6602 * because it can guarantee that this child's data is not visible at
6603 * all (for example, for dissenting quorum children that have no other
6604 * parents).
6606 bool bdrv_recurse_can_replace(BlockDriverState *bs,
6607 BlockDriverState *to_replace)
6609 if (!bs || !bs->drv) {
6610 return false;
6613 if (bs == to_replace) {
6614 return true;
6617 /* See what the driver can do */
6618 if (bs->drv->bdrv_recurse_can_replace) {
6619 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6622 /* For filters without an own implementation, we can recurse on our own */
6623 if (bs->drv->is_filter) {
6624 BdrvChild *child = bs->file ?: bs->backing;
6625 return bdrv_recurse_can_replace(child->bs, to_replace);
6628 /* Safe default */
6629 return false;
6633 * Check whether the given @node_name can be replaced by a node that
6634 * has the same data as @parent_bs. If so, return @node_name's BDS;
6635 * NULL otherwise.
6637 * @node_name must be a (recursive) *child of @parent_bs (or this
6638 * function will return NULL).
6640 * The result (whether the node can be replaced or not) is only valid
6641 * for as long as no graph or permission changes occur.
6643 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6644 const char *node_name, Error **errp)
6646 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
6647 AioContext *aio_context;
6649 if (!to_replace_bs) {
6650 error_setg(errp, "Node name '%s' not found", node_name);
6651 return NULL;
6654 aio_context = bdrv_get_aio_context(to_replace_bs);
6655 aio_context_acquire(aio_context);
6657 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
6658 to_replace_bs = NULL;
6659 goto out;
6662 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6663 * most non filter in order to prevent data corruption.
6664 * Another benefit is that this tests exclude backing files which are
6665 * blocked by the backing blockers.
6667 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6668 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6669 "because it cannot be guaranteed that doing so would not "
6670 "lead to an abrupt change of visible data",
6671 node_name, parent_bs->node_name);
6672 to_replace_bs = NULL;
6673 goto out;
6676 out:
6677 aio_context_release(aio_context);
6678 return to_replace_bs;
6682 * Iterates through the list of runtime option keys that are said to
6683 * be "strong" for a BDS. An option is called "strong" if it changes
6684 * a BDS's data. For example, the null block driver's "size" and
6685 * "read-zeroes" options are strong, but its "latency-ns" option is
6686 * not.
6688 * If a key returned by this function ends with a dot, all options
6689 * starting with that prefix are strong.
6691 static const char *const *strong_options(BlockDriverState *bs,
6692 const char *const *curopt)
6694 static const char *const global_options[] = {
6695 "driver", "filename", NULL
6698 if (!curopt) {
6699 return &global_options[0];
6702 curopt++;
6703 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6704 curopt = bs->drv->strong_runtime_opts;
6707 return (curopt && *curopt) ? curopt : NULL;
6711 * Copies all strong runtime options from bs->options to the given
6712 * QDict. The set of strong option keys is determined by invoking
6713 * strong_options().
6715 * Returns true iff any strong option was present in bs->options (and
6716 * thus copied to the target QDict) with the exception of "filename"
6717 * and "driver". The caller is expected to use this value to decide
6718 * whether the existence of strong options prevents the generation of
6719 * a plain filename.
6721 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6723 bool found_any = false;
6724 const char *const *option_name = NULL;
6726 if (!bs->drv) {
6727 return false;
6730 while ((option_name = strong_options(bs, option_name))) {
6731 bool option_given = false;
6733 assert(strlen(*option_name) > 0);
6734 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6735 QObject *entry = qdict_get(bs->options, *option_name);
6736 if (!entry) {
6737 continue;
6740 qdict_put_obj(d, *option_name, qobject_ref(entry));
6741 option_given = true;
6742 } else {
6743 const QDictEntry *entry;
6744 for (entry = qdict_first(bs->options); entry;
6745 entry = qdict_next(bs->options, entry))
6747 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6748 qdict_put_obj(d, qdict_entry_key(entry),
6749 qobject_ref(qdict_entry_value(entry)));
6750 option_given = true;
6755 /* While "driver" and "filename" need to be included in a JSON filename,
6756 * their existence does not prohibit generation of a plain filename. */
6757 if (!found_any && option_given &&
6758 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6760 found_any = true;
6764 if (!qdict_haskey(d, "driver")) {
6765 /* Drivers created with bdrv_new_open_driver() may not have a
6766 * @driver option. Add it here. */
6767 qdict_put_str(d, "driver", bs->drv->format_name);
6770 return found_any;
6773 /* Note: This function may return false positives; it may return true
6774 * even if opening the backing file specified by bs's image header
6775 * would result in exactly bs->backing. */
6776 static bool bdrv_backing_overridden(BlockDriverState *bs)
6778 if (bs->backing) {
6779 return strcmp(bs->auto_backing_file,
6780 bs->backing->bs->filename);
6781 } else {
6782 /* No backing BDS, so if the image header reports any backing
6783 * file, it must have been suppressed */
6784 return bs->auto_backing_file[0] != '\0';
6788 /* Updates the following BDS fields:
6789 * - exact_filename: A filename which may be used for opening a block device
6790 * which (mostly) equals the given BDS (even without any
6791 * other options; so reading and writing must return the same
6792 * results, but caching etc. may be different)
6793 * - full_open_options: Options which, when given when opening a block device
6794 * (without a filename), result in a BDS (mostly)
6795 * equalling the given one
6796 * - filename: If exact_filename is set, it is copied here. Otherwise,
6797 * full_open_options is converted to a JSON object, prefixed with
6798 * "json:" (for use through the JSON pseudo protocol) and put here.
6800 void bdrv_refresh_filename(BlockDriverState *bs)
6802 BlockDriver *drv = bs->drv;
6803 BdrvChild *child;
6804 QDict *opts;
6805 bool backing_overridden;
6806 bool generate_json_filename; /* Whether our default implementation should
6807 fill exact_filename (false) or not (true) */
6809 if (!drv) {
6810 return;
6813 /* This BDS's file name may depend on any of its children's file names, so
6814 * refresh those first */
6815 QLIST_FOREACH(child, &bs->children, next) {
6816 bdrv_refresh_filename(child->bs);
6819 if (bs->implicit) {
6820 /* For implicit nodes, just copy everything from the single child */
6821 child = QLIST_FIRST(&bs->children);
6822 assert(QLIST_NEXT(child, next) == NULL);
6824 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6825 child->bs->exact_filename);
6826 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6828 qobject_unref(bs->full_open_options);
6829 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6831 return;
6834 backing_overridden = bdrv_backing_overridden(bs);
6836 if (bs->open_flags & BDRV_O_NO_IO) {
6837 /* Without I/O, the backing file does not change anything.
6838 * Therefore, in such a case (primarily qemu-img), we can
6839 * pretend the backing file has not been overridden even if
6840 * it technically has been. */
6841 backing_overridden = false;
6844 /* Gather the options QDict */
6845 opts = qdict_new();
6846 generate_json_filename = append_strong_runtime_options(opts, bs);
6847 generate_json_filename |= backing_overridden;
6849 if (drv->bdrv_gather_child_options) {
6850 /* Some block drivers may not want to present all of their children's
6851 * options, or name them differently from BdrvChild.name */
6852 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6853 } else {
6854 QLIST_FOREACH(child, &bs->children, next) {
6855 if (child->klass == &child_backing && !backing_overridden) {
6856 /* We can skip the backing BDS if it has not been overridden */
6857 continue;
6860 qdict_put(opts, child->name,
6861 qobject_ref(child->bs->full_open_options));
6864 if (backing_overridden && !bs->backing) {
6865 /* Force no backing file */
6866 qdict_put_null(opts, "backing");
6870 qobject_unref(bs->full_open_options);
6871 bs->full_open_options = opts;
6873 if (drv->bdrv_refresh_filename) {
6874 /* Obsolete information is of no use here, so drop the old file name
6875 * information before refreshing it */
6876 bs->exact_filename[0] = '\0';
6878 drv->bdrv_refresh_filename(bs);
6879 } else if (bs->file) {
6880 /* Try to reconstruct valid information from the underlying file */
6882 bs->exact_filename[0] = '\0';
6885 * We can use the underlying file's filename if:
6886 * - it has a filename,
6887 * - the file is a protocol BDS, and
6888 * - opening that file (as this BDS's format) will automatically create
6889 * the BDS tree we have right now, that is:
6890 * - the user did not significantly change this BDS's behavior with
6891 * some explicit (strong) options
6892 * - no non-file child of this BDS has been overridden by the user
6893 * Both of these conditions are represented by generate_json_filename.
6895 if (bs->file->bs->exact_filename[0] &&
6896 bs->file->bs->drv->bdrv_file_open &&
6897 !generate_json_filename)
6899 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6903 if (bs->exact_filename[0]) {
6904 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
6905 } else {
6906 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6907 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6908 qstring_get_str(json));
6909 qobject_unref(json);
6913 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6915 BlockDriver *drv = bs->drv;
6917 if (!drv) {
6918 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6919 return NULL;
6922 if (drv->bdrv_dirname) {
6923 return drv->bdrv_dirname(bs, errp);
6926 if (bs->file) {
6927 return bdrv_dirname(bs->file->bs, errp);
6930 bdrv_refresh_filename(bs);
6931 if (bs->exact_filename[0] != '\0') {
6932 return path_combine(bs->exact_filename, "");
6935 error_setg(errp, "Cannot generate a base directory for %s nodes",
6936 drv->format_name);
6937 return NULL;
6941 * Hot add/remove a BDS's child. So the user can take a child offline when
6942 * it is broken and take a new child online
6944 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6945 Error **errp)
6948 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6949 error_setg(errp, "The node %s does not support adding a child",
6950 bdrv_get_device_or_node_name(parent_bs));
6951 return;
6954 if (!QLIST_EMPTY(&child_bs->parents)) {
6955 error_setg(errp, "The node %s already has a parent",
6956 child_bs->node_name);
6957 return;
6960 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6963 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6965 BdrvChild *tmp;
6967 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6968 error_setg(errp, "The node %s does not support removing a child",
6969 bdrv_get_device_or_node_name(parent_bs));
6970 return;
6973 QLIST_FOREACH(tmp, &parent_bs->children, next) {
6974 if (tmp == child) {
6975 break;
6979 if (!tmp) {
6980 error_setg(errp, "The node %s does not have a child named %s",
6981 bdrv_get_device_or_node_name(parent_bs),
6982 bdrv_get_device_or_node_name(child->bs));
6983 return;
6986 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
6989 int bdrv_make_empty(BdrvChild *c, Error **errp)
6991 BlockDriver *drv = c->bs->drv;
6992 int ret;
6994 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
6996 if (!drv->bdrv_make_empty) {
6997 error_setg(errp, "%s does not support emptying nodes",
6998 drv->format_name);
6999 return -ENOTSUP;
7002 ret = drv->bdrv_make_empty(c->bs);
7003 if (ret < 0) {
7004 error_setg_errno(errp, -ret, "Failed to empty %s",
7005 c->bs->filename);
7006 return ret;
7009 return 0;