block: Make backing files child_of_bds children
[qemu/ar7.git] / block.c
blob131ae20ffca4bac84b48b8cd21b9a5e6d01ea2cd
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 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2946 * mostly used for COW backing children (role = COW), but also for
2947 * filtered children (role = FILTERED | PRIMARY).
2949 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
2951 if (bs->drv && bs->drv->is_filter) {
2952 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
2953 } else {
2954 return BDRV_CHILD_COW;
2959 * Sets the backing file link of a BDS. A new reference is created; callers
2960 * which don't need their own reference any more must call bdrv_unref().
2962 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2963 Error **errp)
2965 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2966 bdrv_inherits_from_recursive(backing_hd, bs);
2968 if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2969 return;
2972 if (backing_hd) {
2973 bdrv_ref(backing_hd);
2976 if (bs->backing) {
2977 bdrv_unref_child(bs, bs->backing);
2978 bs->backing = NULL;
2981 if (!backing_hd) {
2982 goto out;
2985 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
2986 bdrv_backing_role(bs), errp);
2987 /* If backing_hd was already part of bs's backing chain, and
2988 * inherits_from pointed recursively to bs then let's update it to
2989 * point directly to bs (else it will become NULL). */
2990 if (bs->backing && update_inherits_from) {
2991 backing_hd->inherits_from = bs;
2994 out:
2995 bdrv_refresh_limits(bs, NULL);
2999 * Opens the backing file for a BlockDriverState if not yet open
3001 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3002 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3003 * itself, all options starting with "${bdref_key}." are considered part of the
3004 * BlockdevRef.
3006 * TODO Can this be unified with bdrv_open_image()?
3008 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3009 const char *bdref_key, Error **errp)
3011 char *backing_filename = NULL;
3012 char *bdref_key_dot;
3013 const char *reference = NULL;
3014 int ret = 0;
3015 bool implicit_backing = false;
3016 BlockDriverState *backing_hd;
3017 QDict *options;
3018 QDict *tmp_parent_options = NULL;
3019 Error *local_err = NULL;
3021 if (bs->backing != NULL) {
3022 goto free_exit;
3025 /* NULL means an empty set of options */
3026 if (parent_options == NULL) {
3027 tmp_parent_options = qdict_new();
3028 parent_options = tmp_parent_options;
3031 bs->open_flags &= ~BDRV_O_NO_BACKING;
3033 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3034 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3035 g_free(bdref_key_dot);
3038 * Caution: while qdict_get_try_str() is fine, getting non-string
3039 * types would require more care. When @parent_options come from
3040 * -blockdev or blockdev_add, its members are typed according to
3041 * the QAPI schema, but when they come from -drive, they're all
3042 * QString.
3044 reference = qdict_get_try_str(parent_options, bdref_key);
3045 if (reference || qdict_haskey(options, "file.filename")) {
3046 /* keep backing_filename NULL */
3047 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3048 qobject_unref(options);
3049 goto free_exit;
3050 } else {
3051 if (qdict_size(options) == 0) {
3052 /* If the user specifies options that do not modify the
3053 * backing file's behavior, we might still consider it the
3054 * implicit backing file. But it's easier this way, and
3055 * just specifying some of the backing BDS's options is
3056 * only possible with -drive anyway (otherwise the QAPI
3057 * schema forces the user to specify everything). */
3058 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3061 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3062 if (local_err) {
3063 ret = -EINVAL;
3064 error_propagate(errp, local_err);
3065 qobject_unref(options);
3066 goto free_exit;
3070 if (!bs->drv || !bs->drv->supports_backing) {
3071 ret = -EINVAL;
3072 error_setg(errp, "Driver doesn't support backing files");
3073 qobject_unref(options);
3074 goto free_exit;
3077 if (!reference &&
3078 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3079 qdict_put_str(options, "driver", bs->backing_format);
3082 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3083 &child_of_bds, bdrv_backing_role(bs), errp);
3084 if (!backing_hd) {
3085 bs->open_flags |= BDRV_O_NO_BACKING;
3086 error_prepend(errp, "Could not open backing file: ");
3087 ret = -EINVAL;
3088 goto free_exit;
3091 if (implicit_backing) {
3092 bdrv_refresh_filename(backing_hd);
3093 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3094 backing_hd->filename);
3097 /* Hook up the backing file link; drop our reference, bs owns the
3098 * backing_hd reference now */
3099 bdrv_set_backing_hd(bs, backing_hd, &local_err);
3100 bdrv_unref(backing_hd);
3101 if (local_err) {
3102 error_propagate(errp, local_err);
3103 ret = -EINVAL;
3104 goto free_exit;
3107 qdict_del(parent_options, bdref_key);
3109 free_exit:
3110 g_free(backing_filename);
3111 qobject_unref(tmp_parent_options);
3112 return ret;
3115 static BlockDriverState *
3116 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3117 BlockDriverState *parent, const BdrvChildClass *child_class,
3118 BdrvChildRole child_role, bool allow_none, Error **errp)
3120 BlockDriverState *bs = NULL;
3121 QDict *image_options;
3122 char *bdref_key_dot;
3123 const char *reference;
3125 assert(child_class != NULL);
3127 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3128 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3129 g_free(bdref_key_dot);
3132 * Caution: while qdict_get_try_str() is fine, getting non-string
3133 * types would require more care. When @options come from
3134 * -blockdev or blockdev_add, its members are typed according to
3135 * the QAPI schema, but when they come from -drive, they're all
3136 * QString.
3138 reference = qdict_get_try_str(options, bdref_key);
3139 if (!filename && !reference && !qdict_size(image_options)) {
3140 if (!allow_none) {
3141 error_setg(errp, "A block device must be specified for \"%s\"",
3142 bdref_key);
3144 qobject_unref(image_options);
3145 goto done;
3148 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3149 parent, child_class, child_role, errp);
3150 if (!bs) {
3151 goto done;
3154 done:
3155 qdict_del(options, bdref_key);
3156 return bs;
3160 * Opens a disk image whose options are given as BlockdevRef in another block
3161 * device's options.
3163 * If allow_none is true, no image will be opened if filename is false and no
3164 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3166 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3167 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3168 * itself, all options starting with "${bdref_key}." are considered part of the
3169 * BlockdevRef.
3171 * The BlockdevRef will be removed from the options QDict.
3173 BdrvChild *bdrv_open_child(const char *filename,
3174 QDict *options, const char *bdref_key,
3175 BlockDriverState *parent,
3176 const BdrvChildClass *child_class,
3177 BdrvChildRole child_role,
3178 bool allow_none, Error **errp)
3180 BlockDriverState *bs;
3182 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3183 child_role, allow_none, errp);
3184 if (bs == NULL) {
3185 return NULL;
3188 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3189 errp);
3193 * TODO Future callers may need to specify parent/child_class in order for
3194 * option inheritance to work. Existing callers use it for the root node.
3196 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3198 BlockDriverState *bs = NULL;
3199 QObject *obj = NULL;
3200 QDict *qdict = NULL;
3201 const char *reference = NULL;
3202 Visitor *v = NULL;
3204 if (ref->type == QTYPE_QSTRING) {
3205 reference = ref->u.reference;
3206 } else {
3207 BlockdevOptions *options = &ref->u.definition;
3208 assert(ref->type == QTYPE_QDICT);
3210 v = qobject_output_visitor_new(&obj);
3211 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3212 visit_complete(v, &obj);
3214 qdict = qobject_to(QDict, obj);
3215 qdict_flatten(qdict);
3217 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3218 * compatibility with other callers) rather than what we want as the
3219 * real defaults. Apply the defaults here instead. */
3220 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3221 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3222 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3223 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3227 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3228 obj = NULL;
3229 qobject_unref(obj);
3230 visit_free(v);
3231 return bs;
3234 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3235 int flags,
3236 QDict *snapshot_options,
3237 Error **errp)
3239 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3240 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3241 int64_t total_size;
3242 QemuOpts *opts = NULL;
3243 BlockDriverState *bs_snapshot = NULL;
3244 Error *local_err = NULL;
3245 int ret;
3247 /* if snapshot, we create a temporary backing file and open it
3248 instead of opening 'filename' directly */
3250 /* Get the required size from the image */
3251 total_size = bdrv_getlength(bs);
3252 if (total_size < 0) {
3253 error_setg_errno(errp, -total_size, "Could not get image size");
3254 goto out;
3257 /* Create the temporary image */
3258 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3259 if (ret < 0) {
3260 error_setg_errno(errp, -ret, "Could not get temporary filename");
3261 goto out;
3264 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3265 &error_abort);
3266 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3267 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3268 qemu_opts_del(opts);
3269 if (ret < 0) {
3270 error_prepend(errp, "Could not create temporary overlay '%s': ",
3271 tmp_filename);
3272 goto out;
3275 /* Prepare options QDict for the temporary file */
3276 qdict_put_str(snapshot_options, "file.driver", "file");
3277 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3278 qdict_put_str(snapshot_options, "driver", "qcow2");
3280 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3281 snapshot_options = NULL;
3282 if (!bs_snapshot) {
3283 goto out;
3286 /* bdrv_append() consumes a strong reference to bs_snapshot
3287 * (i.e. it will call bdrv_unref() on it) even on error, so in
3288 * order to be able to return one, we have to increase
3289 * bs_snapshot's refcount here */
3290 bdrv_ref(bs_snapshot);
3291 bdrv_append(bs_snapshot, bs, &local_err);
3292 if (local_err) {
3293 error_propagate(errp, local_err);
3294 bs_snapshot = NULL;
3295 goto out;
3298 out:
3299 qobject_unref(snapshot_options);
3300 g_free(tmp_filename);
3301 return bs_snapshot;
3305 * Opens a disk image (raw, qcow2, vmdk, ...)
3307 * options is a QDict of options to pass to the block drivers, or NULL for an
3308 * empty set of options. The reference to the QDict belongs to the block layer
3309 * after the call (even on failure), so if the caller intends to reuse the
3310 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3312 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3313 * If it is not NULL, the referenced BDS will be reused.
3315 * The reference parameter may be used to specify an existing block device which
3316 * should be opened. If specified, neither options nor a filename may be given,
3317 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3319 static BlockDriverState *bdrv_open_inherit(const char *filename,
3320 const char *reference,
3321 QDict *options, int flags,
3322 BlockDriverState *parent,
3323 const BdrvChildClass *child_class,
3324 BdrvChildRole child_role,
3325 Error **errp)
3327 int ret;
3328 BlockBackend *file = NULL;
3329 BlockDriverState *bs;
3330 BlockDriver *drv = NULL;
3331 BdrvChild *child;
3332 const char *drvname;
3333 const char *backing;
3334 Error *local_err = NULL;
3335 QDict *snapshot_options = NULL;
3336 int snapshot_flags = 0;
3338 assert(!child_class || !flags);
3339 assert(!child_class == !parent);
3341 if (reference) {
3342 bool options_non_empty = options ? qdict_size(options) : false;
3343 qobject_unref(options);
3345 if (filename || options_non_empty) {
3346 error_setg(errp, "Cannot reference an existing block device with "
3347 "additional options or a new filename");
3348 return NULL;
3351 bs = bdrv_lookup_bs(reference, reference, errp);
3352 if (!bs) {
3353 return NULL;
3356 bdrv_ref(bs);
3357 return bs;
3360 bs = bdrv_new();
3362 /* NULL means an empty set of options */
3363 if (options == NULL) {
3364 options = qdict_new();
3367 /* json: syntax counts as explicit options, as if in the QDict */
3368 parse_json_protocol(options, &filename, &local_err);
3369 if (local_err) {
3370 goto fail;
3373 bs->explicit_options = qdict_clone_shallow(options);
3375 if (child_class) {
3376 bool parent_is_format;
3378 if (parent->drv) {
3379 parent_is_format = parent->drv->is_format;
3380 } else {
3382 * parent->drv is not set yet because this node is opened for
3383 * (potential) format probing. That means that @parent is going
3384 * to be a format node.
3386 parent_is_format = true;
3389 bs->inherits_from = parent;
3390 child_class->inherit_options(child_role, parent_is_format,
3391 &flags, options,
3392 parent->open_flags, parent->options);
3395 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3396 if (ret < 0) {
3397 goto fail;
3401 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3402 * Caution: getting a boolean member of @options requires care.
3403 * When @options come from -blockdev or blockdev_add, members are
3404 * typed according to the QAPI schema, but when they come from
3405 * -drive, they're all QString.
3407 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3408 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3409 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3410 } else {
3411 flags &= ~BDRV_O_RDWR;
3414 if (flags & BDRV_O_SNAPSHOT) {
3415 snapshot_options = qdict_new();
3416 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3417 flags, options);
3418 /* Let bdrv_backing_options() override "read-only" */
3419 qdict_del(options, BDRV_OPT_READ_ONLY);
3420 bdrv_inherited_options(BDRV_CHILD_COW, true,
3421 &flags, options, flags, options);
3424 bs->open_flags = flags;
3425 bs->options = options;
3426 options = qdict_clone_shallow(options);
3428 /* Find the right image format driver */
3429 /* See cautionary note on accessing @options above */
3430 drvname = qdict_get_try_str(options, "driver");
3431 if (drvname) {
3432 drv = bdrv_find_format(drvname);
3433 if (!drv) {
3434 error_setg(errp, "Unknown driver: '%s'", drvname);
3435 goto fail;
3439 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3441 /* See cautionary note on accessing @options above */
3442 backing = qdict_get_try_str(options, "backing");
3443 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3444 (backing && *backing == '\0'))
3446 if (backing) {
3447 warn_report("Use of \"backing\": \"\" is deprecated; "
3448 "use \"backing\": null instead");
3450 flags |= BDRV_O_NO_BACKING;
3451 qdict_del(bs->explicit_options, "backing");
3452 qdict_del(bs->options, "backing");
3453 qdict_del(options, "backing");
3456 /* Open image file without format layer. This BlockBackend is only used for
3457 * probing, the block drivers will do their own bdrv_open_child() for the
3458 * same BDS, which is why we put the node name back into options. */
3459 if ((flags & BDRV_O_PROTOCOL) == 0) {
3460 BlockDriverState *file_bs;
3462 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3463 &child_file, 0, true, &local_err);
3464 if (local_err) {
3465 goto fail;
3467 if (file_bs != NULL) {
3468 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3469 * looking at the header to guess the image format. This works even
3470 * in cases where a guest would not see a consistent state. */
3471 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3472 blk_insert_bs(file, file_bs, &local_err);
3473 bdrv_unref(file_bs);
3474 if (local_err) {
3475 goto fail;
3478 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3482 /* Image format probing */
3483 bs->probed = !drv;
3484 if (!drv && file) {
3485 ret = find_image_format(file, filename, &drv, &local_err);
3486 if (ret < 0) {
3487 goto fail;
3490 * This option update would logically belong in bdrv_fill_options(),
3491 * but we first need to open bs->file for the probing to work, while
3492 * opening bs->file already requires the (mostly) final set of options
3493 * so that cache mode etc. can be inherited.
3495 * Adding the driver later is somewhat ugly, but it's not an option
3496 * that would ever be inherited, so it's correct. We just need to make
3497 * sure to update both bs->options (which has the full effective
3498 * options for bs) and options (which has file.* already removed).
3500 qdict_put_str(bs->options, "driver", drv->format_name);
3501 qdict_put_str(options, "driver", drv->format_name);
3502 } else if (!drv) {
3503 error_setg(errp, "Must specify either driver or file");
3504 goto fail;
3507 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3508 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3509 /* file must be NULL if a protocol BDS is about to be created
3510 * (the inverse results in an error message from bdrv_open_common()) */
3511 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3513 /* Open the image */
3514 ret = bdrv_open_common(bs, file, options, &local_err);
3515 if (ret < 0) {
3516 goto fail;
3519 if (file) {
3520 blk_unref(file);
3521 file = NULL;
3524 /* If there is a backing file, use it */
3525 if ((flags & BDRV_O_NO_BACKING) == 0) {
3526 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3527 if (ret < 0) {
3528 goto close_and_fail;
3532 /* Remove all children options and references
3533 * from bs->options and bs->explicit_options */
3534 QLIST_FOREACH(child, &bs->children, next) {
3535 char *child_key_dot;
3536 child_key_dot = g_strdup_printf("%s.", child->name);
3537 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3538 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3539 qdict_del(bs->explicit_options, child->name);
3540 qdict_del(bs->options, child->name);
3541 g_free(child_key_dot);
3544 /* Check if any unknown options were used */
3545 if (qdict_size(options) != 0) {
3546 const QDictEntry *entry = qdict_first(options);
3547 if (flags & BDRV_O_PROTOCOL) {
3548 error_setg(errp, "Block protocol '%s' doesn't support the option "
3549 "'%s'", drv->format_name, entry->key);
3550 } else {
3551 error_setg(errp,
3552 "Block format '%s' does not support the option '%s'",
3553 drv->format_name, entry->key);
3556 goto close_and_fail;
3559 bdrv_parent_cb_change_media(bs, true);
3561 qobject_unref(options);
3562 options = NULL;
3564 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3565 * temporary snapshot afterwards. */
3566 if (snapshot_flags) {
3567 BlockDriverState *snapshot_bs;
3568 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3569 snapshot_options, &local_err);
3570 snapshot_options = NULL;
3571 if (local_err) {
3572 goto close_and_fail;
3574 /* We are not going to return bs but the overlay on top of it
3575 * (snapshot_bs); thus, we have to drop the strong reference to bs
3576 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3577 * though, because the overlay still has a reference to it. */
3578 bdrv_unref(bs);
3579 bs = snapshot_bs;
3582 return bs;
3584 fail:
3585 blk_unref(file);
3586 qobject_unref(snapshot_options);
3587 qobject_unref(bs->explicit_options);
3588 qobject_unref(bs->options);
3589 qobject_unref(options);
3590 bs->options = NULL;
3591 bs->explicit_options = NULL;
3592 bdrv_unref(bs);
3593 error_propagate(errp, local_err);
3594 return NULL;
3596 close_and_fail:
3597 bdrv_unref(bs);
3598 qobject_unref(snapshot_options);
3599 qobject_unref(options);
3600 error_propagate(errp, local_err);
3601 return NULL;
3604 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3605 QDict *options, int flags, Error **errp)
3607 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3608 NULL, 0, errp);
3611 /* Return true if the NULL-terminated @list contains @str */
3612 static bool is_str_in_list(const char *str, const char *const *list)
3614 if (str && list) {
3615 int i;
3616 for (i = 0; list[i] != NULL; i++) {
3617 if (!strcmp(str, list[i])) {
3618 return true;
3622 return false;
3626 * Check that every option set in @bs->options is also set in
3627 * @new_opts.
3629 * Options listed in the common_options list and in
3630 * @bs->drv->mutable_opts are skipped.
3632 * Return 0 on success, otherwise return -EINVAL and set @errp.
3634 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3635 const QDict *new_opts, Error **errp)
3637 const QDictEntry *e;
3638 /* These options are common to all block drivers and are handled
3639 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3640 const char *const common_options[] = {
3641 "node-name", "discard", "cache.direct", "cache.no-flush",
3642 "read-only", "auto-read-only", "detect-zeroes", NULL
3645 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3646 if (!qdict_haskey(new_opts, e->key) &&
3647 !is_str_in_list(e->key, common_options) &&
3648 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3649 error_setg(errp, "Option '%s' cannot be reset "
3650 "to its default value", e->key);
3651 return -EINVAL;
3655 return 0;
3659 * Returns true if @child can be reached recursively from @bs
3661 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3662 BlockDriverState *child)
3664 BdrvChild *c;
3666 if (bs == child) {
3667 return true;
3670 QLIST_FOREACH(c, &bs->children, next) {
3671 if (bdrv_recurse_has_child(c->bs, child)) {
3672 return true;
3676 return false;
3680 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3681 * reopen of multiple devices.
3683 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3684 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3685 * be created and initialized. This newly created BlockReopenQueue should be
3686 * passed back in for subsequent calls that are intended to be of the same
3687 * atomic 'set'.
3689 * bs is the BlockDriverState to add to the reopen queue.
3691 * options contains the changed options for the associated bs
3692 * (the BlockReopenQueue takes ownership)
3694 * flags contains the open flags for the associated bs
3696 * returns a pointer to bs_queue, which is either the newly allocated
3697 * bs_queue, or the existing bs_queue being used.
3699 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3701 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3702 BlockDriverState *bs,
3703 QDict *options,
3704 const BdrvChildClass *klass,
3705 BdrvChildRole role,
3706 bool parent_is_format,
3707 QDict *parent_options,
3708 int parent_flags,
3709 bool keep_old_opts)
3711 assert(bs != NULL);
3713 BlockReopenQueueEntry *bs_entry;
3714 BdrvChild *child;
3715 QDict *old_options, *explicit_options, *options_copy;
3716 int flags;
3717 QemuOpts *opts;
3719 /* Make sure that the caller remembered to use a drained section. This is
3720 * important to avoid graph changes between the recursive queuing here and
3721 * bdrv_reopen_multiple(). */
3722 assert(bs->quiesce_counter > 0);
3724 if (bs_queue == NULL) {
3725 bs_queue = g_new0(BlockReopenQueue, 1);
3726 QTAILQ_INIT(bs_queue);
3729 if (!options) {
3730 options = qdict_new();
3733 /* Check if this BlockDriverState is already in the queue */
3734 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3735 if (bs == bs_entry->state.bs) {
3736 break;
3741 * Precedence of options:
3742 * 1. Explicitly passed in options (highest)
3743 * 2. Retained from explicitly set options of bs
3744 * 3. Inherited from parent node
3745 * 4. Retained from effective options of bs
3748 /* Old explicitly set values (don't overwrite by inherited value) */
3749 if (bs_entry || keep_old_opts) {
3750 old_options = qdict_clone_shallow(bs_entry ?
3751 bs_entry->state.explicit_options :
3752 bs->explicit_options);
3753 bdrv_join_options(bs, options, old_options);
3754 qobject_unref(old_options);
3757 explicit_options = qdict_clone_shallow(options);
3759 /* Inherit from parent node */
3760 if (parent_options) {
3761 flags = 0;
3762 klass->inherit_options(role, parent_is_format, &flags, options,
3763 parent_flags, parent_options);
3764 } else {
3765 flags = bdrv_get_flags(bs);
3768 if (keep_old_opts) {
3769 /* Old values are used for options that aren't set yet */
3770 old_options = qdict_clone_shallow(bs->options);
3771 bdrv_join_options(bs, options, old_options);
3772 qobject_unref(old_options);
3775 /* We have the final set of options so let's update the flags */
3776 options_copy = qdict_clone_shallow(options);
3777 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3778 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3779 update_flags_from_options(&flags, opts);
3780 qemu_opts_del(opts);
3781 qobject_unref(options_copy);
3783 /* bdrv_open_inherit() sets and clears some additional flags internally */
3784 flags &= ~BDRV_O_PROTOCOL;
3785 if (flags & BDRV_O_RDWR) {
3786 flags |= BDRV_O_ALLOW_RDWR;
3789 if (!bs_entry) {
3790 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3791 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3792 } else {
3793 qobject_unref(bs_entry->state.options);
3794 qobject_unref(bs_entry->state.explicit_options);
3797 bs_entry->state.bs = bs;
3798 bs_entry->state.options = options;
3799 bs_entry->state.explicit_options = explicit_options;
3800 bs_entry->state.flags = flags;
3802 /* This needs to be overwritten in bdrv_reopen_prepare() */
3803 bs_entry->state.perm = UINT64_MAX;
3804 bs_entry->state.shared_perm = 0;
3807 * If keep_old_opts is false then it means that unspecified
3808 * options must be reset to their original value. We don't allow
3809 * resetting 'backing' but we need to know if the option is
3810 * missing in order to decide if we have to return an error.
3812 if (!keep_old_opts) {
3813 bs_entry->state.backing_missing =
3814 !qdict_haskey(options, "backing") &&
3815 !qdict_haskey(options, "backing.driver");
3818 QLIST_FOREACH(child, &bs->children, next) {
3819 QDict *new_child_options = NULL;
3820 bool child_keep_old = keep_old_opts;
3822 /* reopen can only change the options of block devices that were
3823 * implicitly created and inherited options. For other (referenced)
3824 * block devices, a syntax like "backing.foo" results in an error. */
3825 if (child->bs->inherits_from != bs) {
3826 continue;
3829 /* Check if the options contain a child reference */
3830 if (qdict_haskey(options, child->name)) {
3831 const char *childref = qdict_get_try_str(options, child->name);
3833 * The current child must not be reopened if the child
3834 * reference is null or points to a different node.
3836 if (g_strcmp0(childref, child->bs->node_name)) {
3837 continue;
3840 * If the child reference points to the current child then
3841 * reopen it with its existing set of options (note that
3842 * it can still inherit new options from the parent).
3844 child_keep_old = true;
3845 } else {
3846 /* Extract child options ("child-name.*") */
3847 char *child_key_dot = g_strdup_printf("%s.", child->name);
3848 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3849 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3850 g_free(child_key_dot);
3853 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3854 child->klass, child->role, bs->drv->is_format,
3855 options, flags, child_keep_old);
3858 return bs_queue;
3861 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3862 BlockDriverState *bs,
3863 QDict *options, bool keep_old_opts)
3865 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3866 NULL, 0, keep_old_opts);
3870 * Reopen multiple BlockDriverStates atomically & transactionally.
3872 * The queue passed in (bs_queue) must have been built up previous
3873 * via bdrv_reopen_queue().
3875 * Reopens all BDS specified in the queue, with the appropriate
3876 * flags. All devices are prepared for reopen, and failure of any
3877 * device will cause all device changes to be abandoned, and intermediate
3878 * data cleaned up.
3880 * If all devices prepare successfully, then the changes are committed
3881 * to all devices.
3883 * All affected nodes must be drained between bdrv_reopen_queue() and
3884 * bdrv_reopen_multiple().
3886 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3888 int ret = -1;
3889 BlockReopenQueueEntry *bs_entry, *next;
3891 assert(bs_queue != NULL);
3893 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3894 assert(bs_entry->state.bs->quiesce_counter > 0);
3895 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3896 goto cleanup;
3898 bs_entry->prepared = true;
3901 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3902 BDRVReopenState *state = &bs_entry->state;
3903 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3904 state->shared_perm, NULL, NULL, errp);
3905 if (ret < 0) {
3906 goto cleanup_perm;
3908 /* Check if new_backing_bs would accept the new permissions */
3909 if (state->replace_backing_bs && state->new_backing_bs) {
3910 uint64_t nperm, nshared;
3911 bdrv_child_perm(state->bs, state->new_backing_bs,
3912 NULL, &child_of_bds, bdrv_backing_role(state->bs),
3913 bs_queue, state->perm, state->shared_perm,
3914 &nperm, &nshared);
3915 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3916 nperm, nshared, NULL, NULL, errp);
3917 if (ret < 0) {
3918 goto cleanup_perm;
3921 bs_entry->perms_checked = true;
3925 * If we reach this point, we have success and just need to apply the
3926 * changes.
3928 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3929 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3930 * children are usually goes after parents in reopen-queue, so go from last
3931 * to first element.
3933 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3934 bdrv_reopen_commit(&bs_entry->state);
3937 ret = 0;
3938 cleanup_perm:
3939 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3940 BDRVReopenState *state = &bs_entry->state;
3942 if (!bs_entry->perms_checked) {
3943 continue;
3946 if (ret == 0) {
3947 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3948 } else {
3949 bdrv_abort_perm_update(state->bs);
3950 if (state->replace_backing_bs && state->new_backing_bs) {
3951 bdrv_abort_perm_update(state->new_backing_bs);
3956 if (ret == 0) {
3957 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3958 BlockDriverState *bs = bs_entry->state.bs;
3960 if (bs->drv->bdrv_reopen_commit_post)
3961 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3964 cleanup:
3965 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3966 if (ret) {
3967 if (bs_entry->prepared) {
3968 bdrv_reopen_abort(&bs_entry->state);
3970 qobject_unref(bs_entry->state.explicit_options);
3971 qobject_unref(bs_entry->state.options);
3973 if (bs_entry->state.new_backing_bs) {
3974 bdrv_unref(bs_entry->state.new_backing_bs);
3976 g_free(bs_entry);
3978 g_free(bs_queue);
3980 return ret;
3983 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3984 Error **errp)
3986 int ret;
3987 BlockReopenQueue *queue;
3988 QDict *opts = qdict_new();
3990 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3992 bdrv_subtree_drained_begin(bs);
3993 queue = bdrv_reopen_queue(NULL, bs, opts, true);
3994 ret = bdrv_reopen_multiple(queue, errp);
3995 bdrv_subtree_drained_end(bs);
3997 return ret;
4000 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
4001 BdrvChild *c)
4003 BlockReopenQueueEntry *entry;
4005 QTAILQ_FOREACH(entry, q, entry) {
4006 BlockDriverState *bs = entry->state.bs;
4007 BdrvChild *child;
4009 QLIST_FOREACH(child, &bs->children, next) {
4010 if (child == c) {
4011 return entry;
4016 return NULL;
4019 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
4020 uint64_t *perm, uint64_t *shared)
4022 BdrvChild *c;
4023 BlockReopenQueueEntry *parent;
4024 uint64_t cumulative_perms = 0;
4025 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
4027 QLIST_FOREACH(c, &bs->parents, next_parent) {
4028 parent = find_parent_in_reopen_queue(q, c);
4029 if (!parent) {
4030 cumulative_perms |= c->perm;
4031 cumulative_shared_perms &= c->shared_perm;
4032 } else {
4033 uint64_t nperm, nshared;
4035 bdrv_child_perm(parent->state.bs, bs, c, c->klass, c->role, q,
4036 parent->state.perm, parent->state.shared_perm,
4037 &nperm, &nshared);
4039 cumulative_perms |= nperm;
4040 cumulative_shared_perms &= nshared;
4043 *perm = cumulative_perms;
4044 *shared = cumulative_shared_perms;
4047 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
4048 BdrvChild *child,
4049 BlockDriverState *new_child,
4050 Error **errp)
4052 AioContext *parent_ctx = bdrv_get_aio_context(parent);
4053 AioContext *child_ctx = bdrv_get_aio_context(new_child);
4054 GSList *ignore;
4055 bool ret;
4057 ignore = g_slist_prepend(NULL, child);
4058 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
4059 g_slist_free(ignore);
4060 if (ret) {
4061 return ret;
4064 ignore = g_slist_prepend(NULL, child);
4065 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4066 g_slist_free(ignore);
4067 return ret;
4071 * Take a BDRVReopenState and check if the value of 'backing' in the
4072 * reopen_state->options QDict is valid or not.
4074 * If 'backing' is missing from the QDict then return 0.
4076 * If 'backing' contains the node name of the backing file of
4077 * reopen_state->bs then return 0.
4079 * If 'backing' contains a different node name (or is null) then check
4080 * whether the current backing file can be replaced with the new one.
4081 * If that's the case then reopen_state->replace_backing_bs is set to
4082 * true and reopen_state->new_backing_bs contains a pointer to the new
4083 * backing BlockDriverState (or NULL).
4085 * Return 0 on success, otherwise return < 0 and set @errp.
4087 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4088 Error **errp)
4090 BlockDriverState *bs = reopen_state->bs;
4091 BlockDriverState *overlay_bs, *new_backing_bs;
4092 QObject *value;
4093 const char *str;
4095 value = qdict_get(reopen_state->options, "backing");
4096 if (value == NULL) {
4097 return 0;
4100 switch (qobject_type(value)) {
4101 case QTYPE_QNULL:
4102 new_backing_bs = NULL;
4103 break;
4104 case QTYPE_QSTRING:
4105 str = qobject_get_try_str(value);
4106 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4107 if (new_backing_bs == NULL) {
4108 return -EINVAL;
4109 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4110 error_setg(errp, "Making '%s' a backing file of '%s' "
4111 "would create a cycle", str, bs->node_name);
4112 return -EINVAL;
4114 break;
4115 default:
4116 /* 'backing' does not allow any other data type */
4117 g_assert_not_reached();
4121 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4122 * bdrv_reopen_commit() won't fail.
4124 if (new_backing_bs) {
4125 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4126 return -EINVAL;
4131 * Find the "actual" backing file by skipping all links that point
4132 * to an implicit node, if any (e.g. a commit filter node).
4134 overlay_bs = bs;
4135 while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
4136 overlay_bs = backing_bs(overlay_bs);
4139 /* If we want to replace the backing file we need some extra checks */
4140 if (new_backing_bs != backing_bs(overlay_bs)) {
4141 /* Check for implicit nodes between bs and its backing file */
4142 if (bs != overlay_bs) {
4143 error_setg(errp, "Cannot change backing link if '%s' has "
4144 "an implicit backing file", bs->node_name);
4145 return -EPERM;
4147 /* Check if the backing link that we want to replace is frozen */
4148 if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
4149 errp)) {
4150 return -EPERM;
4152 reopen_state->replace_backing_bs = true;
4153 if (new_backing_bs) {
4154 bdrv_ref(new_backing_bs);
4155 reopen_state->new_backing_bs = new_backing_bs;
4159 return 0;
4163 * Prepares a BlockDriverState for reopen. All changes are staged in the
4164 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4165 * the block driver layer .bdrv_reopen_prepare()
4167 * bs is the BlockDriverState to reopen
4168 * flags are the new open flags
4169 * queue is the reopen queue
4171 * Returns 0 on success, non-zero on error. On error errp will be set
4172 * as well.
4174 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4175 * It is the responsibility of the caller to then call the abort() or
4176 * commit() for any other BDS that have been left in a prepare() state
4179 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4180 Error **errp)
4182 int ret = -1;
4183 int old_flags;
4184 Error *local_err = NULL;
4185 BlockDriver *drv;
4186 QemuOpts *opts;
4187 QDict *orig_reopen_opts;
4188 char *discard = NULL;
4189 bool read_only;
4190 bool drv_prepared = false;
4192 assert(reopen_state != NULL);
4193 assert(reopen_state->bs->drv != NULL);
4194 drv = reopen_state->bs->drv;
4196 /* This function and each driver's bdrv_reopen_prepare() remove
4197 * entries from reopen_state->options as they are processed, so
4198 * we need to make a copy of the original QDict. */
4199 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4201 /* Process generic block layer options */
4202 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4203 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
4204 if (local_err) {
4205 error_propagate(errp, local_err);
4206 ret = -EINVAL;
4207 goto error;
4210 /* This was already called in bdrv_reopen_queue_child() so the flags
4211 * are up-to-date. This time we simply want to remove the options from
4212 * QemuOpts in order to indicate that they have been processed. */
4213 old_flags = reopen_state->flags;
4214 update_flags_from_options(&reopen_state->flags, opts);
4215 assert(old_flags == reopen_state->flags);
4217 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4218 if (discard != NULL) {
4219 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4220 error_setg(errp, "Invalid discard option");
4221 ret = -EINVAL;
4222 goto error;
4226 reopen_state->detect_zeroes =
4227 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4228 if (local_err) {
4229 error_propagate(errp, local_err);
4230 ret = -EINVAL;
4231 goto error;
4234 /* All other options (including node-name and driver) must be unchanged.
4235 * Put them back into the QDict, so that they are checked at the end
4236 * of this function. */
4237 qemu_opts_to_qdict(opts, reopen_state->options);
4239 /* If we are to stay read-only, do not allow permission change
4240 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4241 * not set, or if the BDS still has copy_on_read enabled */
4242 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4243 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4244 if (local_err) {
4245 error_propagate(errp, local_err);
4246 goto error;
4249 /* Calculate required permissions after reopening */
4250 bdrv_reopen_perm(queue, reopen_state->bs,
4251 &reopen_state->perm, &reopen_state->shared_perm);
4253 ret = bdrv_flush(reopen_state->bs);
4254 if (ret) {
4255 error_setg_errno(errp, -ret, "Error flushing drive");
4256 goto error;
4259 if (drv->bdrv_reopen_prepare) {
4261 * If a driver-specific option is missing, it means that we
4262 * should reset it to its default value.
4263 * But not all options allow that, so we need to check it first.
4265 ret = bdrv_reset_options_allowed(reopen_state->bs,
4266 reopen_state->options, errp);
4267 if (ret) {
4268 goto error;
4271 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4272 if (ret) {
4273 if (local_err != NULL) {
4274 error_propagate(errp, local_err);
4275 } else {
4276 bdrv_refresh_filename(reopen_state->bs);
4277 error_setg(errp, "failed while preparing to reopen image '%s'",
4278 reopen_state->bs->filename);
4280 goto error;
4282 } else {
4283 /* It is currently mandatory to have a bdrv_reopen_prepare()
4284 * handler for each supported drv. */
4285 error_setg(errp, "Block format '%s' used by node '%s' "
4286 "does not support reopening files", drv->format_name,
4287 bdrv_get_device_or_node_name(reopen_state->bs));
4288 ret = -1;
4289 goto error;
4292 drv_prepared = true;
4295 * We must provide the 'backing' option if the BDS has a backing
4296 * file or if the image file has a backing file name as part of
4297 * its metadata. Otherwise the 'backing' option can be omitted.
4299 if (drv->supports_backing && reopen_state->backing_missing &&
4300 (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
4301 error_setg(errp, "backing is missing for '%s'",
4302 reopen_state->bs->node_name);
4303 ret = -EINVAL;
4304 goto error;
4308 * Allow changing the 'backing' option. The new value can be
4309 * either a reference to an existing node (using its node name)
4310 * or NULL to simply detach the current backing file.
4312 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4313 if (ret < 0) {
4314 goto error;
4316 qdict_del(reopen_state->options, "backing");
4318 /* Options that are not handled are only okay if they are unchanged
4319 * compared to the old state. It is expected that some options are only
4320 * used for the initial open, but not reopen (e.g. filename) */
4321 if (qdict_size(reopen_state->options)) {
4322 const QDictEntry *entry = qdict_first(reopen_state->options);
4324 do {
4325 QObject *new = entry->value;
4326 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4328 /* Allow child references (child_name=node_name) as long as they
4329 * point to the current child (i.e. everything stays the same). */
4330 if (qobject_type(new) == QTYPE_QSTRING) {
4331 BdrvChild *child;
4332 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4333 if (!strcmp(child->name, entry->key)) {
4334 break;
4338 if (child) {
4339 const char *str = qobject_get_try_str(new);
4340 if (!strcmp(child->bs->node_name, str)) {
4341 continue; /* Found child with this name, skip option */
4347 * TODO: When using -drive to specify blockdev options, all values
4348 * will be strings; however, when using -blockdev, blockdev-add or
4349 * filenames using the json:{} pseudo-protocol, they will be
4350 * correctly typed.
4351 * In contrast, reopening options are (currently) always strings
4352 * (because you can only specify them through qemu-io; all other
4353 * callers do not specify any options).
4354 * Therefore, when using anything other than -drive to create a BDS,
4355 * this cannot detect non-string options as unchanged, because
4356 * qobject_is_equal() always returns false for objects of different
4357 * type. In the future, this should be remedied by correctly typing
4358 * all options. For now, this is not too big of an issue because
4359 * the user can simply omit options which cannot be changed anyway,
4360 * so they will stay unchanged.
4362 if (!qobject_is_equal(new, old)) {
4363 error_setg(errp, "Cannot change the option '%s'", entry->key);
4364 ret = -EINVAL;
4365 goto error;
4367 } while ((entry = qdict_next(reopen_state->options, entry)));
4370 ret = 0;
4372 /* Restore the original reopen_state->options QDict */
4373 qobject_unref(reopen_state->options);
4374 reopen_state->options = qobject_ref(orig_reopen_opts);
4376 error:
4377 if (ret < 0 && drv_prepared) {
4378 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4379 * call drv->bdrv_reopen_abort() before signaling an error
4380 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4381 * when the respective bdrv_reopen_prepare() has failed) */
4382 if (drv->bdrv_reopen_abort) {
4383 drv->bdrv_reopen_abort(reopen_state);
4386 qemu_opts_del(opts);
4387 qobject_unref(orig_reopen_opts);
4388 g_free(discard);
4389 return ret;
4393 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4394 * makes them final by swapping the staging BlockDriverState contents into
4395 * the active BlockDriverState contents.
4397 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4399 BlockDriver *drv;
4400 BlockDriverState *bs;
4401 BdrvChild *child;
4403 assert(reopen_state != NULL);
4404 bs = reopen_state->bs;
4405 drv = bs->drv;
4406 assert(drv != NULL);
4408 /* If there are any driver level actions to take */
4409 if (drv->bdrv_reopen_commit) {
4410 drv->bdrv_reopen_commit(reopen_state);
4413 /* set BDS specific flags now */
4414 qobject_unref(bs->explicit_options);
4415 qobject_unref(bs->options);
4417 bs->explicit_options = reopen_state->explicit_options;
4418 bs->options = reopen_state->options;
4419 bs->open_flags = reopen_state->flags;
4420 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
4421 bs->detect_zeroes = reopen_state->detect_zeroes;
4423 if (reopen_state->replace_backing_bs) {
4424 qdict_del(bs->explicit_options, "backing");
4425 qdict_del(bs->options, "backing");
4428 /* Remove child references from bs->options and bs->explicit_options.
4429 * Child options were already removed in bdrv_reopen_queue_child() */
4430 QLIST_FOREACH(child, &bs->children, next) {
4431 qdict_del(bs->explicit_options, child->name);
4432 qdict_del(bs->options, child->name);
4436 * Change the backing file if a new one was specified. We do this
4437 * after updating bs->options, so bdrv_refresh_filename() (called
4438 * from bdrv_set_backing_hd()) has the new values.
4440 if (reopen_state->replace_backing_bs) {
4441 BlockDriverState *old_backing_bs = backing_bs(bs);
4442 assert(!old_backing_bs || !old_backing_bs->implicit);
4443 /* Abort the permission update on the backing bs we're detaching */
4444 if (old_backing_bs) {
4445 bdrv_abort_perm_update(old_backing_bs);
4447 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4450 bdrv_refresh_limits(bs, NULL);
4454 * Abort the reopen, and delete and free the staged changes in
4455 * reopen_state
4457 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4459 BlockDriver *drv;
4461 assert(reopen_state != NULL);
4462 drv = reopen_state->bs->drv;
4463 assert(drv != NULL);
4465 if (drv->bdrv_reopen_abort) {
4466 drv->bdrv_reopen_abort(reopen_state);
4471 static void bdrv_close(BlockDriverState *bs)
4473 BdrvAioNotifier *ban, *ban_next;
4474 BdrvChild *child, *next;
4476 assert(!bs->refcnt);
4478 bdrv_drained_begin(bs); /* complete I/O */
4479 bdrv_flush(bs);
4480 bdrv_drain(bs); /* in case flush left pending I/O */
4482 if (bs->drv) {
4483 if (bs->drv->bdrv_close) {
4484 bs->drv->bdrv_close(bs);
4486 bs->drv = NULL;
4489 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4490 bdrv_unref_child(bs, child);
4493 bs->backing = NULL;
4494 bs->file = NULL;
4495 g_free(bs->opaque);
4496 bs->opaque = NULL;
4497 atomic_set(&bs->copy_on_read, 0);
4498 bs->backing_file[0] = '\0';
4499 bs->backing_format[0] = '\0';
4500 bs->total_sectors = 0;
4501 bs->encrypted = false;
4502 bs->sg = false;
4503 qobject_unref(bs->options);
4504 qobject_unref(bs->explicit_options);
4505 bs->options = NULL;
4506 bs->explicit_options = NULL;
4507 qobject_unref(bs->full_open_options);
4508 bs->full_open_options = NULL;
4510 bdrv_release_named_dirty_bitmaps(bs);
4511 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4513 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4514 g_free(ban);
4516 QLIST_INIT(&bs->aio_notifiers);
4517 bdrv_drained_end(bs);
4520 void bdrv_close_all(void)
4522 assert(job_next(NULL) == NULL);
4523 nbd_export_close_all();
4525 /* Drop references from requests still in flight, such as canceled block
4526 * jobs whose AIO context has not been polled yet */
4527 bdrv_drain_all();
4529 blk_remove_all_bs();
4530 blockdev_close_all_bdrv_states();
4532 assert(QTAILQ_EMPTY(&all_bdrv_states));
4535 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4537 GQueue *queue;
4538 GHashTable *found;
4539 bool ret;
4541 if (c->klass->stay_at_node) {
4542 return false;
4545 /* If the child @c belongs to the BDS @to, replacing the current
4546 * c->bs by @to would mean to create a loop.
4548 * Such a case occurs when appending a BDS to a backing chain.
4549 * For instance, imagine the following chain:
4551 * guest device -> node A -> further backing chain...
4553 * Now we create a new BDS B which we want to put on top of this
4554 * chain, so we first attach A as its backing node:
4556 * node B
4559 * guest device -> node A -> further backing chain...
4561 * Finally we want to replace A by B. When doing that, we want to
4562 * replace all pointers to A by pointers to B -- except for the
4563 * pointer from B because (1) that would create a loop, and (2)
4564 * that pointer should simply stay intact:
4566 * guest device -> node B
4569 * node A -> further backing chain...
4571 * In general, when replacing a node A (c->bs) by a node B (@to),
4572 * if A is a child of B, that means we cannot replace A by B there
4573 * because that would create a loop. Silently detaching A from B
4574 * is also not really an option. So overall just leaving A in
4575 * place there is the most sensible choice.
4577 * We would also create a loop in any cases where @c is only
4578 * indirectly referenced by @to. Prevent this by returning false
4579 * if @c is found (by breadth-first search) anywhere in the whole
4580 * subtree of @to.
4583 ret = true;
4584 found = g_hash_table_new(NULL, NULL);
4585 g_hash_table_add(found, to);
4586 queue = g_queue_new();
4587 g_queue_push_tail(queue, to);
4589 while (!g_queue_is_empty(queue)) {
4590 BlockDriverState *v = g_queue_pop_head(queue);
4591 BdrvChild *c2;
4593 QLIST_FOREACH(c2, &v->children, next) {
4594 if (c2 == c) {
4595 ret = false;
4596 break;
4599 if (g_hash_table_contains(found, c2->bs)) {
4600 continue;
4603 g_queue_push_tail(queue, c2->bs);
4604 g_hash_table_add(found, c2->bs);
4608 g_queue_free(queue);
4609 g_hash_table_destroy(found);
4611 return ret;
4614 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4615 Error **errp)
4617 BdrvChild *c, *next;
4618 GSList *list = NULL, *p;
4619 uint64_t perm = 0, shared = BLK_PERM_ALL;
4620 int ret;
4622 /* Make sure that @from doesn't go away until we have successfully attached
4623 * all of its parents to @to. */
4624 bdrv_ref(from);
4626 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4627 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
4628 bdrv_drained_begin(from);
4630 /* Put all parents into @list and calculate their cumulative permissions */
4631 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4632 assert(c->bs == from);
4633 if (!should_update_child(c, to)) {
4634 continue;
4636 if (c->frozen) {
4637 error_setg(errp, "Cannot change '%s' link to '%s'",
4638 c->name, from->node_name);
4639 goto out;
4641 list = g_slist_prepend(list, c);
4642 perm |= c->perm;
4643 shared &= c->shared_perm;
4646 /* Check whether the required permissions can be granted on @to, ignoring
4647 * all BdrvChild in @list so that they can't block themselves. */
4648 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
4649 if (ret < 0) {
4650 bdrv_abort_perm_update(to);
4651 goto out;
4654 /* Now actually perform the change. We performed the permission check for
4655 * all elements of @list at once, so set the permissions all at once at the
4656 * very end. */
4657 for (p = list; p != NULL; p = p->next) {
4658 c = p->data;
4660 bdrv_ref(to);
4661 bdrv_replace_child_noperm(c, to);
4662 bdrv_unref(from);
4665 bdrv_get_cumulative_perm(to, &perm, &shared);
4666 bdrv_set_perm(to, perm, shared);
4668 out:
4669 g_slist_free(list);
4670 bdrv_drained_end(from);
4671 bdrv_unref(from);
4675 * Add new bs contents at the top of an image chain while the chain is
4676 * live, while keeping required fields on the top layer.
4678 * This will modify the BlockDriverState fields, and swap contents
4679 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4681 * bs_new must not be attached to a BlockBackend.
4683 * This function does not create any image files.
4685 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4686 * that's what the callers commonly need. bs_new will be referenced by the old
4687 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4688 * reference of its own, it must call bdrv_ref().
4690 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4691 Error **errp)
4693 Error *local_err = NULL;
4695 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4696 if (local_err) {
4697 error_propagate(errp, local_err);
4698 goto out;
4701 bdrv_replace_node(bs_top, bs_new, &local_err);
4702 if (local_err) {
4703 error_propagate(errp, local_err);
4704 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4705 goto out;
4708 /* bs_new is now referenced by its new parents, we don't need the
4709 * additional reference any more. */
4710 out:
4711 bdrv_unref(bs_new);
4714 static void bdrv_delete(BlockDriverState *bs)
4716 assert(bdrv_op_blocker_is_empty(bs));
4717 assert(!bs->refcnt);
4719 /* remove from list, if necessary */
4720 if (bs->node_name[0] != '\0') {
4721 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4723 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4725 bdrv_close(bs);
4727 g_free(bs);
4731 * Run consistency checks on an image
4733 * Returns 0 if the check could be completed (it doesn't mean that the image is
4734 * free of errors) or -errno when an internal error occurred. The results of the
4735 * check are stored in res.
4737 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4738 BdrvCheckResult *res, BdrvCheckMode fix)
4740 if (bs->drv == NULL) {
4741 return -ENOMEDIUM;
4743 if (bs->drv->bdrv_co_check == NULL) {
4744 return -ENOTSUP;
4747 memset(res, 0, sizeof(*res));
4748 return bs->drv->bdrv_co_check(bs, res, fix);
4751 typedef struct CheckCo {
4752 BlockDriverState *bs;
4753 BdrvCheckResult *res;
4754 BdrvCheckMode fix;
4755 int ret;
4756 } CheckCo;
4758 static void coroutine_fn bdrv_check_co_entry(void *opaque)
4760 CheckCo *cco = opaque;
4761 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4762 aio_wait_kick();
4765 int bdrv_check(BlockDriverState *bs,
4766 BdrvCheckResult *res, BdrvCheckMode fix)
4768 Coroutine *co;
4769 CheckCo cco = {
4770 .bs = bs,
4771 .res = res,
4772 .ret = -EINPROGRESS,
4773 .fix = fix,
4776 if (qemu_in_coroutine()) {
4777 /* Fast-path if already in coroutine context */
4778 bdrv_check_co_entry(&cco);
4779 } else {
4780 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4781 bdrv_coroutine_enter(bs, co);
4782 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4785 return cco.ret;
4789 * Return values:
4790 * 0 - success
4791 * -EINVAL - backing format specified, but no file
4792 * -ENOSPC - can't update the backing file because no space is left in the
4793 * image file header
4794 * -ENOTSUP - format driver doesn't support changing the backing file
4796 int bdrv_change_backing_file(BlockDriverState *bs,
4797 const char *backing_file, const char *backing_fmt)
4799 BlockDriver *drv = bs->drv;
4800 int ret;
4802 if (!drv) {
4803 return -ENOMEDIUM;
4806 /* Backing file format doesn't make sense without a backing file */
4807 if (backing_fmt && !backing_file) {
4808 return -EINVAL;
4811 if (drv->bdrv_change_backing_file != NULL) {
4812 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
4813 } else {
4814 ret = -ENOTSUP;
4817 if (ret == 0) {
4818 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4819 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
4820 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4821 backing_file ?: "");
4823 return ret;
4827 * Finds the image layer in the chain that has 'bs' as its backing file.
4829 * active is the current topmost image.
4831 * Returns NULL if bs is not found in active's image chain,
4832 * or if active == bs.
4834 * Returns the bottommost base image if bs == NULL.
4836 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4837 BlockDriverState *bs)
4839 while (active && bs != backing_bs(active)) {
4840 active = backing_bs(active);
4843 return active;
4846 /* Given a BDS, searches for the base layer. */
4847 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4849 return bdrv_find_overlay(bs, NULL);
4853 * Return true if at least one of the backing links between @bs and
4854 * @base is frozen. @errp is set if that's the case.
4855 * @base must be reachable from @bs, or NULL.
4857 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4858 Error **errp)
4860 BlockDriverState *i;
4862 for (i = bs; i != base; i = backing_bs(i)) {
4863 if (i->backing && i->backing->frozen) {
4864 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4865 i->backing->name, i->node_name,
4866 backing_bs(i)->node_name);
4867 return true;
4871 return false;
4875 * Freeze all backing links between @bs and @base.
4876 * If any of the links is already frozen the operation is aborted and
4877 * none of the links are modified.
4878 * @base must be reachable from @bs, or NULL.
4879 * Returns 0 on success. On failure returns < 0 and sets @errp.
4881 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4882 Error **errp)
4884 BlockDriverState *i;
4886 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4887 return -EPERM;
4890 for (i = bs; i != base; i = backing_bs(i)) {
4891 if (i->backing && backing_bs(i)->never_freeze) {
4892 error_setg(errp, "Cannot freeze '%s' link to '%s'",
4893 i->backing->name, backing_bs(i)->node_name);
4894 return -EPERM;
4898 for (i = bs; i != base; i = backing_bs(i)) {
4899 if (i->backing) {
4900 i->backing->frozen = true;
4904 return 0;
4908 * Unfreeze all backing links between @bs and @base. The caller must
4909 * ensure that all links are frozen before using this function.
4910 * @base must be reachable from @bs, or NULL.
4912 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4914 BlockDriverState *i;
4916 for (i = bs; i != base; i = backing_bs(i)) {
4917 if (i->backing) {
4918 assert(i->backing->frozen);
4919 i->backing->frozen = false;
4925 * Drops images above 'base' up to and including 'top', and sets the image
4926 * above 'top' to have base as its backing file.
4928 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4929 * information in 'bs' can be properly updated.
4931 * E.g., this will convert the following chain:
4932 * bottom <- base <- intermediate <- top <- active
4934 * to
4936 * bottom <- base <- active
4938 * It is allowed for bottom==base, in which case it converts:
4940 * base <- intermediate <- top <- active
4942 * to
4944 * base <- active
4946 * If backing_file_str is non-NULL, it will be used when modifying top's
4947 * overlay image metadata.
4949 * Error conditions:
4950 * if active == top, that is considered an error
4953 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4954 const char *backing_file_str)
4956 BlockDriverState *explicit_top = top;
4957 bool update_inherits_from;
4958 BdrvChild *c, *next;
4959 Error *local_err = NULL;
4960 int ret = -EIO;
4962 bdrv_ref(top);
4963 bdrv_subtree_drained_begin(top);
4965 if (!top->drv || !base->drv) {
4966 goto exit;
4969 /* Make sure that base is in the backing chain of top */
4970 if (!bdrv_chain_contains(top, base)) {
4971 goto exit;
4974 /* This function changes all links that point to top and makes
4975 * them point to base. Check that none of them is frozen. */
4976 QLIST_FOREACH(c, &top->parents, next_parent) {
4977 if (c->frozen) {
4978 goto exit;
4982 /* If 'base' recursively inherits from 'top' then we should set
4983 * base->inherits_from to top->inherits_from after 'top' and all
4984 * other intermediate nodes have been dropped.
4985 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4986 * it because no one inherits from it. We use explicit_top for that. */
4987 while (explicit_top && explicit_top->implicit) {
4988 explicit_top = backing_bs(explicit_top);
4990 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4992 /* success - we can delete the intermediate states, and link top->base */
4993 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4994 * we've figured out how they should work. */
4995 if (!backing_file_str) {
4996 bdrv_refresh_filename(base);
4997 backing_file_str = base->filename;
5000 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
5001 /* Check whether we are allowed to switch c from top to base */
5002 GSList *ignore_children = g_slist_prepend(NULL, c);
5003 ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
5004 ignore_children, NULL, &local_err);
5005 g_slist_free(ignore_children);
5006 if (ret < 0) {
5007 error_report_err(local_err);
5008 goto exit;
5011 /* If so, update the backing file path in the image file */
5012 if (c->klass->update_filename) {
5013 ret = c->klass->update_filename(c, base, backing_file_str,
5014 &local_err);
5015 if (ret < 0) {
5016 bdrv_abort_perm_update(base);
5017 error_report_err(local_err);
5018 goto exit;
5022 /* Do the actual switch in the in-memory graph.
5023 * Completes bdrv_check_update_perm() transaction internally. */
5024 bdrv_ref(base);
5025 bdrv_replace_child(c, base);
5026 bdrv_unref(top);
5029 if (update_inherits_from) {
5030 base->inherits_from = explicit_top->inherits_from;
5033 ret = 0;
5034 exit:
5035 bdrv_subtree_drained_end(top);
5036 bdrv_unref(top);
5037 return ret;
5041 * Length of a allocated file in bytes. Sparse files are counted by actual
5042 * allocated space. Return < 0 if error or unknown.
5044 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5046 BlockDriver *drv = bs->drv;
5047 if (!drv) {
5048 return -ENOMEDIUM;
5050 if (drv->bdrv_get_allocated_file_size) {
5051 return drv->bdrv_get_allocated_file_size(bs);
5053 if (bs->file) {
5054 return bdrv_get_allocated_file_size(bs->file->bs);
5056 return -ENOTSUP;
5060 * bdrv_measure:
5061 * @drv: Format driver
5062 * @opts: Creation options for new image
5063 * @in_bs: Existing image containing data for new image (may be NULL)
5064 * @errp: Error object
5065 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5066 * or NULL on error
5068 * Calculate file size required to create a new image.
5070 * If @in_bs is given then space for allocated clusters and zero clusters
5071 * from that image are included in the calculation. If @opts contains a
5072 * backing file that is shared by @in_bs then backing clusters may be omitted
5073 * from the calculation.
5075 * If @in_bs is NULL then the calculation includes no allocated clusters
5076 * unless a preallocation option is given in @opts.
5078 * Note that @in_bs may use a different BlockDriver from @drv.
5080 * If an error occurs the @errp pointer is set.
5082 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5083 BlockDriverState *in_bs, Error **errp)
5085 if (!drv->bdrv_measure) {
5086 error_setg(errp, "Block driver '%s' does not support size measurement",
5087 drv->format_name);
5088 return NULL;
5091 return drv->bdrv_measure(opts, in_bs, errp);
5095 * Return number of sectors on success, -errno on error.
5097 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5099 BlockDriver *drv = bs->drv;
5101 if (!drv)
5102 return -ENOMEDIUM;
5104 if (drv->has_variable_length) {
5105 int ret = refresh_total_sectors(bs, bs->total_sectors);
5106 if (ret < 0) {
5107 return ret;
5110 return bs->total_sectors;
5114 * Return length in bytes on success, -errno on error.
5115 * The length is always a multiple of BDRV_SECTOR_SIZE.
5117 int64_t bdrv_getlength(BlockDriverState *bs)
5119 int64_t ret = bdrv_nb_sectors(bs);
5121 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
5122 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
5125 /* return 0 as number of sectors if no device present or error */
5126 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5128 int64_t nb_sectors = bdrv_nb_sectors(bs);
5130 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5133 bool bdrv_is_sg(BlockDriverState *bs)
5135 return bs->sg;
5138 bool bdrv_is_encrypted(BlockDriverState *bs)
5140 if (bs->backing && bs->backing->bs->encrypted) {
5141 return true;
5143 return bs->encrypted;
5146 const char *bdrv_get_format_name(BlockDriverState *bs)
5148 return bs->drv ? bs->drv->format_name : NULL;
5151 static int qsort_strcmp(const void *a, const void *b)
5153 return strcmp(*(char *const *)a, *(char *const *)b);
5156 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5157 void *opaque, bool read_only)
5159 BlockDriver *drv;
5160 int count = 0;
5161 int i;
5162 const char **formats = NULL;
5164 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5165 if (drv->format_name) {
5166 bool found = false;
5167 int i = count;
5169 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5170 continue;
5173 while (formats && i && !found) {
5174 found = !strcmp(formats[--i], drv->format_name);
5177 if (!found) {
5178 formats = g_renew(const char *, formats, count + 1);
5179 formats[count++] = drv->format_name;
5184 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5185 const char *format_name = block_driver_modules[i].format_name;
5187 if (format_name) {
5188 bool found = false;
5189 int j = count;
5191 if (use_bdrv_whitelist &&
5192 !bdrv_format_is_whitelisted(format_name, read_only)) {
5193 continue;
5196 while (formats && j && !found) {
5197 found = !strcmp(formats[--j], format_name);
5200 if (!found) {
5201 formats = g_renew(const char *, formats, count + 1);
5202 formats[count++] = format_name;
5207 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5209 for (i = 0; i < count; i++) {
5210 it(opaque, formats[i]);
5213 g_free(formats);
5216 /* This function is to find a node in the bs graph */
5217 BlockDriverState *bdrv_find_node(const char *node_name)
5219 BlockDriverState *bs;
5221 assert(node_name);
5223 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5224 if (!strcmp(node_name, bs->node_name)) {
5225 return bs;
5228 return NULL;
5231 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5232 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5233 Error **errp)
5235 BlockDeviceInfoList *list, *entry;
5236 BlockDriverState *bs;
5238 list = NULL;
5239 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5240 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5241 if (!info) {
5242 qapi_free_BlockDeviceInfoList(list);
5243 return NULL;
5245 entry = g_malloc0(sizeof(*entry));
5246 entry->value = info;
5247 entry->next = list;
5248 list = entry;
5251 return list;
5254 #define QAPI_LIST_ADD(list, element) do { \
5255 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
5256 _tmp->value = (element); \
5257 _tmp->next = (list); \
5258 (list) = _tmp; \
5259 } while (0)
5261 typedef struct XDbgBlockGraphConstructor {
5262 XDbgBlockGraph *graph;
5263 GHashTable *graph_nodes;
5264 } XDbgBlockGraphConstructor;
5266 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5268 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5270 gr->graph = g_new0(XDbgBlockGraph, 1);
5271 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5273 return gr;
5276 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5278 XDbgBlockGraph *graph = gr->graph;
5280 g_hash_table_destroy(gr->graph_nodes);
5281 g_free(gr);
5283 return graph;
5286 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5288 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5290 if (ret != 0) {
5291 return ret;
5295 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5296 * answer of g_hash_table_lookup.
5298 ret = g_hash_table_size(gr->graph_nodes) + 1;
5299 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5301 return ret;
5304 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5305 XDbgBlockGraphNodeType type, const char *name)
5307 XDbgBlockGraphNode *n;
5309 n = g_new0(XDbgBlockGraphNode, 1);
5311 n->id = xdbg_graph_node_num(gr, node);
5312 n->type = type;
5313 n->name = g_strdup(name);
5315 QAPI_LIST_ADD(gr->graph->nodes, n);
5318 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5319 const BdrvChild *child)
5321 BlockPermission qapi_perm;
5322 XDbgBlockGraphEdge *edge;
5324 edge = g_new0(XDbgBlockGraphEdge, 1);
5326 edge->parent = xdbg_graph_node_num(gr, parent);
5327 edge->child = xdbg_graph_node_num(gr, child->bs);
5328 edge->name = g_strdup(child->name);
5330 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5331 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5333 if (flag & child->perm) {
5334 QAPI_LIST_ADD(edge->perm, qapi_perm);
5336 if (flag & child->shared_perm) {
5337 QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
5341 QAPI_LIST_ADD(gr->graph->edges, edge);
5345 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5347 BlockBackend *blk;
5348 BlockJob *job;
5349 BlockDriverState *bs;
5350 BdrvChild *child;
5351 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5353 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5354 char *allocated_name = NULL;
5355 const char *name = blk_name(blk);
5357 if (!*name) {
5358 name = allocated_name = blk_get_attached_dev_id(blk);
5360 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5361 name);
5362 g_free(allocated_name);
5363 if (blk_root(blk)) {
5364 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5368 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5369 GSList *el;
5371 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5372 job->job.id);
5373 for (el = job->nodes; el; el = el->next) {
5374 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5378 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5379 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5380 bs->node_name);
5381 QLIST_FOREACH(child, &bs->children, next) {
5382 xdbg_graph_add_edge(gr, bs, child);
5386 return xdbg_graph_finalize(gr);
5389 BlockDriverState *bdrv_lookup_bs(const char *device,
5390 const char *node_name,
5391 Error **errp)
5393 BlockBackend *blk;
5394 BlockDriverState *bs;
5396 if (device) {
5397 blk = blk_by_name(device);
5399 if (blk) {
5400 bs = blk_bs(blk);
5401 if (!bs) {
5402 error_setg(errp, "Device '%s' has no medium", device);
5405 return bs;
5409 if (node_name) {
5410 bs = bdrv_find_node(node_name);
5412 if (bs) {
5413 return bs;
5417 error_setg(errp, "Cannot find device=%s nor node_name=%s",
5418 device ? device : "",
5419 node_name ? node_name : "");
5420 return NULL;
5423 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5424 * return false. If either argument is NULL, return false. */
5425 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5427 while (top && top != base) {
5428 top = backing_bs(top);
5431 return top != NULL;
5434 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5436 if (!bs) {
5437 return QTAILQ_FIRST(&graph_bdrv_states);
5439 return QTAILQ_NEXT(bs, node_list);
5442 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5444 if (!bs) {
5445 return QTAILQ_FIRST(&all_bdrv_states);
5447 return QTAILQ_NEXT(bs, bs_list);
5450 const char *bdrv_get_node_name(const BlockDriverState *bs)
5452 return bs->node_name;
5455 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5457 BdrvChild *c;
5458 const char *name;
5460 /* If multiple parents have a name, just pick the first one. */
5461 QLIST_FOREACH(c, &bs->parents, next_parent) {
5462 if (c->klass->get_name) {
5463 name = c->klass->get_name(c);
5464 if (name && *name) {
5465 return name;
5470 return NULL;
5473 /* TODO check what callers really want: bs->node_name or blk_name() */
5474 const char *bdrv_get_device_name(const BlockDriverState *bs)
5476 return bdrv_get_parent_name(bs) ?: "";
5479 /* This can be used to identify nodes that might not have a device
5480 * name associated. Since node and device names live in the same
5481 * namespace, the result is unambiguous. The exception is if both are
5482 * absent, then this returns an empty (non-null) string. */
5483 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5485 return bdrv_get_parent_name(bs) ?: bs->node_name;
5488 int bdrv_get_flags(BlockDriverState *bs)
5490 return bs->open_flags;
5493 int bdrv_has_zero_init_1(BlockDriverState *bs)
5495 return 1;
5498 int bdrv_has_zero_init(BlockDriverState *bs)
5500 if (!bs->drv) {
5501 return 0;
5504 /* If BS is a copy on write image, it is initialized to
5505 the contents of the base image, which may not be zeroes. */
5506 if (bs->backing) {
5507 return 0;
5509 if (bs->drv->bdrv_has_zero_init) {
5510 return bs->drv->bdrv_has_zero_init(bs);
5512 if (bs->file && bs->drv->is_filter) {
5513 return bdrv_has_zero_init(bs->file->bs);
5516 /* safe default */
5517 return 0;
5520 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
5522 BlockDriverInfo bdi;
5524 if (bs->backing) {
5525 return false;
5528 if (bdrv_get_info(bs, &bdi) == 0) {
5529 return bdi.unallocated_blocks_are_zero;
5532 return false;
5535 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5537 if (!(bs->open_flags & BDRV_O_UNMAP)) {
5538 return false;
5541 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5544 void bdrv_get_backing_filename(BlockDriverState *bs,
5545 char *filename, int filename_size)
5547 pstrcpy(filename, filename_size, bs->backing_file);
5550 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5552 BlockDriver *drv = bs->drv;
5553 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5554 if (!drv) {
5555 return -ENOMEDIUM;
5557 if (!drv->bdrv_get_info) {
5558 if (bs->file && drv->is_filter) {
5559 return bdrv_get_info(bs->file->bs, bdi);
5561 return -ENOTSUP;
5563 memset(bdi, 0, sizeof(*bdi));
5564 return drv->bdrv_get_info(bs, bdi);
5567 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5568 Error **errp)
5570 BlockDriver *drv = bs->drv;
5571 if (drv && drv->bdrv_get_specific_info) {
5572 return drv->bdrv_get_specific_info(bs, errp);
5574 return NULL;
5577 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5579 BlockDriver *drv = bs->drv;
5580 if (!drv || !drv->bdrv_get_specific_stats) {
5581 return NULL;
5583 return drv->bdrv_get_specific_stats(bs);
5586 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5588 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5589 return;
5592 bs->drv->bdrv_debug_event(bs, event);
5595 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5597 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5598 if (bs->file) {
5599 bs = bs->file->bs;
5600 continue;
5603 if (bs->drv->is_filter && bs->backing) {
5604 bs = bs->backing->bs;
5605 continue;
5608 break;
5611 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5612 assert(bs->drv->bdrv_debug_remove_breakpoint);
5613 return bs;
5616 return NULL;
5619 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5620 const char *tag)
5622 bs = bdrv_find_debug_node(bs);
5623 if (bs) {
5624 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5627 return -ENOTSUP;
5630 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5632 bs = bdrv_find_debug_node(bs);
5633 if (bs) {
5634 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5637 return -ENOTSUP;
5640 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5642 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5643 bs = bs->file ? bs->file->bs : NULL;
5646 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5647 return bs->drv->bdrv_debug_resume(bs, tag);
5650 return -ENOTSUP;
5653 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5655 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5656 bs = bs->file ? bs->file->bs : NULL;
5659 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5660 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5663 return false;
5666 /* backing_file can either be relative, or absolute, or a protocol. If it is
5667 * relative, it must be relative to the chain. So, passing in bs->filename
5668 * from a BDS as backing_file should not be done, as that may be relative to
5669 * the CWD rather than the chain. */
5670 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5671 const char *backing_file)
5673 char *filename_full = NULL;
5674 char *backing_file_full = NULL;
5675 char *filename_tmp = NULL;
5676 int is_protocol = 0;
5677 BlockDriverState *curr_bs = NULL;
5678 BlockDriverState *retval = NULL;
5680 if (!bs || !bs->drv || !backing_file) {
5681 return NULL;
5684 filename_full = g_malloc(PATH_MAX);
5685 backing_file_full = g_malloc(PATH_MAX);
5687 is_protocol = path_has_protocol(backing_file);
5689 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
5691 /* If either of the filename paths is actually a protocol, then
5692 * compare unmodified paths; otherwise make paths relative */
5693 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5694 char *backing_file_full_ret;
5696 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
5697 retval = curr_bs->backing->bs;
5698 break;
5700 /* Also check against the full backing filename for the image */
5701 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5702 NULL);
5703 if (backing_file_full_ret) {
5704 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5705 g_free(backing_file_full_ret);
5706 if (equal) {
5707 retval = curr_bs->backing->bs;
5708 break;
5711 } else {
5712 /* If not an absolute filename path, make it relative to the current
5713 * image's filename path */
5714 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5715 NULL);
5716 /* We are going to compare canonicalized absolute pathnames */
5717 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5718 g_free(filename_tmp);
5719 continue;
5721 g_free(filename_tmp);
5723 /* We need to make sure the backing filename we are comparing against
5724 * is relative to the current image filename (or absolute) */
5725 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5726 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5727 g_free(filename_tmp);
5728 continue;
5730 g_free(filename_tmp);
5732 if (strcmp(backing_file_full, filename_full) == 0) {
5733 retval = curr_bs->backing->bs;
5734 break;
5739 g_free(filename_full);
5740 g_free(backing_file_full);
5741 return retval;
5744 void bdrv_init(void)
5746 module_call_init(MODULE_INIT_BLOCK);
5749 void bdrv_init_with_whitelist(void)
5751 use_bdrv_whitelist = 1;
5752 bdrv_init();
5755 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5756 Error **errp)
5758 BdrvChild *child, *parent;
5759 uint64_t perm, shared_perm;
5760 Error *local_err = NULL;
5761 int ret;
5762 BdrvDirtyBitmap *bm;
5764 if (!bs->drv) {
5765 return;
5768 QLIST_FOREACH(child, &bs->children, next) {
5769 bdrv_co_invalidate_cache(child->bs, &local_err);
5770 if (local_err) {
5771 error_propagate(errp, local_err);
5772 return;
5777 * Update permissions, they may differ for inactive nodes.
5779 * Note that the required permissions of inactive images are always a
5780 * subset of the permissions required after activating the image. This
5781 * allows us to just get the permissions upfront without restricting
5782 * drv->bdrv_invalidate_cache().
5784 * It also means that in error cases, we don't have to try and revert to
5785 * the old permissions (which is an operation that could fail, too). We can
5786 * just keep the extended permissions for the next time that an activation
5787 * of the image is tried.
5789 if (bs->open_flags & BDRV_O_INACTIVE) {
5790 bs->open_flags &= ~BDRV_O_INACTIVE;
5791 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5792 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, &local_err);
5793 if (ret < 0) {
5794 bs->open_flags |= BDRV_O_INACTIVE;
5795 error_propagate(errp, local_err);
5796 return;
5798 bdrv_set_perm(bs, perm, shared_perm);
5800 if (bs->drv->bdrv_co_invalidate_cache) {
5801 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5802 if (local_err) {
5803 bs->open_flags |= BDRV_O_INACTIVE;
5804 error_propagate(errp, local_err);
5805 return;
5809 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5810 bdrv_dirty_bitmap_skip_store(bm, false);
5813 ret = refresh_total_sectors(bs, bs->total_sectors);
5814 if (ret < 0) {
5815 bs->open_flags |= BDRV_O_INACTIVE;
5816 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5817 return;
5821 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5822 if (parent->klass->activate) {
5823 parent->klass->activate(parent, &local_err);
5824 if (local_err) {
5825 bs->open_flags |= BDRV_O_INACTIVE;
5826 error_propagate(errp, local_err);
5827 return;
5833 typedef struct InvalidateCacheCo {
5834 BlockDriverState *bs;
5835 Error **errp;
5836 bool done;
5837 } InvalidateCacheCo;
5839 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5841 InvalidateCacheCo *ico = opaque;
5842 bdrv_co_invalidate_cache(ico->bs, ico->errp);
5843 ico->done = true;
5844 aio_wait_kick();
5847 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5849 Coroutine *co;
5850 InvalidateCacheCo ico = {
5851 .bs = bs,
5852 .done = false,
5853 .errp = errp
5856 if (qemu_in_coroutine()) {
5857 /* Fast-path if already in coroutine context */
5858 bdrv_invalidate_cache_co_entry(&ico);
5859 } else {
5860 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
5861 bdrv_coroutine_enter(bs, co);
5862 BDRV_POLL_WHILE(bs, !ico.done);
5866 void bdrv_invalidate_cache_all(Error **errp)
5868 BlockDriverState *bs;
5869 Error *local_err = NULL;
5870 BdrvNextIterator it;
5872 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5873 AioContext *aio_context = bdrv_get_aio_context(bs);
5875 aio_context_acquire(aio_context);
5876 bdrv_invalidate_cache(bs, &local_err);
5877 aio_context_release(aio_context);
5878 if (local_err) {
5879 error_propagate(errp, local_err);
5880 bdrv_next_cleanup(&it);
5881 return;
5886 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5888 BdrvChild *parent;
5890 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5891 if (parent->klass->parent_is_bds) {
5892 BlockDriverState *parent_bs = parent->opaque;
5893 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5894 return true;
5899 return false;
5902 static int bdrv_inactivate_recurse(BlockDriverState *bs)
5904 BdrvChild *child, *parent;
5905 bool tighten_restrictions;
5906 uint64_t perm, shared_perm;
5907 int ret;
5909 if (!bs->drv) {
5910 return -ENOMEDIUM;
5913 /* Make sure that we don't inactivate a child before its parent.
5914 * It will be covered by recursion from the yet active parent. */
5915 if (bdrv_has_bds_parent(bs, true)) {
5916 return 0;
5919 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5921 /* Inactivate this node */
5922 if (bs->drv->bdrv_inactivate) {
5923 ret = bs->drv->bdrv_inactivate(bs);
5924 if (ret < 0) {
5925 return ret;
5929 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5930 if (parent->klass->inactivate) {
5931 ret = parent->klass->inactivate(parent);
5932 if (ret < 0) {
5933 return ret;
5938 bs->open_flags |= BDRV_O_INACTIVE;
5940 /* Update permissions, they may differ for inactive nodes */
5941 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5942 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5943 &tighten_restrictions, NULL);
5944 assert(tighten_restrictions == false);
5945 if (ret < 0) {
5946 /* We only tried to loosen restrictions, so errors are not fatal */
5947 bdrv_abort_perm_update(bs);
5948 } else {
5949 bdrv_set_perm(bs, perm, shared_perm);
5953 /* Recursively inactivate children */
5954 QLIST_FOREACH(child, &bs->children, next) {
5955 ret = bdrv_inactivate_recurse(child->bs);
5956 if (ret < 0) {
5957 return ret;
5961 return 0;
5964 int bdrv_inactivate_all(void)
5966 BlockDriverState *bs = NULL;
5967 BdrvNextIterator it;
5968 int ret = 0;
5969 GSList *aio_ctxs = NULL, *ctx;
5971 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5972 AioContext *aio_context = bdrv_get_aio_context(bs);
5974 if (!g_slist_find(aio_ctxs, aio_context)) {
5975 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5976 aio_context_acquire(aio_context);
5980 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5981 /* Nodes with BDS parents are covered by recursion from the last
5982 * parent that gets inactivated. Don't inactivate them a second
5983 * time if that has already happened. */
5984 if (bdrv_has_bds_parent(bs, false)) {
5985 continue;
5987 ret = bdrv_inactivate_recurse(bs);
5988 if (ret < 0) {
5989 bdrv_next_cleanup(&it);
5990 goto out;
5994 out:
5995 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5996 AioContext *aio_context = ctx->data;
5997 aio_context_release(aio_context);
5999 g_slist_free(aio_ctxs);
6001 return ret;
6004 /**************************************************************/
6005 /* removable device support */
6008 * Return TRUE if the media is present
6010 bool bdrv_is_inserted(BlockDriverState *bs)
6012 BlockDriver *drv = bs->drv;
6013 BdrvChild *child;
6015 if (!drv) {
6016 return false;
6018 if (drv->bdrv_is_inserted) {
6019 return drv->bdrv_is_inserted(bs);
6021 QLIST_FOREACH(child, &bs->children, next) {
6022 if (!bdrv_is_inserted(child->bs)) {
6023 return false;
6026 return true;
6030 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6032 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6034 BlockDriver *drv = bs->drv;
6036 if (drv && drv->bdrv_eject) {
6037 drv->bdrv_eject(bs, eject_flag);
6042 * Lock or unlock the media (if it is locked, the user won't be able
6043 * to eject it manually).
6045 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6047 BlockDriver *drv = bs->drv;
6049 trace_bdrv_lock_medium(bs, locked);
6051 if (drv && drv->bdrv_lock_medium) {
6052 drv->bdrv_lock_medium(bs, locked);
6056 /* Get a reference to bs */
6057 void bdrv_ref(BlockDriverState *bs)
6059 bs->refcnt++;
6062 /* Release a previously grabbed reference to bs.
6063 * If after releasing, reference count is zero, the BlockDriverState is
6064 * deleted. */
6065 void bdrv_unref(BlockDriverState *bs)
6067 if (!bs) {
6068 return;
6070 assert(bs->refcnt > 0);
6071 if (--bs->refcnt == 0) {
6072 bdrv_delete(bs);
6076 struct BdrvOpBlocker {
6077 Error *reason;
6078 QLIST_ENTRY(BdrvOpBlocker) list;
6081 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6083 BdrvOpBlocker *blocker;
6084 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6085 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6086 blocker = QLIST_FIRST(&bs->op_blockers[op]);
6087 error_propagate_prepend(errp, error_copy(blocker->reason),
6088 "Node '%s' is busy: ",
6089 bdrv_get_device_or_node_name(bs));
6090 return true;
6092 return false;
6095 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6097 BdrvOpBlocker *blocker;
6098 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6100 blocker = g_new0(BdrvOpBlocker, 1);
6101 blocker->reason = reason;
6102 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6105 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6107 BdrvOpBlocker *blocker, *next;
6108 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6109 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6110 if (blocker->reason == reason) {
6111 QLIST_REMOVE(blocker, list);
6112 g_free(blocker);
6117 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6119 int i;
6120 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6121 bdrv_op_block(bs, i, reason);
6125 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6127 int i;
6128 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6129 bdrv_op_unblock(bs, i, reason);
6133 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6135 int i;
6137 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6138 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6139 return false;
6142 return true;
6145 void bdrv_img_create(const char *filename, const char *fmt,
6146 const char *base_filename, const char *base_fmt,
6147 char *options, uint64_t img_size, int flags, bool quiet,
6148 Error **errp)
6150 QemuOptsList *create_opts = NULL;
6151 QemuOpts *opts = NULL;
6152 const char *backing_fmt, *backing_file;
6153 int64_t size;
6154 BlockDriver *drv, *proto_drv;
6155 Error *local_err = NULL;
6156 int ret = 0;
6158 /* Find driver and parse its options */
6159 drv = bdrv_find_format(fmt);
6160 if (!drv) {
6161 error_setg(errp, "Unknown file format '%s'", fmt);
6162 return;
6165 proto_drv = bdrv_find_protocol(filename, true, errp);
6166 if (!proto_drv) {
6167 return;
6170 if (!drv->create_opts) {
6171 error_setg(errp, "Format driver '%s' does not support image creation",
6172 drv->format_name);
6173 return;
6176 if (!proto_drv->create_opts) {
6177 error_setg(errp, "Protocol driver '%s' does not support image creation",
6178 proto_drv->format_name);
6179 return;
6182 /* Create parameter list */
6183 create_opts = qemu_opts_append(create_opts, drv->create_opts);
6184 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6186 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6188 /* Parse -o options */
6189 if (options) {
6190 qemu_opts_do_parse(opts, options, NULL, &local_err);
6191 if (local_err) {
6192 goto out;
6196 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6197 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6198 } else if (img_size != UINT64_C(-1)) {
6199 error_setg(errp, "The image size must be specified only once");
6200 goto out;
6203 if (base_filename) {
6204 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
6205 if (local_err) {
6206 error_setg(errp, "Backing file not supported for file format '%s'",
6207 fmt);
6208 goto out;
6212 if (base_fmt) {
6213 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
6214 if (local_err) {
6215 error_setg(errp, "Backing file format not supported for file "
6216 "format '%s'", fmt);
6217 goto out;
6221 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6222 if (backing_file) {
6223 if (!strcmp(filename, backing_file)) {
6224 error_setg(errp, "Error: Trying to create an image with the "
6225 "same filename as the backing file");
6226 goto out;
6230 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6232 /* The size for the image must always be specified, unless we have a backing
6233 * file and we have not been forbidden from opening it. */
6234 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6235 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6236 BlockDriverState *bs;
6237 char *full_backing;
6238 int back_flags;
6239 QDict *backing_options = NULL;
6241 full_backing =
6242 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6243 &local_err);
6244 if (local_err) {
6245 goto out;
6247 assert(full_backing);
6249 /* backing files always opened read-only */
6250 back_flags = flags;
6251 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6253 backing_options = qdict_new();
6254 if (backing_fmt) {
6255 qdict_put_str(backing_options, "driver", backing_fmt);
6257 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
6259 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6260 &local_err);
6261 g_free(full_backing);
6262 if (!bs && size != -1) {
6263 /* Couldn't open BS, but we have a size, so it's nonfatal */
6264 warn_reportf_err(local_err,
6265 "Could not verify backing image. "
6266 "This may become an error in future versions.\n");
6267 local_err = NULL;
6268 } else if (!bs) {
6269 /* Couldn't open bs, do not have size */
6270 error_append_hint(&local_err,
6271 "Could not open backing image to determine size.\n");
6272 goto out;
6273 } else {
6274 if (size == -1) {
6275 /* Opened BS, have no size */
6276 size = bdrv_getlength(bs);
6277 if (size < 0) {
6278 error_setg_errno(errp, -size, "Could not get size of '%s'",
6279 backing_file);
6280 bdrv_unref(bs);
6281 goto out;
6283 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6285 bdrv_unref(bs);
6287 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6289 if (size == -1) {
6290 error_setg(errp, "Image creation needs a size parameter");
6291 goto out;
6294 if (!quiet) {
6295 printf("Formatting '%s', fmt=%s ", filename, fmt);
6296 qemu_opts_print(opts, " ");
6297 puts("");
6300 ret = bdrv_create(drv, filename, opts, &local_err);
6302 if (ret == -EFBIG) {
6303 /* This is generally a better message than whatever the driver would
6304 * deliver (especially because of the cluster_size_hint), since that
6305 * is most probably not much different from "image too large". */
6306 const char *cluster_size_hint = "";
6307 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
6308 cluster_size_hint = " (try using a larger cluster size)";
6310 error_setg(errp, "The image size is too large for file format '%s'"
6311 "%s", fmt, cluster_size_hint);
6312 error_free(local_err);
6313 local_err = NULL;
6316 out:
6317 qemu_opts_del(opts);
6318 qemu_opts_free(create_opts);
6319 error_propagate(errp, local_err);
6322 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6324 return bs ? bs->aio_context : qemu_get_aio_context();
6327 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6329 aio_co_enter(bdrv_get_aio_context(bs), co);
6332 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6334 QLIST_REMOVE(ban, list);
6335 g_free(ban);
6338 static void bdrv_detach_aio_context(BlockDriverState *bs)
6340 BdrvAioNotifier *baf, *baf_tmp;
6342 assert(!bs->walking_aio_notifiers);
6343 bs->walking_aio_notifiers = true;
6344 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6345 if (baf->deleted) {
6346 bdrv_do_remove_aio_context_notifier(baf);
6347 } else {
6348 baf->detach_aio_context(baf->opaque);
6351 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6352 * remove remaining aio notifiers if we aren't called again.
6354 bs->walking_aio_notifiers = false;
6356 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
6357 bs->drv->bdrv_detach_aio_context(bs);
6360 if (bs->quiesce_counter) {
6361 aio_enable_external(bs->aio_context);
6363 bs->aio_context = NULL;
6366 static void bdrv_attach_aio_context(BlockDriverState *bs,
6367 AioContext *new_context)
6369 BdrvAioNotifier *ban, *ban_tmp;
6371 if (bs->quiesce_counter) {
6372 aio_disable_external(new_context);
6375 bs->aio_context = new_context;
6377 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
6378 bs->drv->bdrv_attach_aio_context(bs, new_context);
6381 assert(!bs->walking_aio_notifiers);
6382 bs->walking_aio_notifiers = true;
6383 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6384 if (ban->deleted) {
6385 bdrv_do_remove_aio_context_notifier(ban);
6386 } else {
6387 ban->attached_aio_context(new_context, ban->opaque);
6390 bs->walking_aio_notifiers = false;
6394 * Changes the AioContext used for fd handlers, timers, and BHs by this
6395 * BlockDriverState and all its children and parents.
6397 * Must be called from the main AioContext.
6399 * The caller must own the AioContext lock for the old AioContext of bs, but it
6400 * must not own the AioContext lock for new_context (unless new_context is the
6401 * same as the current context of bs).
6403 * @ignore will accumulate all visited BdrvChild object. The caller is
6404 * responsible for freeing the list afterwards.
6406 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6407 AioContext *new_context, GSList **ignore)
6409 AioContext *old_context = bdrv_get_aio_context(bs);
6410 BdrvChild *child;
6412 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6414 if (old_context == new_context) {
6415 return;
6418 bdrv_drained_begin(bs);
6420 QLIST_FOREACH(child, &bs->children, next) {
6421 if (g_slist_find(*ignore, child)) {
6422 continue;
6424 *ignore = g_slist_prepend(*ignore, child);
6425 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6427 QLIST_FOREACH(child, &bs->parents, next_parent) {
6428 if (g_slist_find(*ignore, child)) {
6429 continue;
6431 assert(child->klass->set_aio_ctx);
6432 *ignore = g_slist_prepend(*ignore, child);
6433 child->klass->set_aio_ctx(child, new_context, ignore);
6436 bdrv_detach_aio_context(bs);
6438 /* Acquire the new context, if necessary */
6439 if (qemu_get_aio_context() != new_context) {
6440 aio_context_acquire(new_context);
6443 bdrv_attach_aio_context(bs, new_context);
6446 * If this function was recursively called from
6447 * bdrv_set_aio_context_ignore(), there may be nodes in the
6448 * subtree that have not yet been moved to the new AioContext.
6449 * Release the old one so bdrv_drained_end() can poll them.
6451 if (qemu_get_aio_context() != old_context) {
6452 aio_context_release(old_context);
6455 bdrv_drained_end(bs);
6457 if (qemu_get_aio_context() != old_context) {
6458 aio_context_acquire(old_context);
6460 if (qemu_get_aio_context() != new_context) {
6461 aio_context_release(new_context);
6465 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6466 GSList **ignore, Error **errp)
6468 if (g_slist_find(*ignore, c)) {
6469 return true;
6471 *ignore = g_slist_prepend(*ignore, c);
6474 * A BdrvChildClass that doesn't handle AioContext changes cannot
6475 * tolerate any AioContext changes
6477 if (!c->klass->can_set_aio_ctx) {
6478 char *user = bdrv_child_user_desc(c);
6479 error_setg(errp, "Changing iothreads is not supported by %s", user);
6480 g_free(user);
6481 return false;
6483 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
6484 assert(!errp || *errp);
6485 return false;
6487 return true;
6490 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6491 GSList **ignore, Error **errp)
6493 if (g_slist_find(*ignore, c)) {
6494 return true;
6496 *ignore = g_slist_prepend(*ignore, c);
6497 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6500 /* @ignore will accumulate all visited BdrvChild object. The caller is
6501 * responsible for freeing the list afterwards. */
6502 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6503 GSList **ignore, Error **errp)
6505 BdrvChild *c;
6507 if (bdrv_get_aio_context(bs) == ctx) {
6508 return true;
6511 QLIST_FOREACH(c, &bs->parents, next_parent) {
6512 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6513 return false;
6516 QLIST_FOREACH(c, &bs->children, next) {
6517 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6518 return false;
6522 return true;
6525 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6526 BdrvChild *ignore_child, Error **errp)
6528 GSList *ignore;
6529 bool ret;
6531 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6532 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6533 g_slist_free(ignore);
6535 if (!ret) {
6536 return -EPERM;
6539 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6540 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6541 g_slist_free(ignore);
6543 return 0;
6546 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6547 Error **errp)
6549 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6552 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6553 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6554 void (*detach_aio_context)(void *opaque), void *opaque)
6556 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6557 *ban = (BdrvAioNotifier){
6558 .attached_aio_context = attached_aio_context,
6559 .detach_aio_context = detach_aio_context,
6560 .opaque = opaque
6563 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6566 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6567 void (*attached_aio_context)(AioContext *,
6568 void *),
6569 void (*detach_aio_context)(void *),
6570 void *opaque)
6572 BdrvAioNotifier *ban, *ban_next;
6574 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6575 if (ban->attached_aio_context == attached_aio_context &&
6576 ban->detach_aio_context == detach_aio_context &&
6577 ban->opaque == opaque &&
6578 ban->deleted == false)
6580 if (bs->walking_aio_notifiers) {
6581 ban->deleted = true;
6582 } else {
6583 bdrv_do_remove_aio_context_notifier(ban);
6585 return;
6589 abort();
6592 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6593 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6594 Error **errp)
6596 if (!bs->drv) {
6597 error_setg(errp, "Node is ejected");
6598 return -ENOMEDIUM;
6600 if (!bs->drv->bdrv_amend_options) {
6601 error_setg(errp, "Block driver '%s' does not support option amendment",
6602 bs->drv->format_name);
6603 return -ENOTSUP;
6605 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6609 * This function checks whether the given @to_replace is allowed to be
6610 * replaced by a node that always shows the same data as @bs. This is
6611 * used for example to verify whether the mirror job can replace
6612 * @to_replace by the target mirrored from @bs.
6613 * To be replaceable, @bs and @to_replace may either be guaranteed to
6614 * always show the same data (because they are only connected through
6615 * filters), or some driver may allow replacing one of its children
6616 * because it can guarantee that this child's data is not visible at
6617 * all (for example, for dissenting quorum children that have no other
6618 * parents).
6620 bool bdrv_recurse_can_replace(BlockDriverState *bs,
6621 BlockDriverState *to_replace)
6623 if (!bs || !bs->drv) {
6624 return false;
6627 if (bs == to_replace) {
6628 return true;
6631 /* See what the driver can do */
6632 if (bs->drv->bdrv_recurse_can_replace) {
6633 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6636 /* For filters without an own implementation, we can recurse on our own */
6637 if (bs->drv->is_filter) {
6638 BdrvChild *child = bs->file ?: bs->backing;
6639 return bdrv_recurse_can_replace(child->bs, to_replace);
6642 /* Safe default */
6643 return false;
6647 * Check whether the given @node_name can be replaced by a node that
6648 * has the same data as @parent_bs. If so, return @node_name's BDS;
6649 * NULL otherwise.
6651 * @node_name must be a (recursive) *child of @parent_bs (or this
6652 * function will return NULL).
6654 * The result (whether the node can be replaced or not) is only valid
6655 * for as long as no graph or permission changes occur.
6657 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6658 const char *node_name, Error **errp)
6660 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
6661 AioContext *aio_context;
6663 if (!to_replace_bs) {
6664 error_setg(errp, "Node name '%s' not found", node_name);
6665 return NULL;
6668 aio_context = bdrv_get_aio_context(to_replace_bs);
6669 aio_context_acquire(aio_context);
6671 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
6672 to_replace_bs = NULL;
6673 goto out;
6676 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6677 * most non filter in order to prevent data corruption.
6678 * Another benefit is that this tests exclude backing files which are
6679 * blocked by the backing blockers.
6681 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6682 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6683 "because it cannot be guaranteed that doing so would not "
6684 "lead to an abrupt change of visible data",
6685 node_name, parent_bs->node_name);
6686 to_replace_bs = NULL;
6687 goto out;
6690 out:
6691 aio_context_release(aio_context);
6692 return to_replace_bs;
6696 * Iterates through the list of runtime option keys that are said to
6697 * be "strong" for a BDS. An option is called "strong" if it changes
6698 * a BDS's data. For example, the null block driver's "size" and
6699 * "read-zeroes" options are strong, but its "latency-ns" option is
6700 * not.
6702 * If a key returned by this function ends with a dot, all options
6703 * starting with that prefix are strong.
6705 static const char *const *strong_options(BlockDriverState *bs,
6706 const char *const *curopt)
6708 static const char *const global_options[] = {
6709 "driver", "filename", NULL
6712 if (!curopt) {
6713 return &global_options[0];
6716 curopt++;
6717 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6718 curopt = bs->drv->strong_runtime_opts;
6721 return (curopt && *curopt) ? curopt : NULL;
6725 * Copies all strong runtime options from bs->options to the given
6726 * QDict. The set of strong option keys is determined by invoking
6727 * strong_options().
6729 * Returns true iff any strong option was present in bs->options (and
6730 * thus copied to the target QDict) with the exception of "filename"
6731 * and "driver". The caller is expected to use this value to decide
6732 * whether the existence of strong options prevents the generation of
6733 * a plain filename.
6735 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6737 bool found_any = false;
6738 const char *const *option_name = NULL;
6740 if (!bs->drv) {
6741 return false;
6744 while ((option_name = strong_options(bs, option_name))) {
6745 bool option_given = false;
6747 assert(strlen(*option_name) > 0);
6748 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6749 QObject *entry = qdict_get(bs->options, *option_name);
6750 if (!entry) {
6751 continue;
6754 qdict_put_obj(d, *option_name, qobject_ref(entry));
6755 option_given = true;
6756 } else {
6757 const QDictEntry *entry;
6758 for (entry = qdict_first(bs->options); entry;
6759 entry = qdict_next(bs->options, entry))
6761 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6762 qdict_put_obj(d, qdict_entry_key(entry),
6763 qobject_ref(qdict_entry_value(entry)));
6764 option_given = true;
6769 /* While "driver" and "filename" need to be included in a JSON filename,
6770 * their existence does not prohibit generation of a plain filename. */
6771 if (!found_any && option_given &&
6772 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6774 found_any = true;
6778 if (!qdict_haskey(d, "driver")) {
6779 /* Drivers created with bdrv_new_open_driver() may not have a
6780 * @driver option. Add it here. */
6781 qdict_put_str(d, "driver", bs->drv->format_name);
6784 return found_any;
6787 /* Note: This function may return false positives; it may return true
6788 * even if opening the backing file specified by bs's image header
6789 * would result in exactly bs->backing. */
6790 static bool bdrv_backing_overridden(BlockDriverState *bs)
6792 if (bs->backing) {
6793 return strcmp(bs->auto_backing_file,
6794 bs->backing->bs->filename);
6795 } else {
6796 /* No backing BDS, so if the image header reports any backing
6797 * file, it must have been suppressed */
6798 return bs->auto_backing_file[0] != '\0';
6802 /* Updates the following BDS fields:
6803 * - exact_filename: A filename which may be used for opening a block device
6804 * which (mostly) equals the given BDS (even without any
6805 * other options; so reading and writing must return the same
6806 * results, but caching etc. may be different)
6807 * - full_open_options: Options which, when given when opening a block device
6808 * (without a filename), result in a BDS (mostly)
6809 * equalling the given one
6810 * - filename: If exact_filename is set, it is copied here. Otherwise,
6811 * full_open_options is converted to a JSON object, prefixed with
6812 * "json:" (for use through the JSON pseudo protocol) and put here.
6814 void bdrv_refresh_filename(BlockDriverState *bs)
6816 BlockDriver *drv = bs->drv;
6817 BdrvChild *child;
6818 QDict *opts;
6819 bool backing_overridden;
6820 bool generate_json_filename; /* Whether our default implementation should
6821 fill exact_filename (false) or not (true) */
6823 if (!drv) {
6824 return;
6827 /* This BDS's file name may depend on any of its children's file names, so
6828 * refresh those first */
6829 QLIST_FOREACH(child, &bs->children, next) {
6830 bdrv_refresh_filename(child->bs);
6833 if (bs->implicit) {
6834 /* For implicit nodes, just copy everything from the single child */
6835 child = QLIST_FIRST(&bs->children);
6836 assert(QLIST_NEXT(child, next) == NULL);
6838 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6839 child->bs->exact_filename);
6840 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6842 qobject_unref(bs->full_open_options);
6843 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6845 return;
6848 backing_overridden = bdrv_backing_overridden(bs);
6850 if (bs->open_flags & BDRV_O_NO_IO) {
6851 /* Without I/O, the backing file does not change anything.
6852 * Therefore, in such a case (primarily qemu-img), we can
6853 * pretend the backing file has not been overridden even if
6854 * it technically has been. */
6855 backing_overridden = false;
6858 /* Gather the options QDict */
6859 opts = qdict_new();
6860 generate_json_filename = append_strong_runtime_options(opts, bs);
6861 generate_json_filename |= backing_overridden;
6863 if (drv->bdrv_gather_child_options) {
6864 /* Some block drivers may not want to present all of their children's
6865 * options, or name them differently from BdrvChild.name */
6866 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6867 } else {
6868 QLIST_FOREACH(child, &bs->children, next) {
6869 if (child == bs->backing && !backing_overridden) {
6870 /* We can skip the backing BDS if it has not been overridden */
6871 continue;
6874 qdict_put(opts, child->name,
6875 qobject_ref(child->bs->full_open_options));
6878 if (backing_overridden && !bs->backing) {
6879 /* Force no backing file */
6880 qdict_put_null(opts, "backing");
6884 qobject_unref(bs->full_open_options);
6885 bs->full_open_options = opts;
6887 if (drv->bdrv_refresh_filename) {
6888 /* Obsolete information is of no use here, so drop the old file name
6889 * information before refreshing it */
6890 bs->exact_filename[0] = '\0';
6892 drv->bdrv_refresh_filename(bs);
6893 } else if (bs->file) {
6894 /* Try to reconstruct valid information from the underlying file */
6896 bs->exact_filename[0] = '\0';
6899 * We can use the underlying file's filename if:
6900 * - it has a filename,
6901 * - the file is a protocol BDS, and
6902 * - opening that file (as this BDS's format) will automatically create
6903 * the BDS tree we have right now, that is:
6904 * - the user did not significantly change this BDS's behavior with
6905 * some explicit (strong) options
6906 * - no non-file child of this BDS has been overridden by the user
6907 * Both of these conditions are represented by generate_json_filename.
6909 if (bs->file->bs->exact_filename[0] &&
6910 bs->file->bs->drv->bdrv_file_open &&
6911 !generate_json_filename)
6913 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6917 if (bs->exact_filename[0]) {
6918 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
6919 } else {
6920 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6921 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6922 qstring_get_str(json));
6923 qobject_unref(json);
6927 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6929 BlockDriver *drv = bs->drv;
6931 if (!drv) {
6932 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6933 return NULL;
6936 if (drv->bdrv_dirname) {
6937 return drv->bdrv_dirname(bs, errp);
6940 if (bs->file) {
6941 return bdrv_dirname(bs->file->bs, errp);
6944 bdrv_refresh_filename(bs);
6945 if (bs->exact_filename[0] != '\0') {
6946 return path_combine(bs->exact_filename, "");
6949 error_setg(errp, "Cannot generate a base directory for %s nodes",
6950 drv->format_name);
6951 return NULL;
6955 * Hot add/remove a BDS's child. So the user can take a child offline when
6956 * it is broken and take a new child online
6958 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6959 Error **errp)
6962 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6963 error_setg(errp, "The node %s does not support adding a child",
6964 bdrv_get_device_or_node_name(parent_bs));
6965 return;
6968 if (!QLIST_EMPTY(&child_bs->parents)) {
6969 error_setg(errp, "The node %s already has a parent",
6970 child_bs->node_name);
6971 return;
6974 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6977 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6979 BdrvChild *tmp;
6981 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6982 error_setg(errp, "The node %s does not support removing a child",
6983 bdrv_get_device_or_node_name(parent_bs));
6984 return;
6987 QLIST_FOREACH(tmp, &parent_bs->children, next) {
6988 if (tmp == child) {
6989 break;
6993 if (!tmp) {
6994 error_setg(errp, "The node %s does not have a child named %s",
6995 bdrv_get_device_or_node_name(parent_bs),
6996 bdrv_get_device_or_node_name(child->bs));
6997 return;
7000 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7003 int bdrv_make_empty(BdrvChild *c, Error **errp)
7005 BlockDriver *drv = c->bs->drv;
7006 int ret;
7008 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7010 if (!drv->bdrv_make_empty) {
7011 error_setg(errp, "%s does not support emptying nodes",
7012 drv->format_name);
7013 return -ENOTSUP;
7016 ret = drv->bdrv_make_empty(c->bs);
7017 if (ret < 0) {
7018 error_setg_errno(errp, -ret, "Failed to empty %s",
7019 c->bs->filename);
7020 return ret;
7023 return 0;