Fix rules for manpage installation
[qemu/ar7.git] / block.c
blob262c98dfb367854c6f21c159a1fe7a93aa2aa94d
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 /* If non-zero, use only whitelisted block drivers */
84 static int use_bdrv_whitelist;
86 #ifdef _WIN32
87 static int is_windows_drive_prefix(const char *filename)
89 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
90 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
91 filename[1] == ':');
94 int is_windows_drive(const char *filename)
96 if (is_windows_drive_prefix(filename) &&
97 filename[2] == '\0')
98 return 1;
99 if (strstart(filename, "\\\\.\\", NULL) ||
100 strstart(filename, "//./", NULL))
101 return 1;
102 return 0;
104 #endif
106 size_t bdrv_opt_mem_align(BlockDriverState *bs)
108 if (!bs || !bs->drv) {
109 /* page size or 4k (hdd sector size) should be on the safe side */
110 return MAX(4096, qemu_real_host_page_size);
113 return bs->bl.opt_mem_alignment;
116 size_t bdrv_min_mem_align(BlockDriverState *bs)
118 if (!bs || !bs->drv) {
119 /* page size or 4k (hdd sector size) should be on the safe side */
120 return MAX(4096, qemu_real_host_page_size);
123 return bs->bl.min_mem_alignment;
126 /* check if the path starts with "<protocol>:" */
127 int path_has_protocol(const char *path)
129 const char *p;
131 #ifdef _WIN32
132 if (is_windows_drive(path) ||
133 is_windows_drive_prefix(path)) {
134 return 0;
136 p = path + strcspn(path, ":/\\");
137 #else
138 p = path + strcspn(path, ":/");
139 #endif
141 return *p == ':';
144 int path_is_absolute(const char *path)
146 #ifdef _WIN32
147 /* specific case for names like: "\\.\d:" */
148 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
149 return 1;
151 return (*path == '/' || *path == '\\');
152 #else
153 return (*path == '/');
154 #endif
157 /* if filename is absolute, just return its duplicate. Otherwise, build a
158 path to it by considering it is relative to base_path. URL are
159 supported. */
160 char *path_combine(const char *base_path, const char *filename)
162 const char *protocol_stripped = NULL;
163 const char *p, *p1;
164 char *result;
165 int len;
167 if (path_is_absolute(filename)) {
168 return g_strdup(filename);
171 if (path_has_protocol(base_path)) {
172 protocol_stripped = strchr(base_path, ':');
173 if (protocol_stripped) {
174 protocol_stripped++;
177 p = protocol_stripped ?: base_path;
179 p1 = strrchr(base_path, '/');
180 #ifdef _WIN32
182 const char *p2;
183 p2 = strrchr(base_path, '\\');
184 if (!p1 || p2 > p1) {
185 p1 = p2;
188 #endif
189 if (p1) {
190 p1++;
191 } else {
192 p1 = base_path;
194 if (p1 > p) {
195 p = p1;
197 len = p - base_path;
199 result = g_malloc(len + strlen(filename) + 1);
200 memcpy(result, base_path, len);
201 strcpy(result + len, filename);
203 return result;
207 * Helper function for bdrv_parse_filename() implementations to remove optional
208 * protocol prefixes (especially "file:") from a filename and for putting the
209 * stripped filename into the options QDict if there is such a prefix.
211 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
212 QDict *options)
214 if (strstart(filename, prefix, &filename)) {
215 /* Stripping the explicit protocol prefix may result in a protocol
216 * prefix being (wrongly) detected (if the filename contains a colon) */
217 if (path_has_protocol(filename)) {
218 QString *fat_filename;
220 /* This means there is some colon before the first slash; therefore,
221 * this cannot be an absolute path */
222 assert(!path_is_absolute(filename));
224 /* And we can thus fix the protocol detection issue by prefixing it
225 * by "./" */
226 fat_filename = qstring_from_str("./");
227 qstring_append(fat_filename, filename);
229 assert(!path_has_protocol(qstring_get_str(fat_filename)));
231 qdict_put(options, "filename", fat_filename);
232 } else {
233 /* If no protocol prefix was detected, we can use the shortened
234 * filename as-is */
235 qdict_put_str(options, "filename", filename);
241 /* Returns whether the image file is opened as read-only. Note that this can
242 * return false and writing to the image file is still not possible because the
243 * image is inactivated. */
244 bool bdrv_is_read_only(BlockDriverState *bs)
246 return bs->read_only;
249 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
250 bool ignore_allow_rdw, Error **errp)
252 /* Do not set read_only if copy_on_read is enabled */
253 if (bs->copy_on_read && read_only) {
254 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
255 bdrv_get_device_or_node_name(bs));
256 return -EINVAL;
259 /* Do not clear read_only if it is prohibited */
260 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
261 !ignore_allow_rdw)
263 error_setg(errp, "Node '%s' is read only",
264 bdrv_get_device_or_node_name(bs));
265 return -EPERM;
268 return 0;
272 * Called by a driver that can only provide a read-only image.
274 * Returns 0 if the node is already read-only or it could switch the node to
275 * read-only because BDRV_O_AUTO_RDONLY is set.
277 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
278 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
279 * is not NULL, it is used as the error message for the Error object.
281 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
282 Error **errp)
284 int ret = 0;
286 if (!(bs->open_flags & BDRV_O_RDWR)) {
287 return 0;
289 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
290 goto fail;
293 ret = bdrv_can_set_read_only(bs, true, false, NULL);
294 if (ret < 0) {
295 goto fail;
298 bs->read_only = true;
299 bs->open_flags &= ~BDRV_O_RDWR;
301 return 0;
303 fail:
304 error_setg(errp, "%s", errmsg ?: "Image is read-only");
305 return -EACCES;
309 * If @backing is empty, this function returns NULL without setting
310 * @errp. In all other cases, NULL will only be returned with @errp
311 * set.
313 * Therefore, a return value of NULL without @errp set means that
314 * there is no backing file; if @errp is set, there is one but its
315 * absolute filename cannot be generated.
317 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
318 const char *backing,
319 Error **errp)
321 if (backing[0] == '\0') {
322 return NULL;
323 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
324 return g_strdup(backing);
325 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
326 error_setg(errp, "Cannot use relative backing file names for '%s'",
327 backed);
328 return NULL;
329 } else {
330 return path_combine(backed, backing);
335 * If @filename is empty or NULL, this function returns NULL without
336 * setting @errp. In all other cases, NULL will only be returned with
337 * @errp set.
339 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
340 const char *filename, Error **errp)
342 char *dir, *full_name;
344 if (!filename || filename[0] == '\0') {
345 return NULL;
346 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
347 return g_strdup(filename);
350 dir = bdrv_dirname(relative_to, errp);
351 if (!dir) {
352 return NULL;
355 full_name = g_strconcat(dir, filename, NULL);
356 g_free(dir);
357 return full_name;
360 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
362 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
365 void bdrv_register(BlockDriver *bdrv)
367 assert(bdrv->format_name);
368 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
371 BlockDriverState *bdrv_new(void)
373 BlockDriverState *bs;
374 int i;
376 bs = g_new0(BlockDriverState, 1);
377 QLIST_INIT(&bs->dirty_bitmaps);
378 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
379 QLIST_INIT(&bs->op_blockers[i]);
381 notifier_with_return_list_init(&bs->before_write_notifiers);
382 qemu_co_mutex_init(&bs->reqs_lock);
383 qemu_mutex_init(&bs->dirty_bitmap_mutex);
384 bs->refcnt = 1;
385 bs->aio_context = qemu_get_aio_context();
387 qemu_co_queue_init(&bs->flush_queue);
389 for (i = 0; i < bdrv_drain_all_count; i++) {
390 bdrv_drained_begin(bs);
393 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
395 return bs;
398 static BlockDriver *bdrv_do_find_format(const char *format_name)
400 BlockDriver *drv1;
402 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
403 if (!strcmp(drv1->format_name, format_name)) {
404 return drv1;
408 return NULL;
411 BlockDriver *bdrv_find_format(const char *format_name)
413 BlockDriver *drv1;
414 int i;
416 drv1 = bdrv_do_find_format(format_name);
417 if (drv1) {
418 return drv1;
421 /* The driver isn't registered, maybe we need to load a module */
422 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
423 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
424 block_module_load_one(block_driver_modules[i].library_name);
425 break;
429 return bdrv_do_find_format(format_name);
432 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
434 static const char *whitelist_rw[] = {
435 CONFIG_BDRV_RW_WHITELIST
437 static const char *whitelist_ro[] = {
438 CONFIG_BDRV_RO_WHITELIST
440 const char **p;
442 if (!whitelist_rw[0] && !whitelist_ro[0]) {
443 return 1; /* no whitelist, anything goes */
446 for (p = whitelist_rw; *p; p++) {
447 if (!strcmp(format_name, *p)) {
448 return 1;
451 if (read_only) {
452 for (p = whitelist_ro; *p; p++) {
453 if (!strcmp(format_name, *p)) {
454 return 1;
458 return 0;
461 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
463 return bdrv_format_is_whitelisted(drv->format_name, read_only);
466 bool bdrv_uses_whitelist(void)
468 return use_bdrv_whitelist;
471 typedef struct CreateCo {
472 BlockDriver *drv;
473 char *filename;
474 QemuOpts *opts;
475 int ret;
476 Error *err;
477 } CreateCo;
479 static void coroutine_fn bdrv_create_co_entry(void *opaque)
481 Error *local_err = NULL;
482 int ret;
484 CreateCo *cco = opaque;
485 assert(cco->drv);
487 ret = cco->drv->bdrv_co_create_opts(cco->drv,
488 cco->filename, cco->opts, &local_err);
489 error_propagate(&cco->err, local_err);
490 cco->ret = ret;
493 int bdrv_create(BlockDriver *drv, const char* filename,
494 QemuOpts *opts, Error **errp)
496 int ret;
498 Coroutine *co;
499 CreateCo cco = {
500 .drv = drv,
501 .filename = g_strdup(filename),
502 .opts = opts,
503 .ret = NOT_DONE,
504 .err = NULL,
507 if (!drv->bdrv_co_create_opts) {
508 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
509 ret = -ENOTSUP;
510 goto out;
513 if (qemu_in_coroutine()) {
514 /* Fast-path if already in coroutine context */
515 bdrv_create_co_entry(&cco);
516 } else {
517 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
518 qemu_coroutine_enter(co);
519 while (cco.ret == NOT_DONE) {
520 aio_poll(qemu_get_aio_context(), true);
524 ret = cco.ret;
525 if (ret < 0) {
526 if (cco.err) {
527 error_propagate(errp, cco.err);
528 } else {
529 error_setg_errno(errp, -ret, "Could not create image");
533 out:
534 g_free(cco.filename);
535 return ret;
539 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
540 * least the given @minimum_size.
542 * On success, return @blk's actual length.
543 * Otherwise, return -errno.
545 static int64_t create_file_fallback_truncate(BlockBackend *blk,
546 int64_t minimum_size, Error **errp)
548 Error *local_err = NULL;
549 int64_t size;
550 int ret;
552 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
553 &local_err);
554 if (ret < 0 && ret != -ENOTSUP) {
555 error_propagate(errp, local_err);
556 return ret;
559 size = blk_getlength(blk);
560 if (size < 0) {
561 error_free(local_err);
562 error_setg_errno(errp, -size,
563 "Failed to inquire the new image file's length");
564 return size;
567 if (size < minimum_size) {
568 /* Need to grow the image, but we failed to do that */
569 error_propagate(errp, local_err);
570 return -ENOTSUP;
573 error_free(local_err);
574 local_err = NULL;
576 return size;
580 * Helper function for bdrv_create_file_fallback(): Zero the first
581 * sector to remove any potentially pre-existing image header.
583 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
584 int64_t current_size,
585 Error **errp)
587 int64_t bytes_to_clear;
588 int ret;
590 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
591 if (bytes_to_clear) {
592 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
593 if (ret < 0) {
594 error_setg_errno(errp, -ret,
595 "Failed to clear the new image's first sector");
596 return ret;
600 return 0;
604 * Simple implementation of bdrv_co_create_opts for protocol drivers
605 * which only support creation via opening a file
606 * (usually existing raw storage device)
608 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
609 const char *filename,
610 QemuOpts *opts,
611 Error **errp)
613 BlockBackend *blk;
614 QDict *options;
615 int64_t size = 0;
616 char *buf = NULL;
617 PreallocMode prealloc;
618 Error *local_err = NULL;
619 int ret;
621 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
622 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
623 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
624 PREALLOC_MODE_OFF, &local_err);
625 g_free(buf);
626 if (local_err) {
627 error_propagate(errp, local_err);
628 return -EINVAL;
631 if (prealloc != PREALLOC_MODE_OFF) {
632 error_setg(errp, "Unsupported preallocation mode '%s'",
633 PreallocMode_str(prealloc));
634 return -ENOTSUP;
637 options = qdict_new();
638 qdict_put_str(options, "driver", drv->format_name);
640 blk = blk_new_open(filename, NULL, options,
641 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
642 if (!blk) {
643 error_prepend(errp, "Protocol driver '%s' does not support image "
644 "creation, and opening the image failed: ",
645 drv->format_name);
646 return -EINVAL;
649 size = create_file_fallback_truncate(blk, size, errp);
650 if (size < 0) {
651 ret = size;
652 goto out;
655 ret = create_file_fallback_zero_first_sector(blk, size, errp);
656 if (ret < 0) {
657 goto out;
660 ret = 0;
661 out:
662 blk_unref(blk);
663 return ret;
666 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
668 BlockDriver *drv;
670 drv = bdrv_find_protocol(filename, true, errp);
671 if (drv == NULL) {
672 return -ENOENT;
675 return bdrv_create(drv, filename, opts, errp);
678 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
680 Error *local_err = NULL;
681 int ret;
683 assert(bs != NULL);
685 if (!bs->drv) {
686 error_setg(errp, "Block node '%s' is not opened", bs->filename);
687 return -ENOMEDIUM;
690 if (!bs->drv->bdrv_co_delete_file) {
691 error_setg(errp, "Driver '%s' does not support image deletion",
692 bs->drv->format_name);
693 return -ENOTSUP;
696 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
697 if (ret < 0) {
698 error_propagate(errp, local_err);
701 return ret;
705 * Try to get @bs's logical and physical block size.
706 * On success, store them in @bsz struct and return 0.
707 * On failure return -errno.
708 * @bs must not be empty.
710 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
712 BlockDriver *drv = bs->drv;
714 if (drv && drv->bdrv_probe_blocksizes) {
715 return drv->bdrv_probe_blocksizes(bs, bsz);
716 } else if (drv && drv->is_filter && bs->file) {
717 return bdrv_probe_blocksizes(bs->file->bs, bsz);
720 return -ENOTSUP;
724 * Try to get @bs's geometry (cyls, heads, sectors).
725 * On success, store them in @geo struct and return 0.
726 * On failure return -errno.
727 * @bs must not be empty.
729 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
731 BlockDriver *drv = bs->drv;
733 if (drv && drv->bdrv_probe_geometry) {
734 return drv->bdrv_probe_geometry(bs, geo);
735 } else if (drv && drv->is_filter && bs->file) {
736 return bdrv_probe_geometry(bs->file->bs, geo);
739 return -ENOTSUP;
743 * Create a uniquely-named empty temporary file.
744 * Return 0 upon success, otherwise a negative errno value.
746 int get_tmp_filename(char *filename, int size)
748 #ifdef _WIN32
749 char temp_dir[MAX_PATH];
750 /* GetTempFileName requires that its output buffer (4th param)
751 have length MAX_PATH or greater. */
752 assert(size >= MAX_PATH);
753 return (GetTempPath(MAX_PATH, temp_dir)
754 && GetTempFileName(temp_dir, "qem", 0, filename)
755 ? 0 : -GetLastError());
756 #else
757 int fd;
758 const char *tmpdir;
759 tmpdir = getenv("TMPDIR");
760 if (!tmpdir) {
761 tmpdir = "/var/tmp";
763 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
764 return -EOVERFLOW;
766 fd = mkstemp(filename);
767 if (fd < 0) {
768 return -errno;
770 if (close(fd) != 0) {
771 unlink(filename);
772 return -errno;
774 return 0;
775 #endif
779 * Detect host devices. By convention, /dev/cdrom[N] is always
780 * recognized as a host CDROM.
782 static BlockDriver *find_hdev_driver(const char *filename)
784 int score_max = 0, score;
785 BlockDriver *drv = NULL, *d;
787 QLIST_FOREACH(d, &bdrv_drivers, list) {
788 if (d->bdrv_probe_device) {
789 score = d->bdrv_probe_device(filename);
790 if (score > score_max) {
791 score_max = score;
792 drv = d;
797 return drv;
800 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
802 BlockDriver *drv1;
804 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
805 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
806 return drv1;
810 return NULL;
813 BlockDriver *bdrv_find_protocol(const char *filename,
814 bool allow_protocol_prefix,
815 Error **errp)
817 BlockDriver *drv1;
818 char protocol[128];
819 int len;
820 const char *p;
821 int i;
823 /* TODO Drivers without bdrv_file_open must be specified explicitly */
826 * XXX(hch): we really should not let host device detection
827 * override an explicit protocol specification, but moving this
828 * later breaks access to device names with colons in them.
829 * Thanks to the brain-dead persistent naming schemes on udev-
830 * based Linux systems those actually are quite common.
832 drv1 = find_hdev_driver(filename);
833 if (drv1) {
834 return drv1;
837 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
838 return &bdrv_file;
841 p = strchr(filename, ':');
842 assert(p != NULL);
843 len = p - filename;
844 if (len > sizeof(protocol) - 1)
845 len = sizeof(protocol) - 1;
846 memcpy(protocol, filename, len);
847 protocol[len] = '\0';
849 drv1 = bdrv_do_find_protocol(protocol);
850 if (drv1) {
851 return drv1;
854 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
855 if (block_driver_modules[i].protocol_name &&
856 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
857 block_module_load_one(block_driver_modules[i].library_name);
858 break;
862 drv1 = bdrv_do_find_protocol(protocol);
863 if (!drv1) {
864 error_setg(errp, "Unknown protocol '%s'", protocol);
866 return drv1;
870 * Guess image format by probing its contents.
871 * This is not a good idea when your image is raw (CVE-2008-2004), but
872 * we do it anyway for backward compatibility.
874 * @buf contains the image's first @buf_size bytes.
875 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
876 * but can be smaller if the image file is smaller)
877 * @filename is its filename.
879 * For all block drivers, call the bdrv_probe() method to get its
880 * probing score.
881 * Return the first block driver with the highest probing score.
883 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
884 const char *filename)
886 int score_max = 0, score;
887 BlockDriver *drv = NULL, *d;
889 QLIST_FOREACH(d, &bdrv_drivers, list) {
890 if (d->bdrv_probe) {
891 score = d->bdrv_probe(buf, buf_size, filename);
892 if (score > score_max) {
893 score_max = score;
894 drv = d;
899 return drv;
902 static int find_image_format(BlockBackend *file, const char *filename,
903 BlockDriver **pdrv, Error **errp)
905 BlockDriver *drv;
906 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
907 int ret = 0;
909 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
910 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
911 *pdrv = &bdrv_raw;
912 return ret;
915 ret = blk_pread(file, 0, buf, sizeof(buf));
916 if (ret < 0) {
917 error_setg_errno(errp, -ret, "Could not read image for determining its "
918 "format");
919 *pdrv = NULL;
920 return ret;
923 drv = bdrv_probe_all(buf, ret, filename);
924 if (!drv) {
925 error_setg(errp, "Could not determine image format: No compatible "
926 "driver found");
927 ret = -ENOENT;
929 *pdrv = drv;
930 return ret;
934 * Set the current 'total_sectors' value
935 * Return 0 on success, -errno on error.
937 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
939 BlockDriver *drv = bs->drv;
941 if (!drv) {
942 return -ENOMEDIUM;
945 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
946 if (bdrv_is_sg(bs))
947 return 0;
949 /* query actual device if possible, otherwise just trust the hint */
950 if (drv->bdrv_getlength) {
951 int64_t length = drv->bdrv_getlength(bs);
952 if (length < 0) {
953 return length;
955 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
958 bs->total_sectors = hint;
959 return 0;
963 * Combines a QDict of new block driver @options with any missing options taken
964 * from @old_options, so that leaving out an option defaults to its old value.
966 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
967 QDict *old_options)
969 if (bs->drv && bs->drv->bdrv_join_options) {
970 bs->drv->bdrv_join_options(options, old_options);
971 } else {
972 qdict_join(options, old_options, false);
976 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
977 int open_flags,
978 Error **errp)
980 Error *local_err = NULL;
981 char *value = qemu_opt_get_del(opts, "detect-zeroes");
982 BlockdevDetectZeroesOptions detect_zeroes =
983 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
984 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
985 g_free(value);
986 if (local_err) {
987 error_propagate(errp, local_err);
988 return detect_zeroes;
991 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
992 !(open_flags & BDRV_O_UNMAP))
994 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
995 "without setting discard operation to unmap");
998 return detect_zeroes;
1002 * Set open flags for aio engine
1004 * Return 0 on success, -1 if the engine specified is invalid
1006 int bdrv_parse_aio(const char *mode, int *flags)
1008 if (!strcmp(mode, "threads")) {
1009 /* do nothing, default */
1010 } else if (!strcmp(mode, "native")) {
1011 *flags |= BDRV_O_NATIVE_AIO;
1012 #ifdef CONFIG_LINUX_IO_URING
1013 } else if (!strcmp(mode, "io_uring")) {
1014 *flags |= BDRV_O_IO_URING;
1015 #endif
1016 } else {
1017 return -1;
1020 return 0;
1024 * Set open flags for a given discard mode
1026 * Return 0 on success, -1 if the discard mode was invalid.
1028 int bdrv_parse_discard_flags(const char *mode, int *flags)
1030 *flags &= ~BDRV_O_UNMAP;
1032 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1033 /* do nothing */
1034 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1035 *flags |= BDRV_O_UNMAP;
1036 } else {
1037 return -1;
1040 return 0;
1044 * Set open flags for a given cache mode
1046 * Return 0 on success, -1 if the cache mode was invalid.
1048 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1050 *flags &= ~BDRV_O_CACHE_MASK;
1052 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1053 *writethrough = false;
1054 *flags |= BDRV_O_NOCACHE;
1055 } else if (!strcmp(mode, "directsync")) {
1056 *writethrough = true;
1057 *flags |= BDRV_O_NOCACHE;
1058 } else if (!strcmp(mode, "writeback")) {
1059 *writethrough = false;
1060 } else if (!strcmp(mode, "unsafe")) {
1061 *writethrough = false;
1062 *flags |= BDRV_O_NO_FLUSH;
1063 } else if (!strcmp(mode, "writethrough")) {
1064 *writethrough = true;
1065 } else {
1066 return -1;
1069 return 0;
1072 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1074 BlockDriverState *parent = c->opaque;
1075 return g_strdup(bdrv_get_device_or_node_name(parent));
1078 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1080 BlockDriverState *bs = child->opaque;
1081 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1084 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1086 BlockDriverState *bs = child->opaque;
1087 return bdrv_drain_poll(bs, false, NULL, false);
1090 static void bdrv_child_cb_drained_end(BdrvChild *child,
1091 int *drained_end_counter)
1093 BlockDriverState *bs = child->opaque;
1094 bdrv_drained_end_no_poll(bs, drained_end_counter);
1097 static int bdrv_child_cb_inactivate(BdrvChild *child)
1099 BlockDriverState *bs = child->opaque;
1100 assert(bs->open_flags & BDRV_O_INACTIVE);
1101 return 0;
1104 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1105 GSList **ignore, Error **errp)
1107 BlockDriverState *bs = child->opaque;
1108 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1111 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1112 GSList **ignore)
1114 BlockDriverState *bs = child->opaque;
1115 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1119 * Returns the options and flags that a temporary snapshot should get, based on
1120 * the originally requested flags (the originally requested image will have
1121 * flags like a backing file)
1123 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1124 int parent_flags, QDict *parent_options)
1126 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1128 /* For temporary files, unconditional cache=unsafe is fine */
1129 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1130 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1132 /* Copy the read-only and discard options from the parent */
1133 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1134 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1136 /* aio=native doesn't work for cache.direct=off, so disable it for the
1137 * temporary snapshot */
1138 *child_flags &= ~BDRV_O_NATIVE_AIO;
1141 static void bdrv_backing_attach(BdrvChild *c)
1143 BlockDriverState *parent = c->opaque;
1144 BlockDriverState *backing_hd = c->bs;
1146 assert(!parent->backing_blocker);
1147 error_setg(&parent->backing_blocker,
1148 "node is used as backing hd of '%s'",
1149 bdrv_get_device_or_node_name(parent));
1151 bdrv_refresh_filename(backing_hd);
1153 parent->open_flags &= ~BDRV_O_NO_BACKING;
1154 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1155 backing_hd->filename);
1156 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1157 backing_hd->drv ? backing_hd->drv->format_name : "");
1159 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1160 /* Otherwise we won't be able to commit or stream */
1161 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1162 parent->backing_blocker);
1163 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1164 parent->backing_blocker);
1166 * We do backup in 3 ways:
1167 * 1. drive backup
1168 * The target bs is new opened, and the source is top BDS
1169 * 2. blockdev backup
1170 * Both the source and the target are top BDSes.
1171 * 3. internal backup(used for block replication)
1172 * Both the source and the target are backing file
1174 * In case 1 and 2, neither the source nor the target is the backing file.
1175 * In case 3, we will block the top BDS, so there is only one block job
1176 * for the top BDS and its backing chain.
1178 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1179 parent->backing_blocker);
1180 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1181 parent->backing_blocker);
1184 static void bdrv_backing_detach(BdrvChild *c)
1186 BlockDriverState *parent = c->opaque;
1188 assert(parent->backing_blocker);
1189 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1190 error_free(parent->backing_blocker);
1191 parent->backing_blocker = NULL;
1194 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1195 const char *filename, Error **errp)
1197 BlockDriverState *parent = c->opaque;
1198 bool read_only = bdrv_is_read_only(parent);
1199 int ret;
1201 if (read_only) {
1202 ret = bdrv_reopen_set_read_only(parent, false, errp);
1203 if (ret < 0) {
1204 return ret;
1208 ret = bdrv_change_backing_file(parent, filename,
1209 base->drv ? base->drv->format_name : "",
1210 false);
1211 if (ret < 0) {
1212 error_setg_errno(errp, -ret, "Could not update backing file link");
1215 if (read_only) {
1216 bdrv_reopen_set_read_only(parent, true, NULL);
1219 return ret;
1223 * Returns the options and flags that a generic child of a BDS should
1224 * get, based on the given options and flags for the parent BDS.
1226 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1227 int *child_flags, QDict *child_options,
1228 int parent_flags, QDict *parent_options)
1230 int flags = parent_flags;
1233 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1234 * Generally, the question to answer is: Should this child be
1235 * format-probed by default?
1239 * Pure and non-filtered data children of non-format nodes should
1240 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1241 * set). This only affects a very limited set of drivers (namely
1242 * quorum and blkverify when this comment was written).
1243 * Force-clear BDRV_O_PROTOCOL then.
1245 if (!parent_is_format &&
1246 (role & BDRV_CHILD_DATA) &&
1247 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1249 flags &= ~BDRV_O_PROTOCOL;
1253 * All children of format nodes (except for COW children) and all
1254 * metadata children in general should never be format-probed.
1255 * Force-set BDRV_O_PROTOCOL then.
1257 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1258 (role & BDRV_CHILD_METADATA))
1260 flags |= BDRV_O_PROTOCOL;
1264 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1265 * the parent.
1267 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1268 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1269 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1271 if (role & BDRV_CHILD_COW) {
1272 /* backing files are opened read-only by default */
1273 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1274 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1275 } else {
1276 /* Inherit the read-only option from the parent if it's not set */
1277 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1278 qdict_copy_default(child_options, parent_options,
1279 BDRV_OPT_AUTO_READ_ONLY);
1283 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1284 * can default to enable it on lower layers regardless of the
1285 * parent option.
1287 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1289 /* Clear flags that only apply to the top layer */
1290 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1292 if (role & BDRV_CHILD_METADATA) {
1293 flags &= ~BDRV_O_NO_IO;
1295 if (role & BDRV_CHILD_COW) {
1296 flags &= ~BDRV_O_TEMPORARY;
1299 *child_flags = flags;
1302 static void bdrv_child_cb_attach(BdrvChild *child)
1304 BlockDriverState *bs = child->opaque;
1306 if (child->role & BDRV_CHILD_COW) {
1307 bdrv_backing_attach(child);
1310 bdrv_apply_subtree_drain(child, bs);
1313 static void bdrv_child_cb_detach(BdrvChild *child)
1315 BlockDriverState *bs = child->opaque;
1317 if (child->role & BDRV_CHILD_COW) {
1318 bdrv_backing_detach(child);
1321 bdrv_unapply_subtree_drain(child, bs);
1324 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1325 const char *filename, Error **errp)
1327 if (c->role & BDRV_CHILD_COW) {
1328 return bdrv_backing_update_filename(c, base, filename, errp);
1330 return 0;
1333 const BdrvChildClass child_of_bds = {
1334 .parent_is_bds = true,
1335 .get_parent_desc = bdrv_child_get_parent_desc,
1336 .inherit_options = bdrv_inherited_options,
1337 .drained_begin = bdrv_child_cb_drained_begin,
1338 .drained_poll = bdrv_child_cb_drained_poll,
1339 .drained_end = bdrv_child_cb_drained_end,
1340 .attach = bdrv_child_cb_attach,
1341 .detach = bdrv_child_cb_detach,
1342 .inactivate = bdrv_child_cb_inactivate,
1343 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1344 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1345 .update_filename = bdrv_child_cb_update_filename,
1348 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1350 int open_flags = flags;
1353 * Clear flags that are internal to the block layer before opening the
1354 * image.
1356 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1358 return open_flags;
1361 static void update_flags_from_options(int *flags, QemuOpts *opts)
1363 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1365 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1366 *flags |= BDRV_O_NO_FLUSH;
1369 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1370 *flags |= BDRV_O_NOCACHE;
1373 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1374 *flags |= BDRV_O_RDWR;
1377 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1378 *flags |= BDRV_O_AUTO_RDONLY;
1382 static void update_options_from_flags(QDict *options, int flags)
1384 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1385 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1387 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1388 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1389 flags & BDRV_O_NO_FLUSH);
1391 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1392 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1394 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1395 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1396 flags & BDRV_O_AUTO_RDONLY);
1400 static void bdrv_assign_node_name(BlockDriverState *bs,
1401 const char *node_name,
1402 Error **errp)
1404 char *gen_node_name = NULL;
1406 if (!node_name) {
1407 node_name = gen_node_name = id_generate(ID_BLOCK);
1408 } else if (!id_wellformed(node_name)) {
1410 * Check for empty string or invalid characters, but not if it is
1411 * generated (generated names use characters not available to the user)
1413 error_setg(errp, "Invalid node name");
1414 return;
1417 /* takes care of avoiding namespaces collisions */
1418 if (blk_by_name(node_name)) {
1419 error_setg(errp, "node-name=%s is conflicting with a device id",
1420 node_name);
1421 goto out;
1424 /* takes care of avoiding duplicates node names */
1425 if (bdrv_find_node(node_name)) {
1426 error_setg(errp, "Duplicate node name");
1427 goto out;
1430 /* Make sure that the node name isn't truncated */
1431 if (strlen(node_name) >= sizeof(bs->node_name)) {
1432 error_setg(errp, "Node name too long");
1433 goto out;
1436 /* copy node name into the bs and insert it into the graph list */
1437 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1438 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1439 out:
1440 g_free(gen_node_name);
1443 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1444 const char *node_name, QDict *options,
1445 int open_flags, Error **errp)
1447 Error *local_err = NULL;
1448 int i, ret;
1450 bdrv_assign_node_name(bs, node_name, &local_err);
1451 if (local_err) {
1452 error_propagate(errp, local_err);
1453 return -EINVAL;
1456 bs->drv = drv;
1457 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1458 bs->opaque = g_malloc0(drv->instance_size);
1460 if (drv->bdrv_file_open) {
1461 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1462 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1463 } else if (drv->bdrv_open) {
1464 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1465 } else {
1466 ret = 0;
1469 if (ret < 0) {
1470 if (local_err) {
1471 error_propagate(errp, local_err);
1472 } else if (bs->filename[0]) {
1473 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1474 } else {
1475 error_setg_errno(errp, -ret, "Could not open image");
1477 goto open_failed;
1480 ret = refresh_total_sectors(bs, bs->total_sectors);
1481 if (ret < 0) {
1482 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1483 return ret;
1486 bdrv_refresh_limits(bs, &local_err);
1487 if (local_err) {
1488 error_propagate(errp, local_err);
1489 return -EINVAL;
1492 assert(bdrv_opt_mem_align(bs) != 0);
1493 assert(bdrv_min_mem_align(bs) != 0);
1494 assert(is_power_of_2(bs->bl.request_alignment));
1496 for (i = 0; i < bs->quiesce_counter; i++) {
1497 if (drv->bdrv_co_drain_begin) {
1498 drv->bdrv_co_drain_begin(bs);
1502 return 0;
1503 open_failed:
1504 bs->drv = NULL;
1505 if (bs->file != NULL) {
1506 bdrv_unref_child(bs, bs->file);
1507 bs->file = NULL;
1509 g_free(bs->opaque);
1510 bs->opaque = NULL;
1511 return ret;
1514 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1515 int flags, Error **errp)
1517 BlockDriverState *bs;
1518 int ret;
1520 bs = bdrv_new();
1521 bs->open_flags = flags;
1522 bs->explicit_options = qdict_new();
1523 bs->options = qdict_new();
1524 bs->opaque = NULL;
1526 update_options_from_flags(bs->options, flags);
1528 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1529 if (ret < 0) {
1530 qobject_unref(bs->explicit_options);
1531 bs->explicit_options = NULL;
1532 qobject_unref(bs->options);
1533 bs->options = NULL;
1534 bdrv_unref(bs);
1535 return NULL;
1538 return bs;
1541 QemuOptsList bdrv_runtime_opts = {
1542 .name = "bdrv_common",
1543 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1544 .desc = {
1546 .name = "node-name",
1547 .type = QEMU_OPT_STRING,
1548 .help = "Node name of the block device node",
1551 .name = "driver",
1552 .type = QEMU_OPT_STRING,
1553 .help = "Block driver to use for the node",
1556 .name = BDRV_OPT_CACHE_DIRECT,
1557 .type = QEMU_OPT_BOOL,
1558 .help = "Bypass software writeback cache on the host",
1561 .name = BDRV_OPT_CACHE_NO_FLUSH,
1562 .type = QEMU_OPT_BOOL,
1563 .help = "Ignore flush requests",
1566 .name = BDRV_OPT_READ_ONLY,
1567 .type = QEMU_OPT_BOOL,
1568 .help = "Node is opened in read-only mode",
1571 .name = BDRV_OPT_AUTO_READ_ONLY,
1572 .type = QEMU_OPT_BOOL,
1573 .help = "Node can become read-only if opening read-write fails",
1576 .name = "detect-zeroes",
1577 .type = QEMU_OPT_STRING,
1578 .help = "try to optimize zero writes (off, on, unmap)",
1581 .name = BDRV_OPT_DISCARD,
1582 .type = QEMU_OPT_STRING,
1583 .help = "discard operation (ignore/off, unmap/on)",
1586 .name = BDRV_OPT_FORCE_SHARE,
1587 .type = QEMU_OPT_BOOL,
1588 .help = "always accept other writers (default: off)",
1590 { /* end of list */ }
1594 QemuOptsList bdrv_create_opts_simple = {
1595 .name = "simple-create-opts",
1596 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1597 .desc = {
1599 .name = BLOCK_OPT_SIZE,
1600 .type = QEMU_OPT_SIZE,
1601 .help = "Virtual disk size"
1604 .name = BLOCK_OPT_PREALLOC,
1605 .type = QEMU_OPT_STRING,
1606 .help = "Preallocation mode (allowed values: off)"
1608 { /* end of list */ }
1613 * Common part for opening disk images and files
1615 * Removes all processed options from *options.
1617 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1618 QDict *options, Error **errp)
1620 int ret, open_flags;
1621 const char *filename;
1622 const char *driver_name = NULL;
1623 const char *node_name = NULL;
1624 const char *discard;
1625 QemuOpts *opts;
1626 BlockDriver *drv;
1627 Error *local_err = NULL;
1629 assert(bs->file == NULL);
1630 assert(options != NULL && bs->options != options);
1632 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1633 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1634 ret = -EINVAL;
1635 goto fail_opts;
1638 update_flags_from_options(&bs->open_flags, opts);
1640 driver_name = qemu_opt_get(opts, "driver");
1641 drv = bdrv_find_format(driver_name);
1642 assert(drv != NULL);
1644 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1646 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1647 error_setg(errp,
1648 BDRV_OPT_FORCE_SHARE
1649 "=on can only be used with read-only images");
1650 ret = -EINVAL;
1651 goto fail_opts;
1654 if (file != NULL) {
1655 bdrv_refresh_filename(blk_bs(file));
1656 filename = blk_bs(file)->filename;
1657 } else {
1659 * Caution: while qdict_get_try_str() is fine, getting
1660 * non-string types would require more care. When @options
1661 * come from -blockdev or blockdev_add, its members are typed
1662 * according to the QAPI schema, but when they come from
1663 * -drive, they're all QString.
1665 filename = qdict_get_try_str(options, "filename");
1668 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1669 error_setg(errp, "The '%s' block driver requires a file name",
1670 drv->format_name);
1671 ret = -EINVAL;
1672 goto fail_opts;
1675 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1676 drv->format_name);
1678 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1680 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1681 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1682 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1683 } else {
1684 ret = -ENOTSUP;
1686 if (ret < 0) {
1687 error_setg(errp,
1688 !bs->read_only && bdrv_is_whitelisted(drv, true)
1689 ? "Driver '%s' can only be used for read-only devices"
1690 : "Driver '%s' is not whitelisted",
1691 drv->format_name);
1692 goto fail_opts;
1696 /* bdrv_new() and bdrv_close() make it so */
1697 assert(atomic_read(&bs->copy_on_read) == 0);
1699 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1700 if (!bs->read_only) {
1701 bdrv_enable_copy_on_read(bs);
1702 } else {
1703 error_setg(errp, "Can't use copy-on-read on read-only device");
1704 ret = -EINVAL;
1705 goto fail_opts;
1709 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1710 if (discard != NULL) {
1711 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1712 error_setg(errp, "Invalid discard option");
1713 ret = -EINVAL;
1714 goto fail_opts;
1718 bs->detect_zeroes =
1719 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1720 if (local_err) {
1721 error_propagate(errp, local_err);
1722 ret = -EINVAL;
1723 goto fail_opts;
1726 if (filename != NULL) {
1727 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1728 } else {
1729 bs->filename[0] = '\0';
1731 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1733 /* Open the image, either directly or using a protocol */
1734 open_flags = bdrv_open_flags(bs, bs->open_flags);
1735 node_name = qemu_opt_get(opts, "node-name");
1737 assert(!drv->bdrv_file_open || file == NULL);
1738 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1739 if (ret < 0) {
1740 goto fail_opts;
1743 qemu_opts_del(opts);
1744 return 0;
1746 fail_opts:
1747 qemu_opts_del(opts);
1748 return ret;
1751 static GCC_FMT_ATTR(1, 0)
1752 QDict *parse_json_filename(const char *filename, Error **errp)
1754 QObject *options_obj;
1755 QDict *options;
1756 int ret;
1758 ret = strstart(filename, "json:", &filename);
1759 assert(ret);
1761 options_obj = qobject_from_json(filename, errp);
1762 if (!options_obj) {
1763 error_prepend(errp, "Could not parse the JSON options: ");
1764 return NULL;
1767 options = qobject_to(QDict, options_obj);
1768 if (!options) {
1769 qobject_unref(options_obj);
1770 error_setg(errp, "Invalid JSON object given");
1771 return NULL;
1774 qdict_flatten(options);
1776 return options;
1779 static void parse_json_protocol(QDict *options, const char **pfilename,
1780 Error **errp)
1782 QDict *json_options;
1783 Error *local_err = NULL;
1785 /* Parse json: pseudo-protocol */
1786 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1787 return;
1790 json_options = parse_json_filename(*pfilename, &local_err);
1791 if (local_err) {
1792 error_propagate(errp, local_err);
1793 return;
1796 /* Options given in the filename have lower priority than options
1797 * specified directly */
1798 qdict_join(options, json_options, false);
1799 qobject_unref(json_options);
1800 *pfilename = NULL;
1804 * Fills in default options for opening images and converts the legacy
1805 * filename/flags pair to option QDict entries.
1806 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1807 * block driver has been specified explicitly.
1809 static int bdrv_fill_options(QDict **options, const char *filename,
1810 int *flags, Error **errp)
1812 const char *drvname;
1813 bool protocol = *flags & BDRV_O_PROTOCOL;
1814 bool parse_filename = false;
1815 BlockDriver *drv = NULL;
1816 Error *local_err = NULL;
1819 * Caution: while qdict_get_try_str() is fine, getting non-string
1820 * types would require more care. When @options come from
1821 * -blockdev or blockdev_add, its members are typed according to
1822 * the QAPI schema, but when they come from -drive, they're all
1823 * QString.
1825 drvname = qdict_get_try_str(*options, "driver");
1826 if (drvname) {
1827 drv = bdrv_find_format(drvname);
1828 if (!drv) {
1829 error_setg(errp, "Unknown driver '%s'", drvname);
1830 return -ENOENT;
1832 /* If the user has explicitly specified the driver, this choice should
1833 * override the BDRV_O_PROTOCOL flag */
1834 protocol = drv->bdrv_file_open;
1837 if (protocol) {
1838 *flags |= BDRV_O_PROTOCOL;
1839 } else {
1840 *flags &= ~BDRV_O_PROTOCOL;
1843 /* Translate cache options from flags into options */
1844 update_options_from_flags(*options, *flags);
1846 /* Fetch the file name from the options QDict if necessary */
1847 if (protocol && filename) {
1848 if (!qdict_haskey(*options, "filename")) {
1849 qdict_put_str(*options, "filename", filename);
1850 parse_filename = true;
1851 } else {
1852 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1853 "the same time");
1854 return -EINVAL;
1858 /* Find the right block driver */
1859 /* See cautionary note on accessing @options above */
1860 filename = qdict_get_try_str(*options, "filename");
1862 if (!drvname && protocol) {
1863 if (filename) {
1864 drv = bdrv_find_protocol(filename, parse_filename, errp);
1865 if (!drv) {
1866 return -EINVAL;
1869 drvname = drv->format_name;
1870 qdict_put_str(*options, "driver", drvname);
1871 } else {
1872 error_setg(errp, "Must specify either driver or file");
1873 return -EINVAL;
1877 assert(drv || !protocol);
1879 /* Driver-specific filename parsing */
1880 if (drv && drv->bdrv_parse_filename && parse_filename) {
1881 drv->bdrv_parse_filename(filename, *options, &local_err);
1882 if (local_err) {
1883 error_propagate(errp, local_err);
1884 return -EINVAL;
1887 if (!drv->bdrv_needs_filename) {
1888 qdict_del(*options, "filename");
1892 return 0;
1895 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1896 uint64_t perm, uint64_t shared,
1897 GSList *ignore_children,
1898 bool *tighten_restrictions, Error **errp);
1899 static void bdrv_child_abort_perm_update(BdrvChild *c);
1900 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1902 typedef struct BlockReopenQueueEntry {
1903 bool prepared;
1904 bool perms_checked;
1905 BDRVReopenState state;
1906 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1907 } BlockReopenQueueEntry;
1910 * Return the flags that @bs will have after the reopens in @q have
1911 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1912 * return the current flags.
1914 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1916 BlockReopenQueueEntry *entry;
1918 if (q != NULL) {
1919 QTAILQ_FOREACH(entry, q, entry) {
1920 if (entry->state.bs == bs) {
1921 return entry->state.flags;
1926 return bs->open_flags;
1929 /* Returns whether the image file can be written to after the reopen queue @q
1930 * has been successfully applied, or right now if @q is NULL. */
1931 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1932 BlockReopenQueue *q)
1934 int flags = bdrv_reopen_get_flags(q, bs);
1936 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1940 * Return whether the BDS can be written to. This is not necessarily
1941 * the same as !bdrv_is_read_only(bs), as inactivated images may not
1942 * be written to but do not count as read-only images.
1944 bool bdrv_is_writable(BlockDriverState *bs)
1946 return bdrv_is_writable_after_reopen(bs, NULL);
1949 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
1950 BdrvChild *c, BdrvChildRole role,
1951 BlockReopenQueue *reopen_queue,
1952 uint64_t parent_perm, uint64_t parent_shared,
1953 uint64_t *nperm, uint64_t *nshared)
1955 assert(bs->drv && bs->drv->bdrv_child_perm);
1956 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
1957 parent_perm, parent_shared,
1958 nperm, nshared);
1959 /* TODO Take force_share from reopen_queue */
1960 if (child_bs && child_bs->force_share) {
1961 *nshared = BLK_PERM_ALL;
1966 * Check whether permissions on this node can be changed in a way that
1967 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1968 * permissions of all its parents. This involves checking whether all necessary
1969 * permission changes to child nodes can be performed.
1971 * Will set *tighten_restrictions to true if and only if new permissions have to
1972 * be taken or currently shared permissions are to be unshared. Otherwise,
1973 * errors are not fatal as long as the caller accepts that the restrictions
1974 * remain tighter than they need to be. The caller still has to abort the
1975 * transaction.
1976 * @tighten_restrictions cannot be used together with @q: When reopening, we may
1977 * encounter fatal errors even though no restrictions are to be tightened. For
1978 * example, changing a node from RW to RO will fail if the WRITE permission is
1979 * to be kept.
1981 * A call to this function must always be followed by a call to bdrv_set_perm()
1982 * or bdrv_abort_perm_update().
1984 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1985 uint64_t cumulative_perms,
1986 uint64_t cumulative_shared_perms,
1987 GSList *ignore_children,
1988 bool *tighten_restrictions, Error **errp)
1990 BlockDriver *drv = bs->drv;
1991 BdrvChild *c;
1992 int ret;
1994 assert(!q || !tighten_restrictions);
1996 if (tighten_restrictions) {
1997 uint64_t current_perms, current_shared;
1998 uint64_t added_perms, removed_shared_perms;
2000 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2002 added_perms = cumulative_perms & ~current_perms;
2003 removed_shared_perms = current_shared & ~cumulative_shared_perms;
2005 *tighten_restrictions = added_perms || removed_shared_perms;
2008 /* Write permissions never work with read-only images */
2009 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2010 !bdrv_is_writable_after_reopen(bs, q))
2012 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2013 error_setg(errp, "Block node is read-only");
2014 } else {
2015 uint64_t current_perms, current_shared;
2016 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2017 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2018 error_setg(errp, "Cannot make block node read-only, there is "
2019 "a writer on it");
2020 } else {
2021 error_setg(errp, "Cannot make block node read-only and create "
2022 "a writer on it");
2026 return -EPERM;
2030 * Unaligned requests will automatically be aligned to bl.request_alignment
2031 * and without RESIZE we can't extend requests to write to space beyond the
2032 * end of the image, so it's required that the image size is aligned.
2034 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2035 !(cumulative_perms & BLK_PERM_RESIZE))
2037 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2038 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2039 "Image size is not a multiple of request "
2040 "alignment");
2041 return -EPERM;
2045 /* Check this node */
2046 if (!drv) {
2047 return 0;
2050 if (drv->bdrv_check_perm) {
2051 return drv->bdrv_check_perm(bs, cumulative_perms,
2052 cumulative_shared_perms, errp);
2055 /* Drivers that never have children can omit .bdrv_child_perm() */
2056 if (!drv->bdrv_child_perm) {
2057 assert(QLIST_EMPTY(&bs->children));
2058 return 0;
2061 /* Check all children */
2062 QLIST_FOREACH(c, &bs->children, next) {
2063 uint64_t cur_perm, cur_shared;
2064 bool child_tighten_restr;
2066 bdrv_child_perm(bs, c->bs, c, c->role, q,
2067 cumulative_perms, cumulative_shared_perms,
2068 &cur_perm, &cur_shared);
2069 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
2070 tighten_restrictions ? &child_tighten_restr
2071 : NULL,
2072 errp);
2073 if (tighten_restrictions) {
2074 *tighten_restrictions |= child_tighten_restr;
2076 if (ret < 0) {
2077 return ret;
2081 return 0;
2085 * Notifies drivers that after a previous bdrv_check_perm() call, the
2086 * permission update is not performed and any preparations made for it (e.g.
2087 * taken file locks) need to be undone.
2089 * This function recursively notifies all child nodes.
2091 static void bdrv_abort_perm_update(BlockDriverState *bs)
2093 BlockDriver *drv = bs->drv;
2094 BdrvChild *c;
2096 if (!drv) {
2097 return;
2100 if (drv->bdrv_abort_perm_update) {
2101 drv->bdrv_abort_perm_update(bs);
2104 QLIST_FOREACH(c, &bs->children, next) {
2105 bdrv_child_abort_perm_update(c);
2109 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
2110 uint64_t cumulative_shared_perms)
2112 BlockDriver *drv = bs->drv;
2113 BdrvChild *c;
2115 if (!drv) {
2116 return;
2119 /* Update this node */
2120 if (drv->bdrv_set_perm) {
2121 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
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;
2130 /* Update all children */
2131 QLIST_FOREACH(c, &bs->children, next) {
2132 uint64_t cur_perm, cur_shared;
2133 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2134 cumulative_perms, cumulative_shared_perms,
2135 &cur_perm, &cur_shared);
2136 bdrv_child_set_perm(c, cur_perm, cur_shared);
2140 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2141 uint64_t *shared_perm)
2143 BdrvChild *c;
2144 uint64_t cumulative_perms = 0;
2145 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2147 QLIST_FOREACH(c, &bs->parents, next_parent) {
2148 cumulative_perms |= c->perm;
2149 cumulative_shared_perms &= c->shared_perm;
2152 *perm = cumulative_perms;
2153 *shared_perm = cumulative_shared_perms;
2156 static char *bdrv_child_user_desc(BdrvChild *c)
2158 if (c->klass->get_parent_desc) {
2159 return c->klass->get_parent_desc(c);
2162 return g_strdup("another user");
2165 char *bdrv_perm_names(uint64_t perm)
2167 struct perm_name {
2168 uint64_t perm;
2169 const char *name;
2170 } permissions[] = {
2171 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2172 { BLK_PERM_WRITE, "write" },
2173 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2174 { BLK_PERM_RESIZE, "resize" },
2175 { BLK_PERM_GRAPH_MOD, "change children" },
2176 { 0, NULL }
2179 GString *result = g_string_sized_new(30);
2180 struct perm_name *p;
2182 for (p = permissions; p->name; p++) {
2183 if (perm & p->perm) {
2184 if (result->len > 0) {
2185 g_string_append(result, ", ");
2187 g_string_append(result, p->name);
2191 return g_string_free(result, FALSE);
2195 * Checks whether a new reference to @bs can be added if the new user requires
2196 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2197 * set, the BdrvChild objects in this list are ignored in the calculations;
2198 * this allows checking permission updates for an existing reference.
2200 * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2202 * Needs to be followed by a call to either bdrv_set_perm() or
2203 * bdrv_abort_perm_update(). */
2204 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2205 uint64_t new_used_perm,
2206 uint64_t new_shared_perm,
2207 GSList *ignore_children,
2208 bool *tighten_restrictions,
2209 Error **errp)
2211 BdrvChild *c;
2212 uint64_t cumulative_perms = new_used_perm;
2213 uint64_t cumulative_shared_perms = new_shared_perm;
2215 assert(!q || !tighten_restrictions);
2217 /* There is no reason why anyone couldn't tolerate write_unchanged */
2218 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2220 QLIST_FOREACH(c, &bs->parents, next_parent) {
2221 if (g_slist_find(ignore_children, c)) {
2222 continue;
2225 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2226 char *user = bdrv_child_user_desc(c);
2227 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
2229 if (tighten_restrictions) {
2230 *tighten_restrictions = true;
2233 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2234 "allow '%s' on %s",
2235 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2236 g_free(user);
2237 g_free(perm_names);
2238 return -EPERM;
2241 if ((c->perm & new_shared_perm) != c->perm) {
2242 char *user = bdrv_child_user_desc(c);
2243 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
2245 if (tighten_restrictions) {
2246 *tighten_restrictions = true;
2249 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2250 "'%s' on %s",
2251 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2252 g_free(user);
2253 g_free(perm_names);
2254 return -EPERM;
2257 cumulative_perms |= c->perm;
2258 cumulative_shared_perms &= c->shared_perm;
2261 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
2262 ignore_children, tighten_restrictions, errp);
2265 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2266 * bdrv_child_abort_perm_update(). */
2267 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2268 uint64_t perm, uint64_t shared,
2269 GSList *ignore_children,
2270 bool *tighten_restrictions, Error **errp)
2272 int ret;
2274 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
2275 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2276 tighten_restrictions, errp);
2277 g_slist_free(ignore_children);
2279 if (ret < 0) {
2280 return ret;
2283 if (!c->has_backup_perm) {
2284 c->has_backup_perm = true;
2285 c->backup_perm = c->perm;
2286 c->backup_shared_perm = c->shared_perm;
2289 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2290 * same child twice during check_perm procedure
2293 c->perm = perm;
2294 c->shared_perm = shared;
2296 return 0;
2299 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
2301 uint64_t cumulative_perms, cumulative_shared_perms;
2303 c->has_backup_perm = false;
2305 c->perm = perm;
2306 c->shared_perm = shared;
2308 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2309 &cumulative_shared_perms);
2310 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2313 static void bdrv_child_abort_perm_update(BdrvChild *c)
2315 if (c->has_backup_perm) {
2316 c->perm = c->backup_perm;
2317 c->shared_perm = c->backup_shared_perm;
2318 c->has_backup_perm = false;
2321 bdrv_abort_perm_update(c->bs);
2324 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2325 Error **errp)
2327 Error *local_err = NULL;
2328 int ret;
2329 bool tighten_restrictions;
2331 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2332 &tighten_restrictions, &local_err);
2333 if (ret < 0) {
2334 bdrv_child_abort_perm_update(c);
2335 if (tighten_restrictions) {
2336 error_propagate(errp, local_err);
2337 } else {
2339 * Our caller may intend to only loosen restrictions and
2340 * does not expect this function to fail. Errors are not
2341 * fatal in such a case, so we can just hide them from our
2342 * caller.
2344 error_free(local_err);
2345 ret = 0;
2347 return ret;
2350 bdrv_child_set_perm(c, perm, shared);
2352 return 0;
2355 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2357 uint64_t parent_perms, parent_shared;
2358 uint64_t perms, shared;
2360 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2361 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2362 parent_perms, parent_shared, &perms, &shared);
2364 return bdrv_child_try_set_perm(c, perms, shared, errp);
2368 * Default implementation for .bdrv_child_perm() for block filters:
2369 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2370 * filtered child.
2372 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2373 BdrvChildRole role,
2374 BlockReopenQueue *reopen_queue,
2375 uint64_t perm, uint64_t shared,
2376 uint64_t *nperm, uint64_t *nshared)
2378 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2379 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2382 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2383 BdrvChildRole role,
2384 BlockReopenQueue *reopen_queue,
2385 uint64_t perm, uint64_t shared,
2386 uint64_t *nperm, uint64_t *nshared)
2388 assert(role & BDRV_CHILD_COW);
2391 * We want consistent read from backing files if the parent needs it.
2392 * No other operations are performed on backing files.
2394 perm &= BLK_PERM_CONSISTENT_READ;
2397 * If the parent can deal with changing data, we're okay with a
2398 * writable and resizable backing file.
2399 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2401 if (shared & BLK_PERM_WRITE) {
2402 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2403 } else {
2404 shared = 0;
2407 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2408 BLK_PERM_WRITE_UNCHANGED;
2410 if (bs->open_flags & BDRV_O_INACTIVE) {
2411 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2414 *nperm = perm;
2415 *nshared = shared;
2418 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2419 BdrvChildRole role,
2420 BlockReopenQueue *reopen_queue,
2421 uint64_t perm, uint64_t shared,
2422 uint64_t *nperm, uint64_t *nshared)
2424 int flags;
2426 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2428 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2431 * Apart from the modifications below, the same permissions are
2432 * forwarded and left alone as for filters
2434 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2435 perm, shared, &perm, &shared);
2437 if (role & BDRV_CHILD_METADATA) {
2438 /* Format drivers may touch metadata even if the guest doesn't write */
2439 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2440 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2444 * bs->file always needs to be consistent because of the
2445 * metadata. We can never allow other users to resize or write
2446 * to it.
2448 if (!(flags & BDRV_O_NO_IO)) {
2449 perm |= BLK_PERM_CONSISTENT_READ;
2451 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2454 if (role & BDRV_CHILD_DATA) {
2456 * Technically, everything in this block is a subset of the
2457 * BDRV_CHILD_METADATA path taken above, and so this could
2458 * be an "else if" branch. However, that is not obvious, and
2459 * this function is not performance critical, therefore we let
2460 * this be an independent "if".
2464 * We cannot allow other users to resize the file because the
2465 * format driver might have some assumptions about the size
2466 * (e.g. because it is stored in metadata, or because the file
2467 * is split into fixed-size data files).
2469 shared &= ~BLK_PERM_RESIZE;
2472 * WRITE_UNCHANGED often cannot be performed as such on the
2473 * data file. For example, the qcow2 driver may still need to
2474 * write copied clusters on copy-on-read.
2476 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2477 perm |= BLK_PERM_WRITE;
2481 * If the data file is written to, the format driver may
2482 * expect to be able to resize it by writing beyond the EOF.
2484 if (perm & BLK_PERM_WRITE) {
2485 perm |= BLK_PERM_RESIZE;
2489 if (bs->open_flags & BDRV_O_INACTIVE) {
2490 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2493 *nperm = perm;
2494 *nshared = shared;
2497 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2498 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2499 uint64_t perm, uint64_t shared,
2500 uint64_t *nperm, uint64_t *nshared)
2502 if (role & BDRV_CHILD_FILTERED) {
2503 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2504 BDRV_CHILD_COW)));
2505 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2506 perm, shared, nperm, nshared);
2507 } else if (role & BDRV_CHILD_COW) {
2508 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2509 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2510 perm, shared, nperm, nshared);
2511 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2512 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2513 perm, shared, nperm, nshared);
2514 } else {
2515 g_assert_not_reached();
2519 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2521 static const uint64_t permissions[] = {
2522 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2523 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2524 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2525 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2526 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2529 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2530 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2532 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2534 return permissions[qapi_perm];
2537 static void bdrv_replace_child_noperm(BdrvChild *child,
2538 BlockDriverState *new_bs)
2540 BlockDriverState *old_bs = child->bs;
2541 int new_bs_quiesce_counter;
2542 int drain_saldo;
2544 assert(!child->frozen);
2546 if (old_bs && new_bs) {
2547 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2550 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2551 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2554 * If the new child node is drained but the old one was not, flush
2555 * all outstanding requests to the old child node.
2557 while (drain_saldo > 0 && child->klass->drained_begin) {
2558 bdrv_parent_drained_begin_single(child, true);
2559 drain_saldo--;
2562 if (old_bs) {
2563 /* Detach first so that the recursive drain sections coming from @child
2564 * are already gone and we only end the drain sections that came from
2565 * elsewhere. */
2566 if (child->klass->detach) {
2567 child->klass->detach(child);
2569 QLIST_REMOVE(child, next_parent);
2572 child->bs = new_bs;
2574 if (new_bs) {
2575 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2578 * Detaching the old node may have led to the new node's
2579 * quiesce_counter having been decreased. Not a problem, we
2580 * just need to recognize this here and then invoke
2581 * drained_end appropriately more often.
2583 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2584 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2586 /* Attach only after starting new drained sections, so that recursive
2587 * drain sections coming from @child don't get an extra .drained_begin
2588 * callback. */
2589 if (child->klass->attach) {
2590 child->klass->attach(child);
2595 * If the old child node was drained but the new one is not, allow
2596 * requests to come in only after the new node has been attached.
2598 while (drain_saldo < 0 && child->klass->drained_end) {
2599 bdrv_parent_drained_end_single(child);
2600 drain_saldo++;
2605 * Updates @child to change its reference to point to @new_bs, including
2606 * checking and applying the necessary permisson updates both to the old node
2607 * and to @new_bs.
2609 * NULL is passed as @new_bs for removing the reference before freeing @child.
2611 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2612 * function uses bdrv_set_perm() to update the permissions according to the new
2613 * reference that @new_bs gets.
2615 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2617 BlockDriverState *old_bs = child->bs;
2618 uint64_t perm, shared_perm;
2620 bdrv_replace_child_noperm(child, new_bs);
2623 * Start with the new node's permissions. If @new_bs is a (direct
2624 * or indirect) child of @old_bs, we must complete the permission
2625 * update on @new_bs before we loosen the restrictions on @old_bs.
2626 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2627 * updating the permissions of @new_bs, and thus not purely loosen
2628 * restrictions.
2630 if (new_bs) {
2631 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2632 bdrv_set_perm(new_bs, perm, shared_perm);
2635 if (old_bs) {
2636 /* Update permissions for old node. This is guaranteed to succeed
2637 * because we're just taking a parent away, so we're loosening
2638 * restrictions. */
2639 bool tighten_restrictions;
2640 int ret;
2642 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
2643 ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2644 &tighten_restrictions, NULL);
2645 assert(tighten_restrictions == false);
2646 if (ret < 0) {
2647 /* We only tried to loosen restrictions, so errors are not fatal */
2648 bdrv_abort_perm_update(old_bs);
2649 } else {
2650 bdrv_set_perm(old_bs, perm, shared_perm);
2653 /* When the parent requiring a non-default AioContext is removed, the
2654 * node moves back to the main AioContext */
2655 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2660 * This function steals the reference to child_bs from the caller.
2661 * That reference is later dropped by bdrv_root_unref_child().
2663 * On failure NULL is returned, errp is set and the reference to
2664 * child_bs is also dropped.
2666 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2667 * (unless @child_bs is already in @ctx).
2669 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2670 const char *child_name,
2671 const BdrvChildClass *child_class,
2672 BdrvChildRole child_role,
2673 AioContext *ctx,
2674 uint64_t perm, uint64_t shared_perm,
2675 void *opaque, Error **errp)
2677 BdrvChild *child;
2678 Error *local_err = NULL;
2679 int ret;
2681 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2682 errp);
2683 if (ret < 0) {
2684 bdrv_abort_perm_update(child_bs);
2685 bdrv_unref(child_bs);
2686 return NULL;
2689 child = g_new(BdrvChild, 1);
2690 *child = (BdrvChild) {
2691 .bs = NULL,
2692 .name = g_strdup(child_name),
2693 .klass = child_class,
2694 .role = child_role,
2695 .perm = perm,
2696 .shared_perm = shared_perm,
2697 .opaque = opaque,
2700 /* If the AioContexts don't match, first try to move the subtree of
2701 * child_bs into the AioContext of the new parent. If this doesn't work,
2702 * try moving the parent into the AioContext of child_bs instead. */
2703 if (bdrv_get_aio_context(child_bs) != ctx) {
2704 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2705 if (ret < 0 && child_class->can_set_aio_ctx) {
2706 GSList *ignore = g_slist_prepend(NULL, child);
2707 ctx = bdrv_get_aio_context(child_bs);
2708 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2709 error_free(local_err);
2710 ret = 0;
2711 g_slist_free(ignore);
2712 ignore = g_slist_prepend(NULL, child);
2713 child_class->set_aio_ctx(child, ctx, &ignore);
2715 g_slist_free(ignore);
2717 if (ret < 0) {
2718 error_propagate(errp, local_err);
2719 g_free(child);
2720 bdrv_abort_perm_update(child_bs);
2721 bdrv_unref(child_bs);
2722 return NULL;
2726 /* This performs the matching bdrv_set_perm() for the above check. */
2727 bdrv_replace_child(child, child_bs);
2729 return child;
2733 * This function transfers the reference to child_bs from the caller
2734 * to parent_bs. That reference is later dropped by parent_bs on
2735 * bdrv_close() or if someone calls bdrv_unref_child().
2737 * On failure NULL is returned, errp is set and the reference to
2738 * child_bs is also dropped.
2740 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2741 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2743 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2744 BlockDriverState *child_bs,
2745 const char *child_name,
2746 const BdrvChildClass *child_class,
2747 BdrvChildRole child_role,
2748 Error **errp)
2750 BdrvChild *child;
2751 uint64_t perm, shared_perm;
2753 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2755 assert(parent_bs->drv);
2756 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2757 perm, shared_perm, &perm, &shared_perm);
2759 child = bdrv_root_attach_child(child_bs, child_name, child_class,
2760 child_role, bdrv_get_aio_context(parent_bs),
2761 perm, shared_perm, parent_bs, errp);
2762 if (child == NULL) {
2763 return NULL;
2766 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2767 return child;
2770 static void bdrv_detach_child(BdrvChild *child)
2772 QLIST_SAFE_REMOVE(child, next);
2774 bdrv_replace_child(child, NULL);
2776 g_free(child->name);
2777 g_free(child);
2780 void bdrv_root_unref_child(BdrvChild *child)
2782 BlockDriverState *child_bs;
2784 child_bs = child->bs;
2785 bdrv_detach_child(child);
2786 bdrv_unref(child_bs);
2790 * Clear all inherits_from pointers from children and grandchildren of
2791 * @root that point to @root, where necessary.
2793 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
2795 BdrvChild *c;
2797 if (child->bs->inherits_from == root) {
2799 * Remove inherits_from only when the last reference between root and
2800 * child->bs goes away.
2802 QLIST_FOREACH(c, &root->children, next) {
2803 if (c != child && c->bs == child->bs) {
2804 break;
2807 if (c == NULL) {
2808 child->bs->inherits_from = NULL;
2812 QLIST_FOREACH(c, &child->bs->children, next) {
2813 bdrv_unset_inherits_from(root, c);
2817 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2819 if (child == NULL) {
2820 return;
2823 bdrv_unset_inherits_from(parent, child);
2824 bdrv_root_unref_child(child);
2828 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2830 BdrvChild *c;
2831 QLIST_FOREACH(c, &bs->parents, next_parent) {
2832 if (c->klass->change_media) {
2833 c->klass->change_media(c, load);
2838 /* Return true if you can reach parent going through child->inherits_from
2839 * recursively. If parent or child are NULL, return false */
2840 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2841 BlockDriverState *parent)
2843 while (child && child != parent) {
2844 child = child->inherits_from;
2847 return child != NULL;
2851 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2852 * mostly used for COW backing children (role = COW), but also for
2853 * filtered children (role = FILTERED | PRIMARY).
2855 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
2857 if (bs->drv && bs->drv->is_filter) {
2858 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
2859 } else {
2860 return BDRV_CHILD_COW;
2865 * Sets the backing file link of a BDS. A new reference is created; callers
2866 * which don't need their own reference any more must call bdrv_unref().
2868 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2869 Error **errp)
2871 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2872 bdrv_inherits_from_recursive(backing_hd, bs);
2874 if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2875 return;
2878 if (backing_hd) {
2879 bdrv_ref(backing_hd);
2882 if (bs->backing) {
2883 bdrv_unref_child(bs, bs->backing);
2884 bs->backing = NULL;
2887 if (!backing_hd) {
2888 goto out;
2891 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
2892 bdrv_backing_role(bs), errp);
2893 /* If backing_hd was already part of bs's backing chain, and
2894 * inherits_from pointed recursively to bs then let's update it to
2895 * point directly to bs (else it will become NULL). */
2896 if (bs->backing && update_inherits_from) {
2897 backing_hd->inherits_from = bs;
2900 out:
2901 bdrv_refresh_limits(bs, NULL);
2905 * Opens the backing file for a BlockDriverState if not yet open
2907 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2908 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2909 * itself, all options starting with "${bdref_key}." are considered part of the
2910 * BlockdevRef.
2912 * TODO Can this be unified with bdrv_open_image()?
2914 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2915 const char *bdref_key, Error **errp)
2917 char *backing_filename = NULL;
2918 char *bdref_key_dot;
2919 const char *reference = NULL;
2920 int ret = 0;
2921 bool implicit_backing = false;
2922 BlockDriverState *backing_hd;
2923 QDict *options;
2924 QDict *tmp_parent_options = NULL;
2925 Error *local_err = NULL;
2927 if (bs->backing != NULL) {
2928 goto free_exit;
2931 /* NULL means an empty set of options */
2932 if (parent_options == NULL) {
2933 tmp_parent_options = qdict_new();
2934 parent_options = tmp_parent_options;
2937 bs->open_flags &= ~BDRV_O_NO_BACKING;
2939 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2940 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2941 g_free(bdref_key_dot);
2944 * Caution: while qdict_get_try_str() is fine, getting non-string
2945 * types would require more care. When @parent_options come from
2946 * -blockdev or blockdev_add, its members are typed according to
2947 * the QAPI schema, but when they come from -drive, they're all
2948 * QString.
2950 reference = qdict_get_try_str(parent_options, bdref_key);
2951 if (reference || qdict_haskey(options, "file.filename")) {
2952 /* keep backing_filename NULL */
2953 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2954 qobject_unref(options);
2955 goto free_exit;
2956 } else {
2957 if (qdict_size(options) == 0) {
2958 /* If the user specifies options that do not modify the
2959 * backing file's behavior, we might still consider it the
2960 * implicit backing file. But it's easier this way, and
2961 * just specifying some of the backing BDS's options is
2962 * only possible with -drive anyway (otherwise the QAPI
2963 * schema forces the user to specify everything). */
2964 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2967 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
2968 if (local_err) {
2969 ret = -EINVAL;
2970 error_propagate(errp, local_err);
2971 qobject_unref(options);
2972 goto free_exit;
2976 if (!bs->drv || !bs->drv->supports_backing) {
2977 ret = -EINVAL;
2978 error_setg(errp, "Driver doesn't support backing files");
2979 qobject_unref(options);
2980 goto free_exit;
2983 if (!reference &&
2984 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2985 qdict_put_str(options, "driver", bs->backing_format);
2988 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
2989 &child_of_bds, bdrv_backing_role(bs), errp);
2990 if (!backing_hd) {
2991 bs->open_flags |= BDRV_O_NO_BACKING;
2992 error_prepend(errp, "Could not open backing file: ");
2993 ret = -EINVAL;
2994 goto free_exit;
2997 if (implicit_backing) {
2998 bdrv_refresh_filename(backing_hd);
2999 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3000 backing_hd->filename);
3003 /* Hook up the backing file link; drop our reference, bs owns the
3004 * backing_hd reference now */
3005 bdrv_set_backing_hd(bs, backing_hd, &local_err);
3006 bdrv_unref(backing_hd);
3007 if (local_err) {
3008 error_propagate(errp, local_err);
3009 ret = -EINVAL;
3010 goto free_exit;
3013 qdict_del(parent_options, bdref_key);
3015 free_exit:
3016 g_free(backing_filename);
3017 qobject_unref(tmp_parent_options);
3018 return ret;
3021 static BlockDriverState *
3022 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3023 BlockDriverState *parent, const BdrvChildClass *child_class,
3024 BdrvChildRole child_role, bool allow_none, Error **errp)
3026 BlockDriverState *bs = NULL;
3027 QDict *image_options;
3028 char *bdref_key_dot;
3029 const char *reference;
3031 assert(child_class != NULL);
3033 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3034 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3035 g_free(bdref_key_dot);
3038 * Caution: while qdict_get_try_str() is fine, getting non-string
3039 * types would require more care. When @options come from
3040 * -blockdev or blockdev_add, its members are typed according to
3041 * the QAPI schema, but when they come from -drive, they're all
3042 * QString.
3044 reference = qdict_get_try_str(options, bdref_key);
3045 if (!filename && !reference && !qdict_size(image_options)) {
3046 if (!allow_none) {
3047 error_setg(errp, "A block device must be specified for \"%s\"",
3048 bdref_key);
3050 qobject_unref(image_options);
3051 goto done;
3054 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3055 parent, child_class, child_role, errp);
3056 if (!bs) {
3057 goto done;
3060 done:
3061 qdict_del(options, bdref_key);
3062 return bs;
3066 * Opens a disk image whose options are given as BlockdevRef in another block
3067 * device's options.
3069 * If allow_none is true, no image will be opened if filename is false and no
3070 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3072 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3073 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3074 * itself, all options starting with "${bdref_key}." are considered part of the
3075 * BlockdevRef.
3077 * The BlockdevRef will be removed from the options QDict.
3079 BdrvChild *bdrv_open_child(const char *filename,
3080 QDict *options, const char *bdref_key,
3081 BlockDriverState *parent,
3082 const BdrvChildClass *child_class,
3083 BdrvChildRole child_role,
3084 bool allow_none, Error **errp)
3086 BlockDriverState *bs;
3088 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3089 child_role, allow_none, errp);
3090 if (bs == NULL) {
3091 return NULL;
3094 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3095 errp);
3099 * TODO Future callers may need to specify parent/child_class in order for
3100 * option inheritance to work. Existing callers use it for the root node.
3102 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3104 BlockDriverState *bs = NULL;
3105 QObject *obj = NULL;
3106 QDict *qdict = NULL;
3107 const char *reference = NULL;
3108 Visitor *v = NULL;
3110 if (ref->type == QTYPE_QSTRING) {
3111 reference = ref->u.reference;
3112 } else {
3113 BlockdevOptions *options = &ref->u.definition;
3114 assert(ref->type == QTYPE_QDICT);
3116 v = qobject_output_visitor_new(&obj);
3117 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3118 visit_complete(v, &obj);
3120 qdict = qobject_to(QDict, obj);
3121 qdict_flatten(qdict);
3123 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3124 * compatibility with other callers) rather than what we want as the
3125 * real defaults. Apply the defaults here instead. */
3126 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3127 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3128 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3129 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3133 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3134 obj = NULL;
3135 qobject_unref(obj);
3136 visit_free(v);
3137 return bs;
3140 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3141 int flags,
3142 QDict *snapshot_options,
3143 Error **errp)
3145 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3146 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3147 int64_t total_size;
3148 QemuOpts *opts = NULL;
3149 BlockDriverState *bs_snapshot = NULL;
3150 Error *local_err = NULL;
3151 int ret;
3153 /* if snapshot, we create a temporary backing file and open it
3154 instead of opening 'filename' directly */
3156 /* Get the required size from the image */
3157 total_size = bdrv_getlength(bs);
3158 if (total_size < 0) {
3159 error_setg_errno(errp, -total_size, "Could not get image size");
3160 goto out;
3163 /* Create the temporary image */
3164 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3165 if (ret < 0) {
3166 error_setg_errno(errp, -ret, "Could not get temporary filename");
3167 goto out;
3170 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3171 &error_abort);
3172 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3173 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3174 qemu_opts_del(opts);
3175 if (ret < 0) {
3176 error_prepend(errp, "Could not create temporary overlay '%s': ",
3177 tmp_filename);
3178 goto out;
3181 /* Prepare options QDict for the temporary file */
3182 qdict_put_str(snapshot_options, "file.driver", "file");
3183 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3184 qdict_put_str(snapshot_options, "driver", "qcow2");
3186 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3187 snapshot_options = NULL;
3188 if (!bs_snapshot) {
3189 goto out;
3192 /* bdrv_append() consumes a strong reference to bs_snapshot
3193 * (i.e. it will call bdrv_unref() on it) even on error, so in
3194 * order to be able to return one, we have to increase
3195 * bs_snapshot's refcount here */
3196 bdrv_ref(bs_snapshot);
3197 bdrv_append(bs_snapshot, bs, &local_err);
3198 if (local_err) {
3199 error_propagate(errp, local_err);
3200 bs_snapshot = NULL;
3201 goto out;
3204 out:
3205 qobject_unref(snapshot_options);
3206 g_free(tmp_filename);
3207 return bs_snapshot;
3211 * Opens a disk image (raw, qcow2, vmdk, ...)
3213 * options is a QDict of options to pass to the block drivers, or NULL for an
3214 * empty set of options. The reference to the QDict belongs to the block layer
3215 * after the call (even on failure), so if the caller intends to reuse the
3216 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3218 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3219 * If it is not NULL, the referenced BDS will be reused.
3221 * The reference parameter may be used to specify an existing block device which
3222 * should be opened. If specified, neither options nor a filename may be given,
3223 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3225 static BlockDriverState *bdrv_open_inherit(const char *filename,
3226 const char *reference,
3227 QDict *options, int flags,
3228 BlockDriverState *parent,
3229 const BdrvChildClass *child_class,
3230 BdrvChildRole child_role,
3231 Error **errp)
3233 int ret;
3234 BlockBackend *file = NULL;
3235 BlockDriverState *bs;
3236 BlockDriver *drv = NULL;
3237 BdrvChild *child;
3238 const char *drvname;
3239 const char *backing;
3240 Error *local_err = NULL;
3241 QDict *snapshot_options = NULL;
3242 int snapshot_flags = 0;
3244 assert(!child_class || !flags);
3245 assert(!child_class == !parent);
3247 if (reference) {
3248 bool options_non_empty = options ? qdict_size(options) : false;
3249 qobject_unref(options);
3251 if (filename || options_non_empty) {
3252 error_setg(errp, "Cannot reference an existing block device with "
3253 "additional options or a new filename");
3254 return NULL;
3257 bs = bdrv_lookup_bs(reference, reference, errp);
3258 if (!bs) {
3259 return NULL;
3262 bdrv_ref(bs);
3263 return bs;
3266 bs = bdrv_new();
3268 /* NULL means an empty set of options */
3269 if (options == NULL) {
3270 options = qdict_new();
3273 /* json: syntax counts as explicit options, as if in the QDict */
3274 parse_json_protocol(options, &filename, &local_err);
3275 if (local_err) {
3276 goto fail;
3279 bs->explicit_options = qdict_clone_shallow(options);
3281 if (child_class) {
3282 bool parent_is_format;
3284 if (parent->drv) {
3285 parent_is_format = parent->drv->is_format;
3286 } else {
3288 * parent->drv is not set yet because this node is opened for
3289 * (potential) format probing. That means that @parent is going
3290 * to be a format node.
3292 parent_is_format = true;
3295 bs->inherits_from = parent;
3296 child_class->inherit_options(child_role, parent_is_format,
3297 &flags, options,
3298 parent->open_flags, parent->options);
3301 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3302 if (ret < 0) {
3303 goto fail;
3307 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3308 * Caution: getting a boolean member of @options requires care.
3309 * When @options come from -blockdev or blockdev_add, members are
3310 * typed according to the QAPI schema, but when they come from
3311 * -drive, they're all QString.
3313 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3314 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3315 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3316 } else {
3317 flags &= ~BDRV_O_RDWR;
3320 if (flags & BDRV_O_SNAPSHOT) {
3321 snapshot_options = qdict_new();
3322 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3323 flags, options);
3324 /* Let bdrv_backing_options() override "read-only" */
3325 qdict_del(options, BDRV_OPT_READ_ONLY);
3326 bdrv_inherited_options(BDRV_CHILD_COW, true,
3327 &flags, options, flags, options);
3330 bs->open_flags = flags;
3331 bs->options = options;
3332 options = qdict_clone_shallow(options);
3334 /* Find the right image format driver */
3335 /* See cautionary note on accessing @options above */
3336 drvname = qdict_get_try_str(options, "driver");
3337 if (drvname) {
3338 drv = bdrv_find_format(drvname);
3339 if (!drv) {
3340 error_setg(errp, "Unknown driver: '%s'", drvname);
3341 goto fail;
3345 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3347 /* See cautionary note on accessing @options above */
3348 backing = qdict_get_try_str(options, "backing");
3349 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3350 (backing && *backing == '\0'))
3352 if (backing) {
3353 warn_report("Use of \"backing\": \"\" is deprecated; "
3354 "use \"backing\": null instead");
3356 flags |= BDRV_O_NO_BACKING;
3357 qdict_del(bs->explicit_options, "backing");
3358 qdict_del(bs->options, "backing");
3359 qdict_del(options, "backing");
3362 /* Open image file without format layer. This BlockBackend is only used for
3363 * probing, the block drivers will do their own bdrv_open_child() for the
3364 * same BDS, which is why we put the node name back into options. */
3365 if ((flags & BDRV_O_PROTOCOL) == 0) {
3366 BlockDriverState *file_bs;
3368 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3369 &child_of_bds, BDRV_CHILD_IMAGE,
3370 true, &local_err);
3371 if (local_err) {
3372 goto fail;
3374 if (file_bs != NULL) {
3375 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3376 * looking at the header to guess the image format. This works even
3377 * in cases where a guest would not see a consistent state. */
3378 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3379 blk_insert_bs(file, file_bs, &local_err);
3380 bdrv_unref(file_bs);
3381 if (local_err) {
3382 goto fail;
3385 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3389 /* Image format probing */
3390 bs->probed = !drv;
3391 if (!drv && file) {
3392 ret = find_image_format(file, filename, &drv, &local_err);
3393 if (ret < 0) {
3394 goto fail;
3397 * This option update would logically belong in bdrv_fill_options(),
3398 * but we first need to open bs->file for the probing to work, while
3399 * opening bs->file already requires the (mostly) final set of options
3400 * so that cache mode etc. can be inherited.
3402 * Adding the driver later is somewhat ugly, but it's not an option
3403 * that would ever be inherited, so it's correct. We just need to make
3404 * sure to update both bs->options (which has the full effective
3405 * options for bs) and options (which has file.* already removed).
3407 qdict_put_str(bs->options, "driver", drv->format_name);
3408 qdict_put_str(options, "driver", drv->format_name);
3409 } else if (!drv) {
3410 error_setg(errp, "Must specify either driver or file");
3411 goto fail;
3414 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3415 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3416 /* file must be NULL if a protocol BDS is about to be created
3417 * (the inverse results in an error message from bdrv_open_common()) */
3418 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3420 /* Open the image */
3421 ret = bdrv_open_common(bs, file, options, &local_err);
3422 if (ret < 0) {
3423 goto fail;
3426 if (file) {
3427 blk_unref(file);
3428 file = NULL;
3431 /* If there is a backing file, use it */
3432 if ((flags & BDRV_O_NO_BACKING) == 0) {
3433 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3434 if (ret < 0) {
3435 goto close_and_fail;
3439 /* Remove all children options and references
3440 * from bs->options and bs->explicit_options */
3441 QLIST_FOREACH(child, &bs->children, next) {
3442 char *child_key_dot;
3443 child_key_dot = g_strdup_printf("%s.", child->name);
3444 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3445 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3446 qdict_del(bs->explicit_options, child->name);
3447 qdict_del(bs->options, child->name);
3448 g_free(child_key_dot);
3451 /* Check if any unknown options were used */
3452 if (qdict_size(options) != 0) {
3453 const QDictEntry *entry = qdict_first(options);
3454 if (flags & BDRV_O_PROTOCOL) {
3455 error_setg(errp, "Block protocol '%s' doesn't support the option "
3456 "'%s'", drv->format_name, entry->key);
3457 } else {
3458 error_setg(errp,
3459 "Block format '%s' does not support the option '%s'",
3460 drv->format_name, entry->key);
3463 goto close_and_fail;
3466 bdrv_parent_cb_change_media(bs, true);
3468 qobject_unref(options);
3469 options = NULL;
3471 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3472 * temporary snapshot afterwards. */
3473 if (snapshot_flags) {
3474 BlockDriverState *snapshot_bs;
3475 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3476 snapshot_options, &local_err);
3477 snapshot_options = NULL;
3478 if (local_err) {
3479 goto close_and_fail;
3481 /* We are not going to return bs but the overlay on top of it
3482 * (snapshot_bs); thus, we have to drop the strong reference to bs
3483 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3484 * though, because the overlay still has a reference to it. */
3485 bdrv_unref(bs);
3486 bs = snapshot_bs;
3489 return bs;
3491 fail:
3492 blk_unref(file);
3493 qobject_unref(snapshot_options);
3494 qobject_unref(bs->explicit_options);
3495 qobject_unref(bs->options);
3496 qobject_unref(options);
3497 bs->options = NULL;
3498 bs->explicit_options = NULL;
3499 bdrv_unref(bs);
3500 error_propagate(errp, local_err);
3501 return NULL;
3503 close_and_fail:
3504 bdrv_unref(bs);
3505 qobject_unref(snapshot_options);
3506 qobject_unref(options);
3507 error_propagate(errp, local_err);
3508 return NULL;
3511 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3512 QDict *options, int flags, Error **errp)
3514 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3515 NULL, 0, errp);
3518 /* Return true if the NULL-terminated @list contains @str */
3519 static bool is_str_in_list(const char *str, const char *const *list)
3521 if (str && list) {
3522 int i;
3523 for (i = 0; list[i] != NULL; i++) {
3524 if (!strcmp(str, list[i])) {
3525 return true;
3529 return false;
3533 * Check that every option set in @bs->options is also set in
3534 * @new_opts.
3536 * Options listed in the common_options list and in
3537 * @bs->drv->mutable_opts are skipped.
3539 * Return 0 on success, otherwise return -EINVAL and set @errp.
3541 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3542 const QDict *new_opts, Error **errp)
3544 const QDictEntry *e;
3545 /* These options are common to all block drivers and are handled
3546 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3547 const char *const common_options[] = {
3548 "node-name", "discard", "cache.direct", "cache.no-flush",
3549 "read-only", "auto-read-only", "detect-zeroes", NULL
3552 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3553 if (!qdict_haskey(new_opts, e->key) &&
3554 !is_str_in_list(e->key, common_options) &&
3555 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3556 error_setg(errp, "Option '%s' cannot be reset "
3557 "to its default value", e->key);
3558 return -EINVAL;
3562 return 0;
3566 * Returns true if @child can be reached recursively from @bs
3568 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3569 BlockDriverState *child)
3571 BdrvChild *c;
3573 if (bs == child) {
3574 return true;
3577 QLIST_FOREACH(c, &bs->children, next) {
3578 if (bdrv_recurse_has_child(c->bs, child)) {
3579 return true;
3583 return false;
3587 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3588 * reopen of multiple devices.
3590 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3591 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3592 * be created and initialized. This newly created BlockReopenQueue should be
3593 * passed back in for subsequent calls that are intended to be of the same
3594 * atomic 'set'.
3596 * bs is the BlockDriverState to add to the reopen queue.
3598 * options contains the changed options for the associated bs
3599 * (the BlockReopenQueue takes ownership)
3601 * flags contains the open flags for the associated bs
3603 * returns a pointer to bs_queue, which is either the newly allocated
3604 * bs_queue, or the existing bs_queue being used.
3606 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3608 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3609 BlockDriverState *bs,
3610 QDict *options,
3611 const BdrvChildClass *klass,
3612 BdrvChildRole role,
3613 bool parent_is_format,
3614 QDict *parent_options,
3615 int parent_flags,
3616 bool keep_old_opts)
3618 assert(bs != NULL);
3620 BlockReopenQueueEntry *bs_entry;
3621 BdrvChild *child;
3622 QDict *old_options, *explicit_options, *options_copy;
3623 int flags;
3624 QemuOpts *opts;
3626 /* Make sure that the caller remembered to use a drained section. This is
3627 * important to avoid graph changes between the recursive queuing here and
3628 * bdrv_reopen_multiple(). */
3629 assert(bs->quiesce_counter > 0);
3631 if (bs_queue == NULL) {
3632 bs_queue = g_new0(BlockReopenQueue, 1);
3633 QTAILQ_INIT(bs_queue);
3636 if (!options) {
3637 options = qdict_new();
3640 /* Check if this BlockDriverState is already in the queue */
3641 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3642 if (bs == bs_entry->state.bs) {
3643 break;
3648 * Precedence of options:
3649 * 1. Explicitly passed in options (highest)
3650 * 2. Retained from explicitly set options of bs
3651 * 3. Inherited from parent node
3652 * 4. Retained from effective options of bs
3655 /* Old explicitly set values (don't overwrite by inherited value) */
3656 if (bs_entry || keep_old_opts) {
3657 old_options = qdict_clone_shallow(bs_entry ?
3658 bs_entry->state.explicit_options :
3659 bs->explicit_options);
3660 bdrv_join_options(bs, options, old_options);
3661 qobject_unref(old_options);
3664 explicit_options = qdict_clone_shallow(options);
3666 /* Inherit from parent node */
3667 if (parent_options) {
3668 flags = 0;
3669 klass->inherit_options(role, parent_is_format, &flags, options,
3670 parent_flags, parent_options);
3671 } else {
3672 flags = bdrv_get_flags(bs);
3675 if (keep_old_opts) {
3676 /* Old values are used for options that aren't set yet */
3677 old_options = qdict_clone_shallow(bs->options);
3678 bdrv_join_options(bs, options, old_options);
3679 qobject_unref(old_options);
3682 /* We have the final set of options so let's update the flags */
3683 options_copy = qdict_clone_shallow(options);
3684 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3685 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3686 update_flags_from_options(&flags, opts);
3687 qemu_opts_del(opts);
3688 qobject_unref(options_copy);
3690 /* bdrv_open_inherit() sets and clears some additional flags internally */
3691 flags &= ~BDRV_O_PROTOCOL;
3692 if (flags & BDRV_O_RDWR) {
3693 flags |= BDRV_O_ALLOW_RDWR;
3696 if (!bs_entry) {
3697 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3698 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3699 } else {
3700 qobject_unref(bs_entry->state.options);
3701 qobject_unref(bs_entry->state.explicit_options);
3704 bs_entry->state.bs = bs;
3705 bs_entry->state.options = options;
3706 bs_entry->state.explicit_options = explicit_options;
3707 bs_entry->state.flags = flags;
3709 /* This needs to be overwritten in bdrv_reopen_prepare() */
3710 bs_entry->state.perm = UINT64_MAX;
3711 bs_entry->state.shared_perm = 0;
3714 * If keep_old_opts is false then it means that unspecified
3715 * options must be reset to their original value. We don't allow
3716 * resetting 'backing' but we need to know if the option is
3717 * missing in order to decide if we have to return an error.
3719 if (!keep_old_opts) {
3720 bs_entry->state.backing_missing =
3721 !qdict_haskey(options, "backing") &&
3722 !qdict_haskey(options, "backing.driver");
3725 QLIST_FOREACH(child, &bs->children, next) {
3726 QDict *new_child_options = NULL;
3727 bool child_keep_old = keep_old_opts;
3729 /* reopen can only change the options of block devices that were
3730 * implicitly created and inherited options. For other (referenced)
3731 * block devices, a syntax like "backing.foo" results in an error. */
3732 if (child->bs->inherits_from != bs) {
3733 continue;
3736 /* Check if the options contain a child reference */
3737 if (qdict_haskey(options, child->name)) {
3738 const char *childref = qdict_get_try_str(options, child->name);
3740 * The current child must not be reopened if the child
3741 * reference is null or points to a different node.
3743 if (g_strcmp0(childref, child->bs->node_name)) {
3744 continue;
3747 * If the child reference points to the current child then
3748 * reopen it with its existing set of options (note that
3749 * it can still inherit new options from the parent).
3751 child_keep_old = true;
3752 } else {
3753 /* Extract child options ("child-name.*") */
3754 char *child_key_dot = g_strdup_printf("%s.", child->name);
3755 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3756 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3757 g_free(child_key_dot);
3760 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3761 child->klass, child->role, bs->drv->is_format,
3762 options, flags, child_keep_old);
3765 return bs_queue;
3768 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3769 BlockDriverState *bs,
3770 QDict *options, bool keep_old_opts)
3772 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3773 NULL, 0, keep_old_opts);
3777 * Reopen multiple BlockDriverStates atomically & transactionally.
3779 * The queue passed in (bs_queue) must have been built up previous
3780 * via bdrv_reopen_queue().
3782 * Reopens all BDS specified in the queue, with the appropriate
3783 * flags. All devices are prepared for reopen, and failure of any
3784 * device will cause all device changes to be abandoned, and intermediate
3785 * data cleaned up.
3787 * If all devices prepare successfully, then the changes are committed
3788 * to all devices.
3790 * All affected nodes must be drained between bdrv_reopen_queue() and
3791 * bdrv_reopen_multiple().
3793 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3795 int ret = -1;
3796 BlockReopenQueueEntry *bs_entry, *next;
3798 assert(bs_queue != NULL);
3800 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3801 assert(bs_entry->state.bs->quiesce_counter > 0);
3802 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3803 goto cleanup;
3805 bs_entry->prepared = true;
3808 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3809 BDRVReopenState *state = &bs_entry->state;
3810 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3811 state->shared_perm, NULL, NULL, errp);
3812 if (ret < 0) {
3813 goto cleanup_perm;
3815 /* Check if new_backing_bs would accept the new permissions */
3816 if (state->replace_backing_bs && state->new_backing_bs) {
3817 uint64_t nperm, nshared;
3818 bdrv_child_perm(state->bs, state->new_backing_bs,
3819 NULL, bdrv_backing_role(state->bs),
3820 bs_queue, state->perm, state->shared_perm,
3821 &nperm, &nshared);
3822 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3823 nperm, nshared, NULL, NULL, errp);
3824 if (ret < 0) {
3825 goto cleanup_perm;
3828 bs_entry->perms_checked = true;
3832 * If we reach this point, we have success and just need to apply the
3833 * changes.
3835 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3836 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3837 * children are usually goes after parents in reopen-queue, so go from last
3838 * to first element.
3840 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3841 bdrv_reopen_commit(&bs_entry->state);
3844 ret = 0;
3845 cleanup_perm:
3846 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3847 BDRVReopenState *state = &bs_entry->state;
3849 if (!bs_entry->perms_checked) {
3850 continue;
3853 if (ret == 0) {
3854 bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3855 } else {
3856 bdrv_abort_perm_update(state->bs);
3857 if (state->replace_backing_bs && state->new_backing_bs) {
3858 bdrv_abort_perm_update(state->new_backing_bs);
3863 if (ret == 0) {
3864 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3865 BlockDriverState *bs = bs_entry->state.bs;
3867 if (bs->drv->bdrv_reopen_commit_post)
3868 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3871 cleanup:
3872 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3873 if (ret) {
3874 if (bs_entry->prepared) {
3875 bdrv_reopen_abort(&bs_entry->state);
3877 qobject_unref(bs_entry->state.explicit_options);
3878 qobject_unref(bs_entry->state.options);
3880 if (bs_entry->state.new_backing_bs) {
3881 bdrv_unref(bs_entry->state.new_backing_bs);
3883 g_free(bs_entry);
3885 g_free(bs_queue);
3887 return ret;
3890 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3891 Error **errp)
3893 int ret;
3894 BlockReopenQueue *queue;
3895 QDict *opts = qdict_new();
3897 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3899 bdrv_subtree_drained_begin(bs);
3900 queue = bdrv_reopen_queue(NULL, bs, opts, true);
3901 ret = bdrv_reopen_multiple(queue, errp);
3902 bdrv_subtree_drained_end(bs);
3904 return ret;
3907 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3908 BdrvChild *c)
3910 BlockReopenQueueEntry *entry;
3912 QTAILQ_FOREACH(entry, q, entry) {
3913 BlockDriverState *bs = entry->state.bs;
3914 BdrvChild *child;
3916 QLIST_FOREACH(child, &bs->children, next) {
3917 if (child == c) {
3918 return entry;
3923 return NULL;
3926 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3927 uint64_t *perm, uint64_t *shared)
3929 BdrvChild *c;
3930 BlockReopenQueueEntry *parent;
3931 uint64_t cumulative_perms = 0;
3932 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3934 QLIST_FOREACH(c, &bs->parents, next_parent) {
3935 parent = find_parent_in_reopen_queue(q, c);
3936 if (!parent) {
3937 cumulative_perms |= c->perm;
3938 cumulative_shared_perms &= c->shared_perm;
3939 } else {
3940 uint64_t nperm, nshared;
3942 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3943 parent->state.perm, parent->state.shared_perm,
3944 &nperm, &nshared);
3946 cumulative_perms |= nperm;
3947 cumulative_shared_perms &= nshared;
3950 *perm = cumulative_perms;
3951 *shared = cumulative_shared_perms;
3954 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
3955 BdrvChild *child,
3956 BlockDriverState *new_child,
3957 Error **errp)
3959 AioContext *parent_ctx = bdrv_get_aio_context(parent);
3960 AioContext *child_ctx = bdrv_get_aio_context(new_child);
3961 GSList *ignore;
3962 bool ret;
3964 ignore = g_slist_prepend(NULL, child);
3965 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
3966 g_slist_free(ignore);
3967 if (ret) {
3968 return ret;
3971 ignore = g_slist_prepend(NULL, child);
3972 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
3973 g_slist_free(ignore);
3974 return ret;
3978 * Take a BDRVReopenState and check if the value of 'backing' in the
3979 * reopen_state->options QDict is valid or not.
3981 * If 'backing' is missing from the QDict then return 0.
3983 * If 'backing' contains the node name of the backing file of
3984 * reopen_state->bs then return 0.
3986 * If 'backing' contains a different node name (or is null) then check
3987 * whether the current backing file can be replaced with the new one.
3988 * If that's the case then reopen_state->replace_backing_bs is set to
3989 * true and reopen_state->new_backing_bs contains a pointer to the new
3990 * backing BlockDriverState (or NULL).
3992 * Return 0 on success, otherwise return < 0 and set @errp.
3994 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
3995 Error **errp)
3997 BlockDriverState *bs = reopen_state->bs;
3998 BlockDriverState *overlay_bs, *new_backing_bs;
3999 QObject *value;
4000 const char *str;
4002 value = qdict_get(reopen_state->options, "backing");
4003 if (value == NULL) {
4004 return 0;
4007 switch (qobject_type(value)) {
4008 case QTYPE_QNULL:
4009 new_backing_bs = NULL;
4010 break;
4011 case QTYPE_QSTRING:
4012 str = qobject_get_try_str(value);
4013 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4014 if (new_backing_bs == NULL) {
4015 return -EINVAL;
4016 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4017 error_setg(errp, "Making '%s' a backing file of '%s' "
4018 "would create a cycle", str, bs->node_name);
4019 return -EINVAL;
4021 break;
4022 default:
4023 /* 'backing' does not allow any other data type */
4024 g_assert_not_reached();
4028 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4029 * bdrv_reopen_commit() won't fail.
4031 if (new_backing_bs) {
4032 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4033 return -EINVAL;
4038 * Find the "actual" backing file by skipping all links that point
4039 * to an implicit node, if any (e.g. a commit filter node).
4041 overlay_bs = bs;
4042 while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
4043 overlay_bs = backing_bs(overlay_bs);
4046 /* If we want to replace the backing file we need some extra checks */
4047 if (new_backing_bs != backing_bs(overlay_bs)) {
4048 /* Check for implicit nodes between bs and its backing file */
4049 if (bs != overlay_bs) {
4050 error_setg(errp, "Cannot change backing link if '%s' has "
4051 "an implicit backing file", bs->node_name);
4052 return -EPERM;
4054 /* Check if the backing link that we want to replace is frozen */
4055 if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
4056 errp)) {
4057 return -EPERM;
4059 reopen_state->replace_backing_bs = true;
4060 if (new_backing_bs) {
4061 bdrv_ref(new_backing_bs);
4062 reopen_state->new_backing_bs = new_backing_bs;
4066 return 0;
4070 * Prepares a BlockDriverState for reopen. All changes are staged in the
4071 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4072 * the block driver layer .bdrv_reopen_prepare()
4074 * bs is the BlockDriverState to reopen
4075 * flags are the new open flags
4076 * queue is the reopen queue
4078 * Returns 0 on success, non-zero on error. On error errp will be set
4079 * as well.
4081 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4082 * It is the responsibility of the caller to then call the abort() or
4083 * commit() for any other BDS that have been left in a prepare() state
4086 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4087 Error **errp)
4089 int ret = -1;
4090 int old_flags;
4091 Error *local_err = NULL;
4092 BlockDriver *drv;
4093 QemuOpts *opts;
4094 QDict *orig_reopen_opts;
4095 char *discard = NULL;
4096 bool read_only;
4097 bool drv_prepared = false;
4099 assert(reopen_state != NULL);
4100 assert(reopen_state->bs->drv != NULL);
4101 drv = reopen_state->bs->drv;
4103 /* This function and each driver's bdrv_reopen_prepare() remove
4104 * entries from reopen_state->options as they are processed, so
4105 * we need to make a copy of the original QDict. */
4106 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4108 /* Process generic block layer options */
4109 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4110 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4111 ret = -EINVAL;
4112 goto error;
4115 /* This was already called in bdrv_reopen_queue_child() so the flags
4116 * are up-to-date. This time we simply want to remove the options from
4117 * QemuOpts in order to indicate that they have been processed. */
4118 old_flags = reopen_state->flags;
4119 update_flags_from_options(&reopen_state->flags, opts);
4120 assert(old_flags == reopen_state->flags);
4122 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4123 if (discard != NULL) {
4124 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4125 error_setg(errp, "Invalid discard option");
4126 ret = -EINVAL;
4127 goto error;
4131 reopen_state->detect_zeroes =
4132 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4133 if (local_err) {
4134 error_propagate(errp, local_err);
4135 ret = -EINVAL;
4136 goto error;
4139 /* All other options (including node-name and driver) must be unchanged.
4140 * Put them back into the QDict, so that they are checked at the end
4141 * of this function. */
4142 qemu_opts_to_qdict(opts, reopen_state->options);
4144 /* If we are to stay read-only, do not allow permission change
4145 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4146 * not set, or if the BDS still has copy_on_read enabled */
4147 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4148 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4149 if (local_err) {
4150 error_propagate(errp, local_err);
4151 goto error;
4154 /* Calculate required permissions after reopening */
4155 bdrv_reopen_perm(queue, reopen_state->bs,
4156 &reopen_state->perm, &reopen_state->shared_perm);
4158 ret = bdrv_flush(reopen_state->bs);
4159 if (ret) {
4160 error_setg_errno(errp, -ret, "Error flushing drive");
4161 goto error;
4164 if (drv->bdrv_reopen_prepare) {
4166 * If a driver-specific option is missing, it means that we
4167 * should reset it to its default value.
4168 * But not all options allow that, so we need to check it first.
4170 ret = bdrv_reset_options_allowed(reopen_state->bs,
4171 reopen_state->options, errp);
4172 if (ret) {
4173 goto error;
4176 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4177 if (ret) {
4178 if (local_err != NULL) {
4179 error_propagate(errp, local_err);
4180 } else {
4181 bdrv_refresh_filename(reopen_state->bs);
4182 error_setg(errp, "failed while preparing to reopen image '%s'",
4183 reopen_state->bs->filename);
4185 goto error;
4187 } else {
4188 /* It is currently mandatory to have a bdrv_reopen_prepare()
4189 * handler for each supported drv. */
4190 error_setg(errp, "Block format '%s' used by node '%s' "
4191 "does not support reopening files", drv->format_name,
4192 bdrv_get_device_or_node_name(reopen_state->bs));
4193 ret = -1;
4194 goto error;
4197 drv_prepared = true;
4200 * We must provide the 'backing' option if the BDS has a backing
4201 * file or if the image file has a backing file name as part of
4202 * its metadata. Otherwise the 'backing' option can be omitted.
4204 if (drv->supports_backing && reopen_state->backing_missing &&
4205 (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
4206 error_setg(errp, "backing is missing for '%s'",
4207 reopen_state->bs->node_name);
4208 ret = -EINVAL;
4209 goto error;
4213 * Allow changing the 'backing' option. The new value can be
4214 * either a reference to an existing node (using its node name)
4215 * or NULL to simply detach the current backing file.
4217 ret = bdrv_reopen_parse_backing(reopen_state, errp);
4218 if (ret < 0) {
4219 goto error;
4221 qdict_del(reopen_state->options, "backing");
4223 /* Options that are not handled are only okay if they are unchanged
4224 * compared to the old state. It is expected that some options are only
4225 * used for the initial open, but not reopen (e.g. filename) */
4226 if (qdict_size(reopen_state->options)) {
4227 const QDictEntry *entry = qdict_first(reopen_state->options);
4229 do {
4230 QObject *new = entry->value;
4231 QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4233 /* Allow child references (child_name=node_name) as long as they
4234 * point to the current child (i.e. everything stays the same). */
4235 if (qobject_type(new) == QTYPE_QSTRING) {
4236 BdrvChild *child;
4237 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4238 if (!strcmp(child->name, entry->key)) {
4239 break;
4243 if (child) {
4244 const char *str = qobject_get_try_str(new);
4245 if (!strcmp(child->bs->node_name, str)) {
4246 continue; /* Found child with this name, skip option */
4252 * TODO: When using -drive to specify blockdev options, all values
4253 * will be strings; however, when using -blockdev, blockdev-add or
4254 * filenames using the json:{} pseudo-protocol, they will be
4255 * correctly typed.
4256 * In contrast, reopening options are (currently) always strings
4257 * (because you can only specify them through qemu-io; all other
4258 * callers do not specify any options).
4259 * Therefore, when using anything other than -drive to create a BDS,
4260 * this cannot detect non-string options as unchanged, because
4261 * qobject_is_equal() always returns false for objects of different
4262 * type. In the future, this should be remedied by correctly typing
4263 * all options. For now, this is not too big of an issue because
4264 * the user can simply omit options which cannot be changed anyway,
4265 * so they will stay unchanged.
4267 if (!qobject_is_equal(new, old)) {
4268 error_setg(errp, "Cannot change the option '%s'", entry->key);
4269 ret = -EINVAL;
4270 goto error;
4272 } while ((entry = qdict_next(reopen_state->options, entry)));
4275 ret = 0;
4277 /* Restore the original reopen_state->options QDict */
4278 qobject_unref(reopen_state->options);
4279 reopen_state->options = qobject_ref(orig_reopen_opts);
4281 error:
4282 if (ret < 0 && drv_prepared) {
4283 /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4284 * call drv->bdrv_reopen_abort() before signaling an error
4285 * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4286 * when the respective bdrv_reopen_prepare() has failed) */
4287 if (drv->bdrv_reopen_abort) {
4288 drv->bdrv_reopen_abort(reopen_state);
4291 qemu_opts_del(opts);
4292 qobject_unref(orig_reopen_opts);
4293 g_free(discard);
4294 return ret;
4298 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4299 * makes them final by swapping the staging BlockDriverState contents into
4300 * the active BlockDriverState contents.
4302 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4304 BlockDriver *drv;
4305 BlockDriverState *bs;
4306 BdrvChild *child;
4308 assert(reopen_state != NULL);
4309 bs = reopen_state->bs;
4310 drv = bs->drv;
4311 assert(drv != NULL);
4313 /* If there are any driver level actions to take */
4314 if (drv->bdrv_reopen_commit) {
4315 drv->bdrv_reopen_commit(reopen_state);
4318 /* set BDS specific flags now */
4319 qobject_unref(bs->explicit_options);
4320 qobject_unref(bs->options);
4322 bs->explicit_options = reopen_state->explicit_options;
4323 bs->options = reopen_state->options;
4324 bs->open_flags = reopen_state->flags;
4325 bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
4326 bs->detect_zeroes = reopen_state->detect_zeroes;
4328 if (reopen_state->replace_backing_bs) {
4329 qdict_del(bs->explicit_options, "backing");
4330 qdict_del(bs->options, "backing");
4333 /* Remove child references from bs->options and bs->explicit_options.
4334 * Child options were already removed in bdrv_reopen_queue_child() */
4335 QLIST_FOREACH(child, &bs->children, next) {
4336 qdict_del(bs->explicit_options, child->name);
4337 qdict_del(bs->options, child->name);
4341 * Change the backing file if a new one was specified. We do this
4342 * after updating bs->options, so bdrv_refresh_filename() (called
4343 * from bdrv_set_backing_hd()) has the new values.
4345 if (reopen_state->replace_backing_bs) {
4346 BlockDriverState *old_backing_bs = backing_bs(bs);
4347 assert(!old_backing_bs || !old_backing_bs->implicit);
4348 /* Abort the permission update on the backing bs we're detaching */
4349 if (old_backing_bs) {
4350 bdrv_abort_perm_update(old_backing_bs);
4352 bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4355 bdrv_refresh_limits(bs, NULL);
4359 * Abort the reopen, and delete and free the staged changes in
4360 * reopen_state
4362 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4364 BlockDriver *drv;
4366 assert(reopen_state != NULL);
4367 drv = reopen_state->bs->drv;
4368 assert(drv != NULL);
4370 if (drv->bdrv_reopen_abort) {
4371 drv->bdrv_reopen_abort(reopen_state);
4376 static void bdrv_close(BlockDriverState *bs)
4378 BdrvAioNotifier *ban, *ban_next;
4379 BdrvChild *child, *next;
4381 assert(!bs->refcnt);
4383 bdrv_drained_begin(bs); /* complete I/O */
4384 bdrv_flush(bs);
4385 bdrv_drain(bs); /* in case flush left pending I/O */
4387 if (bs->drv) {
4388 if (bs->drv->bdrv_close) {
4389 bs->drv->bdrv_close(bs);
4391 bs->drv = NULL;
4394 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4395 bdrv_unref_child(bs, child);
4398 bs->backing = NULL;
4399 bs->file = NULL;
4400 g_free(bs->opaque);
4401 bs->opaque = NULL;
4402 atomic_set(&bs->copy_on_read, 0);
4403 bs->backing_file[0] = '\0';
4404 bs->backing_format[0] = '\0';
4405 bs->total_sectors = 0;
4406 bs->encrypted = false;
4407 bs->sg = false;
4408 qobject_unref(bs->options);
4409 qobject_unref(bs->explicit_options);
4410 bs->options = NULL;
4411 bs->explicit_options = NULL;
4412 qobject_unref(bs->full_open_options);
4413 bs->full_open_options = NULL;
4415 bdrv_release_named_dirty_bitmaps(bs);
4416 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4418 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4419 g_free(ban);
4421 QLIST_INIT(&bs->aio_notifiers);
4422 bdrv_drained_end(bs);
4425 void bdrv_close_all(void)
4427 assert(job_next(NULL) == NULL);
4428 nbd_export_close_all();
4430 /* Drop references from requests still in flight, such as canceled block
4431 * jobs whose AIO context has not been polled yet */
4432 bdrv_drain_all();
4434 blk_remove_all_bs();
4435 blockdev_close_all_bdrv_states();
4437 assert(QTAILQ_EMPTY(&all_bdrv_states));
4440 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4442 GQueue *queue;
4443 GHashTable *found;
4444 bool ret;
4446 if (c->klass->stay_at_node) {
4447 return false;
4450 /* If the child @c belongs to the BDS @to, replacing the current
4451 * c->bs by @to would mean to create a loop.
4453 * Such a case occurs when appending a BDS to a backing chain.
4454 * For instance, imagine the following chain:
4456 * guest device -> node A -> further backing chain...
4458 * Now we create a new BDS B which we want to put on top of this
4459 * chain, so we first attach A as its backing node:
4461 * node B
4464 * guest device -> node A -> further backing chain...
4466 * Finally we want to replace A by B. When doing that, we want to
4467 * replace all pointers to A by pointers to B -- except for the
4468 * pointer from B because (1) that would create a loop, and (2)
4469 * that pointer should simply stay intact:
4471 * guest device -> node B
4474 * node A -> further backing chain...
4476 * In general, when replacing a node A (c->bs) by a node B (@to),
4477 * if A is a child of B, that means we cannot replace A by B there
4478 * because that would create a loop. Silently detaching A from B
4479 * is also not really an option. So overall just leaving A in
4480 * place there is the most sensible choice.
4482 * We would also create a loop in any cases where @c is only
4483 * indirectly referenced by @to. Prevent this by returning false
4484 * if @c is found (by breadth-first search) anywhere in the whole
4485 * subtree of @to.
4488 ret = true;
4489 found = g_hash_table_new(NULL, NULL);
4490 g_hash_table_add(found, to);
4491 queue = g_queue_new();
4492 g_queue_push_tail(queue, to);
4494 while (!g_queue_is_empty(queue)) {
4495 BlockDriverState *v = g_queue_pop_head(queue);
4496 BdrvChild *c2;
4498 QLIST_FOREACH(c2, &v->children, next) {
4499 if (c2 == c) {
4500 ret = false;
4501 break;
4504 if (g_hash_table_contains(found, c2->bs)) {
4505 continue;
4508 g_queue_push_tail(queue, c2->bs);
4509 g_hash_table_add(found, c2->bs);
4513 g_queue_free(queue);
4514 g_hash_table_destroy(found);
4516 return ret;
4519 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4520 Error **errp)
4522 BdrvChild *c, *next;
4523 GSList *list = NULL, *p;
4524 uint64_t perm = 0, shared = BLK_PERM_ALL;
4525 int ret;
4527 /* Make sure that @from doesn't go away until we have successfully attached
4528 * all of its parents to @to. */
4529 bdrv_ref(from);
4531 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4532 assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
4533 bdrv_drained_begin(from);
4535 /* Put all parents into @list and calculate their cumulative permissions */
4536 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4537 assert(c->bs == from);
4538 if (!should_update_child(c, to)) {
4539 continue;
4541 if (c->frozen) {
4542 error_setg(errp, "Cannot change '%s' link to '%s'",
4543 c->name, from->node_name);
4544 goto out;
4546 list = g_slist_prepend(list, c);
4547 perm |= c->perm;
4548 shared &= c->shared_perm;
4551 /* Check whether the required permissions can be granted on @to, ignoring
4552 * all BdrvChild in @list so that they can't block themselves. */
4553 ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
4554 if (ret < 0) {
4555 bdrv_abort_perm_update(to);
4556 goto out;
4559 /* Now actually perform the change. We performed the permission check for
4560 * all elements of @list at once, so set the permissions all at once at the
4561 * very end. */
4562 for (p = list; p != NULL; p = p->next) {
4563 c = p->data;
4565 bdrv_ref(to);
4566 bdrv_replace_child_noperm(c, to);
4567 bdrv_unref(from);
4570 bdrv_get_cumulative_perm(to, &perm, &shared);
4571 bdrv_set_perm(to, perm, shared);
4573 out:
4574 g_slist_free(list);
4575 bdrv_drained_end(from);
4576 bdrv_unref(from);
4580 * Add new bs contents at the top of an image chain while the chain is
4581 * live, while keeping required fields on the top layer.
4583 * This will modify the BlockDriverState fields, and swap contents
4584 * between bs_new and bs_top. Both bs_new and bs_top are modified.
4586 * bs_new must not be attached to a BlockBackend.
4588 * This function does not create any image files.
4590 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4591 * that's what the callers commonly need. bs_new will be referenced by the old
4592 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4593 * reference of its own, it must call bdrv_ref().
4595 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4596 Error **errp)
4598 Error *local_err = NULL;
4600 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4601 if (local_err) {
4602 error_propagate(errp, local_err);
4603 goto out;
4606 bdrv_replace_node(bs_top, bs_new, &local_err);
4607 if (local_err) {
4608 error_propagate(errp, local_err);
4609 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4610 goto out;
4613 /* bs_new is now referenced by its new parents, we don't need the
4614 * additional reference any more. */
4615 out:
4616 bdrv_unref(bs_new);
4619 static void bdrv_delete(BlockDriverState *bs)
4621 assert(bdrv_op_blocker_is_empty(bs));
4622 assert(!bs->refcnt);
4624 /* remove from list, if necessary */
4625 if (bs->node_name[0] != '\0') {
4626 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4628 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4630 bdrv_close(bs);
4632 g_free(bs);
4636 * Run consistency checks on an image
4638 * Returns 0 if the check could be completed (it doesn't mean that the image is
4639 * free of errors) or -errno when an internal error occurred. The results of the
4640 * check are stored in res.
4642 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4643 BdrvCheckResult *res, BdrvCheckMode fix)
4645 if (bs->drv == NULL) {
4646 return -ENOMEDIUM;
4648 if (bs->drv->bdrv_co_check == NULL) {
4649 return -ENOTSUP;
4652 memset(res, 0, sizeof(*res));
4653 return bs->drv->bdrv_co_check(bs, res, fix);
4656 typedef struct CheckCo {
4657 BlockDriverState *bs;
4658 BdrvCheckResult *res;
4659 BdrvCheckMode fix;
4660 int ret;
4661 } CheckCo;
4663 static void coroutine_fn bdrv_check_co_entry(void *opaque)
4665 CheckCo *cco = opaque;
4666 cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4667 aio_wait_kick();
4670 int bdrv_check(BlockDriverState *bs,
4671 BdrvCheckResult *res, BdrvCheckMode fix)
4673 Coroutine *co;
4674 CheckCo cco = {
4675 .bs = bs,
4676 .res = res,
4677 .ret = -EINPROGRESS,
4678 .fix = fix,
4681 if (qemu_in_coroutine()) {
4682 /* Fast-path if already in coroutine context */
4683 bdrv_check_co_entry(&cco);
4684 } else {
4685 co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4686 bdrv_coroutine_enter(bs, co);
4687 BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4690 return cco.ret;
4694 * Return values:
4695 * 0 - success
4696 * -EINVAL - backing format specified, but no file
4697 * -ENOSPC - can't update the backing file because no space is left in the
4698 * image file header
4699 * -ENOTSUP - format driver doesn't support changing the backing file
4701 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
4702 const char *backing_fmt, bool warn)
4704 BlockDriver *drv = bs->drv;
4705 int ret;
4707 if (!drv) {
4708 return -ENOMEDIUM;
4711 /* Backing file format doesn't make sense without a backing file */
4712 if (backing_fmt && !backing_file) {
4713 return -EINVAL;
4716 if (warn && backing_file && !backing_fmt) {
4717 warn_report("Deprecated use of backing file without explicit "
4718 "backing format, use of this image requires "
4719 "potentially unsafe format probing");
4722 if (drv->bdrv_change_backing_file != NULL) {
4723 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
4724 } else {
4725 ret = -ENOTSUP;
4728 if (ret == 0) {
4729 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4730 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
4731 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4732 backing_file ?: "");
4734 return ret;
4738 * Finds the image layer in the chain that has 'bs' as its backing file.
4740 * active is the current topmost image.
4742 * Returns NULL if bs is not found in active's image chain,
4743 * or if active == bs.
4745 * Returns the bottommost base image if bs == NULL.
4747 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4748 BlockDriverState *bs)
4750 while (active && bs != backing_bs(active)) {
4751 active = backing_bs(active);
4754 return active;
4757 /* Given a BDS, searches for the base layer. */
4758 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4760 return bdrv_find_overlay(bs, NULL);
4764 * Return true if at least one of the backing links between @bs and
4765 * @base is frozen. @errp is set if that's the case.
4766 * @base must be reachable from @bs, or NULL.
4768 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4769 Error **errp)
4771 BlockDriverState *i;
4773 for (i = bs; i != base; i = backing_bs(i)) {
4774 if (i->backing && i->backing->frozen) {
4775 error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4776 i->backing->name, i->node_name,
4777 backing_bs(i)->node_name);
4778 return true;
4782 return false;
4786 * Freeze all backing links between @bs and @base.
4787 * If any of the links is already frozen the operation is aborted and
4788 * none of the links are modified.
4789 * @base must be reachable from @bs, or NULL.
4790 * Returns 0 on success. On failure returns < 0 and sets @errp.
4792 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4793 Error **errp)
4795 BlockDriverState *i;
4797 if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4798 return -EPERM;
4801 for (i = bs; i != base; i = backing_bs(i)) {
4802 if (i->backing && backing_bs(i)->never_freeze) {
4803 error_setg(errp, "Cannot freeze '%s' link to '%s'",
4804 i->backing->name, backing_bs(i)->node_name);
4805 return -EPERM;
4809 for (i = bs; i != base; i = backing_bs(i)) {
4810 if (i->backing) {
4811 i->backing->frozen = true;
4815 return 0;
4819 * Unfreeze all backing links between @bs and @base. The caller must
4820 * ensure that all links are frozen before using this function.
4821 * @base must be reachable from @bs, or NULL.
4823 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4825 BlockDriverState *i;
4827 for (i = bs; i != base; i = backing_bs(i)) {
4828 if (i->backing) {
4829 assert(i->backing->frozen);
4830 i->backing->frozen = false;
4836 * Drops images above 'base' up to and including 'top', and sets the image
4837 * above 'top' to have base as its backing file.
4839 * Requires that the overlay to 'top' is opened r/w, so that the backing file
4840 * information in 'bs' can be properly updated.
4842 * E.g., this will convert the following chain:
4843 * bottom <- base <- intermediate <- top <- active
4845 * to
4847 * bottom <- base <- active
4849 * It is allowed for bottom==base, in which case it converts:
4851 * base <- intermediate <- top <- active
4853 * to
4855 * base <- active
4857 * If backing_file_str is non-NULL, it will be used when modifying top's
4858 * overlay image metadata.
4860 * Error conditions:
4861 * if active == top, that is considered an error
4864 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4865 const char *backing_file_str)
4867 BlockDriverState *explicit_top = top;
4868 bool update_inherits_from;
4869 BdrvChild *c, *next;
4870 Error *local_err = NULL;
4871 int ret = -EIO;
4873 bdrv_ref(top);
4874 bdrv_subtree_drained_begin(top);
4876 if (!top->drv || !base->drv) {
4877 goto exit;
4880 /* Make sure that base is in the backing chain of top */
4881 if (!bdrv_chain_contains(top, base)) {
4882 goto exit;
4885 /* This function changes all links that point to top and makes
4886 * them point to base. Check that none of them is frozen. */
4887 QLIST_FOREACH(c, &top->parents, next_parent) {
4888 if (c->frozen) {
4889 goto exit;
4893 /* If 'base' recursively inherits from 'top' then we should set
4894 * base->inherits_from to top->inherits_from after 'top' and all
4895 * other intermediate nodes have been dropped.
4896 * If 'top' is an implicit node (e.g. "commit_top") we should skip
4897 * it because no one inherits from it. We use explicit_top for that. */
4898 while (explicit_top && explicit_top->implicit) {
4899 explicit_top = backing_bs(explicit_top);
4901 update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4903 /* success - we can delete the intermediate states, and link top->base */
4904 /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4905 * we've figured out how they should work. */
4906 if (!backing_file_str) {
4907 bdrv_refresh_filename(base);
4908 backing_file_str = base->filename;
4911 QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
4912 /* Check whether we are allowed to switch c from top to base */
4913 GSList *ignore_children = g_slist_prepend(NULL, c);
4914 ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
4915 ignore_children, NULL, &local_err);
4916 g_slist_free(ignore_children);
4917 if (ret < 0) {
4918 error_report_err(local_err);
4919 goto exit;
4922 /* If so, update the backing file path in the image file */
4923 if (c->klass->update_filename) {
4924 ret = c->klass->update_filename(c, base, backing_file_str,
4925 &local_err);
4926 if (ret < 0) {
4927 bdrv_abort_perm_update(base);
4928 error_report_err(local_err);
4929 goto exit;
4933 /* Do the actual switch in the in-memory graph.
4934 * Completes bdrv_check_update_perm() transaction internally. */
4935 bdrv_ref(base);
4936 bdrv_replace_child(c, base);
4937 bdrv_unref(top);
4940 if (update_inherits_from) {
4941 base->inherits_from = explicit_top->inherits_from;
4944 ret = 0;
4945 exit:
4946 bdrv_subtree_drained_end(top);
4947 bdrv_unref(top);
4948 return ret;
4952 * Length of a allocated file in bytes. Sparse files are counted by actual
4953 * allocated space. Return < 0 if error or unknown.
4955 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
4957 BlockDriver *drv = bs->drv;
4958 if (!drv) {
4959 return -ENOMEDIUM;
4961 if (drv->bdrv_get_allocated_file_size) {
4962 return drv->bdrv_get_allocated_file_size(bs);
4964 if (bs->file) {
4965 return bdrv_get_allocated_file_size(bs->file->bs);
4967 return -ENOTSUP;
4971 * bdrv_measure:
4972 * @drv: Format driver
4973 * @opts: Creation options for new image
4974 * @in_bs: Existing image containing data for new image (may be NULL)
4975 * @errp: Error object
4976 * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
4977 * or NULL on error
4979 * Calculate file size required to create a new image.
4981 * If @in_bs is given then space for allocated clusters and zero clusters
4982 * from that image are included in the calculation. If @opts contains a
4983 * backing file that is shared by @in_bs then backing clusters may be omitted
4984 * from the calculation.
4986 * If @in_bs is NULL then the calculation includes no allocated clusters
4987 * unless a preallocation option is given in @opts.
4989 * Note that @in_bs may use a different BlockDriver from @drv.
4991 * If an error occurs the @errp pointer is set.
4993 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
4994 BlockDriverState *in_bs, Error **errp)
4996 if (!drv->bdrv_measure) {
4997 error_setg(errp, "Block driver '%s' does not support size measurement",
4998 drv->format_name);
4999 return NULL;
5002 return drv->bdrv_measure(opts, in_bs, errp);
5006 * Return number of sectors on success, -errno on error.
5008 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5010 BlockDriver *drv = bs->drv;
5012 if (!drv)
5013 return -ENOMEDIUM;
5015 if (drv->has_variable_length) {
5016 int ret = refresh_total_sectors(bs, bs->total_sectors);
5017 if (ret < 0) {
5018 return ret;
5021 return bs->total_sectors;
5025 * Return length in bytes on success, -errno on error.
5026 * The length is always a multiple of BDRV_SECTOR_SIZE.
5028 int64_t bdrv_getlength(BlockDriverState *bs)
5030 int64_t ret = bdrv_nb_sectors(bs);
5032 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
5033 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
5036 /* return 0 as number of sectors if no device present or error */
5037 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5039 int64_t nb_sectors = bdrv_nb_sectors(bs);
5041 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5044 bool bdrv_is_sg(BlockDriverState *bs)
5046 return bs->sg;
5049 bool bdrv_is_encrypted(BlockDriverState *bs)
5051 if (bs->backing && bs->backing->bs->encrypted) {
5052 return true;
5054 return bs->encrypted;
5057 const char *bdrv_get_format_name(BlockDriverState *bs)
5059 return bs->drv ? bs->drv->format_name : NULL;
5062 static int qsort_strcmp(const void *a, const void *b)
5064 return strcmp(*(char *const *)a, *(char *const *)b);
5067 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5068 void *opaque, bool read_only)
5070 BlockDriver *drv;
5071 int count = 0;
5072 int i;
5073 const char **formats = NULL;
5075 QLIST_FOREACH(drv, &bdrv_drivers, list) {
5076 if (drv->format_name) {
5077 bool found = false;
5078 int i = count;
5080 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5081 continue;
5084 while (formats && i && !found) {
5085 found = !strcmp(formats[--i], drv->format_name);
5088 if (!found) {
5089 formats = g_renew(const char *, formats, count + 1);
5090 formats[count++] = drv->format_name;
5095 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5096 const char *format_name = block_driver_modules[i].format_name;
5098 if (format_name) {
5099 bool found = false;
5100 int j = count;
5102 if (use_bdrv_whitelist &&
5103 !bdrv_format_is_whitelisted(format_name, read_only)) {
5104 continue;
5107 while (formats && j && !found) {
5108 found = !strcmp(formats[--j], format_name);
5111 if (!found) {
5112 formats = g_renew(const char *, formats, count + 1);
5113 formats[count++] = format_name;
5118 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5120 for (i = 0; i < count; i++) {
5121 it(opaque, formats[i]);
5124 g_free(formats);
5127 /* This function is to find a node in the bs graph */
5128 BlockDriverState *bdrv_find_node(const char *node_name)
5130 BlockDriverState *bs;
5132 assert(node_name);
5134 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5135 if (!strcmp(node_name, bs->node_name)) {
5136 return bs;
5139 return NULL;
5142 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5143 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5144 Error **errp)
5146 BlockDeviceInfoList *list, *entry;
5147 BlockDriverState *bs;
5149 list = NULL;
5150 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5151 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5152 if (!info) {
5153 qapi_free_BlockDeviceInfoList(list);
5154 return NULL;
5156 entry = g_malloc0(sizeof(*entry));
5157 entry->value = info;
5158 entry->next = list;
5159 list = entry;
5162 return list;
5165 #define QAPI_LIST_ADD(list, element) do { \
5166 typeof(list) _tmp = g_new(typeof(*(list)), 1); \
5167 _tmp->value = (element); \
5168 _tmp->next = (list); \
5169 (list) = _tmp; \
5170 } while (0)
5172 typedef struct XDbgBlockGraphConstructor {
5173 XDbgBlockGraph *graph;
5174 GHashTable *graph_nodes;
5175 } XDbgBlockGraphConstructor;
5177 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5179 XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5181 gr->graph = g_new0(XDbgBlockGraph, 1);
5182 gr->graph_nodes = g_hash_table_new(NULL, NULL);
5184 return gr;
5187 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5189 XDbgBlockGraph *graph = gr->graph;
5191 g_hash_table_destroy(gr->graph_nodes);
5192 g_free(gr);
5194 return graph;
5197 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5199 uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5201 if (ret != 0) {
5202 return ret;
5206 * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5207 * answer of g_hash_table_lookup.
5209 ret = g_hash_table_size(gr->graph_nodes) + 1;
5210 g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5212 return ret;
5215 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5216 XDbgBlockGraphNodeType type, const char *name)
5218 XDbgBlockGraphNode *n;
5220 n = g_new0(XDbgBlockGraphNode, 1);
5222 n->id = xdbg_graph_node_num(gr, node);
5223 n->type = type;
5224 n->name = g_strdup(name);
5226 QAPI_LIST_ADD(gr->graph->nodes, n);
5229 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
5230 const BdrvChild *child)
5232 BlockPermission qapi_perm;
5233 XDbgBlockGraphEdge *edge;
5235 edge = g_new0(XDbgBlockGraphEdge, 1);
5237 edge->parent = xdbg_graph_node_num(gr, parent);
5238 edge->child = xdbg_graph_node_num(gr, child->bs);
5239 edge->name = g_strdup(child->name);
5241 for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
5242 uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
5244 if (flag & child->perm) {
5245 QAPI_LIST_ADD(edge->perm, qapi_perm);
5247 if (flag & child->shared_perm) {
5248 QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
5252 QAPI_LIST_ADD(gr->graph->edges, edge);
5256 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
5258 BlockBackend *blk;
5259 BlockJob *job;
5260 BlockDriverState *bs;
5261 BdrvChild *child;
5262 XDbgBlockGraphConstructor *gr = xdbg_graph_new();
5264 for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
5265 char *allocated_name = NULL;
5266 const char *name = blk_name(blk);
5268 if (!*name) {
5269 name = allocated_name = blk_get_attached_dev_id(blk);
5271 xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
5272 name);
5273 g_free(allocated_name);
5274 if (blk_root(blk)) {
5275 xdbg_graph_add_edge(gr, blk, blk_root(blk));
5279 for (job = block_job_next(NULL); job; job = block_job_next(job)) {
5280 GSList *el;
5282 xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
5283 job->job.id);
5284 for (el = job->nodes; el; el = el->next) {
5285 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
5289 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5290 xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
5291 bs->node_name);
5292 QLIST_FOREACH(child, &bs->children, next) {
5293 xdbg_graph_add_edge(gr, bs, child);
5297 return xdbg_graph_finalize(gr);
5300 BlockDriverState *bdrv_lookup_bs(const char *device,
5301 const char *node_name,
5302 Error **errp)
5304 BlockBackend *blk;
5305 BlockDriverState *bs;
5307 if (device) {
5308 blk = blk_by_name(device);
5310 if (blk) {
5311 bs = blk_bs(blk);
5312 if (!bs) {
5313 error_setg(errp, "Device '%s' has no medium", device);
5316 return bs;
5320 if (node_name) {
5321 bs = bdrv_find_node(node_name);
5323 if (bs) {
5324 return bs;
5328 error_setg(errp, "Cannot find device=%s nor node_name=%s",
5329 device ? device : "",
5330 node_name ? node_name : "");
5331 return NULL;
5334 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5335 * return false. If either argument is NULL, return false. */
5336 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5338 while (top && top != base) {
5339 top = backing_bs(top);
5342 return top != NULL;
5345 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5347 if (!bs) {
5348 return QTAILQ_FIRST(&graph_bdrv_states);
5350 return QTAILQ_NEXT(bs, node_list);
5353 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5355 if (!bs) {
5356 return QTAILQ_FIRST(&all_bdrv_states);
5358 return QTAILQ_NEXT(bs, bs_list);
5361 const char *bdrv_get_node_name(const BlockDriverState *bs)
5363 return bs->node_name;
5366 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5368 BdrvChild *c;
5369 const char *name;
5371 /* If multiple parents have a name, just pick the first one. */
5372 QLIST_FOREACH(c, &bs->parents, next_parent) {
5373 if (c->klass->get_name) {
5374 name = c->klass->get_name(c);
5375 if (name && *name) {
5376 return name;
5381 return NULL;
5384 /* TODO check what callers really want: bs->node_name or blk_name() */
5385 const char *bdrv_get_device_name(const BlockDriverState *bs)
5387 return bdrv_get_parent_name(bs) ?: "";
5390 /* This can be used to identify nodes that might not have a device
5391 * name associated. Since node and device names live in the same
5392 * namespace, the result is unambiguous. The exception is if both are
5393 * absent, then this returns an empty (non-null) string. */
5394 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5396 return bdrv_get_parent_name(bs) ?: bs->node_name;
5399 int bdrv_get_flags(BlockDriverState *bs)
5401 return bs->open_flags;
5404 int bdrv_has_zero_init_1(BlockDriverState *bs)
5406 return 1;
5409 int bdrv_has_zero_init(BlockDriverState *bs)
5411 if (!bs->drv) {
5412 return 0;
5415 /* If BS is a copy on write image, it is initialized to
5416 the contents of the base image, which may not be zeroes. */
5417 if (bs->backing) {
5418 return 0;
5420 if (bs->drv->bdrv_has_zero_init) {
5421 return bs->drv->bdrv_has_zero_init(bs);
5423 if (bs->file && bs->drv->is_filter) {
5424 return bdrv_has_zero_init(bs->file->bs);
5427 /* safe default */
5428 return 0;
5431 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5433 if (!(bs->open_flags & BDRV_O_UNMAP)) {
5434 return false;
5437 return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5440 void bdrv_get_backing_filename(BlockDriverState *bs,
5441 char *filename, int filename_size)
5443 pstrcpy(filename, filename_size, bs->backing_file);
5446 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5448 BlockDriver *drv = bs->drv;
5449 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5450 if (!drv) {
5451 return -ENOMEDIUM;
5453 if (!drv->bdrv_get_info) {
5454 if (bs->file && drv->is_filter) {
5455 return bdrv_get_info(bs->file->bs, bdi);
5457 return -ENOTSUP;
5459 memset(bdi, 0, sizeof(*bdi));
5460 return drv->bdrv_get_info(bs, bdi);
5463 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5464 Error **errp)
5466 BlockDriver *drv = bs->drv;
5467 if (drv && drv->bdrv_get_specific_info) {
5468 return drv->bdrv_get_specific_info(bs, errp);
5470 return NULL;
5473 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5475 BlockDriver *drv = bs->drv;
5476 if (!drv || !drv->bdrv_get_specific_stats) {
5477 return NULL;
5479 return drv->bdrv_get_specific_stats(bs);
5482 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5484 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5485 return;
5488 bs->drv->bdrv_debug_event(bs, event);
5491 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5493 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5494 if (bs->file) {
5495 bs = bs->file->bs;
5496 continue;
5499 if (bs->drv->is_filter && bs->backing) {
5500 bs = bs->backing->bs;
5501 continue;
5504 break;
5507 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5508 assert(bs->drv->bdrv_debug_remove_breakpoint);
5509 return bs;
5512 return NULL;
5515 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5516 const char *tag)
5518 bs = bdrv_find_debug_node(bs);
5519 if (bs) {
5520 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5523 return -ENOTSUP;
5526 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5528 bs = bdrv_find_debug_node(bs);
5529 if (bs) {
5530 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5533 return -ENOTSUP;
5536 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5538 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5539 bs = bs->file ? bs->file->bs : NULL;
5542 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5543 return bs->drv->bdrv_debug_resume(bs, tag);
5546 return -ENOTSUP;
5549 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5551 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5552 bs = bs->file ? bs->file->bs : NULL;
5555 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5556 return bs->drv->bdrv_debug_is_suspended(bs, tag);
5559 return false;
5562 /* backing_file can either be relative, or absolute, or a protocol. If it is
5563 * relative, it must be relative to the chain. So, passing in bs->filename
5564 * from a BDS as backing_file should not be done, as that may be relative to
5565 * the CWD rather than the chain. */
5566 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5567 const char *backing_file)
5569 char *filename_full = NULL;
5570 char *backing_file_full = NULL;
5571 char *filename_tmp = NULL;
5572 int is_protocol = 0;
5573 BlockDriverState *curr_bs = NULL;
5574 BlockDriverState *retval = NULL;
5576 if (!bs || !bs->drv || !backing_file) {
5577 return NULL;
5580 filename_full = g_malloc(PATH_MAX);
5581 backing_file_full = g_malloc(PATH_MAX);
5583 is_protocol = path_has_protocol(backing_file);
5585 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
5587 /* If either of the filename paths is actually a protocol, then
5588 * compare unmodified paths; otherwise make paths relative */
5589 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5590 char *backing_file_full_ret;
5592 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
5593 retval = curr_bs->backing->bs;
5594 break;
5596 /* Also check against the full backing filename for the image */
5597 backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5598 NULL);
5599 if (backing_file_full_ret) {
5600 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5601 g_free(backing_file_full_ret);
5602 if (equal) {
5603 retval = curr_bs->backing->bs;
5604 break;
5607 } else {
5608 /* If not an absolute filename path, make it relative to the current
5609 * image's filename path */
5610 filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5611 NULL);
5612 /* We are going to compare canonicalized absolute pathnames */
5613 if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5614 g_free(filename_tmp);
5615 continue;
5617 g_free(filename_tmp);
5619 /* We need to make sure the backing filename we are comparing against
5620 * is relative to the current image filename (or absolute) */
5621 filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5622 if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5623 g_free(filename_tmp);
5624 continue;
5626 g_free(filename_tmp);
5628 if (strcmp(backing_file_full, filename_full) == 0) {
5629 retval = curr_bs->backing->bs;
5630 break;
5635 g_free(filename_full);
5636 g_free(backing_file_full);
5637 return retval;
5640 void bdrv_init(void)
5642 module_call_init(MODULE_INIT_BLOCK);
5645 void bdrv_init_with_whitelist(void)
5647 use_bdrv_whitelist = 1;
5648 bdrv_init();
5651 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5652 Error **errp)
5654 BdrvChild *child, *parent;
5655 uint64_t perm, shared_perm;
5656 Error *local_err = NULL;
5657 int ret;
5658 BdrvDirtyBitmap *bm;
5660 if (!bs->drv) {
5661 return;
5664 QLIST_FOREACH(child, &bs->children, next) {
5665 bdrv_co_invalidate_cache(child->bs, &local_err);
5666 if (local_err) {
5667 error_propagate(errp, local_err);
5668 return;
5673 * Update permissions, they may differ for inactive nodes.
5675 * Note that the required permissions of inactive images are always a
5676 * subset of the permissions required after activating the image. This
5677 * allows us to just get the permissions upfront without restricting
5678 * drv->bdrv_invalidate_cache().
5680 * It also means that in error cases, we don't have to try and revert to
5681 * the old permissions (which is an operation that could fail, too). We can
5682 * just keep the extended permissions for the next time that an activation
5683 * of the image is tried.
5685 if (bs->open_flags & BDRV_O_INACTIVE) {
5686 bs->open_flags &= ~BDRV_O_INACTIVE;
5687 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5688 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, errp);
5689 if (ret < 0) {
5690 bs->open_flags |= BDRV_O_INACTIVE;
5691 return;
5693 bdrv_set_perm(bs, perm, shared_perm);
5695 if (bs->drv->bdrv_co_invalidate_cache) {
5696 bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5697 if (local_err) {
5698 bs->open_flags |= BDRV_O_INACTIVE;
5699 error_propagate(errp, local_err);
5700 return;
5704 FOR_EACH_DIRTY_BITMAP(bs, bm) {
5705 bdrv_dirty_bitmap_skip_store(bm, false);
5708 ret = refresh_total_sectors(bs, bs->total_sectors);
5709 if (ret < 0) {
5710 bs->open_flags |= BDRV_O_INACTIVE;
5711 error_setg_errno(errp, -ret, "Could not refresh total sector count");
5712 return;
5716 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5717 if (parent->klass->activate) {
5718 parent->klass->activate(parent, &local_err);
5719 if (local_err) {
5720 bs->open_flags |= BDRV_O_INACTIVE;
5721 error_propagate(errp, local_err);
5722 return;
5728 typedef struct InvalidateCacheCo {
5729 BlockDriverState *bs;
5730 Error **errp;
5731 bool done;
5732 } InvalidateCacheCo;
5734 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5736 InvalidateCacheCo *ico = opaque;
5737 bdrv_co_invalidate_cache(ico->bs, ico->errp);
5738 ico->done = true;
5739 aio_wait_kick();
5742 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5744 Coroutine *co;
5745 InvalidateCacheCo ico = {
5746 .bs = bs,
5747 .done = false,
5748 .errp = errp
5751 if (qemu_in_coroutine()) {
5752 /* Fast-path if already in coroutine context */
5753 bdrv_invalidate_cache_co_entry(&ico);
5754 } else {
5755 co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
5756 bdrv_coroutine_enter(bs, co);
5757 BDRV_POLL_WHILE(bs, !ico.done);
5761 void bdrv_invalidate_cache_all(Error **errp)
5763 BlockDriverState *bs;
5764 Error *local_err = NULL;
5765 BdrvNextIterator it;
5767 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5768 AioContext *aio_context = bdrv_get_aio_context(bs);
5770 aio_context_acquire(aio_context);
5771 bdrv_invalidate_cache(bs, &local_err);
5772 aio_context_release(aio_context);
5773 if (local_err) {
5774 error_propagate(errp, local_err);
5775 bdrv_next_cleanup(&it);
5776 return;
5781 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5783 BdrvChild *parent;
5785 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5786 if (parent->klass->parent_is_bds) {
5787 BlockDriverState *parent_bs = parent->opaque;
5788 if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5789 return true;
5794 return false;
5797 static int bdrv_inactivate_recurse(BlockDriverState *bs)
5799 BdrvChild *child, *parent;
5800 bool tighten_restrictions;
5801 uint64_t perm, shared_perm;
5802 int ret;
5804 if (!bs->drv) {
5805 return -ENOMEDIUM;
5808 /* Make sure that we don't inactivate a child before its parent.
5809 * It will be covered by recursion from the yet active parent. */
5810 if (bdrv_has_bds_parent(bs, true)) {
5811 return 0;
5814 assert(!(bs->open_flags & BDRV_O_INACTIVE));
5816 /* Inactivate this node */
5817 if (bs->drv->bdrv_inactivate) {
5818 ret = bs->drv->bdrv_inactivate(bs);
5819 if (ret < 0) {
5820 return ret;
5824 QLIST_FOREACH(parent, &bs->parents, next_parent) {
5825 if (parent->klass->inactivate) {
5826 ret = parent->klass->inactivate(parent);
5827 if (ret < 0) {
5828 return ret;
5833 bs->open_flags |= BDRV_O_INACTIVE;
5835 /* Update permissions, they may differ for inactive nodes */
5836 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5837 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5838 &tighten_restrictions, NULL);
5839 assert(tighten_restrictions == false);
5840 if (ret < 0) {
5841 /* We only tried to loosen restrictions, so errors are not fatal */
5842 bdrv_abort_perm_update(bs);
5843 } else {
5844 bdrv_set_perm(bs, perm, shared_perm);
5848 /* Recursively inactivate children */
5849 QLIST_FOREACH(child, &bs->children, next) {
5850 ret = bdrv_inactivate_recurse(child->bs);
5851 if (ret < 0) {
5852 return ret;
5856 return 0;
5859 int bdrv_inactivate_all(void)
5861 BlockDriverState *bs = NULL;
5862 BdrvNextIterator it;
5863 int ret = 0;
5864 GSList *aio_ctxs = NULL, *ctx;
5866 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5867 AioContext *aio_context = bdrv_get_aio_context(bs);
5869 if (!g_slist_find(aio_ctxs, aio_context)) {
5870 aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5871 aio_context_acquire(aio_context);
5875 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5876 /* Nodes with BDS parents are covered by recursion from the last
5877 * parent that gets inactivated. Don't inactivate them a second
5878 * time if that has already happened. */
5879 if (bdrv_has_bds_parent(bs, false)) {
5880 continue;
5882 ret = bdrv_inactivate_recurse(bs);
5883 if (ret < 0) {
5884 bdrv_next_cleanup(&it);
5885 goto out;
5889 out:
5890 for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5891 AioContext *aio_context = ctx->data;
5892 aio_context_release(aio_context);
5894 g_slist_free(aio_ctxs);
5896 return ret;
5899 /**************************************************************/
5900 /* removable device support */
5903 * Return TRUE if the media is present
5905 bool bdrv_is_inserted(BlockDriverState *bs)
5907 BlockDriver *drv = bs->drv;
5908 BdrvChild *child;
5910 if (!drv) {
5911 return false;
5913 if (drv->bdrv_is_inserted) {
5914 return drv->bdrv_is_inserted(bs);
5916 QLIST_FOREACH(child, &bs->children, next) {
5917 if (!bdrv_is_inserted(child->bs)) {
5918 return false;
5921 return true;
5925 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5927 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
5929 BlockDriver *drv = bs->drv;
5931 if (drv && drv->bdrv_eject) {
5932 drv->bdrv_eject(bs, eject_flag);
5937 * Lock or unlock the media (if it is locked, the user won't be able
5938 * to eject it manually).
5940 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
5942 BlockDriver *drv = bs->drv;
5944 trace_bdrv_lock_medium(bs, locked);
5946 if (drv && drv->bdrv_lock_medium) {
5947 drv->bdrv_lock_medium(bs, locked);
5951 /* Get a reference to bs */
5952 void bdrv_ref(BlockDriverState *bs)
5954 bs->refcnt++;
5957 /* Release a previously grabbed reference to bs.
5958 * If after releasing, reference count is zero, the BlockDriverState is
5959 * deleted. */
5960 void bdrv_unref(BlockDriverState *bs)
5962 if (!bs) {
5963 return;
5965 assert(bs->refcnt > 0);
5966 if (--bs->refcnt == 0) {
5967 bdrv_delete(bs);
5971 struct BdrvOpBlocker {
5972 Error *reason;
5973 QLIST_ENTRY(BdrvOpBlocker) list;
5976 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5978 BdrvOpBlocker *blocker;
5979 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5980 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5981 blocker = QLIST_FIRST(&bs->op_blockers[op]);
5982 error_propagate_prepend(errp, error_copy(blocker->reason),
5983 "Node '%s' is busy: ",
5984 bdrv_get_device_or_node_name(bs));
5985 return true;
5987 return false;
5990 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5992 BdrvOpBlocker *blocker;
5993 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5995 blocker = g_new0(BdrvOpBlocker, 1);
5996 blocker->reason = reason;
5997 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6000 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6002 BdrvOpBlocker *blocker, *next;
6003 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6004 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6005 if (blocker->reason == reason) {
6006 QLIST_REMOVE(blocker, list);
6007 g_free(blocker);
6012 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6014 int i;
6015 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6016 bdrv_op_block(bs, i, reason);
6020 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6022 int i;
6023 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6024 bdrv_op_unblock(bs, i, reason);
6028 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6030 int i;
6032 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6033 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6034 return false;
6037 return true;
6040 void bdrv_img_create(const char *filename, const char *fmt,
6041 const char *base_filename, const char *base_fmt,
6042 char *options, uint64_t img_size, int flags, bool quiet,
6043 Error **errp)
6045 QemuOptsList *create_opts = NULL;
6046 QemuOpts *opts = NULL;
6047 const char *backing_fmt, *backing_file;
6048 int64_t size;
6049 BlockDriver *drv, *proto_drv;
6050 Error *local_err = NULL;
6051 int ret = 0;
6053 /* Find driver and parse its options */
6054 drv = bdrv_find_format(fmt);
6055 if (!drv) {
6056 error_setg(errp, "Unknown file format '%s'", fmt);
6057 return;
6060 proto_drv = bdrv_find_protocol(filename, true, errp);
6061 if (!proto_drv) {
6062 return;
6065 if (!drv->create_opts) {
6066 error_setg(errp, "Format driver '%s' does not support image creation",
6067 drv->format_name);
6068 return;
6071 if (!proto_drv->create_opts) {
6072 error_setg(errp, "Protocol driver '%s' does not support image creation",
6073 proto_drv->format_name);
6074 return;
6077 /* Create parameter list */
6078 create_opts = qemu_opts_append(create_opts, drv->create_opts);
6079 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6081 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6083 /* Parse -o options */
6084 if (options) {
6085 if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
6086 goto out;
6090 if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6091 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6092 } else if (img_size != UINT64_C(-1)) {
6093 error_setg(errp, "The image size must be specified only once");
6094 goto out;
6097 if (base_filename) {
6098 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
6099 NULL)) {
6100 error_setg(errp, "Backing file not supported for file format '%s'",
6101 fmt);
6102 goto out;
6106 if (base_fmt) {
6107 if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
6108 error_setg(errp, "Backing file format not supported for file "
6109 "format '%s'", fmt);
6110 goto out;
6114 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6115 if (backing_file) {
6116 if (!strcmp(filename, backing_file)) {
6117 error_setg(errp, "Error: Trying to create an image with the "
6118 "same filename as the backing file");
6119 goto out;
6123 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6125 /* The size for the image must always be specified, unless we have a backing
6126 * file and we have not been forbidden from opening it. */
6127 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6128 if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6129 BlockDriverState *bs;
6130 char *full_backing;
6131 int back_flags;
6132 QDict *backing_options = NULL;
6134 full_backing =
6135 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6136 &local_err);
6137 if (local_err) {
6138 goto out;
6140 assert(full_backing);
6142 /* backing files always opened read-only */
6143 back_flags = flags;
6144 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
6146 backing_options = qdict_new();
6147 if (backing_fmt) {
6148 qdict_put_str(backing_options, "driver", backing_fmt);
6150 qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
6152 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
6153 &local_err);
6154 g_free(full_backing);
6155 if (!bs) {
6156 error_append_hint(&local_err, "Could not open backing image.\n");
6157 goto out;
6158 } else {
6159 if (!backing_fmt) {
6160 warn_report("Deprecated use of backing file without explicit "
6161 "backing format (detected format of %s)",
6162 bs->drv->format_name);
6163 if (bs->drv != &bdrv_raw) {
6165 * A probe of raw deserves the most attention:
6166 * leaving the backing format out of the image
6167 * will ensure bs->probed is set (ensuring we
6168 * don't accidentally commit into the backing
6169 * file), and allow more spots to warn the users
6170 * to fix their toolchain when opening this image
6171 * later. For other images, we can safely record
6172 * the format that we probed.
6174 backing_fmt = bs->drv->format_name;
6175 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, backing_fmt,
6176 NULL);
6179 if (size == -1) {
6180 /* Opened BS, have no size */
6181 size = bdrv_getlength(bs);
6182 if (size < 0) {
6183 error_setg_errno(errp, -size, "Could not get size of '%s'",
6184 backing_file);
6185 bdrv_unref(bs);
6186 goto out;
6188 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
6190 bdrv_unref(bs);
6192 /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
6193 } else if (backing_file && !backing_fmt) {
6194 warn_report("Deprecated use of unopened backing file without "
6195 "explicit backing format, use of this image requires "
6196 "potentially unsafe format probing");
6199 if (size == -1) {
6200 error_setg(errp, "Image creation needs a size parameter");
6201 goto out;
6204 if (!quiet) {
6205 printf("Formatting '%s', fmt=%s ", filename, fmt);
6206 qemu_opts_print(opts, " ");
6207 puts("");
6208 fflush(stdout);
6211 ret = bdrv_create(drv, filename, opts, &local_err);
6213 if (ret == -EFBIG) {
6214 /* This is generally a better message than whatever the driver would
6215 * deliver (especially because of the cluster_size_hint), since that
6216 * is most probably not much different from "image too large". */
6217 const char *cluster_size_hint = "";
6218 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
6219 cluster_size_hint = " (try using a larger cluster size)";
6221 error_setg(errp, "The image size is too large for file format '%s'"
6222 "%s", fmt, cluster_size_hint);
6223 error_free(local_err);
6224 local_err = NULL;
6227 out:
6228 qemu_opts_del(opts);
6229 qemu_opts_free(create_opts);
6230 error_propagate(errp, local_err);
6233 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
6235 return bs ? bs->aio_context : qemu_get_aio_context();
6238 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
6240 aio_co_enter(bdrv_get_aio_context(bs), co);
6243 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
6245 QLIST_REMOVE(ban, list);
6246 g_free(ban);
6249 static void bdrv_detach_aio_context(BlockDriverState *bs)
6251 BdrvAioNotifier *baf, *baf_tmp;
6253 assert(!bs->walking_aio_notifiers);
6254 bs->walking_aio_notifiers = true;
6255 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
6256 if (baf->deleted) {
6257 bdrv_do_remove_aio_context_notifier(baf);
6258 } else {
6259 baf->detach_aio_context(baf->opaque);
6262 /* Never mind iterating again to check for ->deleted. bdrv_close() will
6263 * remove remaining aio notifiers if we aren't called again.
6265 bs->walking_aio_notifiers = false;
6267 if (bs->drv && bs->drv->bdrv_detach_aio_context) {
6268 bs->drv->bdrv_detach_aio_context(bs);
6271 if (bs->quiesce_counter) {
6272 aio_enable_external(bs->aio_context);
6274 bs->aio_context = NULL;
6277 static void bdrv_attach_aio_context(BlockDriverState *bs,
6278 AioContext *new_context)
6280 BdrvAioNotifier *ban, *ban_tmp;
6282 if (bs->quiesce_counter) {
6283 aio_disable_external(new_context);
6286 bs->aio_context = new_context;
6288 if (bs->drv && bs->drv->bdrv_attach_aio_context) {
6289 bs->drv->bdrv_attach_aio_context(bs, new_context);
6292 assert(!bs->walking_aio_notifiers);
6293 bs->walking_aio_notifiers = true;
6294 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
6295 if (ban->deleted) {
6296 bdrv_do_remove_aio_context_notifier(ban);
6297 } else {
6298 ban->attached_aio_context(new_context, ban->opaque);
6301 bs->walking_aio_notifiers = false;
6305 * Changes the AioContext used for fd handlers, timers, and BHs by this
6306 * BlockDriverState and all its children and parents.
6308 * Must be called from the main AioContext.
6310 * The caller must own the AioContext lock for the old AioContext of bs, but it
6311 * must not own the AioContext lock for new_context (unless new_context is the
6312 * same as the current context of bs).
6314 * @ignore will accumulate all visited BdrvChild object. The caller is
6315 * responsible for freeing the list afterwards.
6317 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6318 AioContext *new_context, GSList **ignore)
6320 AioContext *old_context = bdrv_get_aio_context(bs);
6321 BdrvChild *child;
6323 g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6325 if (old_context == new_context) {
6326 return;
6329 bdrv_drained_begin(bs);
6331 QLIST_FOREACH(child, &bs->children, next) {
6332 if (g_slist_find(*ignore, child)) {
6333 continue;
6335 *ignore = g_slist_prepend(*ignore, child);
6336 bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6338 QLIST_FOREACH(child, &bs->parents, next_parent) {
6339 if (g_slist_find(*ignore, child)) {
6340 continue;
6342 assert(child->klass->set_aio_ctx);
6343 *ignore = g_slist_prepend(*ignore, child);
6344 child->klass->set_aio_ctx(child, new_context, ignore);
6347 bdrv_detach_aio_context(bs);
6349 /* Acquire the new context, if necessary */
6350 if (qemu_get_aio_context() != new_context) {
6351 aio_context_acquire(new_context);
6354 bdrv_attach_aio_context(bs, new_context);
6357 * If this function was recursively called from
6358 * bdrv_set_aio_context_ignore(), there may be nodes in the
6359 * subtree that have not yet been moved to the new AioContext.
6360 * Release the old one so bdrv_drained_end() can poll them.
6362 if (qemu_get_aio_context() != old_context) {
6363 aio_context_release(old_context);
6366 bdrv_drained_end(bs);
6368 if (qemu_get_aio_context() != old_context) {
6369 aio_context_acquire(old_context);
6371 if (qemu_get_aio_context() != new_context) {
6372 aio_context_release(new_context);
6376 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6377 GSList **ignore, Error **errp)
6379 if (g_slist_find(*ignore, c)) {
6380 return true;
6382 *ignore = g_slist_prepend(*ignore, c);
6385 * A BdrvChildClass that doesn't handle AioContext changes cannot
6386 * tolerate any AioContext changes
6388 if (!c->klass->can_set_aio_ctx) {
6389 char *user = bdrv_child_user_desc(c);
6390 error_setg(errp, "Changing iothreads is not supported by %s", user);
6391 g_free(user);
6392 return false;
6394 if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
6395 assert(!errp || *errp);
6396 return false;
6398 return true;
6401 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6402 GSList **ignore, Error **errp)
6404 if (g_slist_find(*ignore, c)) {
6405 return true;
6407 *ignore = g_slist_prepend(*ignore, c);
6408 return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6411 /* @ignore will accumulate all visited BdrvChild object. The caller is
6412 * responsible for freeing the list afterwards. */
6413 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6414 GSList **ignore, Error **errp)
6416 BdrvChild *c;
6418 if (bdrv_get_aio_context(bs) == ctx) {
6419 return true;
6422 QLIST_FOREACH(c, &bs->parents, next_parent) {
6423 if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6424 return false;
6427 QLIST_FOREACH(c, &bs->children, next) {
6428 if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6429 return false;
6433 return true;
6436 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6437 BdrvChild *ignore_child, Error **errp)
6439 GSList *ignore;
6440 bool ret;
6442 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6443 ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6444 g_slist_free(ignore);
6446 if (!ret) {
6447 return -EPERM;
6450 ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6451 bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6452 g_slist_free(ignore);
6454 return 0;
6457 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6458 Error **errp)
6460 return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6463 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6464 void (*attached_aio_context)(AioContext *new_context, void *opaque),
6465 void (*detach_aio_context)(void *opaque), void *opaque)
6467 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6468 *ban = (BdrvAioNotifier){
6469 .attached_aio_context = attached_aio_context,
6470 .detach_aio_context = detach_aio_context,
6471 .opaque = opaque
6474 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6477 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6478 void (*attached_aio_context)(AioContext *,
6479 void *),
6480 void (*detach_aio_context)(void *),
6481 void *opaque)
6483 BdrvAioNotifier *ban, *ban_next;
6485 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6486 if (ban->attached_aio_context == attached_aio_context &&
6487 ban->detach_aio_context == detach_aio_context &&
6488 ban->opaque == opaque &&
6489 ban->deleted == false)
6491 if (bs->walking_aio_notifiers) {
6492 ban->deleted = true;
6493 } else {
6494 bdrv_do_remove_aio_context_notifier(ban);
6496 return;
6500 abort();
6503 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6504 BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6505 bool force,
6506 Error **errp)
6508 if (!bs->drv) {
6509 error_setg(errp, "Node is ejected");
6510 return -ENOMEDIUM;
6512 if (!bs->drv->bdrv_amend_options) {
6513 error_setg(errp, "Block driver '%s' does not support option amendment",
6514 bs->drv->format_name);
6515 return -ENOTSUP;
6517 return bs->drv->bdrv_amend_options(bs, opts, status_cb,
6518 cb_opaque, force, errp);
6522 * This function checks whether the given @to_replace is allowed to be
6523 * replaced by a node that always shows the same data as @bs. This is
6524 * used for example to verify whether the mirror job can replace
6525 * @to_replace by the target mirrored from @bs.
6526 * To be replaceable, @bs and @to_replace may either be guaranteed to
6527 * always show the same data (because they are only connected through
6528 * filters), or some driver may allow replacing one of its children
6529 * because it can guarantee that this child's data is not visible at
6530 * all (for example, for dissenting quorum children that have no other
6531 * parents).
6533 bool bdrv_recurse_can_replace(BlockDriverState *bs,
6534 BlockDriverState *to_replace)
6536 if (!bs || !bs->drv) {
6537 return false;
6540 if (bs == to_replace) {
6541 return true;
6544 /* See what the driver can do */
6545 if (bs->drv->bdrv_recurse_can_replace) {
6546 return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
6549 /* For filters without an own implementation, we can recurse on our own */
6550 if (bs->drv->is_filter) {
6551 BdrvChild *child = bs->file ?: bs->backing;
6552 return bdrv_recurse_can_replace(child->bs, to_replace);
6555 /* Safe default */
6556 return false;
6560 * Check whether the given @node_name can be replaced by a node that
6561 * has the same data as @parent_bs. If so, return @node_name's BDS;
6562 * NULL otherwise.
6564 * @node_name must be a (recursive) *child of @parent_bs (or this
6565 * function will return NULL).
6567 * The result (whether the node can be replaced or not) is only valid
6568 * for as long as no graph or permission changes occur.
6570 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6571 const char *node_name, Error **errp)
6573 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
6574 AioContext *aio_context;
6576 if (!to_replace_bs) {
6577 error_setg(errp, "Node name '%s' not found", node_name);
6578 return NULL;
6581 aio_context = bdrv_get_aio_context(to_replace_bs);
6582 aio_context_acquire(aio_context);
6584 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
6585 to_replace_bs = NULL;
6586 goto out;
6589 /* We don't want arbitrary node of the BDS chain to be replaced only the top
6590 * most non filter in order to prevent data corruption.
6591 * Another benefit is that this tests exclude backing files which are
6592 * blocked by the backing blockers.
6594 if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
6595 error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
6596 "because it cannot be guaranteed that doing so would not "
6597 "lead to an abrupt change of visible data",
6598 node_name, parent_bs->node_name);
6599 to_replace_bs = NULL;
6600 goto out;
6603 out:
6604 aio_context_release(aio_context);
6605 return to_replace_bs;
6609 * Iterates through the list of runtime option keys that are said to
6610 * be "strong" for a BDS. An option is called "strong" if it changes
6611 * a BDS's data. For example, the null block driver's "size" and
6612 * "read-zeroes" options are strong, but its "latency-ns" option is
6613 * not.
6615 * If a key returned by this function ends with a dot, all options
6616 * starting with that prefix are strong.
6618 static const char *const *strong_options(BlockDriverState *bs,
6619 const char *const *curopt)
6621 static const char *const global_options[] = {
6622 "driver", "filename", NULL
6625 if (!curopt) {
6626 return &global_options[0];
6629 curopt++;
6630 if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6631 curopt = bs->drv->strong_runtime_opts;
6634 return (curopt && *curopt) ? curopt : NULL;
6638 * Copies all strong runtime options from bs->options to the given
6639 * QDict. The set of strong option keys is determined by invoking
6640 * strong_options().
6642 * Returns true iff any strong option was present in bs->options (and
6643 * thus copied to the target QDict) with the exception of "filename"
6644 * and "driver". The caller is expected to use this value to decide
6645 * whether the existence of strong options prevents the generation of
6646 * a plain filename.
6648 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6650 bool found_any = false;
6651 const char *const *option_name = NULL;
6653 if (!bs->drv) {
6654 return false;
6657 while ((option_name = strong_options(bs, option_name))) {
6658 bool option_given = false;
6660 assert(strlen(*option_name) > 0);
6661 if ((*option_name)[strlen(*option_name) - 1] != '.') {
6662 QObject *entry = qdict_get(bs->options, *option_name);
6663 if (!entry) {
6664 continue;
6667 qdict_put_obj(d, *option_name, qobject_ref(entry));
6668 option_given = true;
6669 } else {
6670 const QDictEntry *entry;
6671 for (entry = qdict_first(bs->options); entry;
6672 entry = qdict_next(bs->options, entry))
6674 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6675 qdict_put_obj(d, qdict_entry_key(entry),
6676 qobject_ref(qdict_entry_value(entry)));
6677 option_given = true;
6682 /* While "driver" and "filename" need to be included in a JSON filename,
6683 * their existence does not prohibit generation of a plain filename. */
6684 if (!found_any && option_given &&
6685 strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6687 found_any = true;
6691 if (!qdict_haskey(d, "driver")) {
6692 /* Drivers created with bdrv_new_open_driver() may not have a
6693 * @driver option. Add it here. */
6694 qdict_put_str(d, "driver", bs->drv->format_name);
6697 return found_any;
6700 /* Note: This function may return false positives; it may return true
6701 * even if opening the backing file specified by bs's image header
6702 * would result in exactly bs->backing. */
6703 static bool bdrv_backing_overridden(BlockDriverState *bs)
6705 if (bs->backing) {
6706 return strcmp(bs->auto_backing_file,
6707 bs->backing->bs->filename);
6708 } else {
6709 /* No backing BDS, so if the image header reports any backing
6710 * file, it must have been suppressed */
6711 return bs->auto_backing_file[0] != '\0';
6715 /* Updates the following BDS fields:
6716 * - exact_filename: A filename which may be used for opening a block device
6717 * which (mostly) equals the given BDS (even without any
6718 * other options; so reading and writing must return the same
6719 * results, but caching etc. may be different)
6720 * - full_open_options: Options which, when given when opening a block device
6721 * (without a filename), result in a BDS (mostly)
6722 * equalling the given one
6723 * - filename: If exact_filename is set, it is copied here. Otherwise,
6724 * full_open_options is converted to a JSON object, prefixed with
6725 * "json:" (for use through the JSON pseudo protocol) and put here.
6727 void bdrv_refresh_filename(BlockDriverState *bs)
6729 BlockDriver *drv = bs->drv;
6730 BdrvChild *child;
6731 QDict *opts;
6732 bool backing_overridden;
6733 bool generate_json_filename; /* Whether our default implementation should
6734 fill exact_filename (false) or not (true) */
6736 if (!drv) {
6737 return;
6740 /* This BDS's file name may depend on any of its children's file names, so
6741 * refresh those first */
6742 QLIST_FOREACH(child, &bs->children, next) {
6743 bdrv_refresh_filename(child->bs);
6746 if (bs->implicit) {
6747 /* For implicit nodes, just copy everything from the single child */
6748 child = QLIST_FIRST(&bs->children);
6749 assert(QLIST_NEXT(child, next) == NULL);
6751 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6752 child->bs->exact_filename);
6753 pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6755 qobject_unref(bs->full_open_options);
6756 bs->full_open_options = qobject_ref(child->bs->full_open_options);
6758 return;
6761 backing_overridden = bdrv_backing_overridden(bs);
6763 if (bs->open_flags & BDRV_O_NO_IO) {
6764 /* Without I/O, the backing file does not change anything.
6765 * Therefore, in such a case (primarily qemu-img), we can
6766 * pretend the backing file has not been overridden even if
6767 * it technically has been. */
6768 backing_overridden = false;
6771 /* Gather the options QDict */
6772 opts = qdict_new();
6773 generate_json_filename = append_strong_runtime_options(opts, bs);
6774 generate_json_filename |= backing_overridden;
6776 if (drv->bdrv_gather_child_options) {
6777 /* Some block drivers may not want to present all of their children's
6778 * options, or name them differently from BdrvChild.name */
6779 drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6780 } else {
6781 QLIST_FOREACH(child, &bs->children, next) {
6782 if (child == bs->backing && !backing_overridden) {
6783 /* We can skip the backing BDS if it has not been overridden */
6784 continue;
6787 qdict_put(opts, child->name,
6788 qobject_ref(child->bs->full_open_options));
6791 if (backing_overridden && !bs->backing) {
6792 /* Force no backing file */
6793 qdict_put_null(opts, "backing");
6797 qobject_unref(bs->full_open_options);
6798 bs->full_open_options = opts;
6800 if (drv->bdrv_refresh_filename) {
6801 /* Obsolete information is of no use here, so drop the old file name
6802 * information before refreshing it */
6803 bs->exact_filename[0] = '\0';
6805 drv->bdrv_refresh_filename(bs);
6806 } else if (bs->file) {
6807 /* Try to reconstruct valid information from the underlying file */
6809 bs->exact_filename[0] = '\0';
6812 * We can use the underlying file's filename if:
6813 * - it has a filename,
6814 * - the file is a protocol BDS, and
6815 * - opening that file (as this BDS's format) will automatically create
6816 * the BDS tree we have right now, that is:
6817 * - the user did not significantly change this BDS's behavior with
6818 * some explicit (strong) options
6819 * - no non-file child of this BDS has been overridden by the user
6820 * Both of these conditions are represented by generate_json_filename.
6822 if (bs->file->bs->exact_filename[0] &&
6823 bs->file->bs->drv->bdrv_file_open &&
6824 !generate_json_filename)
6826 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6830 if (bs->exact_filename[0]) {
6831 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
6832 } else {
6833 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6834 if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6835 qstring_get_str(json)) >= sizeof(bs->filename)) {
6836 /* Give user a hint if we truncated things. */
6837 strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
6839 qobject_unref(json);
6843 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6845 BlockDriver *drv = bs->drv;
6847 if (!drv) {
6848 error_setg(errp, "Node '%s' is ejected", bs->node_name);
6849 return NULL;
6852 if (drv->bdrv_dirname) {
6853 return drv->bdrv_dirname(bs, errp);
6856 if (bs->file) {
6857 return bdrv_dirname(bs->file->bs, errp);
6860 bdrv_refresh_filename(bs);
6861 if (bs->exact_filename[0] != '\0') {
6862 return path_combine(bs->exact_filename, "");
6865 error_setg(errp, "Cannot generate a base directory for %s nodes",
6866 drv->format_name);
6867 return NULL;
6871 * Hot add/remove a BDS's child. So the user can take a child offline when
6872 * it is broken and take a new child online
6874 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6875 Error **errp)
6878 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6879 error_setg(errp, "The node %s does not support adding a child",
6880 bdrv_get_device_or_node_name(parent_bs));
6881 return;
6884 if (!QLIST_EMPTY(&child_bs->parents)) {
6885 error_setg(errp, "The node %s already has a parent",
6886 child_bs->node_name);
6887 return;
6890 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6893 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6895 BdrvChild *tmp;
6897 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6898 error_setg(errp, "The node %s does not support removing a child",
6899 bdrv_get_device_or_node_name(parent_bs));
6900 return;
6903 QLIST_FOREACH(tmp, &parent_bs->children, next) {
6904 if (tmp == child) {
6905 break;
6909 if (!tmp) {
6910 error_setg(errp, "The node %s does not have a child named %s",
6911 bdrv_get_device_or_node_name(parent_bs),
6912 bdrv_get_device_or_node_name(child->bs));
6913 return;
6916 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
6919 int bdrv_make_empty(BdrvChild *c, Error **errp)
6921 BlockDriver *drv = c->bs->drv;
6922 int ret;
6924 assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
6926 if (!drv->bdrv_make_empty) {
6927 error_setg(errp, "%s does not support emptying nodes",
6928 drv->format_name);
6929 return -ENOTSUP;
6932 ret = drv->bdrv_make_empty(c->bs);
6933 if (ret < 0) {
6934 error_setg_errno(errp, -ret, "Failed to empty %s",
6935 c->bs->filename);
6936 return ret;
6939 return 0;