block: Unify bdrv_child_cb_detach()
[qemu.git] / block.c
blobf63417c06d8cf2374052a9bbcfa24bb346d78fb2
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,
1176 * Returns the options and flags that bs->file should get if the use of formats
1177 * (and not only protocols) is permitted for it, based on the given options and
1178 * flags for the parent BDS
1180 static void bdrv_inherited_fmt_options(BdrvChildRole role,
1181 bool parent_is_format,
1182 int *child_flags, QDict *child_options,
1183 int parent_flags, QDict *parent_options)
1185 bdrv_inherited_options(BDRV_CHILD_DATA, false,
1186 child_flags, child_options,
1187 parent_flags, parent_options);
1190 const BdrvChildClass child_format = {
1191 .parent_is_bds = true,
1192 .get_parent_desc = bdrv_child_get_parent_desc,
1193 .inherit_options = bdrv_inherited_fmt_options,
1194 .drained_begin = bdrv_child_cb_drained_begin,
1195 .drained_poll = bdrv_child_cb_drained_poll,
1196 .drained_end = bdrv_child_cb_drained_end,
1197 .attach = bdrv_child_cb_attach,
1198 .detach = bdrv_child_cb_detach,
1199 .inactivate = bdrv_child_cb_inactivate,
1200 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1201 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1204 static void bdrv_backing_attach(BdrvChild *c)
1206 BlockDriverState *parent = c->opaque;
1207 BlockDriverState *backing_hd = c->bs;
1209 assert(!parent->backing_blocker);
1210 error_setg(&parent->backing_blocker,
1211 "node is used as backing hd of '%s'",
1212 bdrv_get_device_or_node_name(parent));
1214 bdrv_refresh_filename(backing_hd);
1216 parent->open_flags &= ~BDRV_O_NO_BACKING;
1217 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1218 backing_hd->filename);
1219 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1220 backing_hd->drv ? backing_hd->drv->format_name : "");
1222 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1223 /* Otherwise we won't be able to commit or stream */
1224 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1225 parent->backing_blocker);
1226 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1227 parent->backing_blocker);
1229 * We do backup in 3 ways:
1230 * 1. drive backup
1231 * The target bs is new opened, and the source is top BDS
1232 * 2. blockdev backup
1233 * Both the source and the target are top BDSes.
1234 * 3. internal backup(used for block replication)
1235 * Both the source and the target are backing file
1237 * In case 1 and 2, neither the source nor the target is the backing file.
1238 * In case 3, we will block the top BDS, so there is only one block job
1239 * for the top BDS and its backing chain.
1241 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1242 parent->backing_blocker);
1243 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1244 parent->backing_blocker);
1247 /* XXX: Will be removed along with child_backing */
1248 static void bdrv_child_cb_attach_backing(BdrvChild *c)
1250 if (!(c->role & BDRV_CHILD_COW)) {
1251 bdrv_backing_attach(c);
1253 bdrv_child_cb_attach(c);
1256 static void bdrv_backing_detach(BdrvChild *c)
1258 BlockDriverState *parent = c->opaque;
1260 assert(parent->backing_blocker);
1261 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1262 error_free(parent->backing_blocker);
1263 parent->backing_blocker = NULL;
1266 /* XXX: Will be removed along with child_backing */
1267 static void bdrv_child_cb_detach_backing(BdrvChild *c)
1269 if (!(c->role & BDRV_CHILD_COW)) {
1270 bdrv_backing_detach(c);
1272 bdrv_child_cb_detach(c);
1276 * Returns the options and flags that bs->backing should get, based on the
1277 * given options and flags for the parent BDS
1279 static void bdrv_backing_options(BdrvChildRole role, bool parent_is_format,
1280 int *child_flags, QDict *child_options,
1281 int parent_flags, QDict *parent_options)
1283 bdrv_inherited_options(BDRV_CHILD_COW, true,
1284 child_flags, child_options,
1285 parent_flags, parent_options);
1288 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1289 const char *filename, Error **errp)
1291 BlockDriverState *parent = c->opaque;
1292 bool read_only = bdrv_is_read_only(parent);
1293 int ret;
1295 if (read_only) {
1296 ret = bdrv_reopen_set_read_only(parent, false, errp);
1297 if (ret < 0) {
1298 return ret;
1302 ret = bdrv_change_backing_file(parent, filename,
1303 base->drv ? base->drv->format_name : "");
1304 if (ret < 0) {
1305 error_setg_errno(errp, -ret, "Could not update backing file link");
1308 if (read_only) {
1309 bdrv_reopen_set_read_only(parent, true, NULL);
1312 return ret;
1315 const BdrvChildClass child_backing = {
1316 .parent_is_bds = true,
1317 .get_parent_desc = bdrv_child_get_parent_desc,
1318 .attach = bdrv_child_cb_attach_backing,
1319 .detach = bdrv_child_cb_detach_backing,
1320 .inherit_options = bdrv_backing_options,
1321 .drained_begin = bdrv_child_cb_drained_begin,
1322 .drained_poll = bdrv_child_cb_drained_poll,
1323 .drained_end = bdrv_child_cb_drained_end,
1324 .inactivate = bdrv_child_cb_inactivate,
1325 .update_filename = bdrv_backing_update_filename,
1326 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1327 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1331 * Returns the options and flags that a generic child of a BDS should
1332 * get, based on the given options and flags for the parent BDS.
1334 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1335 int *child_flags, QDict *child_options,
1336 int parent_flags, QDict *parent_options)
1338 int flags = parent_flags;
1341 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1342 * Generally, the question to answer is: Should this child be
1343 * format-probed by default?
1347 * Pure and non-filtered data children of non-format nodes should
1348 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1349 * set). This only affects a very limited set of drivers (namely
1350 * quorum and blkverify when this comment was written).
1351 * Force-clear BDRV_O_PROTOCOL then.
1353 if (!parent_is_format &&
1354 (role & BDRV_CHILD_DATA) &&
1355 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1357 flags &= ~BDRV_O_PROTOCOL;
1361 * All children of format nodes (except for COW children) and all
1362 * metadata children in general should never be format-probed.
1363 * Force-set BDRV_O_PROTOCOL then.
1365 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1366 (role & BDRV_CHILD_METADATA))
1368 flags |= BDRV_O_PROTOCOL;
1372 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1373 * the parent.
1375 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1376 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1377 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1379 if (role & BDRV_CHILD_COW) {
1380 /* backing files are opened read-only by default */
1381 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1382 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1383 } else {
1384 /* Inherit the read-only option from the parent if it's not set */
1385 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1386 qdict_copy_default(child_options, parent_options,
1387 BDRV_OPT_AUTO_READ_ONLY);
1391 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1392 * can default to enable it on lower layers regardless of the
1393 * parent option.
1395 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1397 /* Clear flags that only apply to the top layer */
1398 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1400 if (role & BDRV_CHILD_METADATA) {
1401 flags &= ~BDRV_O_NO_IO;
1403 if (role & BDRV_CHILD_COW) {
1404 flags &= ~BDRV_O_TEMPORARY;
1407 *child_flags = flags;
1410 static void bdrv_child_cb_attach(BdrvChild *child)
1412 BlockDriverState *bs = child->opaque;
1414 if (child->role & BDRV_CHILD_COW) {
1415 bdrv_backing_attach(child);
1418 bdrv_apply_subtree_drain(child, bs);
1421 static void bdrv_child_cb_detach(BdrvChild *child)
1423 BlockDriverState *bs = child->opaque;
1425 if (child->role & BDRV_CHILD_COW) {
1426 bdrv_backing_detach(child);
1429 bdrv_unapply_subtree_drain(child, bs);
1432 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1434 int open_flags = flags;
1437 * Clear flags that are internal to the block layer before opening the
1438 * image.
1440 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1442 return open_flags;
1445 static void update_flags_from_options(int *flags, QemuOpts *opts)
1447 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1449 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1450 *flags |= BDRV_O_NO_FLUSH;
1453 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1454 *flags |= BDRV_O_NOCACHE;
1457 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1458 *flags |= BDRV_O_RDWR;
1461 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1462 *flags |= BDRV_O_AUTO_RDONLY;
1466 static void update_options_from_flags(QDict *options, int flags)
1468 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1469 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1471 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1472 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1473 flags & BDRV_O_NO_FLUSH);
1475 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1476 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1478 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1479 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1480 flags & BDRV_O_AUTO_RDONLY);
1484 static void bdrv_assign_node_name(BlockDriverState *bs,
1485 const char *node_name,
1486 Error **errp)
1488 char *gen_node_name = NULL;
1490 if (!node_name) {
1491 node_name = gen_node_name = id_generate(ID_BLOCK);
1492 } else if (!id_wellformed(node_name)) {
1494 * Check for empty string or invalid characters, but not if it is
1495 * generated (generated names use characters not available to the user)
1497 error_setg(errp, "Invalid node name");
1498 return;
1501 /* takes care of avoiding namespaces collisions */
1502 if (blk_by_name(node_name)) {
1503 error_setg(errp, "node-name=%s is conflicting with a device id",
1504 node_name);
1505 goto out;
1508 /* takes care of avoiding duplicates node names */
1509 if (bdrv_find_node(node_name)) {
1510 error_setg(errp, "Duplicate node name");
1511 goto out;
1514 /* Make sure that the node name isn't truncated */
1515 if (strlen(node_name) >= sizeof(bs->node_name)) {
1516 error_setg(errp, "Node name too long");
1517 goto out;
1520 /* copy node name into the bs and insert it into the graph list */
1521 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1522 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1523 out:
1524 g_free(gen_node_name);
1527 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1528 const char *node_name, QDict *options,
1529 int open_flags, Error **errp)
1531 Error *local_err = NULL;
1532 int i, ret;
1534 bdrv_assign_node_name(bs, node_name, &local_err);
1535 if (local_err) {
1536 error_propagate(errp, local_err);
1537 return -EINVAL;
1540 bs->drv = drv;
1541 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1542 bs->opaque = g_malloc0(drv->instance_size);
1544 if (drv->bdrv_file_open) {
1545 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1546 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1547 } else if (drv->bdrv_open) {
1548 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1549 } else {
1550 ret = 0;
1553 if (ret < 0) {
1554 if (local_err) {
1555 error_propagate(errp, local_err);
1556 } else if (bs->filename[0]) {
1557 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1558 } else {
1559 error_setg_errno(errp, -ret, "Could not open image");
1561 goto open_failed;
1564 ret = refresh_total_sectors(bs, bs->total_sectors);
1565 if (ret < 0) {
1566 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1567 return ret;
1570 bdrv_refresh_limits(bs, &local_err);
1571 if (local_err) {
1572 error_propagate(errp, local_err);
1573 return -EINVAL;
1576 assert(bdrv_opt_mem_align(bs) != 0);
1577 assert(bdrv_min_mem_align(bs) != 0);
1578 assert(is_power_of_2(bs->bl.request_alignment));
1580 for (i = 0; i < bs->quiesce_counter; i++) {
1581 if (drv->bdrv_co_drain_begin) {
1582 drv->bdrv_co_drain_begin(bs);
1586 return 0;
1587 open_failed:
1588 bs->drv = NULL;
1589 if (bs->file != NULL) {
1590 bdrv_unref_child(bs, bs->file);
1591 bs->file = NULL;
1593 g_free(bs->opaque);
1594 bs->opaque = NULL;
1595 return ret;
1598 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1599 int flags, Error **errp)
1601 BlockDriverState *bs;
1602 int ret;
1604 bs = bdrv_new();
1605 bs->open_flags = flags;
1606 bs->explicit_options = qdict_new();
1607 bs->options = qdict_new();
1608 bs->opaque = NULL;
1610 update_options_from_flags(bs->options, flags);
1612 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1613 if (ret < 0) {
1614 qobject_unref(bs->explicit_options);
1615 bs->explicit_options = NULL;
1616 qobject_unref(bs->options);
1617 bs->options = NULL;
1618 bdrv_unref(bs);
1619 return NULL;
1622 return bs;
1625 QemuOptsList bdrv_runtime_opts = {
1626 .name = "bdrv_common",
1627 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1628 .desc = {
1630 .name = "node-name",
1631 .type = QEMU_OPT_STRING,
1632 .help = "Node name of the block device node",
1635 .name = "driver",
1636 .type = QEMU_OPT_STRING,
1637 .help = "Block driver to use for the node",
1640 .name = BDRV_OPT_CACHE_DIRECT,
1641 .type = QEMU_OPT_BOOL,
1642 .help = "Bypass software writeback cache on the host",
1645 .name = BDRV_OPT_CACHE_NO_FLUSH,
1646 .type = QEMU_OPT_BOOL,
1647 .help = "Ignore flush requests",
1650 .name = BDRV_OPT_READ_ONLY,
1651 .type = QEMU_OPT_BOOL,
1652 .help = "Node is opened in read-only mode",
1655 .name = BDRV_OPT_AUTO_READ_ONLY,
1656 .type = QEMU_OPT_BOOL,
1657 .help = "Node can become read-only if opening read-write fails",
1660 .name = "detect-zeroes",
1661 .type = QEMU_OPT_STRING,
1662 .help = "try to optimize zero writes (off, on, unmap)",
1665 .name = BDRV_OPT_DISCARD,
1666 .type = QEMU_OPT_STRING,
1667 .help = "discard operation (ignore/off, unmap/on)",
1670 .name = BDRV_OPT_FORCE_SHARE,
1671 .type = QEMU_OPT_BOOL,
1672 .help = "always accept other writers (default: off)",
1674 { /* end of list */ }
1678 QemuOptsList bdrv_create_opts_simple = {
1679 .name = "simple-create-opts",
1680 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1681 .desc = {
1683 .name = BLOCK_OPT_SIZE,
1684 .type = QEMU_OPT_SIZE,
1685 .help = "Virtual disk size"
1688 .name = BLOCK_OPT_PREALLOC,
1689 .type = QEMU_OPT_STRING,
1690 .help = "Preallocation mode (allowed values: off)"
1692 { /* end of list */ }
1697 * Common part for opening disk images and files
1699 * Removes all processed options from *options.
1701 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1702 QDict *options, Error **errp)
1704 int ret, open_flags;
1705 const char *filename;
1706 const char *driver_name = NULL;
1707 const char *node_name = NULL;
1708 const char *discard;
1709 QemuOpts *opts;
1710 BlockDriver *drv;
1711 Error *local_err = NULL;
1713 assert(bs->file == NULL);
1714 assert(options != NULL && bs->options != options);
1716 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1717 qemu_opts_absorb_qdict(opts, options, &local_err);
1718 if (local_err) {
1719 error_propagate(errp, local_err);
1720 ret = -EINVAL;
1721 goto fail_opts;
1724 update_flags_from_options(&bs->open_flags, opts);
1726 driver_name = qemu_opt_get(opts, "driver");
1727 drv = bdrv_find_format(driver_name);
1728 assert(drv != NULL);
1730 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1732 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1733 error_setg(errp,
1734 BDRV_OPT_FORCE_SHARE
1735 "=on can only be used with read-only images");
1736 ret = -EINVAL;
1737 goto fail_opts;
1740 if (file != NULL) {
1741 bdrv_refresh_filename(blk_bs(file));
1742 filename = blk_bs(file)->filename;
1743 } else {
1745 * Caution: while qdict_get_try_str() is fine, getting
1746 * non-string types would require more care. When @options
1747 * come from -blockdev or blockdev_add, its members are typed
1748 * according to the QAPI schema, but when they come from
1749 * -drive, they're all QString.
1751 filename = qdict_get_try_str(options, "filename");
1754 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1755 error_setg(errp, "The '%s' block driver requires a file name",
1756 drv->format_name);
1757 ret = -EINVAL;
1758 goto fail_opts;
1761 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1762 drv->format_name);
1764 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1766 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1767 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1768 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1769 } else {
1770 ret = -ENOTSUP;
1772 if (ret < 0) {
1773 error_setg(errp,
1774 !bs->read_only && bdrv_is_whitelisted(drv, true)
1775 ? "Driver '%s' can only be used for read-only devices"
1776 : "Driver '%s' is not whitelisted",
1777 drv->format_name);
1778 goto fail_opts;
1782 /* bdrv_new() and bdrv_close() make it so */
1783 assert(atomic_read(&bs->copy_on_read) == 0);
1785 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1786 if (!bs->read_only) {
1787 bdrv_enable_copy_on_read(bs);
1788 } else {
1789 error_setg(errp, "Can't use copy-on-read on read-only device");
1790 ret = -EINVAL;
1791 goto fail_opts;
1795 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1796 if (discard != NULL) {
1797 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1798 error_setg(errp, "Invalid discard option");
1799 ret = -EINVAL;
1800 goto fail_opts;
1804 bs->detect_zeroes =
1805 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1806 if (local_err) {
1807 error_propagate(errp, local_err);
1808 ret = -EINVAL;
1809 goto fail_opts;
1812 if (filename != NULL) {
1813 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1814 } else {
1815 bs->filename[0] = '\0';
1817 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1819 /* Open the image, either directly or using a protocol */
1820 open_flags = bdrv_open_flags(bs, bs->open_flags);
1821 node_name = qemu_opt_get(opts, "node-name");
1823 assert(!drv->bdrv_file_open || file == NULL);
1824 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1825 if (ret < 0) {
1826 goto fail_opts;
1829 qemu_opts_del(opts);
1830 return 0;
1832 fail_opts:
1833 qemu_opts_del(opts);
1834 return ret;
1837 static QDict *parse_json_filename(const char *filename, Error **errp)
1839 QObject *options_obj;
1840 QDict *options;
1841 int ret;
1843 ret = strstart(filename, "json:", &filename);
1844 assert(ret);
1846 options_obj = qobject_from_json(filename, errp);
1847 if (!options_obj) {
1848 error_prepend(errp, "Could not parse the JSON options: ");
1849 return NULL;
1852 options = qobject_to(QDict, options_obj);
1853 if (!options) {
1854 qobject_unref(options_obj);
1855 error_setg(errp, "Invalid JSON object given");
1856 return NULL;
1859 qdict_flatten(options);
1861 return options;
1864 static void parse_json_protocol(QDict *options, const char **pfilename,
1865 Error **errp)
1867 QDict *json_options;
1868 Error *local_err = NULL;
1870 /* Parse json: pseudo-protocol */
1871 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1872 return;
1875 json_options = parse_json_filename(*pfilename, &local_err);
1876 if (local_err) {
1877 error_propagate(errp, local_err);
1878 return;
1881 /* Options given in the filename have lower priority than options
1882 * specified directly */
1883 qdict_join(options, json_options, false);
1884 qobject_unref(json_options);
1885 *pfilename = NULL;
1889 * Fills in default options for opening images and converts the legacy
1890 * filename/flags pair to option QDict entries.
1891 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1892 * block driver has been specified explicitly.
1894 static int bdrv_fill_options(QDict **options, const char *filename,
1895 int *flags, Error **errp)
1897 const char *drvname;
1898 bool protocol = *flags & BDRV_O_PROTOCOL;
1899 bool parse_filename = false;
1900 BlockDriver *drv = NULL;
1901 Error *local_err = NULL;
1904 * Caution: while qdict_get_try_str() is fine, getting non-string
1905 * types would require more care. When @options come from
1906 * -blockdev or blockdev_add, its members are typed according to
1907 * the QAPI schema, but when they come from -drive, they're all
1908 * QString.
1910 drvname = qdict_get_try_str(*options, "driver");
1911 if (drvname) {
1912 drv = bdrv_find_format(drvname);
1913 if (!drv) {
1914 error_setg(errp, "Unknown driver '%s'", drvname);
1915 return -ENOENT;
1917 /* If the user has explicitly specified the driver, this choice should
1918 * override the BDRV_O_PROTOCOL flag */
1919 protocol = drv->bdrv_file_open;
1922 if (protocol) {
1923 *flags |= BDRV_O_PROTOCOL;
1924 } else {
1925 *flags &= ~BDRV_O_PROTOCOL;
1928 /* Translate cache options from flags into options */
1929 update_options_from_flags(*options, *flags);
1931 /* Fetch the file name from the options QDict if necessary */
1932 if (protocol && filename) {
1933 if (!qdict_haskey(*options, "filename")) {
1934 qdict_put_str(*options, "filename", filename);
1935 parse_filename = true;
1936 } else {
1937 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1938 "the same time");
1939 return -EINVAL;
1943 /* Find the right block driver */
1944 /* See cautionary note on accessing @options above */
1945 filename = qdict_get_try_str(*options, "filename");
1947 if (!drvname && protocol) {
1948 if (filename) {
1949 drv = bdrv_find_protocol(filename, parse_filename, errp);
1950 if (!drv) {
1951 return -EINVAL;
1954 drvname = drv->format_name;
1955 qdict_put_str(*options, "driver", drvname);
1956 } else {
1957 error_setg(errp, "Must specify either driver or file");
1958 return -EINVAL;
1962 assert(drv || !protocol);
1964 /* Driver-specific filename parsing */
1965 if (drv && drv->bdrv_parse_filename && parse_filename) {
1966 drv->bdrv_parse_filename(filename, *options, &local_err);
1967 if (local_err) {
1968 error_propagate(errp, local_err);
1969 return -EINVAL;
1972 if (!drv->bdrv_needs_filename) {
1973 qdict_del(*options, "filename");
1977 return 0;
1980 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1981 uint64_t perm, uint64_t shared,
1982 GSList *ignore_children,
1983 bool *tighten_restrictions, Error **errp);
1984 static void bdrv_child_abort_perm_update(BdrvChild *c);
1985 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1987 typedef struct BlockReopenQueueEntry {
1988 bool prepared;
1989 bool perms_checked;
1990 BDRVReopenState state;
1991 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1992 } BlockReopenQueueEntry;
1995 * Return the flags that @bs will have after the reopens in @q have
1996 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1997 * return the current flags.
1999 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2001 BlockReopenQueueEntry *entry;
2003 if (q != NULL) {
2004 QTAILQ_FOREACH(entry, q, entry) {
2005 if (entry->state.bs == bs) {
2006 return entry->state.flags;
2011 return bs->open_flags;
2014 /* Returns whether the image file can be written to after the reopen queue @q
2015 * has been successfully applied, or right now if @q is NULL. */
2016 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2017 BlockReopenQueue *q)
2019 int flags = bdrv_reopen_get_flags(q, bs);
2021 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2025 * Return whether the BDS can be written to. This is not necessarily
2026 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2027 * be written to but do not count as read-only images.
2029 bool bdrv_is_writable(BlockDriverState *bs)
2031 return bdrv_is_writable_after_reopen(bs, NULL);
2034 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2035 BdrvChild *c, const BdrvChildClass *child_class,
2036 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2037 uint64_t parent_perm, uint64_t parent_shared,
2038 uint64_t *nperm, uint64_t *nshared)
2040 assert(bs->drv && bs->drv->bdrv_child_perm);
2041 bs->drv->bdrv_child_perm(bs, c, child_class, role, reopen_queue,
2042 parent_perm, parent_shared,
2043 nperm, nshared);
2044 /* TODO Take force_share from reopen_queue */
2045 if (child_bs && child_bs->force_share) {
2046 *nshared = BLK_PERM_ALL;
2051 * Check whether permissions on this node can be changed in a way that
2052 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2053 * permissions of all its parents. This involves checking whether all necessary
2054 * permission changes to child nodes can be performed.
2056 * Will set *tighten_restrictions to true if and only if new permissions have to
2057 * be taken or currently shared permissions are to be unshared. Otherwise,
2058 * errors are not fatal as long as the caller accepts that the restrictions
2059 * remain tighter than they need to be. The caller still has to abort the
2060 * transaction.
2061 * @tighten_restrictions cannot be used together with @q: When reopening, we may
2062 * encounter fatal errors even though no restrictions are to be tightened. For
2063 * example, changing a node from RW to RO will fail if the WRITE permission is
2064 * to be kept.
2066 * A call to this function must always be followed by a call to bdrv_set_perm()
2067 * or bdrv_abort_perm_update().
2069 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2070 uint64_t cumulative_perms,
2071 uint64_t cumulative_shared_perms,
2072 GSList *ignore_children,
2073 bool *tighten_restrictions, Error **errp)
2075 BlockDriver *drv = bs->drv;
2076 BdrvChild *c;
2077 int ret;
2079 assert(!q || !tighten_restrictions);
2081 if (tighten_restrictions) {
2082 uint64_t current_perms, current_shared;
2083 uint64_t added_perms, removed_shared_perms;
2085 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2087 added_perms = cumulative_perms & ~current_perms;
2088 removed_shared_perms = current_shared & ~cumulative_shared_perms;
2090 *tighten_restrictions = added_perms || removed_shared_perms;
2093 /* Write permissions never work with read-only images */
2094 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2095 !bdrv_is_writable_after_reopen(bs, q))
2097 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2098 error_setg(errp, "Block node is read-only");
2099 } else {
2100 uint64_t current_perms, current_shared;
2101 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2102 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2103 error_setg(errp, "Cannot make block node read-only, there is "
2104 "a writer on it");
2105 } else {
2106 error_setg(errp, "Cannot make block node read-only and create "
2107 "a writer on it");
2111 return -EPERM;
2114 /* Check this node */
2115 if (!drv) {
2116 return 0;
2119 if (drv->bdrv_check_perm) {
2120 return drv->bdrv_check_perm(bs, cumulative_perms,
2121 cumulative_shared_perms, errp);
2124 /* Drivers that never have children can omit .bdrv_child_perm() */
2125 if (!drv->bdrv_child_perm) {
2126 assert(QLIST_EMPTY(&bs->children));
2127 return 0;
2130 /* Check all children */
2131 QLIST_FOREACH(c, &bs->children, next) {
2132 uint64_t cur_perm, cur_shared;
2133 bool child_tighten_restr;
2135 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, q,
2136 cumulative_perms, cumulative_shared_perms,
2137 &cur_perm, &cur_shared);
2138 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
2139 tighten_restrictions ? &child_tighten_restr
2140 : NULL,
2141 errp);
2142 if (tighten_restrictions) {
2143 *tighten_restrictions |= child_tighten_restr;
2145 if (ret < 0) {
2146 return ret;
2150 return 0;
2154 * Notifies drivers that after a previous bdrv_check_perm() call, the
2155 * permission update is not performed and any preparations made for it (e.g.
2156 * taken file locks) need to be undone.
2158 * This function recursively notifies all child nodes.
2160 static void bdrv_abort_perm_update(BlockDriverState *bs)
2162 BlockDriver *drv = bs->drv;
2163 BdrvChild *c;
2165 if (!drv) {
2166 return;
2169 if (drv->bdrv_abort_perm_update) {
2170 drv->bdrv_abort_perm_update(bs);
2173 QLIST_FOREACH(c, &bs->children, next) {
2174 bdrv_child_abort_perm_update(c);
2178 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
2179 uint64_t cumulative_shared_perms)
2181 BlockDriver *drv = bs->drv;
2182 BdrvChild *c;
2184 if (!drv) {
2185 return;
2188 /* Update this node */
2189 if (drv->bdrv_set_perm) {
2190 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2193 /* Drivers that never have children can omit .bdrv_child_perm() */
2194 if (!drv->bdrv_child_perm) {
2195 assert(QLIST_EMPTY(&bs->children));
2196 return;
2199 /* Update all children */
2200 QLIST_FOREACH(c, &bs->children, next) {
2201 uint64_t cur_perm, cur_shared;
2202 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, NULL,
2203 cumulative_perms, cumulative_shared_perms,
2204 &cur_perm, &cur_shared);
2205 bdrv_child_set_perm(c, cur_perm, cur_shared);
2209 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2210 uint64_t *shared_perm)
2212 BdrvChild *c;
2213 uint64_t cumulative_perms = 0;
2214 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2216 QLIST_FOREACH(c, &bs->parents, next_parent) {
2217 cumulative_perms |= c->perm;
2218 cumulative_shared_perms &= c->shared_perm;
2221 *perm = cumulative_perms;
2222 *shared_perm = cumulative_shared_perms;
2225 static char *bdrv_child_user_desc(BdrvChild *c)
2227 if (c->klass->get_parent_desc) {
2228 return c->klass->get_parent_desc(c);
2231 return g_strdup("another user");
2234 char *bdrv_perm_names(uint64_t perm)
2236 struct perm_name {
2237 uint64_t perm;
2238 const char *name;
2239 } permissions[] = {
2240 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2241 { BLK_PERM_WRITE, "write" },
2242 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2243 { BLK_PERM_RESIZE, "resize" },
2244 { BLK_PERM_GRAPH_MOD, "change children" },
2245 { 0, NULL }
2248 GString *result = g_string_sized_new(30);
2249 struct perm_name *p;
2251 for (p = permissions; p->name; p++) {
2252 if (perm & p->perm) {
2253 if (result->len > 0) {
2254 g_string_append(result, ", ");
2256 g_string_append(result, p->name);
2260 return g_string_free(result, FALSE);
2264 * Checks whether a new reference to @bs can be added if the new user requires
2265 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2266 * set, the BdrvChild objects in this list are ignored in the calculations;
2267 * this allows checking permission updates for an existing reference.
2269 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2271 * Needs to be followed by a call to either bdrv_set_perm() or
2272 * bdrv_abort_perm_update(). */
2273 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2274 uint64_t new_used_perm,
2275 uint64_t new_shared_perm,
2276 GSList *ignore_children,
2277 bool *tighten_restrictions,
2278 Error **errp)
2280 BdrvChild *c;
2281 uint64_t cumulative_perms = new_used_perm;
2282 uint64_t cumulative_shared_perms = new_shared_perm;
2284 assert(!q || !tighten_restrictions);
2286 /* There is no reason why anyone couldn't tolerate write_unchanged */
2287 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2289 QLIST_FOREACH(c, &bs->parents, next_parent) {
2290 if (g_slist_find(ignore_children, c)) {
2291 continue;
2294 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2295 char *user = bdrv_child_user_desc(c);
2296 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
2298 if (tighten_restrictions) {
2299 *tighten_restrictions = true;
2302 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2303 "allow '%s' on %s",
2304 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2305 g_free(user);
2306 g_free(perm_names);
2307 return -EPERM;
2310 if ((c->perm & new_shared_perm) != c->perm) {
2311 char *user = bdrv_child_user_desc(c);
2312 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
2314 if (tighten_restrictions) {
2315 *tighten_restrictions = true;
2318 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2319 "'%s' on %s",
2320 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2321 g_free(user);
2322 g_free(perm_names);
2323 return -EPERM;
2326 cumulative_perms |= c->perm;
2327 cumulative_shared_perms &= c->shared_perm;
2330 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
2331 ignore_children, tighten_restrictions, errp);
2334 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2335 * bdrv_child_abort_perm_update(). */
2336 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2337 uint64_t perm, uint64_t shared,
2338 GSList *ignore_children,
2339 bool *tighten_restrictions, Error **errp)
2341 int ret;
2343 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
2344 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2345 tighten_restrictions, errp);
2346 g_slist_free(ignore_children);
2348 if (ret < 0) {
2349 return ret;
2352 if (!c->has_backup_perm) {
2353 c->has_backup_perm = true;
2354 c->backup_perm = c->perm;
2355 c->backup_shared_perm = c->shared_perm;
2358 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2359 * same child twice during check_perm procedure
2362 c->perm = perm;
2363 c->shared_perm = shared;
2365 return 0;
2368 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
2370 uint64_t cumulative_perms, cumulative_shared_perms;
2372 c->has_backup_perm = false;
2374 c->perm = perm;
2375 c->shared_perm = shared;
2377 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2378 &cumulative_shared_perms);
2379 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2382 static void bdrv_child_abort_perm_update(BdrvChild *c)
2384 if (c->has_backup_perm) {
2385 c->perm = c->backup_perm;
2386 c->shared_perm = c->backup_shared_perm;
2387 c->has_backup_perm = false;
2390 bdrv_abort_perm_update(c->bs);
2393 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2394 Error **errp)
2396 Error *local_err = NULL;
2397 int ret;
2398 bool tighten_restrictions;
2400 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2401 &tighten_restrictions, &local_err);
2402 if (ret < 0) {
2403 bdrv_child_abort_perm_update(c);
2404 if (tighten_restrictions) {
2405 error_propagate(errp, local_err);
2406 } else {
2408 * Our caller may intend to only loosen restrictions and
2409 * does not expect this function to fail. Errors are not
2410 * fatal in such a case, so we can just hide them from our
2411 * caller.
2413 error_free(local_err);
2414 ret = 0;
2416 return ret;
2419 bdrv_child_set_perm(c, perm, shared);
2421 return 0;
2424 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2426 uint64_t parent_perms, parent_shared;
2427 uint64_t perms, shared;
2429 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2430 bdrv_child_perm(bs, c->bs, c, c->klass, c->role, NULL,
2431 parent_perms, parent_shared, &perms, &shared);
2433 return bdrv_child_try_set_perm(c, perms, shared, errp);
2436 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2437 const BdrvChildClass *child_class,
2438 BdrvChildRole role,
2439 BlockReopenQueue *reopen_queue,
2440 uint64_t perm, uint64_t shared,
2441 uint64_t *nperm, uint64_t *nshared)
2443 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2444 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2447 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
2448 const BdrvChildClass *child_class,
2449 BdrvChildRole role,
2450 BlockReopenQueue *reopen_queue,
2451 uint64_t perm, uint64_t shared,
2452 uint64_t *nperm, uint64_t *nshared)
2454 bool backing = (child_class == &child_backing);
2455 assert(child_class == &child_backing || child_class == &child_file);
2457 if (!backing) {
2458 int flags = bdrv_reopen_get_flags(reopen_queue, bs);
2460 /* Apart from the modifications below, the same permissions are
2461 * forwarded and left alone as for filters */
2462 bdrv_filter_default_perms(bs, c, child_class, role, reopen_queue,
2463 perm, shared, &perm, &shared);
2465 /* Format drivers may touch metadata even if the guest doesn't write */
2466 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2467 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2470 /* bs->file always needs to be consistent because of the metadata. We
2471 * can never allow other users to resize or write to it. */
2472 if (!(flags & BDRV_O_NO_IO)) {
2473 perm |= BLK_PERM_CONSISTENT_READ;
2475 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2476 } else {
2477 /* We want consistent read from backing files if the parent needs it.
2478 * No other operations are performed on backing files. */
2479 perm &= BLK_PERM_CONSISTENT_READ;
2481 /* If the parent can deal with changing data, we're okay with a
2482 * writable and resizable backing file. */
2483 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
2484 if (shared & BLK_PERM_WRITE) {
2485 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2486 } else {
2487 shared = 0;
2490 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2491 BLK_PERM_WRITE_UNCHANGED;
2494 if (bs->open_flags & BDRV_O_INACTIVE) {
2495 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2498 *nperm = perm;
2499 *nshared = shared;
2502 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2504 static const uint64_t permissions[] = {
2505 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2506 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2507 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2508 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2509 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2512 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2513 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2515 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2517 return permissions[qapi_perm];
2520 static void bdrv_replace_child_noperm(BdrvChild *child,
2521 BlockDriverState *new_bs)
2523 BlockDriverState *old_bs = child->bs;
2524 int new_bs_quiesce_counter;
2525 int drain_saldo;
2527 assert(!child->frozen);
2529 if (old_bs && new_bs) {
2530 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2533 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2534 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2537 * If the new child node is drained but the old one was not, flush
2538 * all outstanding requests to the old child node.
2540 while (drain_saldo > 0 && child->klass->drained_begin) {
2541 bdrv_parent_drained_begin_single(child, true);
2542 drain_saldo--;
2545 if (old_bs) {
2546 /* Detach first so that the recursive drain sections coming from @child
2547 * are already gone and we only end the drain sections that came from
2548 * elsewhere. */
2549 if (child->klass->detach) {
2550 child->klass->detach(child);
2552 QLIST_REMOVE(child, next_parent);
2555 child->bs = new_bs;
2557 if (new_bs) {
2558 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2561 * Detaching the old node may have led to the new node's
2562 * quiesce_counter having been decreased. Not a problem, we
2563 * just need to recognize this here and then invoke
2564 * drained_end appropriately more often.
2566 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2567 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2569 /* Attach only after starting new drained sections, so that recursive
2570 * drain sections coming from @child don't get an extra .drained_begin
2571 * callback. */
2572 if (child->klass->attach) {
2573 child->klass->attach(child);
2578 * If the old child node was drained but the new one is not, allow
2579 * requests to come in only after the new node has been attached.
2581 while (drain_saldo < 0 && child->klass->drained_end) {
2582 bdrv_parent_drained_end_single(child);
2583 drain_saldo++;
2588 * Updates @child to change its reference to point to @new_bs, including
2589 * checking and applying the necessary permisson updates both to the old node
2590 * and to @new_bs.
2592 * NULL is passed as @new_bs for removing the reference before freeing @child.
2594 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2595 * function uses bdrv_set_perm() to update the permissions according to the new
2596 * reference that @new_bs gets.
2598 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2600 BlockDriverState *old_bs = child->bs;
2601 uint64_t perm, shared_perm;
2603 bdrv_replace_child_noperm(child, new_bs);
2606 * Start with the new node's permissions. If @new_bs is a (direct
2607 * or indirect) child of @old_bs, we must complete the permission
2608 * update on @new_bs before we loosen the restrictions on @old_bs.
2609 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2610 * updating the permissions of @new_bs, and thus not purely loosen
2611 * restrictions.
2613 if (new_bs) {
2614 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2615 bdrv_set_perm(new_bs, perm, shared_perm);
2618 if (old_bs) {
2619 /* Update permissions for old node. This is guaranteed to succeed
2620 * because we're just taking a parent away, so we're loosening
2621 * restrictions. */
2622 bool tighten_restrictions;
2623 int ret;
2625 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
2626 ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2627 &tighten_restrictions, NULL);
2628 assert(tighten_restrictions == false);
2629 if (ret < 0) {
2630 /* We only tried to loosen restrictions, so errors are not fatal */
2631 bdrv_abort_perm_update(old_bs);
2632 } else {
2633 bdrv_set_perm(old_bs, perm, shared_perm);
2636 /* When the parent requiring a non-default AioContext is removed, the
2637 * node moves back to the main AioContext */
2638 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2643 * This function steals the reference to child_bs from the caller.
2644 * That reference is later dropped by bdrv_root_unref_child().
2646 * On failure NULL is returned, errp is set and the reference to
2647 * child_bs is also dropped.
2649 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2650 * (unless @child_bs is already in @ctx).
2652 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2653 const char *child_name,
2654 const BdrvChildClass *child_class,
2655 BdrvChildRole child_role,
2656 AioContext *ctx,
2657 uint64_t perm, uint64_t shared_perm,
2658 void *opaque, Error **errp)
2660 BdrvChild *child;
2661 Error *local_err = NULL;
2662 int ret;
2664 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2665 errp);
2666 if (ret < 0) {
2667 bdrv_abort_perm_update(child_bs);
2668 bdrv_unref(child_bs);
2669 return NULL;
2672 child = g_new(BdrvChild, 1);
2673 *child = (BdrvChild) {
2674 .bs = NULL,
2675 .name = g_strdup(child_name),
2676 .klass = child_class,
2677 .role = child_role,
2678 .perm = perm,
2679 .shared_perm = shared_perm,
2680 .opaque = opaque,
2683 /* If the AioContexts don't match, first try to move the subtree of
2684 * child_bs into the AioContext of the new parent. If this doesn't work,
2685 * try moving the parent into the AioContext of child_bs instead. */
2686 if (bdrv_get_aio_context(child_bs) != ctx) {
2687 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2688 if (ret < 0 && child_class->can_set_aio_ctx) {
2689 GSList *ignore = g_slist_prepend(NULL, child);
2690 ctx = bdrv_get_aio_context(child_bs);
2691 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2692 error_free(local_err);
2693 ret = 0;
2694 g_slist_free(ignore);
2695 ignore = g_slist_prepend(NULL, child);
2696 child_class->set_aio_ctx(child, ctx, &ignore);
2698 g_slist_free(ignore);
2700 if (ret < 0) {
2701 error_propagate(errp, local_err);
2702 g_free(child);
2703 bdrv_abort_perm_update(child_bs);
2704 bdrv_unref(child_bs);
2705 return NULL;
2709 /* This performs the matching bdrv_set_perm() for the above check. */
2710 bdrv_replace_child(child, child_bs);
2712 return child;
2716 * This function transfers the reference to child_bs from the caller
2717 * to parent_bs. That reference is later dropped by parent_bs on
2718 * bdrv_close() or if someone calls bdrv_unref_child().
2720 * On failure NULL is returned, errp is set and the reference to
2721 * child_bs is also dropped.
2723 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2724 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2726 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2727 BlockDriverState *child_bs,
2728 const char *child_name,
2729 const BdrvChildClass *child_class,
2730 BdrvChildRole child_role,
2731 Error **errp)
2733 BdrvChild *child;
2734 uint64_t perm, shared_perm;
2736 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2738 assert(parent_bs->drv);
2739 bdrv_child_perm(parent_bs, child_bs, NULL, child_class, child_role, NULL,
2740 perm, shared_perm, &perm, &shared_perm);
2742 child = bdrv_root_attach_child(child_bs, child_name, child_class,
2743 child_role, bdrv_get_aio_context(parent_bs),
2744 perm, shared_perm, parent_bs, errp);
2745 if (child == NULL) {
2746 return NULL;
2749 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2750 return child;
2753 static void bdrv_detach_child(BdrvChild *child)
2755 QLIST_SAFE_REMOVE(child, next);
2757 bdrv_replace_child(child, NULL);
2759 g_free(child->name);
2760 g_free(child);
2763 void bdrv_root_unref_child(BdrvChild *child)
2765 BlockDriverState *child_bs;
2767 child_bs = child->bs;
2768 bdrv_detach_child(child);
2769 bdrv_unref(child_bs);
2773 * Clear all inherits_from pointers from children and grandchildren of
2774 * @root that point to @root, where necessary.
2776 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
2778 BdrvChild *c;
2780 if (child->bs->inherits_from == root) {
2782 * Remove inherits_from only when the last reference between root and
2783 * child->bs goes away.
2785 QLIST_FOREACH(c, &root->children, next) {
2786 if (c != child && c->bs == child->bs) {
2787 break;
2790 if (c == NULL) {
2791 child->bs->inherits_from = NULL;
2795 QLIST_FOREACH(c, &child->bs->children, next) {
2796 bdrv_unset_inherits_from(root, c);
2800 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2802 if (child == NULL) {
2803 return;
2806 bdrv_unset_inherits_from(parent, child);
2807 bdrv_root_unref_child(child);
2811 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2813 BdrvChild *c;
2814 QLIST_FOREACH(c, &bs->parents, next_parent) {
2815 if (c->klass->change_media) {
2816 c->klass->change_media(c, load);
2821 /* Return true if you can reach parent going through child->inherits_from
2822 * recursively. If parent or child are NULL, return false */
2823 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2824 BlockDriverState *parent)
2826 while (child && child != parent) {
2827 child = child->inherits_from;
2830 return child != NULL;
2834 * Sets the backing file link of a BDS. A new reference is created; callers
2835 * which don't need their own reference any more must call bdrv_unref().
2837 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2838 Error **errp)
2840 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2841 bdrv_inherits_from_recursive(backing_hd, bs);
2843 if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2844 return;
2847 if (backing_hd) {
2848 bdrv_ref(backing_hd);
2851 if (bs->backing) {
2852 bdrv_unref_child(bs, bs->backing);
2853 bs->backing = NULL;
2856 if (!backing_hd) {
2857 goto out;
2860 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
2861 0, errp);
2862 /* If backing_hd was already part of bs's backing chain, and
2863 * inherits_from pointed recursively to bs then let's update it to
2864 * point directly to bs (else it will become NULL). */
2865 if (bs->backing && update_inherits_from) {
2866 backing_hd->inherits_from = bs;
2869 out:
2870 bdrv_refresh_limits(bs, NULL);
2874 * Opens the backing file for a BlockDriverState if not yet open
2876 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2877 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2878 * itself, all options starting with "${bdref_key}." are considered part of the
2879 * BlockdevRef.
2881 * TODO Can this be unified with bdrv_open_image()?
2883 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2884 const char *bdref_key, Error **errp)
2886 char *backing_filename = NULL;
2887 char *bdref_key_dot;
2888 const char *reference = NULL;
2889 int ret = 0;
2890 bool implicit_backing = false;
2891 BlockDriverState *backing_hd;
2892 QDict *options;
2893 QDict *tmp_parent_options = NULL;
2894 Error *local_err = NULL;
2896 if (bs->backing != NULL) {
2897 goto free_exit;
2900 /* NULL means an empty set of options */
2901 if (parent_options == NULL) {
2902 tmp_parent_options = qdict_new();
2903 parent_options = tmp_parent_options;
2906 bs->open_flags &= ~BDRV_O_NO_BACKING;
2908 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2909 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2910 g_free(bdref_key_dot);
2913 * Caution: while qdict_get_try_str() is fine, getting non-string
2914 * types would require more care. When @parent_options come from
2915 * -blockdev or blockdev_add, its members are typed according to
2916 * the QAPI schema, but when they come from -drive, they're all
2917 * QString.
2919 reference = qdict_get_try_str(parent_options, bdref_key);
2920 if (reference || qdict_haskey(options, "file.filename")) {
2921 /* keep backing_filename NULL */
2922 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2923 qobject_unref(options);
2924 goto free_exit;
2925 } else {
2926 if (qdict_size(options) == 0) {
2927 /* If the user specifies options that do not modify the
2928 * backing file's behavior, we might still consider it the
2929 * implicit backing file. But it's easier this way, and
2930 * just specifying some of the backing BDS's options is
2931 * only possible with -drive anyway (otherwise the QAPI
2932 * schema forces the user to specify everything). */
2933 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2936 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
2937 if (local_err) {
2938 ret = -EINVAL;
2939 error_propagate(errp, local_err);
2940 qobject_unref(options);
2941 goto free_exit;
2945 if (!bs->drv || !bs->drv->supports_backing) {
2946 ret = -EINVAL;
2947 error_setg(errp, "Driver doesn't support backing files");
2948 qobject_unref(options);
2949 goto free_exit;
2952 if (!reference &&
2953 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2954 qdict_put_str(options, "driver", bs->backing_format);
2957 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
2958 &child_backing, 0, errp);
2959 if (!backing_hd) {
2960 bs->open_flags |= BDRV_O_NO_BACKING;
2961 error_prepend(errp, "Could not open backing file: ");
2962 ret = -EINVAL;
2963 goto free_exit;
2966 if (implicit_backing) {
2967 bdrv_refresh_filename(backing_hd);
2968 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2969 backing_hd->filename);
2972 /* Hook up the backing file link; drop our reference, bs owns the
2973 * backing_hd reference now */
2974 bdrv_set_backing_hd(bs, backing_hd, &local_err);
2975 bdrv_unref(backing_hd);
2976 if (local_err) {
2977 error_propagate(errp, local_err);
2978 ret = -EINVAL;
2979 goto free_exit;
2982 qdict_del(parent_options, bdref_key);
2984 free_exit:
2985 g_free(backing_filename);
2986 qobject_unref(tmp_parent_options);
2987 return ret;
2990 static BlockDriverState *
2991 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2992 BlockDriverState *parent, const BdrvChildClass *child_class,
2993 BdrvChildRole child_role, bool allow_none, Error **errp)
2995 BlockDriverState *bs = NULL;
2996 QDict *image_options;
2997 char *bdref_key_dot;
2998 const char *reference;
3000 assert(child_class != NULL);
3002 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3003 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3004 g_free(bdref_key_dot);
3007 * Caution: while qdict_get_try_str() is fine, getting non-string
3008 * types would require more care. When @options come from
3009 * -blockdev or blockdev_add, its members are typed according to
3010 * the QAPI schema, but when they come from -drive, they're all
3011 * QString.
3013 reference = qdict_get_try_str(options, bdref_key);
3014 if (!filename && !reference && !qdict_size(image_options)) {
3015 if (!allow_none) {
3016 error_setg(errp, "A block device must be specified for \"%s\"",
3017 bdref_key);
3019 qobject_unref(image_options);
3020 goto done;
3023 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3024 parent, child_class, child_role, errp);
3025 if (!bs) {
3026 goto done;
3029 done:
3030 qdict_del(options, bdref_key);
3031 return bs;
3035 * Opens a disk image whose options are given as BlockdevRef in another block
3036 * device's options.
3038 * If allow_none is true, no image will be opened if filename is false and no
3039 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3041 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3042 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3043 * itself, all options starting with "${bdref_key}." are considered part of the
3044 * BlockdevRef.
3046 * The BlockdevRef will be removed from the options QDict.
3048 BdrvChild *bdrv_open_child(const char *filename,
3049 QDict *options, const char *bdref_key,
3050 BlockDriverState *parent,
3051 const BdrvChildClass *child_class,
3052 BdrvChildRole child_role,
3053 bool allow_none, Error **errp)
3055 BlockDriverState *bs;
3057 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3058 child_role, allow_none, errp);
3059 if (bs == NULL) {
3060 return NULL;
3063 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3064 errp);
3068 * TODO Future callers may need to specify parent/child_class in order for
3069 * option inheritance to work. Existing callers use it for the root node.
3071 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3073 BlockDriverState *bs = NULL;
3074 QObject *obj = NULL;
3075 QDict *qdict = NULL;
3076 const char *reference = NULL;
3077 Visitor *v = NULL;
3079 if (ref->type == QTYPE_QSTRING) {
3080 reference = ref->u.reference;
3081 } else {
3082 BlockdevOptions *options = &ref->u.definition;
3083 assert(ref->type == QTYPE_QDICT);
3085 v = qobject_output_visitor_new(&obj);
3086 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3087 visit_complete(v, &obj);
3089 qdict = qobject_to(QDict, obj);
3090 qdict_flatten(qdict);
3092 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3093 * compatibility with other callers) rather than what we want as the
3094 * real defaults. Apply the defaults here instead. */
3095 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3096 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3097 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3098 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3102 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3103 obj = NULL;
3104 qobject_unref(obj);
3105 visit_free(v);
3106 return bs;
3109 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3110 int flags,
3111 QDict *snapshot_options,
3112 Error **errp)
3114 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3115 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3116 int64_t total_size;
3117 QemuOpts *opts = NULL;
3118 BlockDriverState *bs_snapshot = NULL;
3119 Error *local_err = NULL;
3120 int ret;
3122 /* if snapshot, we create a temporary backing file and open it
3123 instead of opening 'filename' directly */
3125 /* Get the required size from the image */
3126 total_size = bdrv_getlength(bs);
3127 if (total_size < 0) {
3128 error_setg_errno(errp, -total_size, "Could not get image size");
3129 goto out;
3132 /* Create the temporary image */
3133 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3134 if (ret < 0) {
3135 error_setg_errno(errp, -ret, "Could not get temporary filename");
3136 goto out;
3139 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3140 &error_abort);
3141 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3142 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3143 qemu_opts_del(opts);
3144 if (ret < 0) {
3145 error_prepend(errp, "Could not create temporary overlay '%s': ",
3146 tmp_filename);
3147 goto out;
3150 /* Prepare options QDict for the temporary file */
3151 qdict_put_str(snapshot_options, "file.driver", "file");
3152 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3153 qdict_put_str(snapshot_options, "driver", "qcow2");
3155 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3156 snapshot_options = NULL;
3157 if (!bs_snapshot) {
3158 goto out;
3161 /* bdrv_append() consumes a strong reference to bs_snapshot
3162 * (i.e. it will call bdrv_unref() on it) even on error, so in
3163 * order to be able to return one, we have to increase
3164 * bs_snapshot's refcount here */
3165 bdrv_ref(bs_snapshot);
3166 bdrv_append(bs_snapshot, bs, &local_err);
3167 if (local_err) {
3168 error_propagate(errp, local_err);
3169 bs_snapshot = NULL;
3170 goto out;
3173 out:
3174 qobject_unref(snapshot_options);
3175 g_free(tmp_filename);
3176 return bs_snapshot;
3180 * Opens a disk image (raw, qcow2, vmdk, ...)
3182 * options is a QDict of options to pass to the block drivers, or NULL for an
3183 * empty set of options. The reference to the QDict belongs to the block layer
3184 * after the call (even on failure), so if the caller intends to reuse the
3185 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3187 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3188 * If it is not NULL, the referenced BDS will be reused.
3190 * The reference parameter may be used to specify an existing block device which
3191 * should be opened. If specified, neither options nor a filename may be given,
3192 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3194 static BlockDriverState *bdrv_open_inherit(const char *filename,
3195 const char *reference,
3196 QDict *options, int flags,
3197 BlockDriverState *parent,
3198 const BdrvChildClass *child_class,
3199 BdrvChildRole child_role,
3200 Error **errp)
3202 int ret;
3203 BlockBackend *file = NULL;
3204 BlockDriverState *bs;
3205 BlockDriver *drv = NULL;
3206 BdrvChild *child;
3207 const char *drvname;
3208 const char *backing;
3209 Error *local_err = NULL;
3210 QDict *snapshot_options = NULL;
3211 int snapshot_flags = 0;
3213 assert(!child_class || !flags);
3214 assert(!child_class == !parent);
3216 if (reference) {
3217 bool options_non_empty = options ? qdict_size(options) : false;
3218 qobject_unref(options);
3220 if (filename || options_non_empty) {
3221 error_setg(errp, "Cannot reference an existing block device with "
3222 "additional options or a new filename");
3223 return NULL;
3226 bs = bdrv_lookup_bs(reference, reference, errp);
3227 if (!bs) {
3228 return NULL;
3231 bdrv_ref(bs);
3232 return bs;
3235 bs = bdrv_new();
3237 /* NULL means an empty set of options */
3238 if (options == NULL) {
3239 options = qdict_new();
3242 /* json: syntax counts as explicit options, as if in the QDict */
3243 parse_json_protocol(options, &filename, &local_err);
3244 if (local_err) {
3245 goto fail;
3248 bs->explicit_options = qdict_clone_shallow(options);
3250 if (child_class) {
3251 bool parent_is_format;
3253 if (parent->drv) {
3254 parent_is_format = parent->drv->is_format;
3255 } else {
3257 * parent->drv is not set yet because this node is opened for
3258 * (potential) format probing. That means that @parent is going
3259 * to be a format node.
3261 parent_is_format = true;
3264 bs->inherits_from = parent;
3265 child_class->inherit_options(child_role, parent_is_format,
3266 &flags, options,
3267 parent->open_flags, parent->options);
3270 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3271 if (ret < 0) {
3272 goto fail;
3276 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3277 * Caution: getting a boolean member of @options requires care.
3278 * When @options come from -blockdev or blockdev_add, members are
3279 * typed according to the QAPI schema, but when they come from
3280 * -drive, they're all QString.
3282 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3283 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3284 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3285 } else {
3286 flags &= ~BDRV_O_RDWR;
3289 if (flags & BDRV_O_SNAPSHOT) {
3290 snapshot_options = qdict_new();
3291 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3292 flags, options);
3293 /* Let bdrv_backing_options() override "read-only" */
3294 qdict_del(options, BDRV_OPT_READ_ONLY);
3295 bdrv_inherited_options(BDRV_CHILD_COW, true,
3296 &flags, options, flags, options);
3299 bs->open_flags = flags;
3300 bs->options = options;
3301 options = qdict_clone_shallow(options);
3303 /* Find the right image format driver */
3304 /* See cautionary note on accessing @options above */
3305 drvname = qdict_get_try_str(options, "driver");
3306 if (drvname) {
3307 drv = bdrv_find_format(drvname);
3308 if (!drv) {
3309 error_setg(errp, "Unknown driver: '%s'", drvname);
3310 goto fail;
3314 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3316 /* See cautionary note on accessing @options above */
3317 backing = qdict_get_try_str(options, "backing");
3318 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3319 (backing && *backing == '\0'))
3321 if (backing) {
3322 warn_report("Use of \"backing\": \"\" is deprecated; "
3323 "use \"backing\": null instead");
3325 flags |= BDRV_O_NO_BACKING;
3326 qdict_del(bs->explicit_options, "backing");
3327 qdict_del(bs->options, "backing");
3328 qdict_del(options, "backing");
3331 /* Open image file without format layer. This BlockBackend is only used for
3332 * probing, the block drivers will do their own bdrv_open_child() for the
3333 * same BDS, which is why we put the node name back into options. */
3334 if ((flags & BDRV_O_PROTOCOL) == 0) {
3335 BlockDriverState *file_bs;
3337 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3338 &child_file, 0, true, &local_err);
3339 if (local_err) {
3340 goto fail;
3342 if (file_bs != NULL) {
3343 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3344 * looking at the header to guess the image format. This works even
3345 * in cases where a guest would not see a consistent state. */
3346 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3347 blk_insert_bs(file, file_bs, &local_err);
3348 bdrv_unref(file_bs);
3349 if (local_err) {
3350 goto fail;
3353 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3357 /* Image format probing */
3358 bs->probed = !drv;
3359 if (!drv && file) {
3360 ret = find_image_format(file, filename, &drv, &local_err);
3361 if (ret < 0) {
3362 goto fail;
3365 * This option update would logically belong in bdrv_fill_options(),
3366 * but we first need to open bs->file for the probing to work, while
3367 * opening bs->file already requires the (mostly) final set of options
3368 * so that cache mode etc. can be inherited.
3370 * Adding the driver later is somewhat ugly, but it's not an option
3371 * that would ever be inherited, so it's correct. We just need to make
3372 * sure to update both bs->options (which has the full effective
3373 * options for bs) and options (which has file.* already removed).
3375 qdict_put_str(bs->options, "driver", drv->format_name);
3376 qdict_put_str(options, "driver", drv->format_name);
3377 } else if (!drv) {
3378 error_setg(errp, "Must specify either driver or file");
3379 goto fail;
3382 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3383 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3384 /* file must be NULL if a protocol BDS is about to be created
3385 * (the inverse results in an error message from bdrv_open_common()) */
3386 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3388 /* Open the image */
3389 ret = bdrv_open_common(bs, file, options, &local_err);
3390 if (ret < 0) {
3391 goto fail;
3394 if (file) {
3395 blk_unref(file);
3396 file = NULL;
3399 /* If there is a backing file, use it */
3400 if ((flags & BDRV_O_NO_BACKING) == 0) {
3401 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3402 if (ret < 0) {
3403 goto close_and_fail;
3407 /* Remove all children options and references
3408 * from bs->options and bs->explicit_options */
3409 QLIST_FOREACH(child, &bs->children, next) {
3410 char *child_key_dot;
3411 child_key_dot = g_strdup_printf("%s.", child->name);
3412 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3413 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3414 qdict_del(bs->explicit_options, child->name);
3415 qdict_del(bs->options, child->name);
3416 g_free(child_key_dot);
3419 /* Check if any unknown options were used */
3420 if (qdict_size(options) != 0) {
3421 const QDictEntry *entry = qdict_first(options);
3422 if (flags & BDRV_O_PROTOCOL) {
3423 error_setg(errp, "Block protocol '%s' doesn't support the option "
3424 "'%s'", drv->format_name, entry->key);
3425 } else {
3426 error_setg(errp,
3427 "Block format '%s' does not support the option '%s'",
3428 drv->format_name, entry->key);
3431 goto close_and_fail;
3434 bdrv_parent_cb_change_media(bs, true);
3436 qobject_unref(options);
3437 options = NULL;
3439 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3440 * temporary snapshot afterwards. */
3441 if (snapshot_flags) {
3442 BlockDriverState *snapshot_bs;
3443 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3444 snapshot_options, &local_err);
3445 snapshot_options = NULL;
3446 if (local_err) {
3447 goto close_and_fail;
3449 /* We are not going to return bs but the overlay on top of it
3450 * (snapshot_bs); thus, we have to drop the strong reference to bs
3451 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3452 * though, because the overlay still has a reference to it. */
3453 bdrv_unref(bs);
3454 bs = snapshot_bs;
3457 return bs;
3459 fail:
3460 blk_unref(file);
3461 qobject_unref(snapshot_options);
3462 qobject_unref(bs->explicit_options);
3463 qobject_unref(bs->options);
3464 qobject_unref(options);
3465 bs->options = NULL;
3466 bs->explicit_options = NULL;
3467 bdrv_unref(bs);
3468 error_propagate(errp, local_err);
3469 return NULL;
3471 close_and_fail:
3472 bdrv_unref(bs);
3473 qobject_unref(snapshot_options);
3474 qobject_unref(options);
3475 error_propagate(errp, local_err);
3476 return NULL;
3479 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3480 QDict *options, int flags, Error **errp)
3482 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3483 NULL, 0, errp);
3486 /* Return true if the NULL-terminated @list contains @str */
3487 static bool is_str_in_list(const char *str, const char *const *list)
3489 if (str && list) {
3490 int i;
3491 for (i = 0; list[i] != NULL; i++) {
3492 if (!strcmp(str, list[i])) {
3493 return true;
3497 return false;
3501 * Check that every option set in @bs->options is also set in
3502 * @new_opts.
3504 * Options listed in the common_options list and in
3505 * @bs->drv->mutable_opts are skipped.
3507 * Return 0 on success, otherwise return -EINVAL and set @errp.
3509 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3510 const QDict *new_opts, Error **errp)
3512 const QDictEntry *e;
3513 /* These options are common to all block drivers and are handled
3514 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3515 const char *const common_options[] = {
3516 "node-name", "discard", "cache.direct", "cache.no-flush",
3517 "read-only", "auto-read-only", "detect-zeroes", NULL
3520 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3521 if (!qdict_haskey(new_opts, e->key) &&
3522 !is_str_in_list(e->key, common_options) &&
3523 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3524 error_setg(errp, "Option '%s' cannot be reset "
3525 "to its default value", e->key);
3526 return -EINVAL;
3530 return 0;
3534 * Returns true if @child can be reached recursively from @bs
3536 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3537 BlockDriverState *child)
3539 BdrvChild *c;
3541 if (bs == child) {
3542 return true;
3545 QLIST_FOREACH(c, &bs->children, next) {
3546 if (bdrv_recurse_has_child(c->bs, child)) {
3547 return true;
3551 return false;
3555 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3556 * reopen of multiple devices.
3558 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3559 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3560 * be created and initialized. This newly created BlockReopenQueue should be
3561 * passed back in for subsequent calls that are intended to be of the same
3562 * atomic 'set'.
3564 * bs is the BlockDriverState to add to the reopen queue.
3566 * options contains the changed options for the associated bs
3567 * (the BlockReopenQueue takes ownership)
3569 * flags contains the open flags for the associated bs
3571 * returns a pointer to bs_queue, which is either the newly allocated
3572 * bs_queue, or the existing bs_queue being used.
3574 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3576 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3577 BlockDriverState *bs,
3578 QDict *options,
3579 const BdrvChildClass *klass,
3580 BdrvChildRole role,
3581 bool parent_is_format,
3582 QDict *parent_options,
3583 int parent_flags,
3584 bool keep_old_opts)
3586 assert(bs != NULL);
3588 BlockReopenQueueEntry *bs_entry;
3589 BdrvChild *child;
3590 QDict *old_options, *explicit_options, *options_copy;
3591 int flags;
3592 QemuOpts *opts;
3594 /* Make sure that the caller remembered to use a drained section. This is
3595 * important to avoid graph changes between the recursive queuing here and
3596 * bdrv_reopen_multiple(). */
3597 assert(bs->quiesce_counter > 0);
3599 if (bs_queue == NULL) {
3600 bs_queue = g_new0(BlockReopenQueue, 1);
3601 QTAILQ_INIT(bs_queue);
3604 if (!options) {
3605 options = qdict_new();
3608 /* Check if this BlockDriverState is already in the queue */
3609 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3610 if (bs == bs_entry->state.bs) {
3611 break;
3616 * Precedence of options:
3617 * 1. Explicitly passed in options (highest)
3618 * 2. Retained from explicitly set options of bs
3619 * 3. Inherited from parent node
3620 * 4. Retained from effective options of bs
3623 /* Old explicitly set values (don't overwrite by inherited value) */
3624 if (bs_entry || keep_old_opts) {
3625 old_options = qdict_clone_shallow(bs_entry ?
3626 bs_entry->state.explicit_options :
3627 bs->explicit_options);
3628 bdrv_join_options(bs, options, old_options);
3629 qobject_unref(old_options);
3632 explicit_options = qdict_clone_shallow(options);
3634 /* Inherit from parent node */
3635 if (parent_options) {
3636 flags = 0;
3637 klass->inherit_options(role, parent_is_format, &flags, options,
3638 parent_flags, parent_options);
3639 } else {
3640 flags = bdrv_get_flags(bs);
3643 if (keep_old_opts) {
3644 /* Old values are used for options that aren't set yet */
3645 old_options = qdict_clone_shallow(bs->options);
3646 bdrv_join_options(bs, options, old_options);
3647 qobject_unref(old_options);
3650 /* We have the final set of options so let's update the flags */
3651 options_copy = qdict_clone_shallow(options);
3652 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3653 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3654 update_flags_from_options(&flags, opts);
3655 qemu_opts_del(opts);
3656 qobject_unref(options_copy);
3658 /* bdrv_open_inherit() sets and clears some additional flags internally */
3659 flags &= ~BDRV_O_PROTOCOL;
3660 if (flags & BDRV_O_RDWR) {
3661 flags |= BDRV_O_ALLOW_RDWR;
3664 if (!bs_entry) {
3665 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3666 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3667 } else {
3668 qobject_unref(bs_entry->state.options);
3669 qobject_unref(bs_entry->state.explicit_options);
3672 bs_entry->state.bs = bs;
3673 bs_entry->state.options = options;
3674 bs_entry->state.explicit_options = explicit_options;
3675 bs_entry->state.flags = flags;
3677 /* This needs to be overwritten in bdrv_reopen_prepare() */
3678 bs_entry->state.perm = UINT64_MAX;
3679 bs_entry->state.shared_perm = 0;
3682 * If keep_old_opts is false then it means that unspecified
3683 * options must be reset to their original value. We don't allow
3684 * resetting 'backing' but we need to know if the option is
3685 * missing in order to decide if we have to return an error.
3687 if (!keep_old_opts) {
3688 bs_entry->state.backing_missing =
3689 !qdict_haskey(options, "backing") &&
3690 !qdict_haskey(options, "backing.driver");
3693 QLIST_FOREACH(child, &bs->children, next) {
3694 QDict *new_child_options = NULL;
3695 bool child_keep_old = keep_old_opts;
3697 /* reopen can only change the options of block devices that were
3698 * implicitly created and inherited options. For other (referenced)
3699 * block devices, a syntax like "backing.foo" results in an error. */
3700 if (child->bs->inherits_from != bs) {
3701 continue;
3704 /* Check if the options contain a child reference */
3705 if (qdict_haskey(options, child->name)) {
3706 const char *childref = qdict_get_try_str(options, child->name);
3708 * The current child must not be reopened if the child
3709 * reference is null or points to a different node.
3711 if (g_strcmp0(childref, child->bs->node_name)) {
3712 continue;
3715 * If the child reference points to the current child then
3716 * reopen it with its existing set of options (note that
3717 * it can still inherit new options from the parent).
3719 child_keep_old = true;
3720 } else {
3721 /* Extract child options ("child-name.*") */
3722 char *child_key_dot = g_strdup_printf("%s.", child->name);
3723 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3724 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3725 g_free(child_key_dot);
3728 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3729 child->klass, child->role, bs->drv->is_format,
3730 options, flags, child_keep_old);
3733 return bs_queue;
3736 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3737 BlockDriverState *bs,
3738 QDict *options, bool keep_old_opts)
3740 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3741 NULL, 0, keep_old_opts);
3745 * Reopen multiple BlockDriverStates atomically & transactionally.
3747 * The queue passed in (bs_queue) must have been built up previous
3748 * via bdrv_reopen_queue().
3750 * Reopens all BDS specified in the queue, with the appropriate
3751 * flags. All devices are prepared for reopen, and failure of any
3752 * device will cause all device changes to be abandoned, and intermediate
3753 * data cleaned up.
3755 * If all devices prepare successfully, then the changes are committed
3756 * to all devices.
3758 * All affected nodes must be drained between bdrv_reopen_queue() and
3759 * bdrv_reopen_multiple().
3761 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3763 int ret = -1;
3764 BlockReopenQueueEntry *bs_entry, *next;
3766 assert(bs_queue != NULL);
3768 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3769 assert(bs_entry->state.bs->quiesce_counter > 0);
3770 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3771 goto cleanup;
3773 bs_entry->prepared = true;
3776 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3777 BDRVReopenState *state = &bs_entry->state;
3778 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3779 state->shared_perm, NULL, NULL, errp);
3780 if (ret < 0) {
3781 goto cleanup_perm;
3783 /* Check if new_backing_bs would accept the new permissions */
3784 if (state->replace_backing_bs && state->new_backing_bs) {
3785 uint64_t nperm, nshared;
3786 bdrv_child_perm(state->bs, state->new_backing_bs,
3787 NULL, &child_backing, 0, bs_queue,
3788 state->perm, state->shared_perm,
3789 &nperm, &nshared);
3790 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3791 nperm, nshared, NULL, NULL, errp);
3792 if (ret < 0) {
3793 goto cleanup_perm;
3796 bs_entry->perms_checked = true;
3800 * If we reach this point, we have success and just need to apply the
3801 * changes.
3803 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3804 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3805 * children are usually goes after parents in reopen-queue, so go from last
3806 * to first element.
3808 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3809 bdrv_reopen_commit(&bs_entry->state);
3812 ret = 0;
3813 cleanup_perm:
3814 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3815 BDRVReopenState *state = &bs_entry->state;
3817 if (!bs_entry->perms_checked) {
3818 continue;
3821 if (ret == 0) {
3822 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3823 } else {
3824 bdrv_abort_perm_update(state->bs);
3825 if (state->replace_backing_bs && state->new_backing_bs) {
3826 bdrv_abort_perm_update(state->new_backing_bs);
3831 if (ret == 0) {
3832 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3833 BlockDriverState *bs = bs_entry->state.bs;
3835 if (bs->drv->bdrv_reopen_commit_post)
3836 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3839 cleanup:
3840 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3841 if (ret) {
3842 if (bs_entry->prepared) {
3843 bdrv_reopen_abort(&bs_entry->state);
3845 qobject_unref(bs_entry->state.explicit_options);
3846 qobject_unref(bs_entry->state.options);
3848 if (bs_entry->state.new_backing_bs) {
3849 bdrv_unref(bs_entry->state.new_backing_bs);
3851 g_free(bs_entry);
3853 g_free(bs_queue);
3855 return ret;
3858 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3859 Error **errp)
3861 int ret;
3862 BlockReopenQueue *queue;
3863 QDict *opts = qdict_new();
3865 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3867 bdrv_subtree_drained_begin(bs);
3868 queue = bdrv_reopen_queue(NULL, bs, opts, true);
3869 ret = bdrv_reopen_multiple(queue, errp);
3870 bdrv_subtree_drained_end(bs);
3872 return ret;
3875 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3876 BdrvChild *c)
3878 BlockReopenQueueEntry *entry;
3880 QTAILQ_FOREACH(entry, q, entry) {
3881 BlockDriverState *bs = entry->state.bs;
3882 BdrvChild *child;
3884 QLIST_FOREACH(child, &bs->children, next) {
3885 if (child == c) {
3886 return entry;
3891 return NULL;
3894 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3895 uint64_t *perm, uint64_t *shared)
3897 BdrvChild *c;
3898 BlockReopenQueueEntry *parent;
3899 uint64_t cumulative_perms = 0;
3900 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3902 QLIST_FOREACH(c, &bs->parents, next_parent) {
3903 parent = find_parent_in_reopen_queue(q, c);
3904 if (!parent) {
3905 cumulative_perms |= c->perm;
3906 cumulative_shared_perms &= c->shared_perm;
3907 } else {
3908 uint64_t nperm, nshared;
3910 bdrv_child_perm(parent->state.bs, bs, c, c->klass, c->role, q,
3911 parent->state.perm, parent->state.shared_perm,
3912 &nperm, &nshared);
3914 cumulative_perms |= nperm;
3915 cumulative_shared_perms &= nshared;
3918 *perm = cumulative_perms;
3919 *shared = cumulative_shared_perms;
3922 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
3923 BdrvChild *child,
3924 BlockDriverState *new_child,
3925 Error **errp)
3927 AioContext *parent_ctx = bdrv_get_aio_context(parent);
3928 AioContext *child_ctx = bdrv_get_aio_context(new_child);
3929 GSList *ignore;
3930 bool ret;
3932 ignore = g_slist_prepend(NULL, child);
3933 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
3934 g_slist_free(ignore);
3935 if (ret) {
3936 return ret;
3939 ignore = g_slist_prepend(NULL, child);
3940 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
3941 g_slist_free(ignore);
3942 return ret;
3946 * Take a BDRVReopenState and check if the value of 'backing' in the
3947 * reopen_state->options QDict is valid or not.
3949 * If 'backing' is missing from the QDict then return 0.
3951 * If 'backing' contains the node name of the backing file of
3952 * reopen_state->bs then return 0.
3954 * If 'backing' contains a different node name (or is null) then check
3955 * whether the current backing file can be replaced with the new one.
3956 * If that's the case then reopen_state->replace_backing_bs is set to
3957 * true and reopen_state->new_backing_bs contains a pointer to the new
3958 * backing BlockDriverState (or NULL).
3960 * Return 0 on success, otherwise return < 0 and set @errp.
3962 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
3963 Error **errp)
3965 BlockDriverState *bs = reopen_state->bs;
3966 BlockDriverState *overlay_bs, *new_backing_bs;
3967 QObject *value;
3968 const char *str;
3970 value = qdict_get(reopen_state->options, "backing");
3971 if (value == NULL) {
3972 return 0;
3975 switch (qobject_type(value)) {
3976 case QTYPE_QNULL:
3977 new_backing_bs = NULL;
3978 break;
3979 case QTYPE_QSTRING:
3980 str = qobject_get_try_str(value);
3981 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
3982 if (new_backing_bs == NULL) {
3983 return -EINVAL;
3984 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
3985 error_setg(errp, "Making '%s' a backing file of '%s' "
3986 "would create a cycle", str, bs->node_name);
3987 return -EINVAL;
3989 break;
3990 default:
3991 /* 'backing' does not allow any other data type */
3992 g_assert_not_reached();
3996 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
3997 * bdrv_reopen_commit() won't fail.
3999 if (new_backing_bs) {
4000 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4001 return -EINVAL;
4006 * Find the "actual" backing file by skipping all links that point
4007 * to an implicit node, if any (e.g. a commit filter node).
4009 overlay_bs = bs;
4010 while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
4011 overlay_bs = backing_bs(overlay_bs);
4014 /* If we want to replace the backing file we need some extra checks */
4015 if (new_backing_bs != backing_bs(overlay_bs)) {
4016 /* Check for implicit nodes between bs and its backing file */
4017 if (bs != overlay_bs) {
4018 error_setg(errp, "Cannot change backing link if '%s' has "
4019 "an implicit backing file", bs->node_name);
4020 return -EPERM;
4022 /* Check if the backing link that we want to replace is frozen */
4023 if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
4024 errp)) {
4025 return -EPERM;
4027 reopen_state->replace_backing_bs = true;
4028 if (new_backing_bs) {
4029 bdrv_ref(new_backing_bs);
4030 reopen_state->new_backing_bs = new_backing_bs;
4034 return 0;
4038 * Prepares a BlockDriverState for reopen. All changes are staged in the
4039 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4040 * the block driver layer .bdrv_reopen_prepare()
4042 * bs is the BlockDriverState to reopen
4043 * flags are the new open flags
4044 * queue is the reopen queue
4046 * Returns 0 on success, non-zero on error. On error errp will be set
4047 * as well.
4049 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4050 * It is the responsibility of the caller to then call the abort() or
4051 * commit() for any other BDS that have been left in a prepare() state
4054 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4055 Error **errp)
4057 int ret = -1;
4058 int old_flags;
4059 Error *local_err = NULL;
4060 BlockDriver *drv;
4061 QemuOpts *opts;
4062 QDict *orig_reopen_opts;
4063 char *discard = NULL;
4064 bool read_only;
4065 bool drv_prepared = false;
4067 assert(reopen_state != NULL);
4068 assert(reopen_state->bs->drv != NULL);
4069 drv = reopen_state->bs->drv;
4071 /* This function and each driver's bdrv_reopen_prepare() remove
4072 * entries from reopen_state->options as they are processed, so
4073 * we need to make a copy of the original QDict. */
4074 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4076 /* Process generic block layer options */
4077 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4078 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
4079 if (local_err) {
4080 error_propagate(errp, local_err);
4081 ret = -EINVAL;
4082 goto error;
4085 /* This was already called in bdrv_reopen_queue_child() so the flags
4086 * are up-to-date. This time we simply want to remove the options from
4087 * QemuOpts in order to indicate that they have been processed. */
4088 old_flags = reopen_state->flags;
4089 update_flags_from_options(&reopen_state->flags, opts);
4090 assert(old_flags == reopen_state->flags);
4092 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4093 if (discard != NULL) {
4094 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4095 error_setg(errp, "Invalid discard option");
4096 ret = -EINVAL;
4097 goto error;
4101 reopen_state->detect_zeroes =
4102 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4103 if (local_err) {
4104 error_propagate(errp, local_err);
4105 ret = -EINVAL;
4106 goto error;
4109 /* All other options (including node-name and driver) must be unchanged.
4110 * Put them back into the QDict, so that they are checked at the end
4111 * of this function. */
4112 qemu_opts_to_qdict(opts, reopen_state->options);
4114 /* If we are to stay read-only, do not allow permission change
4115 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4116 * not set, or if the BDS still has copy_on_read enabled */
4117 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4118 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4119 if (local_err) {
4120 error_propagate(errp, local_err);
4121 goto error;
4124 /* Calculate required permissions after reopening */
4125 bdrv_reopen_perm(queue, reopen_state->bs,
4126 &reopen_state->perm, &reopen_state->shared_perm);
4128 ret = bdrv_flush(reopen_state->bs);
4129 if (ret) {
4130 error_setg_errno(errp, -ret, "Error flushing drive");
4131 goto error;
4134 if (drv->bdrv_reopen_prepare) {
4136 * If a driver-specific option is missing, it means that we
4137 * should reset it to its default value.
4138 * But not all options allow that, so we need to check it first.
4140 ret = bdrv_reset_options_allowed(reopen_state->bs,
4141 reopen_state->options, errp);
4142 if (ret) {
4143 goto error;
4146 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4147 if (ret) {
4148 if (local_err != NULL) {
4149 error_propagate(errp, local_err);
4150 } else {
4151 bdrv_refresh_filename(reopen_state->bs);
4152 error_setg(errp, "failed while preparing to reopen image '%s'",
4153 reopen_state->bs->filename);
4155 goto error;
4157 } else {
4158 /* It is currently mandatory to have a bdrv_reopen_prepare()
4159 * handler for each supported drv. */
4160 error_setg(errp, "Block format '%s' used by node '%s' "
4161 "does not support reopening files", drv->format_name,
4162 bdrv_get_device_or_node_name(reopen_state->bs));
4163 ret = -1;
4164 goto error;
4167 drv_prepared = true;
4170 * We must provide the 'backing' option if the BDS has a backing
4171 * file or if the image file has a backing file name as part of
4172 * its metadata. Otherwise the 'backing' option can be omitted.
4174 if (drv->supports_backing && reopen_state->backing_missing &&
4175 (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
4176 error_setg(errp, "backing is missing for '%s'",
4177 reopen_state->bs->node_name);
4178 ret = -EINVAL;
4179 goto error;
4183 * Allow changing the 'backing' option. The new value can be
4184 * either a reference to an existing node (using its node name)
4185 * or NULL to simply detach the current backing file.
4187 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4188 if (ret < 0) {
4189 goto error;
4191 qdict_del(reopen_state->options, "backing");
4193 /* Options that are not handled are only okay if they are unchanged
4194 * compared to the old state. It is expected that some options are only
4195 * used for the initial open, but not reopen (e.g. filename) */
4196 if (qdict_size(reopen_state->options)) {
4197 const QDictEntry *entry = qdict_first(reopen_state->options);
4199 do {
4200 QObject *new = entry->value;
4201 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4203 /* Allow child references (child_name=node_name) as long as they
4204 * point to the current child (i.e. everything stays the same). */
4205 if (qobject_type(new) == QTYPE_QSTRING) {
4206 BdrvChild *child;
4207 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4208 if (!strcmp(child->name, entry->key)) {
4209 break;
4213 if (child) {
4214 const char *str = qobject_get_try_str(new);
4215 if (!strcmp(child->bs->node_name, str)) {
4216 continue; /* Found child with this name, skip option */
4222 * TODO: When using -drive to specify blockdev options, all values
4223 * will be strings; however, when using -blockdev, blockdev-add or
4224 * filenames using the json:{} pseudo-protocol, they will be
4225 * correctly typed.
4226 * In contrast, reopening options are (currently) always strings
4227 * (because you can only specify them through qemu-io; all other
4228 * callers do not specify any options).
4229 * Therefore, when using anything other than -drive to create a BDS,
4230 * this cannot detect non-string options as unchanged, because
4231 * qobject_is_equal() always returns false for objects of different
4232 * type. In the future, this should be remedied by correctly typing
4233 * all options. For now, this is not too big of an issue because
4234 * the user can simply omit options which cannot be changed anyway,
4235 * so they will stay unchanged.
4237 if (!qobject_is_equal(new, old)) {
4238 error_setg(errp, "Cannot change the option '%s'", entry->key);
4239 ret = -EINVAL;
4240 goto error;
4242 } while ((entry = qdict_next(reopen_state->options, entry)));
4245 ret = 0;
4247 /* Restore the original reopen_state->options QDict */
4248 qobject_unref(reopen_state->options);
4249 reopen_state->options = qobject_ref(orig_reopen_opts);
4251 error:
4252 if (ret < 0 && drv_prepared) {
4253 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4254 * call drv->bdrv_reopen_abort() before signaling an error
4255 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4256 * when the respective bdrv_reopen_prepare() has failed) */
4257 if (drv->bdrv_reopen_abort) {
4258 drv->bdrv_reopen_abort(reopen_state);
4261 qemu_opts_del(opts);
4262 qobject_unref(orig_reopen_opts);
4263 g_free(discard);
4264 return ret;
4268 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4269 * makes them final by swapping the staging BlockDriverState contents into
4270 * the active BlockDriverState contents.
4272 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4274 BlockDriver *drv;
4275 BlockDriverState *bs;
4276 BdrvChild *child;
4278 assert(reopen_state != NULL);
4279 bs = reopen_state->bs;
4280 drv = bs->drv;
4281 assert(drv != NULL);
4283 /* If there are any driver level actions to take */
4284 if (drv->bdrv_reopen_commit) {
4285 drv->bdrv_reopen_commit(reopen_state);
4288 /* set BDS specific flags now */
4289 qobject_unref(bs->explicit_options);
4290 qobject_unref(bs->options);
4292 bs->explicit_options = reopen_state->explicit_options;
4293 bs->options = reopen_state->options;
4294 bs->open_flags = reopen_state->flags;
4295 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
4296 bs->detect_zeroes = reopen_state->detect_zeroes;
4298 if (reopen_state->replace_backing_bs) {
4299 qdict_del(bs->explicit_options, "backing");
4300 qdict_del(bs->options, "backing");
4303 /* Remove child references from bs->options and bs->explicit_options.
4304 * Child options were already removed in bdrv_reopen_queue_child() */
4305 QLIST_FOREACH(child, &bs->children, next) {
4306 qdict_del(bs->explicit_options, child->name);
4307 qdict_del(bs->options, child->name);
4311 * Change the backing file if a new one was specified. We do this
4312 * after updating bs->options, so bdrv_refresh_filename() (called
4313 * from bdrv_set_backing_hd()) has the new values.
4315 if (reopen_state->replace_backing_bs) {
4316 BlockDriverState *old_backing_bs = backing_bs(bs);
4317 assert(!old_backing_bs || !old_backing_bs->implicit);
4318 /* Abort the permission update on the backing bs we're detaching */
4319 if (old_backing_bs) {
4320 bdrv_abort_perm_update(old_backing_bs);
4322 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4325 bdrv_refresh_limits(bs, NULL);
4329 * Abort the reopen, and delete and free the staged changes in
4330 * reopen_state
4332 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4334 BlockDriver *drv;
4336 assert(reopen_state != NULL);
4337 drv = reopen_state->bs->drv;
4338 assert(drv != NULL);
4340 if (drv->bdrv_reopen_abort) {
4341 drv->bdrv_reopen_abort(reopen_state);
4346 static void bdrv_close(BlockDriverState *bs)
4348 BdrvAioNotifier *ban, *ban_next;
4349 BdrvChild *child, *next;
4351 assert(!bs->refcnt);
4353 bdrv_drained_begin(bs); /* complete I/O */
4354 bdrv_flush(bs);
4355 bdrv_drain(bs); /* in case flush left pending I/O */
4357 if (bs->drv) {
4358 if (bs->drv->bdrv_close) {
4359 bs->drv->bdrv_close(bs);
4361 bs->drv = NULL;
4364 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4365 bdrv_unref_child(bs, child);
4368 bs->backing = NULL;
4369 bs->file = NULL;
4370 g_free(bs->opaque);
4371 bs->opaque = NULL;
4372 atomic_set(&bs->copy_on_read, 0);
4373 bs->backing_file[0] = '\0';
4374 bs->backing_format[0] = '\0';
4375 bs->total_sectors = 0;
4376 bs->encrypted = false;
4377 bs->sg = false;
4378 qobject_unref(bs->options);
4379 qobject_unref(bs->explicit_options);
4380 bs->options = NULL;
4381 bs->explicit_options = NULL;
4382 qobject_unref(bs->full_open_options);
4383 bs->full_open_options = NULL;
4385 bdrv_release_named_dirty_bitmaps(bs);
4386 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4388 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4389 g_free(ban);
4391 QLIST_INIT(&bs->aio_notifiers);
4392 bdrv_drained_end(bs);
4395 void bdrv_close_all(void)
4397 assert(job_next(NULL) == NULL);
4398 nbd_export_close_all();
4400 /* Drop references from requests still in flight, such as canceled block
4401 * jobs whose AIO context has not been polled yet */
4402 bdrv_drain_all();
4404 blk_remove_all_bs();
4405 blockdev_close_all_bdrv_states();
4407 assert(QTAILQ_EMPTY(&all_bdrv_states));
4410 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4412 GQueue *queue;
4413 GHashTable *found;
4414 bool ret;
4416 if (c->klass->stay_at_node) {
4417 return false;
4420 /* If the child @c belongs to the BDS @to, replacing the current
4421 * c->bs by @to would mean to create a loop.
4423 * Such a case occurs when appending a BDS to a backing chain.
4424 * For instance, imagine the following chain:
4426 * guest device -> node A -> further backing chain...
4428 * Now we create a new BDS B which we want to put on top of this
4429 * chain, so we first attach A as its backing node:
4431 * node B
4434 * guest device -> node A -> further backing chain...
4436 * Finally we want to replace A by B. When doing that, we want to
4437 * replace all pointers to A by pointers to B -- except for the
4438 * pointer from B because (1) that would create a loop, and (2)
4439 * that pointer should simply stay intact:
4441 * guest device -> node B
4444 * node A -> further backing chain...
4446 * In general, when replacing a node A (c->bs) by a node B (@to),
4447 * if A is a child of B, that means we cannot replace A by B there
4448 * because that would create a loop. Silently detaching A from B
4449 * is also not really an option. So overall just leaving A in
4450 * place there is the most sensible choice.
4452 * We would also create a loop in any cases where @c is only
4453 * indirectly referenced by @to. Prevent this by returning false
4454 * if @c is found (by breadth-first search) anywhere in the whole
4455 * subtree of @to.
4458 ret = true;
4459 found = g_hash_table_new(NULL, NULL);
4460 g_hash_table_add(found, to);
4461 queue = g_queue_new();
4462 g_queue_push_tail(queue, to);
4464 while (!g_queue_is_empty(queue)) {
4465 BlockDriverState *v = g_queue_pop_head(queue);
4466 BdrvChild *c2;
4468 QLIST_FOREACH(c2, &v->children, next) {
4469 if (c2 == c) {
4470 ret = false;
4471 break;
4474 if (g_hash_table_contains(found, c2->bs)) {
4475 continue;
4478 g_queue_push_tail(queue, c2->bs);
4479 g_hash_table_add(found, c2->bs);
4483 g_queue_free(queue);
4484 g_hash_table_destroy(found);
4486 return ret;
4489 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4490 Error **errp)
4492 BdrvChild *c, *next;
4493 GSList *list = NULL, *p;
4494 uint64_t perm = 0, shared = BLK_PERM_ALL;
4495 int ret;
4497 /* Make sure that @from doesn't go away until we have successfully attached
4498 * all of its parents to @to. */
4499 bdrv_ref(from);
4501 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4502 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
4503 bdrv_drained_begin(from);
4505 /* Put all parents into @list and calculate their cumulative permissions */
4506 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4507 assert(c->bs == from);
4508 if (!should_update_child(c, to)) {
4509 continue;
4511 if (c->frozen) {
4512 error_setg(errp, "Cannot change '%s' link to '%s'",
4513 c->name, from->node_name);
4514 goto out;
4516 list = g_slist_prepend(list, c);
4517 perm |= c->perm;
4518 shared &= c->shared_perm;
4521 /* Check whether the required permissions can be granted on @to, ignoring
4522 * all BdrvChild in @list so that they can't block themselves. */
4523 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
4524 if (ret < 0) {
4525 bdrv_abort_perm_update(to);
4526 goto out;
4529 /* Now actually perform the change. We performed the permission check for
4530 * all elements of @list at once, so set the permissions all at once at the
4531 * very end. */
4532 for (p = list; p != NULL; p = p->next) {
4533 c = p->data;
4535 bdrv_ref(to);
4536 bdrv_replace_child_noperm(c, to);
4537 bdrv_unref(from);
4540 bdrv_get_cumulative_perm(to, &perm, &shared);
4541 bdrv_set_perm(to, perm, shared);
4543 out:
4544 g_slist_free(list);
4545 bdrv_drained_end(from);
4546 bdrv_unref(from);
4550 * Add new bs contents at the top of an image chain while the chain is
4551 * live, while keeping required fields on the top layer.
4553 * This will modify the BlockDriverState fields, and swap contents
4554 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4556 * bs_new must not be attached to a BlockBackend.
4558 * This function does not create any image files.
4560 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4561 * that's what the callers commonly need. bs_new will be referenced by the old
4562 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4563 * reference of its own, it must call bdrv_ref().
4565 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4566 Error **errp)
4568 Error *local_err = NULL;
4570 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4571 if (local_err) {
4572 error_propagate(errp, local_err);
4573 goto out;
4576 bdrv_replace_node(bs_top, bs_new, &local_err);
4577 if (local_err) {
4578 error_propagate(errp, local_err);
4579 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4580 goto out;
4583 /* bs_new is now referenced by its new parents, we don't need the
4584 * additional reference any more. */
4585 out:
4586 bdrv_unref(bs_new);
4589 static void bdrv_delete(BlockDriverState *bs)
4591 assert(bdrv_op_blocker_is_empty(bs));
4592 assert(!bs->refcnt);
4594 /* remove from list, if necessary */
4595 if (bs->node_name[0] != '\0') {
4596 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4598 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4600 bdrv_close(bs);
4602 g_free(bs);
4606 * Run consistency checks on an image
4608 * Returns 0 if the check could be completed (it doesn't mean that the image is
4609 * free of errors) or -errno when an internal error occurred. The results of the
4610 * check are stored in res.
4612 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4613 BdrvCheckResult *res, BdrvCheckMode fix)
4615 if (bs->drv == NULL) {
4616 return -ENOMEDIUM;
4618 if (bs->drv->bdrv_co_check == NULL) {
4619 return -ENOTSUP;
4622 memset(res, 0, sizeof(*res));
4623 return bs->drv->bdrv_co_check(bs, res, fix);
4626 typedef struct CheckCo {
4627 BlockDriverState *bs;
4628 BdrvCheckResult *res;
4629 BdrvCheckMode fix;
4630 int ret;
4631 } CheckCo;
4633 static void coroutine_fn bdrv_check_co_entry(void *opaque)
4635 CheckCo *cco = opaque;
4636 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4637 aio_wait_kick();
4640 int bdrv_check(BlockDriverState *bs,
4641 BdrvCheckResult *res, BdrvCheckMode fix)
4643 Coroutine *co;
4644 CheckCo cco = {
4645 .bs = bs,
4646 .res = res,
4647 .ret = -EINPROGRESS,
4648 .fix = fix,
4651 if (qemu_in_coroutine()) {
4652 /* Fast-path if already in coroutine context */
4653 bdrv_check_co_entry(&cco);
4654 } else {
4655 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4656 bdrv_coroutine_enter(bs, co);
4657 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4660 return cco.ret;
4664 * Return values:
4665 * 0 - success
4666 * -EINVAL - backing format specified, but no file
4667 * -ENOSPC - can't update the backing file because no space is left in the
4668 * image file header
4669 * -ENOTSUP - format driver doesn't support changing the backing file
4671 int bdrv_change_backing_file(BlockDriverState *bs,
4672 const char *backing_file, const char *backing_fmt)
4674 BlockDriver *drv = bs->drv;
4675 int ret;
4677 if (!drv) {
4678 return -ENOMEDIUM;
4681 /* Backing file format doesn't make sense without a backing file */
4682 if (backing_fmt && !backing_file) {
4683 return -EINVAL;
4686 if (drv->bdrv_change_backing_file != NULL) {
4687 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
4688 } else {
4689 ret = -ENOTSUP;
4692 if (ret == 0) {
4693 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4694 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
4695 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4696 backing_file ?: "");
4698 return ret;
4702 * Finds the image layer in the chain that has 'bs' as its backing file.
4704 * active is the current topmost image.
4706 * Returns NULL if bs is not found in active's image chain,
4707 * or if active == bs.
4709 * Returns the bottommost base image if bs == NULL.
4711 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4712 BlockDriverState *bs)
4714 while (active && bs != backing_bs(active)) {
4715 active = backing_bs(active);
4718 return active;
4721 /* Given a BDS, searches for the base layer. */
4722 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4724 return bdrv_find_overlay(bs, NULL);
4728 * Return true if at least one of the backing links between @bs and
4729 * @base is frozen. @errp is set if that's the case.
4730 * @base must be reachable from @bs, or NULL.
4732 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4733 Error **errp)
4735 BlockDriverState *i;
4737 for (i = bs; i != base; i = backing_bs(i)) {
4738 if (i->backing && i->backing->frozen) {
4739 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4740 i->backing->name, i->node_name,
4741 backing_bs(i)->node_name);
4742 return true;
4746 return false;
4750 * Freeze all backing links between @bs and @base.
4751 * If any of the links is already frozen the operation is aborted and
4752 * none of the links are modified.
4753 * @base must be reachable from @bs, or NULL.
4754 * Returns 0 on success. On failure returns < 0 and sets @errp.
4756 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4757 Error **errp)
4759 BlockDriverState *i;
4761 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4762 return -EPERM;
4765 for (i = bs; i != base; i = backing_bs(i)) {
4766 if (i->backing && backing_bs(i)->never_freeze) {
4767 error_setg(errp, "Cannot freeze '%s' link to '%s'",
4768 i->backing->name, backing_bs(i)->node_name);
4769 return -EPERM;
4773 for (i = bs; i != base; i = backing_bs(i)) {
4774 if (i->backing) {
4775 i->backing->frozen = true;
4779 return 0;
4783 * Unfreeze all backing links between @bs and @base. The caller must
4784 * ensure that all links are frozen before using this function.
4785 * @base must be reachable from @bs, or NULL.
4787 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4789 BlockDriverState *i;
4791 for (i = bs; i != base; i = backing_bs(i)) {
4792 if (i->backing) {
4793 assert(i->backing->frozen);
4794 i->backing->frozen = false;
4800 * Drops images above 'base' up to and including 'top', and sets the image
4801 * above 'top' to have base as its backing file.
4803 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4804 * information in 'bs' can be properly updated.
4806 * E.g., this will convert the following chain:
4807 * bottom <- base <- intermediate <- top <- active
4809 * to
4811 * bottom <- base <- active
4813 * It is allowed for bottom==base, in which case it converts:
4815 * base <- intermediate <- top <- active
4817 * to
4819 * base <- active
4821 * If backing_file_str is non-NULL, it will be used when modifying top's
4822 * overlay image metadata.
4824 * Error conditions:
4825 * if active == top, that is considered an error
4828 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4829 const char *backing_file_str)
4831 BlockDriverState *explicit_top = top;
4832 bool update_inherits_from;
4833 BdrvChild *c, *next;
4834 Error *local_err = NULL;
4835 int ret = -EIO;
4837 bdrv_ref(top);
4838 bdrv_subtree_drained_begin(top);
4840 if (!top->drv || !base->drv) {
4841 goto exit;
4844 /* Make sure that base is in the backing chain of top */
4845 if (!bdrv_chain_contains(top, base)) {
4846 goto exit;
4849 /* This function changes all links that point to top and makes
4850 * them point to base. Check that none of them is frozen. */
4851 QLIST_FOREACH(c, &top->parents, next_parent) {
4852 if (c->frozen) {
4853 goto exit;
4857 /* If 'base' recursively inherits from 'top' then we should set
4858 * base->inherits_from to top->inherits_from after 'top' and all
4859 * other intermediate nodes have been dropped.
4860 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4861 * it because no one inherits from it. We use explicit_top for that. */
4862 while (explicit_top && explicit_top->implicit) {
4863 explicit_top = backing_bs(explicit_top);
4865 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4867 /* success - we can delete the intermediate states, and link top->base */
4868 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4869 * we've figured out how they should work. */
4870 if (!backing_file_str) {
4871 bdrv_refresh_filename(base);
4872 backing_file_str = base->filename;
4875 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
4876 /* Check whether we are allowed to switch c from top to base */
4877 GSList *ignore_children = g_slist_prepend(NULL, c);
4878 ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
4879 ignore_children, NULL, &local_err);
4880 g_slist_free(ignore_children);
4881 if (ret < 0) {
4882 error_report_err(local_err);
4883 goto exit;
4886 /* If so, update the backing file path in the image file */
4887 if (c->klass->update_filename) {
4888 ret = c->klass->update_filename(c, base, backing_file_str,
4889 &local_err);
4890 if (ret < 0) {
4891 bdrv_abort_perm_update(base);
4892 error_report_err(local_err);
4893 goto exit;
4897 /* Do the actual switch in the in-memory graph.
4898 * Completes bdrv_check_update_perm() transaction internally. */
4899 bdrv_ref(base);
4900 bdrv_replace_child(c, base);
4901 bdrv_unref(top);
4904 if (update_inherits_from) {
4905 base->inherits_from = explicit_top->inherits_from;
4908 ret = 0;
4909 exit:
4910 bdrv_subtree_drained_end(top);
4911 bdrv_unref(top);
4912 return ret;
4916 * Length of a allocated file in bytes. Sparse files are counted by actual
4917 * allocated space. Return < 0 if error or unknown.
4919 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
4921 BlockDriver *drv = bs->drv;
4922 if (!drv) {
4923 return -ENOMEDIUM;
4925 if (drv->bdrv_get_allocated_file_size) {
4926 return drv->bdrv_get_allocated_file_size(bs);
4928 if (bs->file) {
4929 return bdrv_get_allocated_file_size(bs->file->bs);
4931 return -ENOTSUP;
4935 * bdrv_measure:
4936 * @drv: Format driver
4937 * @opts: Creation options for new image
4938 * @in_bs: Existing image containing data for new image (may be NULL)
4939 * @errp: Error object
4940 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
4941 * or NULL on error
4943 * Calculate file size required to create a new image.
4945 * If @in_bs is given then space for allocated clusters and zero clusters
4946 * from that image are included in the calculation. If @opts contains a
4947 * backing file that is shared by @in_bs then backing clusters may be omitted
4948 * from the calculation.
4950 * If @in_bs is NULL then the calculation includes no allocated clusters
4951 * unless a preallocation option is given in @opts.
4953 * Note that @in_bs may use a different BlockDriver from @drv.
4955 * If an error occurs the @errp pointer is set.
4957 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
4958 BlockDriverState *in_bs, Error **errp)
4960 if (!drv->bdrv_measure) {
4961 error_setg(errp, "Block driver '%s' does not support size measurement",
4962 drv->format_name);
4963 return NULL;
4966 return drv->bdrv_measure(opts, in_bs, errp);
4970 * Return number of sectors on success, -errno on error.
4972 int64_t bdrv_nb_sectors(BlockDriverState *bs)
4974 BlockDriver *drv = bs->drv;
4976 if (!drv)
4977 return -ENOMEDIUM;
4979 if (drv->has_variable_length) {
4980 int ret = refresh_total_sectors(bs, bs->total_sectors);
4981 if (ret < 0) {
4982 return ret;
4985 return bs->total_sectors;
4989 * Return length in bytes on success, -errno on error.
4990 * The length is always a multiple of BDRV_SECTOR_SIZE.
4992 int64_t bdrv_getlength(BlockDriverState *bs)
4994 int64_t ret = bdrv_nb_sectors(bs);
4996 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
4997 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
5000 /* return 0 as number of sectors if no device present or error */
5001 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5003 int64_t nb_sectors = bdrv_nb_sectors(bs);
5005 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5008 bool bdrv_is_sg(BlockDriverState *bs)
5010 return bs->sg;
5013 bool bdrv_is_encrypted(BlockDriverState *bs)
5015 if (bs->backing && bs->backing->bs->encrypted) {
5016 return true;
5018 return bs->encrypted;
5021 const char *bdrv_get_format_name(BlockDriverState *bs)
5023 return bs->drv ? bs->drv->format_name : NULL;
5026 static int qsort_strcmp(const void *a, const void *b)
5028 return strcmp(*(char *const *)a, *(char *const *)b);
5031 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5032 void *opaque, bool read_only)
5034 BlockDriver *drv;
5035 int count = 0;
5036 int i;
5037 const char **formats = NULL;
5039 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5040 if (drv->format_name) {
5041 bool found = false;
5042 int i = count;
5044 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5045 continue;
5048 while (formats && i && !found) {
5049 found = !strcmp(formats[--i], drv->format_name);
5052 if (!found) {
5053 formats = g_renew(const char *, formats, count + 1);
5054 formats[count++] = drv->format_name;
5059 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5060 const char *format_name = block_driver_modules[i].format_name;
5062 if (format_name) {
5063 bool found = false;
5064 int j = count;
5066 if (use_bdrv_whitelist &&
5067 !bdrv_format_is_whitelisted(format_name, read_only)) {
5068 continue;
5071 while (formats && j && !found) {
5072 found = !strcmp(formats[--j], format_name);
5075 if (!found) {
5076 formats = g_renew(const char *, formats, count + 1);
5077 formats[count++] = format_name;
5082 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5084 for (i = 0; i < count; i++) {
5085 it(opaque, formats[i]);
5088 g_free(formats);
5091 /* This function is to find a node in the bs graph */
5092 BlockDriverState *bdrv_find_node(const char *node_name)
5094 BlockDriverState *bs;
5096 assert(node_name);
5098 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5099 if (!strcmp(node_name, bs->node_name)) {
5100 return bs;
5103 return NULL;
5106 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5107 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5108 Error **errp)
5110 BlockDeviceInfoList *list, *entry;
5111 BlockDriverState *bs;
5113 list = NULL;
5114 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5115 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5116 if (!info) {
5117 qapi_free_BlockDeviceInfoList(list);
5118 return NULL;
5120 entry = g_malloc0(sizeof(*entry));
5121 entry->value = info;
5122 entry->next = list;
5123 list = entry;
5126 return list;
5129 #define QAPI_LIST_ADD(list, element) do { \
5130 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
5131 _tmp->value = (element); \
5132 _tmp->next = (list); \
5133 (list) = _tmp; \
5134 } while (0)
5136 typedef struct XDbgBlockGraphConstructor {
5137 XDbgBlockGraph *graph;
5138 GHashTable *graph_nodes;
5139 } XDbgBlockGraphConstructor;
5141 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5143 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5145 gr->graph = g_new0(XDbgBlockGraph, 1);
5146 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5148 return gr;
5151 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5153 XDbgBlockGraph *graph = gr->graph;
5155 g_hash_table_destroy(gr->graph_nodes);
5156 g_free(gr);
5158 return graph;
5161 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5163 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5165 if (ret != 0) {
5166 return ret;
5170 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5171 * answer of g_hash_table_lookup.
5173 ret = g_hash_table_size(gr->graph_nodes) + 1;
5174 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5176 return ret;
5179 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5180 XDbgBlockGraphNodeType type, const char *name)
5182 XDbgBlockGraphNode *n;
5184 n = g_new0(XDbgBlockGraphNode, 1);
5186 n->id = xdbg_graph_node_num(gr, node);
5187 n->type = type;
5188 n->name = g_strdup(name);
5190 QAPI_LIST_ADD(gr->graph->nodes, n);
5193 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5194 const BdrvChild *child)
5196 BlockPermission qapi_perm;
5197 XDbgBlockGraphEdge *edge;
5199 edge = g_new0(XDbgBlockGraphEdge, 1);
5201 edge->parent = xdbg_graph_node_num(gr, parent);
5202 edge->child = xdbg_graph_node_num(gr, child->bs);
5203 edge->name = g_strdup(child->name);
5205 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5206 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5208 if (flag & child->perm) {
5209 QAPI_LIST_ADD(edge->perm, qapi_perm);
5211 if (flag & child->shared_perm) {
5212 QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
5216 QAPI_LIST_ADD(gr->graph->edges, edge);
5220 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5222 BlockBackend *blk;
5223 BlockJob *job;
5224 BlockDriverState *bs;
5225 BdrvChild *child;
5226 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5228 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5229 char *allocated_name = NULL;
5230 const char *name = blk_name(blk);
5232 if (!*name) {
5233 name = allocated_name = blk_get_attached_dev_id(blk);
5235 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5236 name);
5237 g_free(allocated_name);
5238 if (blk_root(blk)) {
5239 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5243 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5244 GSList *el;
5246 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5247 job->job.id);
5248 for (el = job->nodes; el; el = el->next) {
5249 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5253 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5254 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5255 bs->node_name);
5256 QLIST_FOREACH(child, &bs->children, next) {
5257 xdbg_graph_add_edge(gr, bs, child);
5261 return xdbg_graph_finalize(gr);
5264 BlockDriverState *bdrv_lookup_bs(const char *device,
5265 const char *node_name,
5266 Error **errp)
5268 BlockBackend *blk;
5269 BlockDriverState *bs;
5271 if (device) {
5272 blk = blk_by_name(device);
5274 if (blk) {
5275 bs = blk_bs(blk);
5276 if (!bs) {
5277 error_setg(errp, "Device '%s' has no medium", device);
5280 return bs;
5284 if (node_name) {
5285 bs = bdrv_find_node(node_name);
5287 if (bs) {
5288 return bs;
5292 error_setg(errp, "Cannot find device=%s nor node_name=%s",
5293 device ? device : "",
5294 node_name ? node_name : "");
5295 return NULL;
5298 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5299 * return false. If either argument is NULL, return false. */
5300 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5302 while (top && top != base) {
5303 top = backing_bs(top);
5306 return top != NULL;
5309 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5311 if (!bs) {
5312 return QTAILQ_FIRST(&graph_bdrv_states);
5314 return QTAILQ_NEXT(bs, node_list);
5317 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5319 if (!bs) {
5320 return QTAILQ_FIRST(&all_bdrv_states);
5322 return QTAILQ_NEXT(bs, bs_list);
5325 const char *bdrv_get_node_name(const BlockDriverState *bs)
5327 return bs->node_name;
5330 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5332 BdrvChild *c;
5333 const char *name;
5335 /* If multiple parents have a name, just pick the first one. */
5336 QLIST_FOREACH(c, &bs->parents, next_parent) {
5337 if (c->klass->get_name) {
5338 name = c->klass->get_name(c);
5339 if (name && *name) {
5340 return name;
5345 return NULL;
5348 /* TODO check what callers really want: bs->node_name or blk_name() */
5349 const char *bdrv_get_device_name(const BlockDriverState *bs)
5351 return bdrv_get_parent_name(bs) ?: "";
5354 /* This can be used to identify nodes that might not have a device
5355 * name associated. Since node and device names live in the same
5356 * namespace, the result is unambiguous. The exception is if both are
5357 * absent, then this returns an empty (non-null) string. */
5358 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5360 return bdrv_get_parent_name(bs) ?: bs->node_name;
5363 int bdrv_get_flags(BlockDriverState *bs)
5365 return bs->open_flags;
5368 int bdrv_has_zero_init_1(BlockDriverState *bs)
5370 return 1;
5373 int bdrv_has_zero_init(BlockDriverState *bs)
5375 if (!bs->drv) {
5376 return 0;
5379 /* If BS is a copy on write image, it is initialized to
5380 the contents of the base image, which may not be zeroes. */
5381 if (bs->backing) {
5382 return 0;
5384 if (bs->drv->bdrv_has_zero_init) {
5385 return bs->drv->bdrv_has_zero_init(bs);
5387 if (bs->file && bs->drv->is_filter) {
5388 return bdrv_has_zero_init(bs->file->bs);
5391 /* safe default */
5392 return 0;
5395 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
5397 BlockDriverInfo bdi;
5399 if (bs->backing) {
5400 return false;
5403 if (bdrv_get_info(bs, &bdi) == 0) {
5404 return bdi.unallocated_blocks_are_zero;
5407 return false;
5410 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5412 if (!(bs->open_flags & BDRV_O_UNMAP)) {
5413 return false;
5416 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5419 void bdrv_get_backing_filename(BlockDriverState *bs,
5420 char *filename, int filename_size)
5422 pstrcpy(filename, filename_size, bs->backing_file);
5425 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5427 BlockDriver *drv = bs->drv;
5428 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5429 if (!drv) {
5430 return -ENOMEDIUM;
5432 if (!drv->bdrv_get_info) {
5433 if (bs->file && drv->is_filter) {
5434 return bdrv_get_info(bs->file->bs, bdi);
5436 return -ENOTSUP;
5438 memset(bdi, 0, sizeof(*bdi));
5439 return drv->bdrv_get_info(bs, bdi);
5442 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5443 Error **errp)
5445 BlockDriver *drv = bs->drv;
5446 if (drv && drv->bdrv_get_specific_info) {
5447 return drv->bdrv_get_specific_info(bs, errp);
5449 return NULL;
5452 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5454 BlockDriver *drv = bs->drv;
5455 if (!drv || !drv->bdrv_get_specific_stats) {
5456 return NULL;
5458 return drv->bdrv_get_specific_stats(bs);
5461 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5463 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5464 return;
5467 bs->drv->bdrv_debug_event(bs, event);
5470 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5472 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5473 if (bs->file) {
5474 bs = bs->file->bs;
5475 continue;
5478 if (bs->drv->is_filter && bs->backing) {
5479 bs = bs->backing->bs;
5480 continue;
5483 break;
5486 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5487 assert(bs->drv->bdrv_debug_remove_breakpoint);
5488 return bs;
5491 return NULL;
5494 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5495 const char *tag)
5497 bs = bdrv_find_debug_node(bs);
5498 if (bs) {
5499 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5502 return -ENOTSUP;
5505 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5507 bs = bdrv_find_debug_node(bs);
5508 if (bs) {
5509 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5512 return -ENOTSUP;
5515 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5517 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5518 bs = bs->file ? bs->file->bs : NULL;
5521 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5522 return bs->drv->bdrv_debug_resume(bs, tag);
5525 return -ENOTSUP;
5528 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5530 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5531 bs = bs->file ? bs->file->bs : NULL;
5534 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5535 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5538 return false;
5541 /* backing_file can either be relative, or absolute, or a protocol. If it is
5542 * relative, it must be relative to the chain. So, passing in bs->filename
5543 * from a BDS as backing_file should not be done, as that may be relative to
5544 * the CWD rather than the chain. */
5545 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5546 const char *backing_file)
5548 char *filename_full = NULL;
5549 char *backing_file_full = NULL;
5550 char *filename_tmp = NULL;
5551 int is_protocol = 0;
5552 BlockDriverState *curr_bs = NULL;
5553 BlockDriverState *retval = NULL;
5555 if (!bs || !bs->drv || !backing_file) {
5556 return NULL;
5559 filename_full = g_malloc(PATH_MAX);
5560 backing_file_full = g_malloc(PATH_MAX);
5562 is_protocol = path_has_protocol(backing_file);
5564 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
5566 /* If either of the filename paths is actually a protocol, then
5567 * compare unmodified paths; otherwise make paths relative */
5568 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5569 char *backing_file_full_ret;
5571 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
5572 retval = curr_bs->backing->bs;
5573 break;
5575 /* Also check against the full backing filename for the image */
5576 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5577 NULL);
5578 if (backing_file_full_ret) {
5579 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5580 g_free(backing_file_full_ret);
5581 if (equal) {
5582 retval = curr_bs->backing->bs;
5583 break;
5586 } else {
5587 /* If not an absolute filename path, make it relative to the current
5588 * image's filename path */
5589 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5590 NULL);
5591 /* We are going to compare canonicalized absolute pathnames */
5592 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5593 g_free(filename_tmp);
5594 continue;
5596 g_free(filename_tmp);
5598 /* We need to make sure the backing filename we are comparing against
5599 * is relative to the current image filename (or absolute) */
5600 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5601 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5602 g_free(filename_tmp);
5603 continue;
5605 g_free(filename_tmp);
5607 if (strcmp(backing_file_full, filename_full) == 0) {
5608 retval = curr_bs->backing->bs;
5609 break;
5614 g_free(filename_full);
5615 g_free(backing_file_full);
5616 return retval;
5619 void bdrv_init(void)
5621 module_call_init(MODULE_INIT_BLOCK);
5624 void bdrv_init_with_whitelist(void)
5626 use_bdrv_whitelist = 1;
5627 bdrv_init();
5630 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5631 Error **errp)
5633 BdrvChild *child, *parent;
5634 uint64_t perm, shared_perm;
5635 Error *local_err = NULL;
5636 int ret;
5637 BdrvDirtyBitmap *bm;
5639 if (!bs->drv) {
5640 return;
5643 QLIST_FOREACH(child, &bs->children, next) {
5644 bdrv_co_invalidate_cache(child->bs, &local_err);
5645 if (local_err) {
5646 error_propagate(errp, local_err);
5647 return;
5652 * Update permissions, they may differ for inactive nodes.
5654 * Note that the required permissions of inactive images are always a
5655 * subset of the permissions required after activating the image. This
5656 * allows us to just get the permissions upfront without restricting
5657 * drv->bdrv_invalidate_cache().
5659 * It also means that in error cases, we don't have to try and revert to
5660 * the old permissions (which is an operation that could fail, too). We can
5661 * just keep the extended permissions for the next time that an activation
5662 * of the image is tried.
5664 if (bs->open_flags & BDRV_O_INACTIVE) {
5665 bs->open_flags &= ~BDRV_O_INACTIVE;
5666 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5667 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, &local_err);
5668 if (ret < 0) {
5669 bs->open_flags |= BDRV_O_INACTIVE;
5670 error_propagate(errp, local_err);
5671 return;
5673 bdrv_set_perm(bs, perm, shared_perm);
5675 if (bs->drv->bdrv_co_invalidate_cache) {
5676 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5677 if (local_err) {
5678 bs->open_flags |= BDRV_O_INACTIVE;
5679 error_propagate(errp, local_err);
5680 return;
5684 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5685 bdrv_dirty_bitmap_skip_store(bm, false);
5688 ret = refresh_total_sectors(bs, bs->total_sectors);
5689 if (ret < 0) {
5690 bs->open_flags |= BDRV_O_INACTIVE;
5691 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5692 return;
5696 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5697 if (parent->klass->activate) {
5698 parent->klass->activate(parent, &local_err);
5699 if (local_err) {
5700 bs->open_flags |= BDRV_O_INACTIVE;
5701 error_propagate(errp, local_err);
5702 return;
5708 typedef struct InvalidateCacheCo {
5709 BlockDriverState *bs;
5710 Error **errp;
5711 bool done;
5712 } InvalidateCacheCo;
5714 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5716 InvalidateCacheCo *ico = opaque;
5717 bdrv_co_invalidate_cache(ico->bs, ico->errp);
5718 ico->done = true;
5719 aio_wait_kick();
5722 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5724 Coroutine *co;
5725 InvalidateCacheCo ico = {
5726 .bs = bs,
5727 .done = false,
5728 .errp = errp
5731 if (qemu_in_coroutine()) {
5732 /* Fast-path if already in coroutine context */
5733 bdrv_invalidate_cache_co_entry(&ico);
5734 } else {
5735 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
5736 bdrv_coroutine_enter(bs, co);
5737 BDRV_POLL_WHILE(bs, !ico.done);
5741 void bdrv_invalidate_cache_all(Error **errp)
5743 BlockDriverState *bs;
5744 Error *local_err = NULL;
5745 BdrvNextIterator it;
5747 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5748 AioContext *aio_context = bdrv_get_aio_context(bs);
5750 aio_context_acquire(aio_context);
5751 bdrv_invalidate_cache(bs, &local_err);
5752 aio_context_release(aio_context);
5753 if (local_err) {
5754 error_propagate(errp, local_err);
5755 bdrv_next_cleanup(&it);
5756 return;
5761 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5763 BdrvChild *parent;
5765 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5766 if (parent->klass->parent_is_bds) {
5767 BlockDriverState *parent_bs = parent->opaque;
5768 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5769 return true;
5774 return false;
5777 static int bdrv_inactivate_recurse(BlockDriverState *bs)
5779 BdrvChild *child, *parent;
5780 bool tighten_restrictions;
5781 uint64_t perm, shared_perm;
5782 int ret;
5784 if (!bs->drv) {
5785 return -ENOMEDIUM;
5788 /* Make sure that we don't inactivate a child before its parent.
5789 * It will be covered by recursion from the yet active parent. */
5790 if (bdrv_has_bds_parent(bs, true)) {
5791 return 0;
5794 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5796 /* Inactivate this node */
5797 if (bs->drv->bdrv_inactivate) {
5798 ret = bs->drv->bdrv_inactivate(bs);
5799 if (ret < 0) {
5800 return ret;
5804 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5805 if (parent->klass->inactivate) {
5806 ret = parent->klass->inactivate(parent);
5807 if (ret < 0) {
5808 return ret;
5813 bs->open_flags |= BDRV_O_INACTIVE;
5815 /* Update permissions, they may differ for inactive nodes */
5816 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5817 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5818 &tighten_restrictions, NULL);
5819 assert(tighten_restrictions == false);
5820 if (ret < 0) {
5821 /* We only tried to loosen restrictions, so errors are not fatal */
5822 bdrv_abort_perm_update(bs);
5823 } else {
5824 bdrv_set_perm(bs, perm, shared_perm);
5828 /* Recursively inactivate children */
5829 QLIST_FOREACH(child, &bs->children, next) {
5830 ret = bdrv_inactivate_recurse(child->bs);
5831 if (ret < 0) {
5832 return ret;
5836 return 0;
5839 int bdrv_inactivate_all(void)
5841 BlockDriverState *bs = NULL;
5842 BdrvNextIterator it;
5843 int ret = 0;
5844 GSList *aio_ctxs = NULL, *ctx;
5846 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5847 AioContext *aio_context = bdrv_get_aio_context(bs);
5849 if (!g_slist_find(aio_ctxs, aio_context)) {
5850 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5851 aio_context_acquire(aio_context);
5855 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5856 /* Nodes with BDS parents are covered by recursion from the last
5857 * parent that gets inactivated. Don't inactivate them a second
5858 * time if that has already happened. */
5859 if (bdrv_has_bds_parent(bs, false)) {
5860 continue;
5862 ret = bdrv_inactivate_recurse(bs);
5863 if (ret < 0) {
5864 bdrv_next_cleanup(&it);
5865 goto out;
5869 out:
5870 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5871 AioContext *aio_context = ctx->data;
5872 aio_context_release(aio_context);
5874 g_slist_free(aio_ctxs);
5876 return ret;
5879 /**************************************************************/
5880 /* removable device support */
5883 * Return TRUE if the media is present
5885 bool bdrv_is_inserted(BlockDriverState *bs)
5887 BlockDriver *drv = bs->drv;
5888 BdrvChild *child;
5890 if (!drv) {
5891 return false;
5893 if (drv->bdrv_is_inserted) {
5894 return drv->bdrv_is_inserted(bs);
5896 QLIST_FOREACH(child, &bs->children, next) {
5897 if (!bdrv_is_inserted(child->bs)) {
5898 return false;
5901 return true;
5905 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5907 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
5909 BlockDriver *drv = bs->drv;
5911 if (drv && drv->bdrv_eject) {
5912 drv->bdrv_eject(bs, eject_flag);
5917 * Lock or unlock the media (if it is locked, the user won't be able
5918 * to eject it manually).
5920 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
5922 BlockDriver *drv = bs->drv;
5924 trace_bdrv_lock_medium(bs, locked);
5926 if (drv && drv->bdrv_lock_medium) {
5927 drv->bdrv_lock_medium(bs, locked);
5931 /* Get a reference to bs */
5932 void bdrv_ref(BlockDriverState *bs)
5934 bs->refcnt++;
5937 /* Release a previously grabbed reference to bs.
5938 * If after releasing, reference count is zero, the BlockDriverState is
5939 * deleted. */
5940 void bdrv_unref(BlockDriverState *bs)
5942 if (!bs) {
5943 return;
5945 assert(bs->refcnt > 0);
5946 if (--bs->refcnt == 0) {
5947 bdrv_delete(bs);
5951 struct BdrvOpBlocker {
5952 Error *reason;
5953 QLIST_ENTRY(BdrvOpBlocker) list;
5956 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5958 BdrvOpBlocker *blocker;
5959 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5960 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5961 blocker = QLIST_FIRST(&bs->op_blockers[op]);
5962 error_propagate_prepend(errp, error_copy(blocker->reason),
5963 "Node '%s' is busy: ",
5964 bdrv_get_device_or_node_name(bs));
5965 return true;
5967 return false;
5970 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5972 BdrvOpBlocker *blocker;
5973 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5975 blocker = g_new0(BdrvOpBlocker, 1);
5976 blocker->reason = reason;
5977 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5980 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5982 BdrvOpBlocker *blocker, *next;
5983 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5984 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5985 if (blocker->reason == reason) {
5986 QLIST_REMOVE(blocker, list);
5987 g_free(blocker);
5992 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5994 int i;
5995 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5996 bdrv_op_block(bs, i, reason);
6000 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6002 int i;
6003 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6004 bdrv_op_unblock(bs, i, reason);
6008 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6010 int i;
6012 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6013 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6014 return false;
6017 return true;
6020 void bdrv_img_create(const char *filename, const char *fmt,
6021 const char *base_filename, const char *base_fmt,
6022 char *options, uint64_t img_size, int flags, bool quiet,
6023 Error **errp)
6025 QemuOptsList *create_opts = NULL;
6026 QemuOpts *opts = NULL;
6027 const char *backing_fmt, *backing_file;
6028 int64_t size;
6029 BlockDriver *drv, *proto_drv;
6030 Error *local_err = NULL;
6031 int ret = 0;
6033 /* Find driver and parse its options */
6034 drv = bdrv_find_format(fmt);
6035 if (!drv) {
6036 error_setg(errp, "Unknown file format '%s'", fmt);
6037 return;
6040 proto_drv = bdrv_find_protocol(filename, true, errp);
6041 if (!proto_drv) {
6042 return;
6045 if (!drv->create_opts) {
6046 error_setg(errp, "Format driver '%s' does not support image creation",
6047 drv->format_name);
6048 return;
6051 if (!proto_drv->create_opts) {
6052 error_setg(errp, "Protocol driver '%s' does not support image creation",
6053 proto_drv->format_name);
6054 return;
6057 /* Create parameter list */
6058 create_opts = qemu_opts_append(create_opts, drv->create_opts);
6059 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6061 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6063 /* Parse -o options */
6064 if (options) {
6065 qemu_opts_do_parse(opts, options, NULL, &local_err);
6066 if (local_err) {
6067 goto out;
6071 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6072 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6073 } else if (img_size != UINT64_C(-1)) {
6074 error_setg(errp, "The image size must be specified only once");
6075 goto out;
6078 if (base_filename) {
6079 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
6080 if (local_err) {
6081 error_setg(errp, "Backing file not supported for file format '%s'",
6082 fmt);
6083 goto out;
6087 if (base_fmt) {
6088 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
6089 if (local_err) {
6090 error_setg(errp, "Backing file format not supported for file "
6091 "format '%s'", fmt);
6092 goto out;
6096 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6097 if (backing_file) {
6098 if (!strcmp(filename, backing_file)) {
6099 error_setg(errp, "Error: Trying to create an image with the "
6100 "same filename as the backing file");
6101 goto out;
6105 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6107 /* The size for the image must always be specified, unless we have a backing
6108 * file and we have not been forbidden from opening it. */
6109 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6110 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6111 BlockDriverState *bs;
6112 char *full_backing;
6113 int back_flags;
6114 QDict *backing_options = NULL;
6116 full_backing =
6117 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6118 &local_err);
6119 if (local_err) {
6120 goto out;
6122 assert(full_backing);
6124 /* backing files always opened read-only */
6125 back_flags = flags;
6126 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6128 backing_options = qdict_new();
6129 if (backing_fmt) {
6130 qdict_put_str(backing_options, "driver", backing_fmt);
6132 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
6134 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6135 &local_err);
6136 g_free(full_backing);
6137 if (!bs && size != -1) {
6138 /* Couldn't open BS, but we have a size, so it's nonfatal */
6139 warn_reportf_err(local_err,
6140 "Could not verify backing image. "
6141 "This may become an error in future versions.\n");
6142 local_err = NULL;
6143 } else if (!bs) {
6144 /* Couldn't open bs, do not have size */
6145 error_append_hint(&local_err,
6146 "Could not open backing image to determine size.\n");
6147 goto out;
6148 } else {
6149 if (size == -1) {
6150 /* Opened BS, have no size */
6151 size = bdrv_getlength(bs);
6152 if (size < 0) {
6153 error_setg_errno(errp, -size, "Could not get size of '%s'",
6154 backing_file);
6155 bdrv_unref(bs);
6156 goto out;
6158 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6160 bdrv_unref(bs);
6162 } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6164 if (size == -1) {
6165 error_setg(errp, "Image creation needs a size parameter");
6166 goto out;
6169 if (!quiet) {
6170 printf("Formatting '%s', fmt=%s ", filename, fmt);
6171 qemu_opts_print(opts, " ");
6172 puts("");
6175 ret = bdrv_create(drv, filename, opts, &local_err);
6177 if (ret == -EFBIG) {
6178 /* This is generally a better message than whatever the driver would
6179 * deliver (especially because of the cluster_size_hint), since that
6180 * is most probably not much different from "image too large". */
6181 const char *cluster_size_hint = "";
6182 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
6183 cluster_size_hint = " (try using a larger cluster size)";
6185 error_setg(errp, "The image size is too large for file format '%s'"
6186 "%s", fmt, cluster_size_hint);
6187 error_free(local_err);
6188 local_err = NULL;
6191 out:
6192 qemu_opts_del(opts);
6193 qemu_opts_free(create_opts);
6194 error_propagate(errp, local_err);
6197 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6199 return bs ? bs->aio_context : qemu_get_aio_context();
6202 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6204 aio_co_enter(bdrv_get_aio_context(bs), co);
6207 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6209 QLIST_REMOVE(ban, list);
6210 g_free(ban);
6213 static void bdrv_detach_aio_context(BlockDriverState *bs)
6215 BdrvAioNotifier *baf, *baf_tmp;
6217 assert(!bs->walking_aio_notifiers);
6218 bs->walking_aio_notifiers = true;
6219 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6220 if (baf->deleted) {
6221 bdrv_do_remove_aio_context_notifier(baf);
6222 } else {
6223 baf->detach_aio_context(baf->opaque);
6226 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6227 * remove remaining aio notifiers if we aren't called again.
6229 bs->walking_aio_notifiers = false;
6231 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
6232 bs->drv->bdrv_detach_aio_context(bs);
6235 if (bs->quiesce_counter) {
6236 aio_enable_external(bs->aio_context);
6238 bs->aio_context = NULL;
6241 static void bdrv_attach_aio_context(BlockDriverState *bs,
6242 AioContext *new_context)
6244 BdrvAioNotifier *ban, *ban_tmp;
6246 if (bs->quiesce_counter) {
6247 aio_disable_external(new_context);
6250 bs->aio_context = new_context;
6252 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
6253 bs->drv->bdrv_attach_aio_context(bs, new_context);
6256 assert(!bs->walking_aio_notifiers);
6257 bs->walking_aio_notifiers = true;
6258 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6259 if (ban->deleted) {
6260 bdrv_do_remove_aio_context_notifier(ban);
6261 } else {
6262 ban->attached_aio_context(new_context, ban->opaque);
6265 bs->walking_aio_notifiers = false;
6269 * Changes the AioContext used for fd handlers, timers, and BHs by this
6270 * BlockDriverState and all its children and parents.
6272 * Must be called from the main AioContext.
6274 * The caller must own the AioContext lock for the old AioContext of bs, but it
6275 * must not own the AioContext lock for new_context (unless new_context is the
6276 * same as the current context of bs).
6278 * @ignore will accumulate all visited BdrvChild object. The caller is
6279 * responsible for freeing the list afterwards.
6281 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6282 AioContext *new_context, GSList **ignore)
6284 AioContext *old_context = bdrv_get_aio_context(bs);
6285 BdrvChild *child;
6287 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6289 if (old_context == new_context) {
6290 return;
6293 bdrv_drained_begin(bs);
6295 QLIST_FOREACH(child, &bs->children, next) {
6296 if (g_slist_find(*ignore, child)) {
6297 continue;
6299 *ignore = g_slist_prepend(*ignore, child);
6300 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6302 QLIST_FOREACH(child, &bs->parents, next_parent) {
6303 if (g_slist_find(*ignore, child)) {
6304 continue;
6306 assert(child->klass->set_aio_ctx);
6307 *ignore = g_slist_prepend(*ignore, child);
6308 child->klass->set_aio_ctx(child, new_context, ignore);
6311 bdrv_detach_aio_context(bs);
6313 /* Acquire the new context, if necessary */
6314 if (qemu_get_aio_context() != new_context) {
6315 aio_context_acquire(new_context);
6318 bdrv_attach_aio_context(bs, new_context);
6321 * If this function was recursively called from
6322 * bdrv_set_aio_context_ignore(), there may be nodes in the
6323 * subtree that have not yet been moved to the new AioContext.
6324 * Release the old one so bdrv_drained_end() can poll them.
6326 if (qemu_get_aio_context() != old_context) {
6327 aio_context_release(old_context);
6330 bdrv_drained_end(bs);
6332 if (qemu_get_aio_context() != old_context) {
6333 aio_context_acquire(old_context);
6335 if (qemu_get_aio_context() != new_context) {
6336 aio_context_release(new_context);
6340 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6341 GSList **ignore, Error **errp)
6343 if (g_slist_find(*ignore, c)) {
6344 return true;
6346 *ignore = g_slist_prepend(*ignore, c);
6349 * A BdrvChildClass that doesn't handle AioContext changes cannot
6350 * tolerate any AioContext changes
6352 if (!c->klass->can_set_aio_ctx) {
6353 char *user = bdrv_child_user_desc(c);
6354 error_setg(errp, "Changing iothreads is not supported by %s", user);
6355 g_free(user);
6356 return false;
6358 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
6359 assert(!errp || *errp);
6360 return false;
6362 return true;
6365 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6366 GSList **ignore, Error **errp)
6368 if (g_slist_find(*ignore, c)) {
6369 return true;
6371 *ignore = g_slist_prepend(*ignore, c);
6372 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6375 /* @ignore will accumulate all visited BdrvChild object. The caller is
6376 * responsible for freeing the list afterwards. */
6377 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6378 GSList **ignore, Error **errp)
6380 BdrvChild *c;
6382 if (bdrv_get_aio_context(bs) == ctx) {
6383 return true;
6386 QLIST_FOREACH(c, &bs->parents, next_parent) {
6387 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6388 return false;
6391 QLIST_FOREACH(c, &bs->children, next) {
6392 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6393 return false;
6397 return true;
6400 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6401 BdrvChild *ignore_child, Error **errp)
6403 GSList *ignore;
6404 bool ret;
6406 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6407 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6408 g_slist_free(ignore);
6410 if (!ret) {
6411 return -EPERM;
6414 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6415 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6416 g_slist_free(ignore);
6418 return 0;
6421 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6422 Error **errp)
6424 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6427 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6428 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6429 void (*detach_aio_context)(void *opaque), void *opaque)
6431 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6432 *ban = (BdrvAioNotifier){
6433 .attached_aio_context = attached_aio_context,
6434 .detach_aio_context = detach_aio_context,
6435 .opaque = opaque
6438 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6441 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6442 void (*attached_aio_context)(AioContext *,
6443 void *),
6444 void (*detach_aio_context)(void *),
6445 void *opaque)
6447 BdrvAioNotifier *ban, *ban_next;
6449 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6450 if (ban->attached_aio_context == attached_aio_context &&
6451 ban->detach_aio_context == detach_aio_context &&
6452 ban->opaque == opaque &&
6453 ban->deleted == false)
6455 if (bs->walking_aio_notifiers) {
6456 ban->deleted = true;
6457 } else {
6458 bdrv_do_remove_aio_context_notifier(ban);
6460 return;
6464 abort();
6467 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6468 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6469 Error **errp)
6471 if (!bs->drv) {
6472 error_setg(errp, "Node is ejected");
6473 return -ENOMEDIUM;
6475 if (!bs->drv->bdrv_amend_options) {
6476 error_setg(errp, "Block driver '%s' does not support option amendment",
6477 bs->drv->format_name);
6478 return -ENOTSUP;
6480 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6484 * This function checks whether the given @to_replace is allowed to be
6485 * replaced by a node that always shows the same data as @bs. This is
6486 * used for example to verify whether the mirror job can replace
6487 * @to_replace by the target mirrored from @bs.
6488 * To be replaceable, @bs and @to_replace may either be guaranteed to
6489 * always show the same data (because they are only connected through
6490 * filters), or some driver may allow replacing one of its children
6491 * because it can guarantee that this child's data is not visible at
6492 * all (for example, for dissenting quorum children that have no other
6493 * parents).
6495 bool bdrv_recurse_can_replace(BlockDriverState *bs,
6496 BlockDriverState *to_replace)
6498 if (!bs || !bs->drv) {
6499 return false;
6502 if (bs == to_replace) {
6503 return true;
6506 /* See what the driver can do */
6507 if (bs->drv->bdrv_recurse_can_replace) {
6508 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6511 /* For filters without an own implementation, we can recurse on our own */
6512 if (bs->drv->is_filter) {
6513 BdrvChild *child = bs->file ?: bs->backing;
6514 return bdrv_recurse_can_replace(child->bs, to_replace);
6517 /* Safe default */
6518 return false;
6522 * Check whether the given @node_name can be replaced by a node that
6523 * has the same data as @parent_bs. If so, return @node_name's BDS;
6524 * NULL otherwise.
6526 * @node_name must be a (recursive) *child of @parent_bs (or this
6527 * function will return NULL).
6529 * The result (whether the node can be replaced or not) is only valid
6530 * for as long as no graph or permission changes occur.
6532 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6533 const char *node_name, Error **errp)
6535 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
6536 AioContext *aio_context;
6538 if (!to_replace_bs) {
6539 error_setg(errp, "Node name '%s' not found", node_name);
6540 return NULL;
6543 aio_context = bdrv_get_aio_context(to_replace_bs);
6544 aio_context_acquire(aio_context);
6546 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
6547 to_replace_bs = NULL;
6548 goto out;
6551 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6552 * most non filter in order to prevent data corruption.
6553 * Another benefit is that this tests exclude backing files which are
6554 * blocked by the backing blockers.
6556 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6557 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6558 "because it cannot be guaranteed that doing so would not "
6559 "lead to an abrupt change of visible data",
6560 node_name, parent_bs->node_name);
6561 to_replace_bs = NULL;
6562 goto out;
6565 out:
6566 aio_context_release(aio_context);
6567 return to_replace_bs;
6571 * Iterates through the list of runtime option keys that are said to
6572 * be "strong" for a BDS. An option is called "strong" if it changes
6573 * a BDS's data. For example, the null block driver's "size" and
6574 * "read-zeroes" options are strong, but its "latency-ns" option is
6575 * not.
6577 * If a key returned by this function ends with a dot, all options
6578 * starting with that prefix are strong.
6580 static const char *const *strong_options(BlockDriverState *bs,
6581 const char *const *curopt)
6583 static const char *const global_options[] = {
6584 "driver", "filename", NULL
6587 if (!curopt) {
6588 return &global_options[0];
6591 curopt++;
6592 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6593 curopt = bs->drv->strong_runtime_opts;
6596 return (curopt && *curopt) ? curopt : NULL;
6600 * Copies all strong runtime options from bs->options to the given
6601 * QDict. The set of strong option keys is determined by invoking
6602 * strong_options().
6604 * Returns true iff any strong option was present in bs->options (and
6605 * thus copied to the target QDict) with the exception of "filename"
6606 * and "driver". The caller is expected to use this value to decide
6607 * whether the existence of strong options prevents the generation of
6608 * a plain filename.
6610 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6612 bool found_any = false;
6613 const char *const *option_name = NULL;
6615 if (!bs->drv) {
6616 return false;
6619 while ((option_name = strong_options(bs, option_name))) {
6620 bool option_given = false;
6622 assert(strlen(*option_name) > 0);
6623 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6624 QObject *entry = qdict_get(bs->options, *option_name);
6625 if (!entry) {
6626 continue;
6629 qdict_put_obj(d, *option_name, qobject_ref(entry));
6630 option_given = true;
6631 } else {
6632 const QDictEntry *entry;
6633 for (entry = qdict_first(bs->options); entry;
6634 entry = qdict_next(bs->options, entry))
6636 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6637 qdict_put_obj(d, qdict_entry_key(entry),
6638 qobject_ref(qdict_entry_value(entry)));
6639 option_given = true;
6644 /* While "driver" and "filename" need to be included in a JSON filename,
6645 * their existence does not prohibit generation of a plain filename. */
6646 if (!found_any && option_given &&
6647 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6649 found_any = true;
6653 if (!qdict_haskey(d, "driver")) {
6654 /* Drivers created with bdrv_new_open_driver() may not have a
6655 * @driver option. Add it here. */
6656 qdict_put_str(d, "driver", bs->drv->format_name);
6659 return found_any;
6662 /* Note: This function may return false positives; it may return true
6663 * even if opening the backing file specified by bs's image header
6664 * would result in exactly bs->backing. */
6665 static bool bdrv_backing_overridden(BlockDriverState *bs)
6667 if (bs->backing) {
6668 return strcmp(bs->auto_backing_file,
6669 bs->backing->bs->filename);
6670 } else {
6671 /* No backing BDS, so if the image header reports any backing
6672 * file, it must have been suppressed */
6673 return bs->auto_backing_file[0] != '\0';
6677 /* Updates the following BDS fields:
6678 * - exact_filename: A filename which may be used for opening a block device
6679 * which (mostly) equals the given BDS (even without any
6680 * other options; so reading and writing must return the same
6681 * results, but caching etc. may be different)
6682 * - full_open_options: Options which, when given when opening a block device
6683 * (without a filename), result in a BDS (mostly)
6684 * equalling the given one
6685 * - filename: If exact_filename is set, it is copied here. Otherwise,
6686 * full_open_options is converted to a JSON object, prefixed with
6687 * "json:" (for use through the JSON pseudo protocol) and put here.
6689 void bdrv_refresh_filename(BlockDriverState *bs)
6691 BlockDriver *drv = bs->drv;
6692 BdrvChild *child;
6693 QDict *opts;
6694 bool backing_overridden;
6695 bool generate_json_filename; /* Whether our default implementation should
6696 fill exact_filename (false) or not (true) */
6698 if (!drv) {
6699 return;
6702 /* This BDS's file name may depend on any of its children's file names, so
6703 * refresh those first */
6704 QLIST_FOREACH(child, &bs->children, next) {
6705 bdrv_refresh_filename(child->bs);
6708 if (bs->implicit) {
6709 /* For implicit nodes, just copy everything from the single child */
6710 child = QLIST_FIRST(&bs->children);
6711 assert(QLIST_NEXT(child, next) == NULL);
6713 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6714 child->bs->exact_filename);
6715 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6717 qobject_unref(bs->full_open_options);
6718 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6720 return;
6723 backing_overridden = bdrv_backing_overridden(bs);
6725 if (bs->open_flags & BDRV_O_NO_IO) {
6726 /* Without I/O, the backing file does not change anything.
6727 * Therefore, in such a case (primarily qemu-img), we can
6728 * pretend the backing file has not been overridden even if
6729 * it technically has been. */
6730 backing_overridden = false;
6733 /* Gather the options QDict */
6734 opts = qdict_new();
6735 generate_json_filename = append_strong_runtime_options(opts, bs);
6736 generate_json_filename |= backing_overridden;
6738 if (drv->bdrv_gather_child_options) {
6739 /* Some block drivers may not want to present all of their children's
6740 * options, or name them differently from BdrvChild.name */
6741 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6742 } else {
6743 QLIST_FOREACH(child, &bs->children, next) {
6744 if (child->klass == &child_backing && !backing_overridden) {
6745 /* We can skip the backing BDS if it has not been overridden */
6746 continue;
6749 qdict_put(opts, child->name,
6750 qobject_ref(child->bs->full_open_options));
6753 if (backing_overridden && !bs->backing) {
6754 /* Force no backing file */
6755 qdict_put_null(opts, "backing");
6759 qobject_unref(bs->full_open_options);
6760 bs->full_open_options = opts;
6762 if (drv->bdrv_refresh_filename) {
6763 /* Obsolete information is of no use here, so drop the old file name
6764 * information before refreshing it */
6765 bs->exact_filename[0] = '\0';
6767 drv->bdrv_refresh_filename(bs);
6768 } else if (bs->file) {
6769 /* Try to reconstruct valid information from the underlying file */
6771 bs->exact_filename[0] = '\0';
6774 * We can use the underlying file's filename if:
6775 * - it has a filename,
6776 * - the file is a protocol BDS, and
6777 * - opening that file (as this BDS's format) will automatically create
6778 * the BDS tree we have right now, that is:
6779 * - the user did not significantly change this BDS's behavior with
6780 * some explicit (strong) options
6781 * - no non-file child of this BDS has been overridden by the user
6782 * Both of these conditions are represented by generate_json_filename.
6784 if (bs->file->bs->exact_filename[0] &&
6785 bs->file->bs->drv->bdrv_file_open &&
6786 !generate_json_filename)
6788 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6792 if (bs->exact_filename[0]) {
6793 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
6794 } else {
6795 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6796 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6797 qstring_get_str(json));
6798 qobject_unref(json);
6802 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6804 BlockDriver *drv = bs->drv;
6806 if (!drv) {
6807 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6808 return NULL;
6811 if (drv->bdrv_dirname) {
6812 return drv->bdrv_dirname(bs, errp);
6815 if (bs->file) {
6816 return bdrv_dirname(bs->file->bs, errp);
6819 bdrv_refresh_filename(bs);
6820 if (bs->exact_filename[0] != '\0') {
6821 return path_combine(bs->exact_filename, "");
6824 error_setg(errp, "Cannot generate a base directory for %s nodes",
6825 drv->format_name);
6826 return NULL;
6830 * Hot add/remove a BDS's child. So the user can take a child offline when
6831 * it is broken and take a new child online
6833 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6834 Error **errp)
6837 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6838 error_setg(errp, "The node %s does not support adding a child",
6839 bdrv_get_device_or_node_name(parent_bs));
6840 return;
6843 if (!QLIST_EMPTY(&child_bs->parents)) {
6844 error_setg(errp, "The node %s already has a parent",
6845 child_bs->node_name);
6846 return;
6849 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6852 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6854 BdrvChild *tmp;
6856 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6857 error_setg(errp, "The node %s does not support removing a child",
6858 bdrv_get_device_or_node_name(parent_bs));
6859 return;
6862 QLIST_FOREACH(tmp, &parent_bs->children, next) {
6863 if (tmp == child) {
6864 break;
6868 if (!tmp) {
6869 error_setg(errp, "The node %s does not have a child named %s",
6870 bdrv_get_device_or_node_name(parent_bs),
6871 bdrv_get_device_or_node_name(child->bs));
6872 return;
6875 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
6878 int bdrv_make_empty(BdrvChild *c, Error **errp)
6880 BlockDriver *drv = c->bs->drv;
6881 int ret;
6883 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
6885 if (!drv->bdrv_make_empty) {
6886 error_setg(errp, "%s does not support emptying nodes",
6887 drv->format_name);
6888 return -ENOTSUP;
6891 ret = drv->bdrv_make_empty(c->bs);
6892 if (ret < 0) {
6893 error_setg_errno(errp, -ret, "Failed to empty %s",
6894 c->bs->filename);
6895 return ret;
6898 return 0;