hw/display/xlnx_dp: Free FIFOs adding xlnx_dp_finalize()
[qemu/ar7.git] / block.c
blobc5b887cec1962a65330d853ffe4d5d04ae1ac08e
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/fuse.h"
30 #include "block/nbd.h"
31 #include "block/qdict.h"
32 #include "qemu/error-report.h"
33 #include "block/module_block.h"
34 #include "qemu/main-loop.h"
35 #include "qemu/module.h"
36 #include "qapi/error.h"
37 #include "qapi/qmp/qdict.h"
38 #include "qapi/qmp/qjson.h"
39 #include "qapi/qmp/qnull.h"
40 #include "qapi/qmp/qstring.h"
41 #include "qapi/qobject-output-visitor.h"
42 #include "qapi/qapi-visit-block-core.h"
43 #include "sysemu/block-backend.h"
44 #include "sysemu/sysemu.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
51 #include "qemu/id.h"
52 #include "block/coroutines.h"
54 #ifdef CONFIG_BSD
55 #include <sys/ioctl.h>
56 #include <sys/queue.h>
57 #ifndef __DragonFly__
58 #include <sys/disk.h>
59 #endif
60 #endif
62 #ifdef _WIN32
63 #include <windows.h>
64 #endif
66 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
68 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
69 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
71 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
72 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
74 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
75 QLIST_HEAD_INITIALIZER(bdrv_drivers);
77 static BlockDriverState *bdrv_open_inherit(const char *filename,
78 const char *reference,
79 QDict *options, int flags,
80 BlockDriverState *parent,
81 const BdrvChildClass *child_class,
82 BdrvChildRole child_role,
83 Error **errp);
85 /* If non-zero, use only whitelisted block drivers */
86 static int use_bdrv_whitelist;
88 #ifdef _WIN32
89 static int is_windows_drive_prefix(const char *filename)
91 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
92 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
93 filename[1] == ':');
96 int is_windows_drive(const char *filename)
98 if (is_windows_drive_prefix(filename) &&
99 filename[2] == '\0')
100 return 1;
101 if (strstart(filename, "\\\\.\\", NULL) ||
102 strstart(filename, "//./", NULL))
103 return 1;
104 return 0;
106 #endif
108 size_t bdrv_opt_mem_align(BlockDriverState *bs)
110 if (!bs || !bs->drv) {
111 /* page size or 4k (hdd sector size) should be on the safe side */
112 return MAX(4096, qemu_real_host_page_size);
115 return bs->bl.opt_mem_alignment;
118 size_t bdrv_min_mem_align(BlockDriverState *bs)
120 if (!bs || !bs->drv) {
121 /* page size or 4k (hdd sector size) should be on the safe side */
122 return MAX(4096, qemu_real_host_page_size);
125 return bs->bl.min_mem_alignment;
128 /* check if the path starts with "<protocol>:" */
129 int path_has_protocol(const char *path)
131 const char *p;
133 #ifdef _WIN32
134 if (is_windows_drive(path) ||
135 is_windows_drive_prefix(path)) {
136 return 0;
138 p = path + strcspn(path, ":/\\");
139 #else
140 p = path + strcspn(path, ":/");
141 #endif
143 return *p == ':';
146 int path_is_absolute(const char *path)
148 #ifdef _WIN32
149 /* specific case for names like: "\\.\d:" */
150 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
151 return 1;
153 return (*path == '/' || *path == '\\');
154 #else
155 return (*path == '/');
156 #endif
159 /* if filename is absolute, just return its duplicate. Otherwise, build a
160 path to it by considering it is relative to base_path. URL are
161 supported. */
162 char *path_combine(const char *base_path, const char *filename)
164 const char *protocol_stripped = NULL;
165 const char *p, *p1;
166 char *result;
167 int len;
169 if (path_is_absolute(filename)) {
170 return g_strdup(filename);
173 if (path_has_protocol(base_path)) {
174 protocol_stripped = strchr(base_path, ':');
175 if (protocol_stripped) {
176 protocol_stripped++;
179 p = protocol_stripped ?: base_path;
181 p1 = strrchr(base_path, '/');
182 #ifdef _WIN32
184 const char *p2;
185 p2 = strrchr(base_path, '\\');
186 if (!p1 || p2 > p1) {
187 p1 = p2;
190 #endif
191 if (p1) {
192 p1++;
193 } else {
194 p1 = base_path;
196 if (p1 > p) {
197 p = p1;
199 len = p - base_path;
201 result = g_malloc(len + strlen(filename) + 1);
202 memcpy(result, base_path, len);
203 strcpy(result + len, filename);
205 return result;
209 * Helper function for bdrv_parse_filename() implementations to remove optional
210 * protocol prefixes (especially "file:") from a filename and for putting the
211 * stripped filename into the options QDict if there is such a prefix.
213 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
214 QDict *options)
216 if (strstart(filename, prefix, &filename)) {
217 /* Stripping the explicit protocol prefix may result in a protocol
218 * prefix being (wrongly) detected (if the filename contains a colon) */
219 if (path_has_protocol(filename)) {
220 GString *fat_filename;
222 /* This means there is some colon before the first slash; therefore,
223 * this cannot be an absolute path */
224 assert(!path_is_absolute(filename));
226 /* And we can thus fix the protocol detection issue by prefixing it
227 * by "./" */
228 fat_filename = g_string_new("./");
229 g_string_append(fat_filename, filename);
231 assert(!path_has_protocol(fat_filename->str));
233 qdict_put(options, "filename",
234 qstring_from_gstring(fat_filename));
235 } else {
236 /* If no protocol prefix was detected, we can use the shortened
237 * filename as-is */
238 qdict_put_str(options, "filename", filename);
244 /* Returns whether the image file is opened as read-only. Note that this can
245 * return false and writing to the image file is still not possible because the
246 * image is inactivated. */
247 bool bdrv_is_read_only(BlockDriverState *bs)
249 return bs->read_only;
252 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
253 bool ignore_allow_rdw, Error **errp)
255 /* Do not set read_only if copy_on_read is enabled */
256 if (bs->copy_on_read && read_only) {
257 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
258 bdrv_get_device_or_node_name(bs));
259 return -EINVAL;
262 /* Do not clear read_only if it is prohibited */
263 if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
264 !ignore_allow_rdw)
266 error_setg(errp, "Node '%s' is read only",
267 bdrv_get_device_or_node_name(bs));
268 return -EPERM;
271 return 0;
275 * Called by a driver that can only provide a read-only image.
277 * Returns 0 if the node is already read-only or it could switch the node to
278 * read-only because BDRV_O_AUTO_RDONLY is set.
280 * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
281 * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
282 * is not NULL, it is used as the error message for the Error object.
284 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
285 Error **errp)
287 int ret = 0;
289 if (!(bs->open_flags & BDRV_O_RDWR)) {
290 return 0;
292 if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
293 goto fail;
296 ret = bdrv_can_set_read_only(bs, true, false, NULL);
297 if (ret < 0) {
298 goto fail;
301 bs->read_only = true;
302 bs->open_flags &= ~BDRV_O_RDWR;
304 return 0;
306 fail:
307 error_setg(errp, "%s", errmsg ?: "Image is read-only");
308 return -EACCES;
312 * If @backing is empty, this function returns NULL without setting
313 * @errp. In all other cases, NULL will only be returned with @errp
314 * set.
316 * Therefore, a return value of NULL without @errp set means that
317 * there is no backing file; if @errp is set, there is one but its
318 * absolute filename cannot be generated.
320 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
321 const char *backing,
322 Error **errp)
324 if (backing[0] == '\0') {
325 return NULL;
326 } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
327 return g_strdup(backing);
328 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
329 error_setg(errp, "Cannot use relative backing file names for '%s'",
330 backed);
331 return NULL;
332 } else {
333 return path_combine(backed, backing);
338 * If @filename is empty or NULL, this function returns NULL without
339 * setting @errp. In all other cases, NULL will only be returned with
340 * @errp set.
342 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
343 const char *filename, Error **errp)
345 char *dir, *full_name;
347 if (!filename || filename[0] == '\0') {
348 return NULL;
349 } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
350 return g_strdup(filename);
353 dir = bdrv_dirname(relative_to, errp);
354 if (!dir) {
355 return NULL;
358 full_name = g_strconcat(dir, filename, NULL);
359 g_free(dir);
360 return full_name;
363 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
365 return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
368 void bdrv_register(BlockDriver *bdrv)
370 assert(bdrv->format_name);
371 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
374 BlockDriverState *bdrv_new(void)
376 BlockDriverState *bs;
377 int i;
379 bs = g_new0(BlockDriverState, 1);
380 QLIST_INIT(&bs->dirty_bitmaps);
381 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
382 QLIST_INIT(&bs->op_blockers[i]);
384 notifier_with_return_list_init(&bs->before_write_notifiers);
385 qemu_co_mutex_init(&bs->reqs_lock);
386 qemu_mutex_init(&bs->dirty_bitmap_mutex);
387 bs->refcnt = 1;
388 bs->aio_context = qemu_get_aio_context();
390 qemu_co_queue_init(&bs->flush_queue);
392 for (i = 0; i < bdrv_drain_all_count; i++) {
393 bdrv_drained_begin(bs);
396 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
398 return bs;
401 static BlockDriver *bdrv_do_find_format(const char *format_name)
403 BlockDriver *drv1;
405 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
406 if (!strcmp(drv1->format_name, format_name)) {
407 return drv1;
411 return NULL;
414 BlockDriver *bdrv_find_format(const char *format_name)
416 BlockDriver *drv1;
417 int i;
419 drv1 = bdrv_do_find_format(format_name);
420 if (drv1) {
421 return drv1;
424 /* The driver isn't registered, maybe we need to load a module */
425 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
426 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
427 block_module_load_one(block_driver_modules[i].library_name);
428 break;
432 return bdrv_do_find_format(format_name);
435 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
437 static const char *whitelist_rw[] = {
438 CONFIG_BDRV_RW_WHITELIST
439 NULL
441 static const char *whitelist_ro[] = {
442 CONFIG_BDRV_RO_WHITELIST
443 NULL
445 const char **p;
447 if (!whitelist_rw[0] && !whitelist_ro[0]) {
448 return 1; /* no whitelist, anything goes */
451 for (p = whitelist_rw; *p; p++) {
452 if (!strcmp(format_name, *p)) {
453 return 1;
456 if (read_only) {
457 for (p = whitelist_ro; *p; p++) {
458 if (!strcmp(format_name, *p)) {
459 return 1;
463 return 0;
466 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
468 return bdrv_format_is_whitelisted(drv->format_name, read_only);
471 bool bdrv_uses_whitelist(void)
473 return use_bdrv_whitelist;
476 typedef struct CreateCo {
477 BlockDriver *drv;
478 char *filename;
479 QemuOpts *opts;
480 int ret;
481 Error *err;
482 } CreateCo;
484 static void coroutine_fn bdrv_create_co_entry(void *opaque)
486 Error *local_err = NULL;
487 int ret;
489 CreateCo *cco = opaque;
490 assert(cco->drv);
492 ret = cco->drv->bdrv_co_create_opts(cco->drv,
493 cco->filename, cco->opts, &local_err);
494 error_propagate(&cco->err, local_err);
495 cco->ret = ret;
498 int bdrv_create(BlockDriver *drv, const char* filename,
499 QemuOpts *opts, Error **errp)
501 int ret;
503 Coroutine *co;
504 CreateCo cco = {
505 .drv = drv,
506 .filename = g_strdup(filename),
507 .opts = opts,
508 .ret = NOT_DONE,
509 .err = NULL,
512 if (!drv->bdrv_co_create_opts) {
513 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
514 ret = -ENOTSUP;
515 goto out;
518 if (qemu_in_coroutine()) {
519 /* Fast-path if already in coroutine context */
520 bdrv_create_co_entry(&cco);
521 } else {
522 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
523 qemu_coroutine_enter(co);
524 while (cco.ret == NOT_DONE) {
525 aio_poll(qemu_get_aio_context(), true);
529 ret = cco.ret;
530 if (ret < 0) {
531 if (cco.err) {
532 error_propagate(errp, cco.err);
533 } else {
534 error_setg_errno(errp, -ret, "Could not create image");
538 out:
539 g_free(cco.filename);
540 return ret;
544 * Helper function for bdrv_create_file_fallback(): Resize @blk to at
545 * least the given @minimum_size.
547 * On success, return @blk's actual length.
548 * Otherwise, return -errno.
550 static int64_t create_file_fallback_truncate(BlockBackend *blk,
551 int64_t minimum_size, Error **errp)
553 Error *local_err = NULL;
554 int64_t size;
555 int ret;
557 ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
558 &local_err);
559 if (ret < 0 && ret != -ENOTSUP) {
560 error_propagate(errp, local_err);
561 return ret;
564 size = blk_getlength(blk);
565 if (size < 0) {
566 error_free(local_err);
567 error_setg_errno(errp, -size,
568 "Failed to inquire the new image file's length");
569 return size;
572 if (size < minimum_size) {
573 /* Need to grow the image, but we failed to do that */
574 error_propagate(errp, local_err);
575 return -ENOTSUP;
578 error_free(local_err);
579 local_err = NULL;
581 return size;
585 * Helper function for bdrv_create_file_fallback(): Zero the first
586 * sector to remove any potentially pre-existing image header.
588 static int create_file_fallback_zero_first_sector(BlockBackend *blk,
589 int64_t current_size,
590 Error **errp)
592 int64_t bytes_to_clear;
593 int ret;
595 bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
596 if (bytes_to_clear) {
597 ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
598 if (ret < 0) {
599 error_setg_errno(errp, -ret,
600 "Failed to clear the new image's first sector");
601 return ret;
605 return 0;
609 * Simple implementation of bdrv_co_create_opts for protocol drivers
610 * which only support creation via opening a file
611 * (usually existing raw storage device)
613 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
614 const char *filename,
615 QemuOpts *opts,
616 Error **errp)
618 BlockBackend *blk;
619 QDict *options;
620 int64_t size = 0;
621 char *buf = NULL;
622 PreallocMode prealloc;
623 Error *local_err = NULL;
624 int ret;
626 size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
627 buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
628 prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
629 PREALLOC_MODE_OFF, &local_err);
630 g_free(buf);
631 if (local_err) {
632 error_propagate(errp, local_err);
633 return -EINVAL;
636 if (prealloc != PREALLOC_MODE_OFF) {
637 error_setg(errp, "Unsupported preallocation mode '%s'",
638 PreallocMode_str(prealloc));
639 return -ENOTSUP;
642 options = qdict_new();
643 qdict_put_str(options, "driver", drv->format_name);
645 blk = blk_new_open(filename, NULL, options,
646 BDRV_O_RDWR | BDRV_O_RESIZE, errp);
647 if (!blk) {
648 error_prepend(errp, "Protocol driver '%s' does not support image "
649 "creation, and opening the image failed: ",
650 drv->format_name);
651 return -EINVAL;
654 size = create_file_fallback_truncate(blk, size, errp);
655 if (size < 0) {
656 ret = size;
657 goto out;
660 ret = create_file_fallback_zero_first_sector(blk, size, errp);
661 if (ret < 0) {
662 goto out;
665 ret = 0;
666 out:
667 blk_unref(blk);
668 return ret;
671 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
673 QemuOpts *protocol_opts;
674 BlockDriver *drv;
675 QDict *qdict;
676 int ret;
678 drv = bdrv_find_protocol(filename, true, errp);
679 if (drv == NULL) {
680 return -ENOENT;
683 if (!drv->create_opts) {
684 error_setg(errp, "Driver '%s' does not support image creation",
685 drv->format_name);
686 return -ENOTSUP;
690 * 'opts' contains a QemuOptsList with a combination of format and protocol
691 * default values.
693 * The format properly removes its options, but the default values remain
694 * in 'opts->list'. So if the protocol has options with the same name
695 * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
696 * of the format, since for overlapping options, the format wins.
698 * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
699 * only the set options, and then convert it back to QemuOpts, using the
700 * create_opts of the protocol. So the new QemuOpts, will contain only the
701 * protocol defaults.
703 qdict = qemu_opts_to_qdict(opts, NULL);
704 protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
705 if (protocol_opts == NULL) {
706 ret = -EINVAL;
707 goto out;
710 ret = bdrv_create(drv, filename, protocol_opts, errp);
711 out:
712 qemu_opts_del(protocol_opts);
713 qobject_unref(qdict);
714 return ret;
717 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
719 Error *local_err = NULL;
720 int ret;
722 assert(bs != NULL);
724 if (!bs->drv) {
725 error_setg(errp, "Block node '%s' is not opened", bs->filename);
726 return -ENOMEDIUM;
729 if (!bs->drv->bdrv_co_delete_file) {
730 error_setg(errp, "Driver '%s' does not support image deletion",
731 bs->drv->format_name);
732 return -ENOTSUP;
735 ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
736 if (ret < 0) {
737 error_propagate(errp, local_err);
740 return ret;
743 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
745 Error *local_err = NULL;
746 int ret;
748 if (!bs) {
749 return;
752 ret = bdrv_co_delete_file(bs, &local_err);
754 * ENOTSUP will happen if the block driver doesn't support
755 * the 'bdrv_co_delete_file' interface. This is a predictable
756 * scenario and shouldn't be reported back to the user.
758 if (ret == -ENOTSUP) {
759 error_free(local_err);
760 } else if (ret < 0) {
761 error_report_err(local_err);
766 * Try to get @bs's logical and physical block size.
767 * On success, store them in @bsz struct and return 0.
768 * On failure return -errno.
769 * @bs must not be empty.
771 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
773 BlockDriver *drv = bs->drv;
774 BlockDriverState *filtered = bdrv_filter_bs(bs);
776 if (drv && drv->bdrv_probe_blocksizes) {
777 return drv->bdrv_probe_blocksizes(bs, bsz);
778 } else if (filtered) {
779 return bdrv_probe_blocksizes(filtered, bsz);
782 return -ENOTSUP;
786 * Try to get @bs's geometry (cyls, heads, sectors).
787 * On success, store them in @geo struct and return 0.
788 * On failure return -errno.
789 * @bs must not be empty.
791 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
793 BlockDriver *drv = bs->drv;
794 BlockDriverState *filtered = bdrv_filter_bs(bs);
796 if (drv && drv->bdrv_probe_geometry) {
797 return drv->bdrv_probe_geometry(bs, geo);
798 } else if (filtered) {
799 return bdrv_probe_geometry(filtered, geo);
802 return -ENOTSUP;
806 * Create a uniquely-named empty temporary file.
807 * Return 0 upon success, otherwise a negative errno value.
809 int get_tmp_filename(char *filename, int size)
811 #ifdef _WIN32
812 char temp_dir[MAX_PATH];
813 /* GetTempFileName requires that its output buffer (4th param)
814 have length MAX_PATH or greater. */
815 assert(size >= MAX_PATH);
816 return (GetTempPath(MAX_PATH, temp_dir)
817 && GetTempFileName(temp_dir, "qem", 0, filename)
818 ? 0 : -GetLastError());
819 #else
820 int fd;
821 const char *tmpdir;
822 tmpdir = getenv("TMPDIR");
823 if (!tmpdir) {
824 tmpdir = "/var/tmp";
826 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
827 return -EOVERFLOW;
829 fd = mkstemp(filename);
830 if (fd < 0) {
831 return -errno;
833 if (close(fd) != 0) {
834 unlink(filename);
835 return -errno;
837 return 0;
838 #endif
842 * Detect host devices. By convention, /dev/cdrom[N] is always
843 * recognized as a host CDROM.
845 static BlockDriver *find_hdev_driver(const char *filename)
847 int score_max = 0, score;
848 BlockDriver *drv = NULL, *d;
850 QLIST_FOREACH(d, &bdrv_drivers, list) {
851 if (d->bdrv_probe_device) {
852 score = d->bdrv_probe_device(filename);
853 if (score > score_max) {
854 score_max = score;
855 drv = d;
860 return drv;
863 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
865 BlockDriver *drv1;
867 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
868 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
869 return drv1;
873 return NULL;
876 BlockDriver *bdrv_find_protocol(const char *filename,
877 bool allow_protocol_prefix,
878 Error **errp)
880 BlockDriver *drv1;
881 char protocol[128];
882 int len;
883 const char *p;
884 int i;
886 /* TODO Drivers without bdrv_file_open must be specified explicitly */
889 * XXX(hch): we really should not let host device detection
890 * override an explicit protocol specification, but moving this
891 * later breaks access to device names with colons in them.
892 * Thanks to the brain-dead persistent naming schemes on udev-
893 * based Linux systems those actually are quite common.
895 drv1 = find_hdev_driver(filename);
896 if (drv1) {
897 return drv1;
900 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
901 return &bdrv_file;
904 p = strchr(filename, ':');
905 assert(p != NULL);
906 len = p - filename;
907 if (len > sizeof(protocol) - 1)
908 len = sizeof(protocol) - 1;
909 memcpy(protocol, filename, len);
910 protocol[len] = '\0';
912 drv1 = bdrv_do_find_protocol(protocol);
913 if (drv1) {
914 return drv1;
917 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
918 if (block_driver_modules[i].protocol_name &&
919 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
920 block_module_load_one(block_driver_modules[i].library_name);
921 break;
925 drv1 = bdrv_do_find_protocol(protocol);
926 if (!drv1) {
927 error_setg(errp, "Unknown protocol '%s'", protocol);
929 return drv1;
933 * Guess image format by probing its contents.
934 * This is not a good idea when your image is raw (CVE-2008-2004), but
935 * we do it anyway for backward compatibility.
937 * @buf contains the image's first @buf_size bytes.
938 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
939 * but can be smaller if the image file is smaller)
940 * @filename is its filename.
942 * For all block drivers, call the bdrv_probe() method to get its
943 * probing score.
944 * Return the first block driver with the highest probing score.
946 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
947 const char *filename)
949 int score_max = 0, score;
950 BlockDriver *drv = NULL, *d;
952 QLIST_FOREACH(d, &bdrv_drivers, list) {
953 if (d->bdrv_probe) {
954 score = d->bdrv_probe(buf, buf_size, filename);
955 if (score > score_max) {
956 score_max = score;
957 drv = d;
962 return drv;
965 static int find_image_format(BlockBackend *file, const char *filename,
966 BlockDriver **pdrv, Error **errp)
968 BlockDriver *drv;
969 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
970 int ret = 0;
972 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
973 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
974 *pdrv = &bdrv_raw;
975 return ret;
978 ret = blk_pread(file, 0, buf, sizeof(buf));
979 if (ret < 0) {
980 error_setg_errno(errp, -ret, "Could not read image for determining its "
981 "format");
982 *pdrv = NULL;
983 return ret;
986 drv = bdrv_probe_all(buf, ret, filename);
987 if (!drv) {
988 error_setg(errp, "Could not determine image format: No compatible "
989 "driver found");
990 ret = -ENOENT;
992 *pdrv = drv;
993 return ret;
997 * Set the current 'total_sectors' value
998 * Return 0 on success, -errno on error.
1000 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1002 BlockDriver *drv = bs->drv;
1004 if (!drv) {
1005 return -ENOMEDIUM;
1008 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1009 if (bdrv_is_sg(bs))
1010 return 0;
1012 /* query actual device if possible, otherwise just trust the hint */
1013 if (drv->bdrv_getlength) {
1014 int64_t length = drv->bdrv_getlength(bs);
1015 if (length < 0) {
1016 return length;
1018 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1021 bs->total_sectors = hint;
1023 if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1024 return -EFBIG;
1027 return 0;
1031 * Combines a QDict of new block driver @options with any missing options taken
1032 * from @old_options, so that leaving out an option defaults to its old value.
1034 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1035 QDict *old_options)
1037 if (bs->drv && bs->drv->bdrv_join_options) {
1038 bs->drv->bdrv_join_options(options, old_options);
1039 } else {
1040 qdict_join(options, old_options, false);
1044 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1045 int open_flags,
1046 Error **errp)
1048 Error *local_err = NULL;
1049 char *value = qemu_opt_get_del(opts, "detect-zeroes");
1050 BlockdevDetectZeroesOptions detect_zeroes =
1051 qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1052 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1053 g_free(value);
1054 if (local_err) {
1055 error_propagate(errp, local_err);
1056 return detect_zeroes;
1059 if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1060 !(open_flags & BDRV_O_UNMAP))
1062 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1063 "without setting discard operation to unmap");
1066 return detect_zeroes;
1070 * Set open flags for aio engine
1072 * Return 0 on success, -1 if the engine specified is invalid
1074 int bdrv_parse_aio(const char *mode, int *flags)
1076 if (!strcmp(mode, "threads")) {
1077 /* do nothing, default */
1078 } else if (!strcmp(mode, "native")) {
1079 *flags |= BDRV_O_NATIVE_AIO;
1080 #ifdef CONFIG_LINUX_IO_URING
1081 } else if (!strcmp(mode, "io_uring")) {
1082 *flags |= BDRV_O_IO_URING;
1083 #endif
1084 } else {
1085 return -1;
1088 return 0;
1092 * Set open flags for a given discard mode
1094 * Return 0 on success, -1 if the discard mode was invalid.
1096 int bdrv_parse_discard_flags(const char *mode, int *flags)
1098 *flags &= ~BDRV_O_UNMAP;
1100 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1101 /* do nothing */
1102 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1103 *flags |= BDRV_O_UNMAP;
1104 } else {
1105 return -1;
1108 return 0;
1112 * Set open flags for a given cache mode
1114 * Return 0 on success, -1 if the cache mode was invalid.
1116 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1118 *flags &= ~BDRV_O_CACHE_MASK;
1120 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1121 *writethrough = false;
1122 *flags |= BDRV_O_NOCACHE;
1123 } else if (!strcmp(mode, "directsync")) {
1124 *writethrough = true;
1125 *flags |= BDRV_O_NOCACHE;
1126 } else if (!strcmp(mode, "writeback")) {
1127 *writethrough = false;
1128 } else if (!strcmp(mode, "unsafe")) {
1129 *writethrough = false;
1130 *flags |= BDRV_O_NO_FLUSH;
1131 } else if (!strcmp(mode, "writethrough")) {
1132 *writethrough = true;
1133 } else {
1134 return -1;
1137 return 0;
1140 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1142 BlockDriverState *parent = c->opaque;
1143 return g_strdup(bdrv_get_device_or_node_name(parent));
1146 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1148 BlockDriverState *bs = child->opaque;
1149 bdrv_do_drained_begin_quiesce(bs, NULL, false);
1152 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1154 BlockDriverState *bs = child->opaque;
1155 return bdrv_drain_poll(bs, false, NULL, false);
1158 static void bdrv_child_cb_drained_end(BdrvChild *child,
1159 int *drained_end_counter)
1161 BlockDriverState *bs = child->opaque;
1162 bdrv_drained_end_no_poll(bs, drained_end_counter);
1165 static int bdrv_child_cb_inactivate(BdrvChild *child)
1167 BlockDriverState *bs = child->opaque;
1168 assert(bs->open_flags & BDRV_O_INACTIVE);
1169 return 0;
1172 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1173 GSList **ignore, Error **errp)
1175 BlockDriverState *bs = child->opaque;
1176 return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1179 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1180 GSList **ignore)
1182 BlockDriverState *bs = child->opaque;
1183 return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1187 * Returns the options and flags that a temporary snapshot should get, based on
1188 * the originally requested flags (the originally requested image will have
1189 * flags like a backing file)
1191 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1192 int parent_flags, QDict *parent_options)
1194 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1196 /* For temporary files, unconditional cache=unsafe is fine */
1197 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1198 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1200 /* Copy the read-only and discard options from the parent */
1201 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1202 qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1204 /* aio=native doesn't work for cache.direct=off, so disable it for the
1205 * temporary snapshot */
1206 *child_flags &= ~BDRV_O_NATIVE_AIO;
1209 static void bdrv_backing_attach(BdrvChild *c)
1211 BlockDriverState *parent = c->opaque;
1212 BlockDriverState *backing_hd = c->bs;
1214 assert(!parent->backing_blocker);
1215 error_setg(&parent->backing_blocker,
1216 "node is used as backing hd of '%s'",
1217 bdrv_get_device_or_node_name(parent));
1219 bdrv_refresh_filename(backing_hd);
1221 parent->open_flags &= ~BDRV_O_NO_BACKING;
1223 bdrv_op_block_all(backing_hd, parent->backing_blocker);
1224 /* Otherwise we won't be able to commit or stream */
1225 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1226 parent->backing_blocker);
1227 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1228 parent->backing_blocker);
1230 * We do backup in 3 ways:
1231 * 1. drive backup
1232 * The target bs is new opened, and the source is top BDS
1233 * 2. blockdev backup
1234 * Both the source and the target are top BDSes.
1235 * 3. internal backup(used for block replication)
1236 * Both the source and the target are backing file
1238 * In case 1 and 2, neither the source nor the target is the backing file.
1239 * In case 3, we will block the top BDS, so there is only one block job
1240 * for the top BDS and its backing chain.
1242 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1243 parent->backing_blocker);
1244 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1245 parent->backing_blocker);
1248 static void bdrv_backing_detach(BdrvChild *c)
1250 BlockDriverState *parent = c->opaque;
1252 assert(parent->backing_blocker);
1253 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1254 error_free(parent->backing_blocker);
1255 parent->backing_blocker = NULL;
1258 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1259 const char *filename, Error **errp)
1261 BlockDriverState *parent = c->opaque;
1262 bool read_only = bdrv_is_read_only(parent);
1263 int ret;
1265 if (read_only) {
1266 ret = bdrv_reopen_set_read_only(parent, false, errp);
1267 if (ret < 0) {
1268 return ret;
1272 ret = bdrv_change_backing_file(parent, filename,
1273 base->drv ? base->drv->format_name : "",
1274 false);
1275 if (ret < 0) {
1276 error_setg_errno(errp, -ret, "Could not update backing file link");
1279 if (read_only) {
1280 bdrv_reopen_set_read_only(parent, true, NULL);
1283 return ret;
1287 * Returns the options and flags that a generic child of a BDS should
1288 * get, based on the given options and flags for the parent BDS.
1290 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1291 int *child_flags, QDict *child_options,
1292 int parent_flags, QDict *parent_options)
1294 int flags = parent_flags;
1297 * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1298 * Generally, the question to answer is: Should this child be
1299 * format-probed by default?
1303 * Pure and non-filtered data children of non-format nodes should
1304 * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1305 * set). This only affects a very limited set of drivers (namely
1306 * quorum and blkverify when this comment was written).
1307 * Force-clear BDRV_O_PROTOCOL then.
1309 if (!parent_is_format &&
1310 (role & BDRV_CHILD_DATA) &&
1311 !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1313 flags &= ~BDRV_O_PROTOCOL;
1317 * All children of format nodes (except for COW children) and all
1318 * metadata children in general should never be format-probed.
1319 * Force-set BDRV_O_PROTOCOL then.
1321 if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1322 (role & BDRV_CHILD_METADATA))
1324 flags |= BDRV_O_PROTOCOL;
1328 * If the cache mode isn't explicitly set, inherit direct and no-flush from
1329 * the parent.
1331 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1332 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1333 qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1335 if (role & BDRV_CHILD_COW) {
1336 /* backing files are opened read-only by default */
1337 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1338 qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1339 } else {
1340 /* Inherit the read-only option from the parent if it's not set */
1341 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1342 qdict_copy_default(child_options, parent_options,
1343 BDRV_OPT_AUTO_READ_ONLY);
1347 * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1348 * can default to enable it on lower layers regardless of the
1349 * parent option.
1351 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1353 /* Clear flags that only apply to the top layer */
1354 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1356 if (role & BDRV_CHILD_METADATA) {
1357 flags &= ~BDRV_O_NO_IO;
1359 if (role & BDRV_CHILD_COW) {
1360 flags &= ~BDRV_O_TEMPORARY;
1363 *child_flags = flags;
1366 static void bdrv_child_cb_attach(BdrvChild *child)
1368 BlockDriverState *bs = child->opaque;
1370 if (child->role & BDRV_CHILD_COW) {
1371 bdrv_backing_attach(child);
1374 bdrv_apply_subtree_drain(child, bs);
1377 static void bdrv_child_cb_detach(BdrvChild *child)
1379 BlockDriverState *bs = child->opaque;
1381 if (child->role & BDRV_CHILD_COW) {
1382 bdrv_backing_detach(child);
1385 bdrv_unapply_subtree_drain(child, bs);
1388 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1389 const char *filename, Error **errp)
1391 if (c->role & BDRV_CHILD_COW) {
1392 return bdrv_backing_update_filename(c, base, filename, errp);
1394 return 0;
1397 const BdrvChildClass child_of_bds = {
1398 .parent_is_bds = true,
1399 .get_parent_desc = bdrv_child_get_parent_desc,
1400 .inherit_options = bdrv_inherited_options,
1401 .drained_begin = bdrv_child_cb_drained_begin,
1402 .drained_poll = bdrv_child_cb_drained_poll,
1403 .drained_end = bdrv_child_cb_drained_end,
1404 .attach = bdrv_child_cb_attach,
1405 .detach = bdrv_child_cb_detach,
1406 .inactivate = bdrv_child_cb_inactivate,
1407 .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1408 .set_aio_ctx = bdrv_child_cb_set_aio_ctx,
1409 .update_filename = bdrv_child_cb_update_filename,
1412 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1414 int open_flags = flags;
1417 * Clear flags that are internal to the block layer before opening the
1418 * image.
1420 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1422 return open_flags;
1425 static void update_flags_from_options(int *flags, QemuOpts *opts)
1427 *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1429 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1430 *flags |= BDRV_O_NO_FLUSH;
1433 if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1434 *flags |= BDRV_O_NOCACHE;
1437 if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1438 *flags |= BDRV_O_RDWR;
1441 if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1442 *flags |= BDRV_O_AUTO_RDONLY;
1446 static void update_options_from_flags(QDict *options, int flags)
1448 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1449 qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1451 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1452 qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1453 flags & BDRV_O_NO_FLUSH);
1455 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1456 qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1458 if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1459 qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1460 flags & BDRV_O_AUTO_RDONLY);
1464 static void bdrv_assign_node_name(BlockDriverState *bs,
1465 const char *node_name,
1466 Error **errp)
1468 char *gen_node_name = NULL;
1470 if (!node_name) {
1471 node_name = gen_node_name = id_generate(ID_BLOCK);
1472 } else if (!id_wellformed(node_name)) {
1474 * Check for empty string or invalid characters, but not if it is
1475 * generated (generated names use characters not available to the user)
1477 error_setg(errp, "Invalid node-name: '%s'", node_name);
1478 return;
1481 /* takes care of avoiding namespaces collisions */
1482 if (blk_by_name(node_name)) {
1483 error_setg(errp, "node-name=%s is conflicting with a device id",
1484 node_name);
1485 goto out;
1488 /* takes care of avoiding duplicates node names */
1489 if (bdrv_find_node(node_name)) {
1490 error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1491 goto out;
1494 /* Make sure that the node name isn't truncated */
1495 if (strlen(node_name) >= sizeof(bs->node_name)) {
1496 error_setg(errp, "Node name too long");
1497 goto out;
1500 /* copy node name into the bs and insert it into the graph list */
1501 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1502 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1503 out:
1504 g_free(gen_node_name);
1507 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1508 const char *node_name, QDict *options,
1509 int open_flags, Error **errp)
1511 Error *local_err = NULL;
1512 int i, ret;
1514 bdrv_assign_node_name(bs, node_name, &local_err);
1515 if (local_err) {
1516 error_propagate(errp, local_err);
1517 return -EINVAL;
1520 bs->drv = drv;
1521 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1522 bs->opaque = g_malloc0(drv->instance_size);
1524 if (drv->bdrv_file_open) {
1525 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1526 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1527 } else if (drv->bdrv_open) {
1528 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1529 } else {
1530 ret = 0;
1533 if (ret < 0) {
1534 if (local_err) {
1535 error_propagate(errp, local_err);
1536 } else if (bs->filename[0]) {
1537 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1538 } else {
1539 error_setg_errno(errp, -ret, "Could not open image");
1541 goto open_failed;
1544 ret = refresh_total_sectors(bs, bs->total_sectors);
1545 if (ret < 0) {
1546 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1547 return ret;
1550 bdrv_refresh_limits(bs, &local_err);
1551 if (local_err) {
1552 error_propagate(errp, local_err);
1553 return -EINVAL;
1556 assert(bdrv_opt_mem_align(bs) != 0);
1557 assert(bdrv_min_mem_align(bs) != 0);
1558 assert(is_power_of_2(bs->bl.request_alignment));
1560 for (i = 0; i < bs->quiesce_counter; i++) {
1561 if (drv->bdrv_co_drain_begin) {
1562 drv->bdrv_co_drain_begin(bs);
1566 return 0;
1567 open_failed:
1568 bs->drv = NULL;
1569 if (bs->file != NULL) {
1570 bdrv_unref_child(bs, bs->file);
1571 bs->file = NULL;
1573 g_free(bs->opaque);
1574 bs->opaque = NULL;
1575 return ret;
1578 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1579 int flags, Error **errp)
1581 BlockDriverState *bs;
1582 int ret;
1584 bs = bdrv_new();
1585 bs->open_flags = flags;
1586 bs->explicit_options = qdict_new();
1587 bs->options = qdict_new();
1588 bs->opaque = NULL;
1590 update_options_from_flags(bs->options, flags);
1592 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1593 if (ret < 0) {
1594 qobject_unref(bs->explicit_options);
1595 bs->explicit_options = NULL;
1596 qobject_unref(bs->options);
1597 bs->options = NULL;
1598 bdrv_unref(bs);
1599 return NULL;
1602 return bs;
1605 QemuOptsList bdrv_runtime_opts = {
1606 .name = "bdrv_common",
1607 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1608 .desc = {
1610 .name = "node-name",
1611 .type = QEMU_OPT_STRING,
1612 .help = "Node name of the block device node",
1615 .name = "driver",
1616 .type = QEMU_OPT_STRING,
1617 .help = "Block driver to use for the node",
1620 .name = BDRV_OPT_CACHE_DIRECT,
1621 .type = QEMU_OPT_BOOL,
1622 .help = "Bypass software writeback cache on the host",
1625 .name = BDRV_OPT_CACHE_NO_FLUSH,
1626 .type = QEMU_OPT_BOOL,
1627 .help = "Ignore flush requests",
1630 .name = BDRV_OPT_READ_ONLY,
1631 .type = QEMU_OPT_BOOL,
1632 .help = "Node is opened in read-only mode",
1635 .name = BDRV_OPT_AUTO_READ_ONLY,
1636 .type = QEMU_OPT_BOOL,
1637 .help = "Node can become read-only if opening read-write fails",
1640 .name = "detect-zeroes",
1641 .type = QEMU_OPT_STRING,
1642 .help = "try to optimize zero writes (off, on, unmap)",
1645 .name = BDRV_OPT_DISCARD,
1646 .type = QEMU_OPT_STRING,
1647 .help = "discard operation (ignore/off, unmap/on)",
1650 .name = BDRV_OPT_FORCE_SHARE,
1651 .type = QEMU_OPT_BOOL,
1652 .help = "always accept other writers (default: off)",
1654 { /* end of list */ }
1658 QemuOptsList bdrv_create_opts_simple = {
1659 .name = "simple-create-opts",
1660 .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1661 .desc = {
1663 .name = BLOCK_OPT_SIZE,
1664 .type = QEMU_OPT_SIZE,
1665 .help = "Virtual disk size"
1668 .name = BLOCK_OPT_PREALLOC,
1669 .type = QEMU_OPT_STRING,
1670 .help = "Preallocation mode (allowed values: off)"
1672 { /* end of list */ }
1677 * Common part for opening disk images and files
1679 * Removes all processed options from *options.
1681 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1682 QDict *options, Error **errp)
1684 int ret, open_flags;
1685 const char *filename;
1686 const char *driver_name = NULL;
1687 const char *node_name = NULL;
1688 const char *discard;
1689 QemuOpts *opts;
1690 BlockDriver *drv;
1691 Error *local_err = NULL;
1693 assert(bs->file == NULL);
1694 assert(options != NULL && bs->options != options);
1696 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1697 if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1698 ret = -EINVAL;
1699 goto fail_opts;
1702 update_flags_from_options(&bs->open_flags, opts);
1704 driver_name = qemu_opt_get(opts, "driver");
1705 drv = bdrv_find_format(driver_name);
1706 assert(drv != NULL);
1708 bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1710 if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1711 error_setg(errp,
1712 BDRV_OPT_FORCE_SHARE
1713 "=on can only be used with read-only images");
1714 ret = -EINVAL;
1715 goto fail_opts;
1718 if (file != NULL) {
1719 bdrv_refresh_filename(blk_bs(file));
1720 filename = blk_bs(file)->filename;
1721 } else {
1723 * Caution: while qdict_get_try_str() is fine, getting
1724 * non-string types would require more care. When @options
1725 * come from -blockdev or blockdev_add, its members are typed
1726 * according to the QAPI schema, but when they come from
1727 * -drive, they're all QString.
1729 filename = qdict_get_try_str(options, "filename");
1732 if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1733 error_setg(errp, "The '%s' block driver requires a file name",
1734 drv->format_name);
1735 ret = -EINVAL;
1736 goto fail_opts;
1739 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1740 drv->format_name);
1742 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1744 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1745 if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1746 ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1747 } else {
1748 ret = -ENOTSUP;
1750 if (ret < 0) {
1751 error_setg(errp,
1752 !bs->read_only && bdrv_is_whitelisted(drv, true)
1753 ? "Driver '%s' can only be used for read-only devices"
1754 : "Driver '%s' is not whitelisted",
1755 drv->format_name);
1756 goto fail_opts;
1760 /* bdrv_new() and bdrv_close() make it so */
1761 assert(qatomic_read(&bs->copy_on_read) == 0);
1763 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1764 if (!bs->read_only) {
1765 bdrv_enable_copy_on_read(bs);
1766 } else {
1767 error_setg(errp, "Can't use copy-on-read on read-only device");
1768 ret = -EINVAL;
1769 goto fail_opts;
1773 discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1774 if (discard != NULL) {
1775 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1776 error_setg(errp, "Invalid discard option");
1777 ret = -EINVAL;
1778 goto fail_opts;
1782 bs->detect_zeroes =
1783 bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1784 if (local_err) {
1785 error_propagate(errp, local_err);
1786 ret = -EINVAL;
1787 goto fail_opts;
1790 if (filename != NULL) {
1791 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1792 } else {
1793 bs->filename[0] = '\0';
1795 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1797 /* Open the image, either directly or using a protocol */
1798 open_flags = bdrv_open_flags(bs, bs->open_flags);
1799 node_name = qemu_opt_get(opts, "node-name");
1801 assert(!drv->bdrv_file_open || file == NULL);
1802 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1803 if (ret < 0) {
1804 goto fail_opts;
1807 qemu_opts_del(opts);
1808 return 0;
1810 fail_opts:
1811 qemu_opts_del(opts);
1812 return ret;
1815 static QDict *parse_json_filename(const char *filename, Error **errp)
1817 QObject *options_obj;
1818 QDict *options;
1819 int ret;
1821 ret = strstart(filename, "json:", &filename);
1822 assert(ret);
1824 options_obj = qobject_from_json(filename, errp);
1825 if (!options_obj) {
1826 error_prepend(errp, "Could not parse the JSON options: ");
1827 return NULL;
1830 options = qobject_to(QDict, options_obj);
1831 if (!options) {
1832 qobject_unref(options_obj);
1833 error_setg(errp, "Invalid JSON object given");
1834 return NULL;
1837 qdict_flatten(options);
1839 return options;
1842 static void parse_json_protocol(QDict *options, const char **pfilename,
1843 Error **errp)
1845 QDict *json_options;
1846 Error *local_err = NULL;
1848 /* Parse json: pseudo-protocol */
1849 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1850 return;
1853 json_options = parse_json_filename(*pfilename, &local_err);
1854 if (local_err) {
1855 error_propagate(errp, local_err);
1856 return;
1859 /* Options given in the filename have lower priority than options
1860 * specified directly */
1861 qdict_join(options, json_options, false);
1862 qobject_unref(json_options);
1863 *pfilename = NULL;
1867 * Fills in default options for opening images and converts the legacy
1868 * filename/flags pair to option QDict entries.
1869 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1870 * block driver has been specified explicitly.
1872 static int bdrv_fill_options(QDict **options, const char *filename,
1873 int *flags, Error **errp)
1875 const char *drvname;
1876 bool protocol = *flags & BDRV_O_PROTOCOL;
1877 bool parse_filename = false;
1878 BlockDriver *drv = NULL;
1879 Error *local_err = NULL;
1882 * Caution: while qdict_get_try_str() is fine, getting non-string
1883 * types would require more care. When @options come from
1884 * -blockdev or blockdev_add, its members are typed according to
1885 * the QAPI schema, but when they come from -drive, they're all
1886 * QString.
1888 drvname = qdict_get_try_str(*options, "driver");
1889 if (drvname) {
1890 drv = bdrv_find_format(drvname);
1891 if (!drv) {
1892 error_setg(errp, "Unknown driver '%s'", drvname);
1893 return -ENOENT;
1895 /* If the user has explicitly specified the driver, this choice should
1896 * override the BDRV_O_PROTOCOL flag */
1897 protocol = drv->bdrv_file_open;
1900 if (protocol) {
1901 *flags |= BDRV_O_PROTOCOL;
1902 } else {
1903 *flags &= ~BDRV_O_PROTOCOL;
1906 /* Translate cache options from flags into options */
1907 update_options_from_flags(*options, *flags);
1909 /* Fetch the file name from the options QDict if necessary */
1910 if (protocol && filename) {
1911 if (!qdict_haskey(*options, "filename")) {
1912 qdict_put_str(*options, "filename", filename);
1913 parse_filename = true;
1914 } else {
1915 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1916 "the same time");
1917 return -EINVAL;
1921 /* Find the right block driver */
1922 /* See cautionary note on accessing @options above */
1923 filename = qdict_get_try_str(*options, "filename");
1925 if (!drvname && protocol) {
1926 if (filename) {
1927 drv = bdrv_find_protocol(filename, parse_filename, errp);
1928 if (!drv) {
1929 return -EINVAL;
1932 drvname = drv->format_name;
1933 qdict_put_str(*options, "driver", drvname);
1934 } else {
1935 error_setg(errp, "Must specify either driver or file");
1936 return -EINVAL;
1940 assert(drv || !protocol);
1942 /* Driver-specific filename parsing */
1943 if (drv && drv->bdrv_parse_filename && parse_filename) {
1944 drv->bdrv_parse_filename(filename, *options, &local_err);
1945 if (local_err) {
1946 error_propagate(errp, local_err);
1947 return -EINVAL;
1950 if (!drv->bdrv_needs_filename) {
1951 qdict_del(*options, "filename");
1955 return 0;
1958 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1959 uint64_t perm, uint64_t shared,
1960 GSList *ignore_children, Error **errp);
1961 static void bdrv_child_abort_perm_update(BdrvChild *c);
1962 static void bdrv_child_set_perm(BdrvChild *c);
1964 typedef struct BlockReopenQueueEntry {
1965 bool prepared;
1966 bool perms_checked;
1967 BDRVReopenState state;
1968 QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1969 } BlockReopenQueueEntry;
1972 * Return the flags that @bs will have after the reopens in @q have
1973 * successfully completed. If @q is NULL (or @bs is not contained in @q),
1974 * return the current flags.
1976 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1978 BlockReopenQueueEntry *entry;
1980 if (q != NULL) {
1981 QTAILQ_FOREACH(entry, q, entry) {
1982 if (entry->state.bs == bs) {
1983 return entry->state.flags;
1988 return bs->open_flags;
1991 /* Returns whether the image file can be written to after the reopen queue @q
1992 * has been successfully applied, or right now if @q is NULL. */
1993 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1994 BlockReopenQueue *q)
1996 int flags = bdrv_reopen_get_flags(q, bs);
1998 return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2002 * Return whether the BDS can be written to. This is not necessarily
2003 * the same as !bdrv_is_read_only(bs), as inactivated images may not
2004 * be written to but do not count as read-only images.
2006 bool bdrv_is_writable(BlockDriverState *bs)
2008 return bdrv_is_writable_after_reopen(bs, NULL);
2011 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2012 BdrvChild *c, BdrvChildRole role,
2013 BlockReopenQueue *reopen_queue,
2014 uint64_t parent_perm, uint64_t parent_shared,
2015 uint64_t *nperm, uint64_t *nshared)
2017 assert(bs->drv && bs->drv->bdrv_child_perm);
2018 bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2019 parent_perm, parent_shared,
2020 nperm, nshared);
2021 /* TODO Take force_share from reopen_queue */
2022 if (child_bs && child_bs->force_share) {
2023 *nshared = BLK_PERM_ALL;
2028 * Check whether permissions on this node can be changed in a way that
2029 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
2030 * permissions of all its parents. This involves checking whether all necessary
2031 * permission changes to child nodes can be performed.
2033 * A call to this function must always be followed by a call to bdrv_set_perm()
2034 * or bdrv_abort_perm_update().
2036 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
2037 uint64_t cumulative_perms,
2038 uint64_t cumulative_shared_perms,
2039 GSList *ignore_children, Error **errp)
2041 BlockDriver *drv = bs->drv;
2042 BdrvChild *c;
2043 int ret;
2045 /* Write permissions never work with read-only images */
2046 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2047 !bdrv_is_writable_after_reopen(bs, q))
2049 if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2050 error_setg(errp, "Block node is read-only");
2051 } else {
2052 uint64_t current_perms, current_shared;
2053 bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
2054 if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
2055 error_setg(errp, "Cannot make block node read-only, there is "
2056 "a writer on it");
2057 } else {
2058 error_setg(errp, "Cannot make block node read-only and create "
2059 "a writer on it");
2063 return -EPERM;
2067 * Unaligned requests will automatically be aligned to bl.request_alignment
2068 * and without RESIZE we can't extend requests to write to space beyond the
2069 * end of the image, so it's required that the image size is aligned.
2071 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2072 !(cumulative_perms & BLK_PERM_RESIZE))
2074 if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2075 error_setg(errp, "Cannot get 'write' permission without 'resize': "
2076 "Image size is not a multiple of request "
2077 "alignment");
2078 return -EPERM;
2082 /* Check this node */
2083 if (!drv) {
2084 return 0;
2087 if (drv->bdrv_check_perm) {
2088 ret = drv->bdrv_check_perm(bs, cumulative_perms,
2089 cumulative_shared_perms, errp);
2090 if (ret < 0) {
2091 return ret;
2095 /* Drivers that never have children can omit .bdrv_child_perm() */
2096 if (!drv->bdrv_child_perm) {
2097 assert(QLIST_EMPTY(&bs->children));
2098 return 0;
2101 /* Check all children */
2102 QLIST_FOREACH(c, &bs->children, next) {
2103 uint64_t cur_perm, cur_shared;
2105 bdrv_child_perm(bs, c->bs, c, c->role, q,
2106 cumulative_perms, cumulative_shared_perms,
2107 &cur_perm, &cur_shared);
2108 ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
2109 errp);
2110 if (ret < 0) {
2111 return ret;
2115 return 0;
2119 * Notifies drivers that after a previous bdrv_check_perm() call, the
2120 * permission update is not performed and any preparations made for it (e.g.
2121 * taken file locks) need to be undone.
2123 * This function recursively notifies all child nodes.
2125 static void bdrv_abort_perm_update(BlockDriverState *bs)
2127 BlockDriver *drv = bs->drv;
2128 BdrvChild *c;
2130 if (!drv) {
2131 return;
2134 if (drv->bdrv_abort_perm_update) {
2135 drv->bdrv_abort_perm_update(bs);
2138 QLIST_FOREACH(c, &bs->children, next) {
2139 bdrv_child_abort_perm_update(c);
2143 static void bdrv_set_perm(BlockDriverState *bs)
2145 uint64_t cumulative_perms, cumulative_shared_perms;
2146 BlockDriver *drv = bs->drv;
2147 BdrvChild *c;
2149 if (!drv) {
2150 return;
2153 bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2155 /* Update this node */
2156 if (drv->bdrv_set_perm) {
2157 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2160 /* Drivers that never have children can omit .bdrv_child_perm() */
2161 if (!drv->bdrv_child_perm) {
2162 assert(QLIST_EMPTY(&bs->children));
2163 return;
2166 /* Update all children */
2167 QLIST_FOREACH(c, &bs->children, next) {
2168 bdrv_child_set_perm(c);
2172 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2173 uint64_t *shared_perm)
2175 BdrvChild *c;
2176 uint64_t cumulative_perms = 0;
2177 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2179 QLIST_FOREACH(c, &bs->parents, next_parent) {
2180 cumulative_perms |= c->perm;
2181 cumulative_shared_perms &= c->shared_perm;
2184 *perm = cumulative_perms;
2185 *shared_perm = cumulative_shared_perms;
2188 static char *bdrv_child_user_desc(BdrvChild *c)
2190 if (c->klass->get_parent_desc) {
2191 return c->klass->get_parent_desc(c);
2194 return g_strdup("another user");
2197 char *bdrv_perm_names(uint64_t perm)
2199 struct perm_name {
2200 uint64_t perm;
2201 const char *name;
2202 } permissions[] = {
2203 { BLK_PERM_CONSISTENT_READ, "consistent read" },
2204 { BLK_PERM_WRITE, "write" },
2205 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2206 { BLK_PERM_RESIZE, "resize" },
2207 { BLK_PERM_GRAPH_MOD, "change children" },
2208 { 0, NULL }
2211 GString *result = g_string_sized_new(30);
2212 struct perm_name *p;
2214 for (p = permissions; p->name; p++) {
2215 if (perm & p->perm) {
2216 if (result->len > 0) {
2217 g_string_append(result, ", ");
2219 g_string_append(result, p->name);
2223 return g_string_free(result, FALSE);
2227 * Checks whether a new reference to @bs can be added if the new user requires
2228 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2229 * set, the BdrvChild objects in this list are ignored in the calculations;
2230 * this allows checking permission updates for an existing reference.
2232 * Needs to be followed by a call to either bdrv_set_perm() or
2233 * bdrv_abort_perm_update(). */
2234 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2235 uint64_t new_used_perm,
2236 uint64_t new_shared_perm,
2237 GSList *ignore_children,
2238 Error **errp)
2240 BdrvChild *c;
2241 uint64_t cumulative_perms = new_used_perm;
2242 uint64_t cumulative_shared_perms = new_shared_perm;
2245 /* There is no reason why anyone couldn't tolerate write_unchanged */
2246 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2248 QLIST_FOREACH(c, &bs->parents, next_parent) {
2249 if (g_slist_find(ignore_children, c)) {
2250 continue;
2253 if ((new_used_perm & c->shared_perm) != new_used_perm) {
2254 char *user = bdrv_child_user_desc(c);
2255 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
2257 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2258 "allow '%s' on %s",
2259 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2260 g_free(user);
2261 g_free(perm_names);
2262 return -EPERM;
2265 if ((c->perm & new_shared_perm) != c->perm) {
2266 char *user = bdrv_child_user_desc(c);
2267 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
2269 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2270 "'%s' on %s",
2271 user, c->name, perm_names, bdrv_get_node_name(c->bs));
2272 g_free(user);
2273 g_free(perm_names);
2274 return -EPERM;
2277 cumulative_perms |= c->perm;
2278 cumulative_shared_perms &= c->shared_perm;
2281 return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
2282 ignore_children, errp);
2285 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2286 * bdrv_child_abort_perm_update(). */
2287 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2288 uint64_t perm, uint64_t shared,
2289 GSList *ignore_children, Error **errp)
2291 int ret;
2293 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
2294 ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children, errp);
2295 g_slist_free(ignore_children);
2297 if (ret < 0) {
2298 return ret;
2301 if (!c->has_backup_perm) {
2302 c->has_backup_perm = true;
2303 c->backup_perm = c->perm;
2304 c->backup_shared_perm = c->shared_perm;
2307 * Note: it's OK if c->has_backup_perm was already set, as we can find the
2308 * same child twice during check_perm procedure
2311 c->perm = perm;
2312 c->shared_perm = shared;
2314 return 0;
2317 static void bdrv_child_set_perm(BdrvChild *c)
2319 c->has_backup_perm = false;
2321 bdrv_set_perm(c->bs);
2324 static void bdrv_child_abort_perm_update(BdrvChild *c)
2326 if (c->has_backup_perm) {
2327 c->perm = c->backup_perm;
2328 c->shared_perm = c->backup_shared_perm;
2329 c->has_backup_perm = false;
2332 bdrv_abort_perm_update(c->bs);
2335 static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
2337 int ret;
2338 uint64_t perm, shared_perm;
2340 bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
2341 ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, errp);
2342 if (ret < 0) {
2343 bdrv_abort_perm_update(bs);
2344 return ret;
2346 bdrv_set_perm(bs);
2348 return 0;
2351 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2352 Error **errp)
2354 Error *local_err = NULL;
2355 int ret;
2357 ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL, &local_err);
2358 if (ret < 0) {
2359 bdrv_child_abort_perm_update(c);
2360 if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2361 /* tighten permissions */
2362 error_propagate(errp, local_err);
2363 } else {
2365 * Our caller may intend to only loosen restrictions and
2366 * does not expect this function to fail. Errors are not
2367 * fatal in such a case, so we can just hide them from our
2368 * caller.
2370 error_free(local_err);
2371 ret = 0;
2373 return ret;
2376 bdrv_child_set_perm(c);
2378 return 0;
2381 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2383 uint64_t parent_perms, parent_shared;
2384 uint64_t perms, shared;
2386 bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2387 bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2388 parent_perms, parent_shared, &perms, &shared);
2390 return bdrv_child_try_set_perm(c, perms, shared, errp);
2394 * Default implementation for .bdrv_child_perm() for block filters:
2395 * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2396 * filtered child.
2398 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2399 BdrvChildRole role,
2400 BlockReopenQueue *reopen_queue,
2401 uint64_t perm, uint64_t shared,
2402 uint64_t *nperm, uint64_t *nshared)
2404 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2405 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2408 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2409 BdrvChildRole role,
2410 BlockReopenQueue *reopen_queue,
2411 uint64_t perm, uint64_t shared,
2412 uint64_t *nperm, uint64_t *nshared)
2414 assert(role & BDRV_CHILD_COW);
2417 * We want consistent read from backing files if the parent needs it.
2418 * No other operations are performed on backing files.
2420 perm &= BLK_PERM_CONSISTENT_READ;
2423 * If the parent can deal with changing data, we're okay with a
2424 * writable and resizable backing file.
2425 * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2427 if (shared & BLK_PERM_WRITE) {
2428 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2429 } else {
2430 shared = 0;
2433 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2434 BLK_PERM_WRITE_UNCHANGED;
2436 if (bs->open_flags & BDRV_O_INACTIVE) {
2437 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2440 *nperm = perm;
2441 *nshared = shared;
2444 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2445 BdrvChildRole role,
2446 BlockReopenQueue *reopen_queue,
2447 uint64_t perm, uint64_t shared,
2448 uint64_t *nperm, uint64_t *nshared)
2450 int flags;
2452 assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2454 flags = bdrv_reopen_get_flags(reopen_queue, bs);
2457 * Apart from the modifications below, the same permissions are
2458 * forwarded and left alone as for filters
2460 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2461 perm, shared, &perm, &shared);
2463 if (role & BDRV_CHILD_METADATA) {
2464 /* Format drivers may touch metadata even if the guest doesn't write */
2465 if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2466 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2470 * bs->file always needs to be consistent because of the
2471 * metadata. We can never allow other users to resize or write
2472 * to it.
2474 if (!(flags & BDRV_O_NO_IO)) {
2475 perm |= BLK_PERM_CONSISTENT_READ;
2477 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2480 if (role & BDRV_CHILD_DATA) {
2482 * Technically, everything in this block is a subset of the
2483 * BDRV_CHILD_METADATA path taken above, and so this could
2484 * be an "else if" branch. However, that is not obvious, and
2485 * this function is not performance critical, therefore we let
2486 * this be an independent "if".
2490 * We cannot allow other users to resize the file because the
2491 * format driver might have some assumptions about the size
2492 * (e.g. because it is stored in metadata, or because the file
2493 * is split into fixed-size data files).
2495 shared &= ~BLK_PERM_RESIZE;
2498 * WRITE_UNCHANGED often cannot be performed as such on the
2499 * data file. For example, the qcow2 driver may still need to
2500 * write copied clusters on copy-on-read.
2502 if (perm & BLK_PERM_WRITE_UNCHANGED) {
2503 perm |= BLK_PERM_WRITE;
2507 * If the data file is written to, the format driver may
2508 * expect to be able to resize it by writing beyond the EOF.
2510 if (perm & BLK_PERM_WRITE) {
2511 perm |= BLK_PERM_RESIZE;
2515 if (bs->open_flags & BDRV_O_INACTIVE) {
2516 shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2519 *nperm = perm;
2520 *nshared = shared;
2523 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2524 BdrvChildRole role, BlockReopenQueue *reopen_queue,
2525 uint64_t perm, uint64_t shared,
2526 uint64_t *nperm, uint64_t *nshared)
2528 if (role & BDRV_CHILD_FILTERED) {
2529 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2530 BDRV_CHILD_COW)));
2531 bdrv_filter_default_perms(bs, c, role, reopen_queue,
2532 perm, shared, nperm, nshared);
2533 } else if (role & BDRV_CHILD_COW) {
2534 assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2535 bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2536 perm, shared, nperm, nshared);
2537 } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2538 bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2539 perm, shared, nperm, nshared);
2540 } else {
2541 g_assert_not_reached();
2545 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2547 static const uint64_t permissions[] = {
2548 [BLOCK_PERMISSION_CONSISTENT_READ] = BLK_PERM_CONSISTENT_READ,
2549 [BLOCK_PERMISSION_WRITE] = BLK_PERM_WRITE,
2550 [BLOCK_PERMISSION_WRITE_UNCHANGED] = BLK_PERM_WRITE_UNCHANGED,
2551 [BLOCK_PERMISSION_RESIZE] = BLK_PERM_RESIZE,
2552 [BLOCK_PERMISSION_GRAPH_MOD] = BLK_PERM_GRAPH_MOD,
2555 QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2556 QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2558 assert(qapi_perm < BLOCK_PERMISSION__MAX);
2560 return permissions[qapi_perm];
2563 static void bdrv_replace_child_noperm(BdrvChild *child,
2564 BlockDriverState *new_bs)
2566 BlockDriverState *old_bs = child->bs;
2567 int new_bs_quiesce_counter;
2568 int drain_saldo;
2570 assert(!child->frozen);
2572 if (old_bs && new_bs) {
2573 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2576 new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2577 drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2580 * If the new child node is drained but the old one was not, flush
2581 * all outstanding requests to the old child node.
2583 while (drain_saldo > 0 && child->klass->drained_begin) {
2584 bdrv_parent_drained_begin_single(child, true);
2585 drain_saldo--;
2588 if (old_bs) {
2589 /* Detach first so that the recursive drain sections coming from @child
2590 * are already gone and we only end the drain sections that came from
2591 * elsewhere. */
2592 if (child->klass->detach) {
2593 child->klass->detach(child);
2595 QLIST_REMOVE(child, next_parent);
2598 child->bs = new_bs;
2600 if (new_bs) {
2601 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2604 * Detaching the old node may have led to the new node's
2605 * quiesce_counter having been decreased. Not a problem, we
2606 * just need to recognize this here and then invoke
2607 * drained_end appropriately more often.
2609 assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2610 drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2612 /* Attach only after starting new drained sections, so that recursive
2613 * drain sections coming from @child don't get an extra .drained_begin
2614 * callback. */
2615 if (child->klass->attach) {
2616 child->klass->attach(child);
2621 * If the old child node was drained but the new one is not, allow
2622 * requests to come in only after the new node has been attached.
2624 while (drain_saldo < 0 && child->klass->drained_end) {
2625 bdrv_parent_drained_end_single(child);
2626 drain_saldo++;
2631 * Updates @child to change its reference to point to @new_bs, including
2632 * checking and applying the necessary permission updates both to the old node
2633 * and to @new_bs.
2635 * NULL is passed as @new_bs for removing the reference before freeing @child.
2637 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2638 * function uses bdrv_set_perm() to update the permissions according to the new
2639 * reference that @new_bs gets.
2641 * Callers must ensure that child->frozen is false.
2643 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2645 BlockDriverState *old_bs = child->bs;
2647 /* Asserts that child->frozen == false */
2648 bdrv_replace_child_noperm(child, new_bs);
2651 * Start with the new node's permissions. If @new_bs is a (direct
2652 * or indirect) child of @old_bs, we must complete the permission
2653 * update on @new_bs before we loosen the restrictions on @old_bs.
2654 * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2655 * updating the permissions of @new_bs, and thus not purely loosen
2656 * restrictions.
2658 if (new_bs) {
2659 bdrv_set_perm(new_bs);
2662 if (old_bs) {
2664 * Update permissions for old node. We're just taking a parent away, so
2665 * we're loosening restrictions. Errors of permission update are not
2666 * fatal in this case, ignore them.
2668 bdrv_refresh_perms(old_bs, NULL);
2670 /* When the parent requiring a non-default AioContext is removed, the
2671 * node moves back to the main AioContext */
2672 bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2677 * This function steals the reference to child_bs from the caller.
2678 * That reference is later dropped by bdrv_root_unref_child().
2680 * On failure NULL is returned, errp is set and the reference to
2681 * child_bs is also dropped.
2683 * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2684 * (unless @child_bs is already in @ctx).
2686 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2687 const char *child_name,
2688 const BdrvChildClass *child_class,
2689 BdrvChildRole child_role,
2690 AioContext *ctx,
2691 uint64_t perm, uint64_t shared_perm,
2692 void *opaque, Error **errp)
2694 BdrvChild *child;
2695 Error *local_err = NULL;
2696 int ret;
2698 ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, errp);
2699 if (ret < 0) {
2700 bdrv_abort_perm_update(child_bs);
2701 bdrv_unref(child_bs);
2702 return NULL;
2705 child = g_new(BdrvChild, 1);
2706 *child = (BdrvChild) {
2707 .bs = NULL,
2708 .name = g_strdup(child_name),
2709 .klass = child_class,
2710 .role = child_role,
2711 .perm = perm,
2712 .shared_perm = shared_perm,
2713 .opaque = opaque,
2716 /* If the AioContexts don't match, first try to move the subtree of
2717 * child_bs into the AioContext of the new parent. If this doesn't work,
2718 * try moving the parent into the AioContext of child_bs instead. */
2719 if (bdrv_get_aio_context(child_bs) != ctx) {
2720 ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2721 if (ret < 0 && child_class->can_set_aio_ctx) {
2722 GSList *ignore = g_slist_prepend(NULL, child);
2723 ctx = bdrv_get_aio_context(child_bs);
2724 if (child_class->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2725 error_free(local_err);
2726 ret = 0;
2727 g_slist_free(ignore);
2728 ignore = g_slist_prepend(NULL, child);
2729 child_class->set_aio_ctx(child, ctx, &ignore);
2731 g_slist_free(ignore);
2733 if (ret < 0) {
2734 error_propagate(errp, local_err);
2735 g_free(child);
2736 bdrv_abort_perm_update(child_bs);
2737 bdrv_unref(child_bs);
2738 return NULL;
2742 /* This performs the matching bdrv_set_perm() for the above check. */
2743 bdrv_replace_child(child, child_bs);
2745 return child;
2749 * This function transfers the reference to child_bs from the caller
2750 * to parent_bs. That reference is later dropped by parent_bs on
2751 * bdrv_close() or if someone calls bdrv_unref_child().
2753 * On failure NULL is returned, errp is set and the reference to
2754 * child_bs is also dropped.
2756 * If @parent_bs and @child_bs are in different AioContexts, the caller must
2757 * hold the AioContext lock for @child_bs, but not for @parent_bs.
2759 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2760 BlockDriverState *child_bs,
2761 const char *child_name,
2762 const BdrvChildClass *child_class,
2763 BdrvChildRole child_role,
2764 Error **errp)
2766 BdrvChild *child;
2767 uint64_t perm, shared_perm;
2769 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2771 assert(parent_bs->drv);
2772 bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2773 perm, shared_perm, &perm, &shared_perm);
2775 child = bdrv_root_attach_child(child_bs, child_name, child_class,
2776 child_role, bdrv_get_aio_context(parent_bs),
2777 perm, shared_perm, parent_bs, errp);
2778 if (child == NULL) {
2779 return NULL;
2782 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2783 return child;
2786 static void bdrv_detach_child(BdrvChild *child)
2788 QLIST_SAFE_REMOVE(child, next);
2790 bdrv_replace_child(child, NULL);
2792 g_free(child->name);
2793 g_free(child);
2796 /* Callers must ensure that child->frozen is false. */
2797 void bdrv_root_unref_child(BdrvChild *child)
2799 BlockDriverState *child_bs;
2801 child_bs = child->bs;
2802 bdrv_detach_child(child);
2803 bdrv_unref(child_bs);
2807 * Clear all inherits_from pointers from children and grandchildren of
2808 * @root that point to @root, where necessary.
2810 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
2812 BdrvChild *c;
2814 if (child->bs->inherits_from == root) {
2816 * Remove inherits_from only when the last reference between root and
2817 * child->bs goes away.
2819 QLIST_FOREACH(c, &root->children, next) {
2820 if (c != child && c->bs == child->bs) {
2821 break;
2824 if (c == NULL) {
2825 child->bs->inherits_from = NULL;
2829 QLIST_FOREACH(c, &child->bs->children, next) {
2830 bdrv_unset_inherits_from(root, c);
2834 /* Callers must ensure that child->frozen is false. */
2835 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2837 if (child == NULL) {
2838 return;
2841 bdrv_unset_inherits_from(parent, child);
2842 bdrv_root_unref_child(child);
2846 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2848 BdrvChild *c;
2849 QLIST_FOREACH(c, &bs->parents, next_parent) {
2850 if (c->klass->change_media) {
2851 c->klass->change_media(c, load);
2856 /* Return true if you can reach parent going through child->inherits_from
2857 * recursively. If parent or child are NULL, return false */
2858 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2859 BlockDriverState *parent)
2861 while (child && child != parent) {
2862 child = child->inherits_from;
2865 return child != NULL;
2869 * Return the BdrvChildRole for @bs's backing child. bs->backing is
2870 * mostly used for COW backing children (role = COW), but also for
2871 * filtered children (role = FILTERED | PRIMARY).
2873 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
2875 if (bs->drv && bs->drv->is_filter) {
2876 return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
2877 } else {
2878 return BDRV_CHILD_COW;
2883 * Sets the bs->backing link of a BDS. A new reference is created; callers
2884 * which don't need their own reference any more must call bdrv_unref().
2886 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2887 Error **errp)
2889 int ret = 0;
2890 bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2891 bdrv_inherits_from_recursive(backing_hd, bs);
2893 if (bdrv_is_backing_chain_frozen(bs, child_bs(bs->backing), errp)) {
2894 return -EPERM;
2897 if (backing_hd) {
2898 bdrv_ref(backing_hd);
2901 if (bs->backing) {
2902 /* Cannot be frozen, we checked that above */
2903 bdrv_unref_child(bs, bs->backing);
2904 bs->backing = NULL;
2907 if (!backing_hd) {
2908 goto out;
2911 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_of_bds,
2912 bdrv_backing_role(bs), errp);
2913 if (!bs->backing) {
2914 ret = -EPERM;
2915 goto out;
2918 /* If backing_hd was already part of bs's backing chain, and
2919 * inherits_from pointed recursively to bs then let's update it to
2920 * point directly to bs (else it will become NULL). */
2921 if (update_inherits_from) {
2922 backing_hd->inherits_from = bs;
2925 out:
2926 bdrv_refresh_limits(bs, NULL);
2928 return ret;
2932 * Opens the backing file for a BlockDriverState if not yet open
2934 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2935 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2936 * itself, all options starting with "${bdref_key}." are considered part of the
2937 * BlockdevRef.
2939 * TODO Can this be unified with bdrv_open_image()?
2941 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2942 const char *bdref_key, Error **errp)
2944 char *backing_filename = NULL;
2945 char *bdref_key_dot;
2946 const char *reference = NULL;
2947 int ret = 0;
2948 bool implicit_backing = false;
2949 BlockDriverState *backing_hd;
2950 QDict *options;
2951 QDict *tmp_parent_options = NULL;
2952 Error *local_err = NULL;
2954 if (bs->backing != NULL) {
2955 goto free_exit;
2958 /* NULL means an empty set of options */
2959 if (parent_options == NULL) {
2960 tmp_parent_options = qdict_new();
2961 parent_options = tmp_parent_options;
2964 bs->open_flags &= ~BDRV_O_NO_BACKING;
2966 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2967 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2968 g_free(bdref_key_dot);
2971 * Caution: while qdict_get_try_str() is fine, getting non-string
2972 * types would require more care. When @parent_options come from
2973 * -blockdev or blockdev_add, its members are typed according to
2974 * the QAPI schema, but when they come from -drive, they're all
2975 * QString.
2977 reference = qdict_get_try_str(parent_options, bdref_key);
2978 if (reference || qdict_haskey(options, "file.filename")) {
2979 /* keep backing_filename NULL */
2980 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2981 qobject_unref(options);
2982 goto free_exit;
2983 } else {
2984 if (qdict_size(options) == 0) {
2985 /* If the user specifies options that do not modify the
2986 * backing file's behavior, we might still consider it the
2987 * implicit backing file. But it's easier this way, and
2988 * just specifying some of the backing BDS's options is
2989 * only possible with -drive anyway (otherwise the QAPI
2990 * schema forces the user to specify everything). */
2991 implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2994 backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
2995 if (local_err) {
2996 ret = -EINVAL;
2997 error_propagate(errp, local_err);
2998 qobject_unref(options);
2999 goto free_exit;
3003 if (!bs->drv || !bs->drv->supports_backing) {
3004 ret = -EINVAL;
3005 error_setg(errp, "Driver doesn't support backing files");
3006 qobject_unref(options);
3007 goto free_exit;
3010 if (!reference &&
3011 bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3012 qdict_put_str(options, "driver", bs->backing_format);
3015 backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3016 &child_of_bds, bdrv_backing_role(bs), errp);
3017 if (!backing_hd) {
3018 bs->open_flags |= BDRV_O_NO_BACKING;
3019 error_prepend(errp, "Could not open backing file: ");
3020 ret = -EINVAL;
3021 goto free_exit;
3024 if (implicit_backing) {
3025 bdrv_refresh_filename(backing_hd);
3026 pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3027 backing_hd->filename);
3030 /* Hook up the backing file link; drop our reference, bs owns the
3031 * backing_hd reference now */
3032 ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3033 bdrv_unref(backing_hd);
3034 if (ret < 0) {
3035 goto free_exit;
3038 qdict_del(parent_options, bdref_key);
3040 free_exit:
3041 g_free(backing_filename);
3042 qobject_unref(tmp_parent_options);
3043 return ret;
3046 static BlockDriverState *
3047 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3048 BlockDriverState *parent, const BdrvChildClass *child_class,
3049 BdrvChildRole child_role, bool allow_none, Error **errp)
3051 BlockDriverState *bs = NULL;
3052 QDict *image_options;
3053 char *bdref_key_dot;
3054 const char *reference;
3056 assert(child_class != NULL);
3058 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3059 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3060 g_free(bdref_key_dot);
3063 * Caution: while qdict_get_try_str() is fine, getting non-string
3064 * types would require more care. When @options come from
3065 * -blockdev or blockdev_add, its members are typed according to
3066 * the QAPI schema, but when they come from -drive, they're all
3067 * QString.
3069 reference = qdict_get_try_str(options, bdref_key);
3070 if (!filename && !reference && !qdict_size(image_options)) {
3071 if (!allow_none) {
3072 error_setg(errp, "A block device must be specified for \"%s\"",
3073 bdref_key);
3075 qobject_unref(image_options);
3076 goto done;
3079 bs = bdrv_open_inherit(filename, reference, image_options, 0,
3080 parent, child_class, child_role, errp);
3081 if (!bs) {
3082 goto done;
3085 done:
3086 qdict_del(options, bdref_key);
3087 return bs;
3091 * Opens a disk image whose options are given as BlockdevRef in another block
3092 * device's options.
3094 * If allow_none is true, no image will be opened if filename is false and no
3095 * BlockdevRef is given. NULL will be returned, but errp remains unset.
3097 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3098 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3099 * itself, all options starting with "${bdref_key}." are considered part of the
3100 * BlockdevRef.
3102 * The BlockdevRef will be removed from the options QDict.
3104 BdrvChild *bdrv_open_child(const char *filename,
3105 QDict *options, const char *bdref_key,
3106 BlockDriverState *parent,
3107 const BdrvChildClass *child_class,
3108 BdrvChildRole child_role,
3109 bool allow_none, Error **errp)
3111 BlockDriverState *bs;
3113 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3114 child_role, allow_none, errp);
3115 if (bs == NULL) {
3116 return NULL;
3119 return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3120 errp);
3124 * TODO Future callers may need to specify parent/child_class in order for
3125 * option inheritance to work. Existing callers use it for the root node.
3127 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3129 BlockDriverState *bs = NULL;
3130 QObject *obj = NULL;
3131 QDict *qdict = NULL;
3132 const char *reference = NULL;
3133 Visitor *v = NULL;
3135 if (ref->type == QTYPE_QSTRING) {
3136 reference = ref->u.reference;
3137 } else {
3138 BlockdevOptions *options = &ref->u.definition;
3139 assert(ref->type == QTYPE_QDICT);
3141 v = qobject_output_visitor_new(&obj);
3142 visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3143 visit_complete(v, &obj);
3145 qdict = qobject_to(QDict, obj);
3146 qdict_flatten(qdict);
3148 /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3149 * compatibility with other callers) rather than what we want as the
3150 * real defaults. Apply the defaults here instead. */
3151 qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3152 qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3153 qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3154 qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3158 bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3159 obj = NULL;
3160 qobject_unref(obj);
3161 visit_free(v);
3162 return bs;
3165 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3166 int flags,
3167 QDict *snapshot_options,
3168 Error **errp)
3170 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
3171 char *tmp_filename = g_malloc0(PATH_MAX + 1);
3172 int64_t total_size;
3173 QemuOpts *opts = NULL;
3174 BlockDriverState *bs_snapshot = NULL;
3175 int ret;
3177 /* if snapshot, we create a temporary backing file and open it
3178 instead of opening 'filename' directly */
3180 /* Get the required size from the image */
3181 total_size = bdrv_getlength(bs);
3182 if (total_size < 0) {
3183 error_setg_errno(errp, -total_size, "Could not get image size");
3184 goto out;
3187 /* Create the temporary image */
3188 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
3189 if (ret < 0) {
3190 error_setg_errno(errp, -ret, "Could not get temporary filename");
3191 goto out;
3194 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3195 &error_abort);
3196 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3197 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3198 qemu_opts_del(opts);
3199 if (ret < 0) {
3200 error_prepend(errp, "Could not create temporary overlay '%s': ",
3201 tmp_filename);
3202 goto out;
3205 /* Prepare options QDict for the temporary file */
3206 qdict_put_str(snapshot_options, "file.driver", "file");
3207 qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3208 qdict_put_str(snapshot_options, "driver", "qcow2");
3210 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3211 snapshot_options = NULL;
3212 if (!bs_snapshot) {
3213 goto out;
3216 /* bdrv_append() consumes a strong reference to bs_snapshot
3217 * (i.e. it will call bdrv_unref() on it) even on error, so in
3218 * order to be able to return one, we have to increase
3219 * bs_snapshot's refcount here */
3220 bdrv_ref(bs_snapshot);
3221 ret = bdrv_append(bs_snapshot, bs, errp);
3222 if (ret < 0) {
3223 bs_snapshot = NULL;
3224 goto out;
3227 out:
3228 qobject_unref(snapshot_options);
3229 g_free(tmp_filename);
3230 return bs_snapshot;
3234 * Opens a disk image (raw, qcow2, vmdk, ...)
3236 * options is a QDict of options to pass to the block drivers, or NULL for an
3237 * empty set of options. The reference to the QDict belongs to the block layer
3238 * after the call (even on failure), so if the caller intends to reuse the
3239 * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3241 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3242 * If it is not NULL, the referenced BDS will be reused.
3244 * The reference parameter may be used to specify an existing block device which
3245 * should be opened. If specified, neither options nor a filename may be given,
3246 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3248 static BlockDriverState *bdrv_open_inherit(const char *filename,
3249 const char *reference,
3250 QDict *options, int flags,
3251 BlockDriverState *parent,
3252 const BdrvChildClass *child_class,
3253 BdrvChildRole child_role,
3254 Error **errp)
3256 int ret;
3257 BlockBackend *file = NULL;
3258 BlockDriverState *bs;
3259 BlockDriver *drv = NULL;
3260 BdrvChild *child;
3261 const char *drvname;
3262 const char *backing;
3263 Error *local_err = NULL;
3264 QDict *snapshot_options = NULL;
3265 int snapshot_flags = 0;
3267 assert(!child_class || !flags);
3268 assert(!child_class == !parent);
3270 if (reference) {
3271 bool options_non_empty = options ? qdict_size(options) : false;
3272 qobject_unref(options);
3274 if (filename || options_non_empty) {
3275 error_setg(errp, "Cannot reference an existing block device with "
3276 "additional options or a new filename");
3277 return NULL;
3280 bs = bdrv_lookup_bs(reference, reference, errp);
3281 if (!bs) {
3282 return NULL;
3285 bdrv_ref(bs);
3286 return bs;
3289 bs = bdrv_new();
3291 /* NULL means an empty set of options */
3292 if (options == NULL) {
3293 options = qdict_new();
3296 /* json: syntax counts as explicit options, as if in the QDict */
3297 parse_json_protocol(options, &filename, &local_err);
3298 if (local_err) {
3299 goto fail;
3302 bs->explicit_options = qdict_clone_shallow(options);
3304 if (child_class) {
3305 bool parent_is_format;
3307 if (parent->drv) {
3308 parent_is_format = parent->drv->is_format;
3309 } else {
3311 * parent->drv is not set yet because this node is opened for
3312 * (potential) format probing. That means that @parent is going
3313 * to be a format node.
3315 parent_is_format = true;
3318 bs->inherits_from = parent;
3319 child_class->inherit_options(child_role, parent_is_format,
3320 &flags, options,
3321 parent->open_flags, parent->options);
3324 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3325 if (ret < 0) {
3326 goto fail;
3330 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3331 * Caution: getting a boolean member of @options requires care.
3332 * When @options come from -blockdev or blockdev_add, members are
3333 * typed according to the QAPI schema, but when they come from
3334 * -drive, they're all QString.
3336 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3337 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3338 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3339 } else {
3340 flags &= ~BDRV_O_RDWR;
3343 if (flags & BDRV_O_SNAPSHOT) {
3344 snapshot_options = qdict_new();
3345 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3346 flags, options);
3347 /* Let bdrv_backing_options() override "read-only" */
3348 qdict_del(options, BDRV_OPT_READ_ONLY);
3349 bdrv_inherited_options(BDRV_CHILD_COW, true,
3350 &flags, options, flags, options);
3353 bs->open_flags = flags;
3354 bs->options = options;
3355 options = qdict_clone_shallow(options);
3357 /* Find the right image format driver */
3358 /* See cautionary note on accessing @options above */
3359 drvname = qdict_get_try_str(options, "driver");
3360 if (drvname) {
3361 drv = bdrv_find_format(drvname);
3362 if (!drv) {
3363 error_setg(errp, "Unknown driver: '%s'", drvname);
3364 goto fail;
3368 assert(drvname || !(flags & BDRV_O_PROTOCOL));
3370 /* See cautionary note on accessing @options above */
3371 backing = qdict_get_try_str(options, "backing");
3372 if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3373 (backing && *backing == '\0'))
3375 if (backing) {
3376 warn_report("Use of \"backing\": \"\" is deprecated; "
3377 "use \"backing\": null instead");
3379 flags |= BDRV_O_NO_BACKING;
3380 qdict_del(bs->explicit_options, "backing");
3381 qdict_del(bs->options, "backing");
3382 qdict_del(options, "backing");
3385 /* Open image file without format layer. This BlockBackend is only used for
3386 * probing, the block drivers will do their own bdrv_open_child() for the
3387 * same BDS, which is why we put the node name back into options. */
3388 if ((flags & BDRV_O_PROTOCOL) == 0) {
3389 BlockDriverState *file_bs;
3391 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3392 &child_of_bds, BDRV_CHILD_IMAGE,
3393 true, &local_err);
3394 if (local_err) {
3395 goto fail;
3397 if (file_bs != NULL) {
3398 /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3399 * looking at the header to guess the image format. This works even
3400 * in cases where a guest would not see a consistent state. */
3401 file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3402 blk_insert_bs(file, file_bs, &local_err);
3403 bdrv_unref(file_bs);
3404 if (local_err) {
3405 goto fail;
3408 qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3412 /* Image format probing */
3413 bs->probed = !drv;
3414 if (!drv && file) {
3415 ret = find_image_format(file, filename, &drv, &local_err);
3416 if (ret < 0) {
3417 goto fail;
3420 * This option update would logically belong in bdrv_fill_options(),
3421 * but we first need to open bs->file for the probing to work, while
3422 * opening bs->file already requires the (mostly) final set of options
3423 * so that cache mode etc. can be inherited.
3425 * Adding the driver later is somewhat ugly, but it's not an option
3426 * that would ever be inherited, so it's correct. We just need to make
3427 * sure to update both bs->options (which has the full effective
3428 * options for bs) and options (which has file.* already removed).
3430 qdict_put_str(bs->options, "driver", drv->format_name);
3431 qdict_put_str(options, "driver", drv->format_name);
3432 } else if (!drv) {
3433 error_setg(errp, "Must specify either driver or file");
3434 goto fail;
3437 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3438 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3439 /* file must be NULL if a protocol BDS is about to be created
3440 * (the inverse results in an error message from bdrv_open_common()) */
3441 assert(!(flags & BDRV_O_PROTOCOL) || !file);
3443 /* Open the image */
3444 ret = bdrv_open_common(bs, file, options, &local_err);
3445 if (ret < 0) {
3446 goto fail;
3449 if (file) {
3450 blk_unref(file);
3451 file = NULL;
3454 /* If there is a backing file, use it */
3455 if ((flags & BDRV_O_NO_BACKING) == 0) {
3456 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3457 if (ret < 0) {
3458 goto close_and_fail;
3462 /* Remove all children options and references
3463 * from bs->options and bs->explicit_options */
3464 QLIST_FOREACH(child, &bs->children, next) {
3465 char *child_key_dot;
3466 child_key_dot = g_strdup_printf("%s.", child->name);
3467 qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3468 qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3469 qdict_del(bs->explicit_options, child->name);
3470 qdict_del(bs->options, child->name);
3471 g_free(child_key_dot);
3474 /* Check if any unknown options were used */
3475 if (qdict_size(options) != 0) {
3476 const QDictEntry *entry = qdict_first(options);
3477 if (flags & BDRV_O_PROTOCOL) {
3478 error_setg(errp, "Block protocol '%s' doesn't support the option "
3479 "'%s'", drv->format_name, entry->key);
3480 } else {
3481 error_setg(errp,
3482 "Block format '%s' does not support the option '%s'",
3483 drv->format_name, entry->key);
3486 goto close_and_fail;
3489 bdrv_parent_cb_change_media(bs, true);
3491 qobject_unref(options);
3492 options = NULL;
3494 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3495 * temporary snapshot afterwards. */
3496 if (snapshot_flags) {
3497 BlockDriverState *snapshot_bs;
3498 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3499 snapshot_options, &local_err);
3500 snapshot_options = NULL;
3501 if (local_err) {
3502 goto close_and_fail;
3504 /* We are not going to return bs but the overlay on top of it
3505 * (snapshot_bs); thus, we have to drop the strong reference to bs
3506 * (which we obtained by calling bdrv_new()). bs will not be deleted,
3507 * though, because the overlay still has a reference to it. */
3508 bdrv_unref(bs);
3509 bs = snapshot_bs;
3512 return bs;
3514 fail:
3515 blk_unref(file);
3516 qobject_unref(snapshot_options);
3517 qobject_unref(bs->explicit_options);
3518 qobject_unref(bs->options);
3519 qobject_unref(options);
3520 bs->options = NULL;
3521 bs->explicit_options = NULL;
3522 bdrv_unref(bs);
3523 error_propagate(errp, local_err);
3524 return NULL;
3526 close_and_fail:
3527 bdrv_unref(bs);
3528 qobject_unref(snapshot_options);
3529 qobject_unref(options);
3530 error_propagate(errp, local_err);
3531 return NULL;
3534 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3535 QDict *options, int flags, Error **errp)
3537 return bdrv_open_inherit(filename, reference, options, flags, NULL,
3538 NULL, 0, errp);
3541 /* Return true if the NULL-terminated @list contains @str */
3542 static bool is_str_in_list(const char *str, const char *const *list)
3544 if (str && list) {
3545 int i;
3546 for (i = 0; list[i] != NULL; i++) {
3547 if (!strcmp(str, list[i])) {
3548 return true;
3552 return false;
3556 * Check that every option set in @bs->options is also set in
3557 * @new_opts.
3559 * Options listed in the common_options list and in
3560 * @bs->drv->mutable_opts are skipped.
3562 * Return 0 on success, otherwise return -EINVAL and set @errp.
3564 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3565 const QDict *new_opts, Error **errp)
3567 const QDictEntry *e;
3568 /* These options are common to all block drivers and are handled
3569 * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3570 const char *const common_options[] = {
3571 "node-name", "discard", "cache.direct", "cache.no-flush",
3572 "read-only", "auto-read-only", "detect-zeroes", NULL
3575 for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3576 if (!qdict_haskey(new_opts, e->key) &&
3577 !is_str_in_list(e->key, common_options) &&
3578 !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3579 error_setg(errp, "Option '%s' cannot be reset "
3580 "to its default value", e->key);
3581 return -EINVAL;
3585 return 0;
3589 * Returns true if @child can be reached recursively from @bs
3591 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3592 BlockDriverState *child)
3594 BdrvChild *c;
3596 if (bs == child) {
3597 return true;
3600 QLIST_FOREACH(c, &bs->children, next) {
3601 if (bdrv_recurse_has_child(c->bs, child)) {
3602 return true;
3606 return false;
3610 * Adds a BlockDriverState to a simple queue for an atomic, transactional
3611 * reopen of multiple devices.
3613 * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3614 * already performed, or alternatively may be NULL a new BlockReopenQueue will
3615 * be created and initialized. This newly created BlockReopenQueue should be
3616 * passed back in for subsequent calls that are intended to be of the same
3617 * atomic 'set'.
3619 * bs is the BlockDriverState to add to the reopen queue.
3621 * options contains the changed options for the associated bs
3622 * (the BlockReopenQueue takes ownership)
3624 * flags contains the open flags for the associated bs
3626 * returns a pointer to bs_queue, which is either the newly allocated
3627 * bs_queue, or the existing bs_queue being used.
3629 * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3631 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3632 BlockDriverState *bs,
3633 QDict *options,
3634 const BdrvChildClass *klass,
3635 BdrvChildRole role,
3636 bool parent_is_format,
3637 QDict *parent_options,
3638 int parent_flags,
3639 bool keep_old_opts)
3641 assert(bs != NULL);
3643 BlockReopenQueueEntry *bs_entry;
3644 BdrvChild *child;
3645 QDict *old_options, *explicit_options, *options_copy;
3646 int flags;
3647 QemuOpts *opts;
3649 /* Make sure that the caller remembered to use a drained section. This is
3650 * important to avoid graph changes between the recursive queuing here and
3651 * bdrv_reopen_multiple(). */
3652 assert(bs->quiesce_counter > 0);
3654 if (bs_queue == NULL) {
3655 bs_queue = g_new0(BlockReopenQueue, 1);
3656 QTAILQ_INIT(bs_queue);
3659 if (!options) {
3660 options = qdict_new();
3663 /* Check if this BlockDriverState is already in the queue */
3664 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3665 if (bs == bs_entry->state.bs) {
3666 break;
3671 * Precedence of options:
3672 * 1. Explicitly passed in options (highest)
3673 * 2. Retained from explicitly set options of bs
3674 * 3. Inherited from parent node
3675 * 4. Retained from effective options of bs
3678 /* Old explicitly set values (don't overwrite by inherited value) */
3679 if (bs_entry || keep_old_opts) {
3680 old_options = qdict_clone_shallow(bs_entry ?
3681 bs_entry->state.explicit_options :
3682 bs->explicit_options);
3683 bdrv_join_options(bs, options, old_options);
3684 qobject_unref(old_options);
3687 explicit_options = qdict_clone_shallow(options);
3689 /* Inherit from parent node */
3690 if (parent_options) {
3691 flags = 0;
3692 klass->inherit_options(role, parent_is_format, &flags, options,
3693 parent_flags, parent_options);
3694 } else {
3695 flags = bdrv_get_flags(bs);
3698 if (keep_old_opts) {
3699 /* Old values are used for options that aren't set yet */
3700 old_options = qdict_clone_shallow(bs->options);
3701 bdrv_join_options(bs, options, old_options);
3702 qobject_unref(old_options);
3705 /* We have the final set of options so let's update the flags */
3706 options_copy = qdict_clone_shallow(options);
3707 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3708 qemu_opts_absorb_qdict(opts, options_copy, NULL);
3709 update_flags_from_options(&flags, opts);
3710 qemu_opts_del(opts);
3711 qobject_unref(options_copy);
3713 /* bdrv_open_inherit() sets and clears some additional flags internally */
3714 flags &= ~BDRV_O_PROTOCOL;
3715 if (flags & BDRV_O_RDWR) {
3716 flags |= BDRV_O_ALLOW_RDWR;
3719 if (!bs_entry) {
3720 bs_entry = g_new0(BlockReopenQueueEntry, 1);
3721 QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3722 } else {
3723 qobject_unref(bs_entry->state.options);
3724 qobject_unref(bs_entry->state.explicit_options);
3727 bs_entry->state.bs = bs;
3728 bs_entry->state.options = options;
3729 bs_entry->state.explicit_options = explicit_options;
3730 bs_entry->state.flags = flags;
3732 /* This needs to be overwritten in bdrv_reopen_prepare() */
3733 bs_entry->state.perm = UINT64_MAX;
3734 bs_entry->state.shared_perm = 0;
3737 * If keep_old_opts is false then it means that unspecified
3738 * options must be reset to their original value. We don't allow
3739 * resetting 'backing' but we need to know if the option is
3740 * missing in order to decide if we have to return an error.
3742 if (!keep_old_opts) {
3743 bs_entry->state.backing_missing =
3744 !qdict_haskey(options, "backing") &&
3745 !qdict_haskey(options, "backing.driver");
3748 QLIST_FOREACH(child, &bs->children, next) {
3749 QDict *new_child_options = NULL;
3750 bool child_keep_old = keep_old_opts;
3752 /* reopen can only change the options of block devices that were
3753 * implicitly created and inherited options. For other (referenced)
3754 * block devices, a syntax like "backing.foo" results in an error. */
3755 if (child->bs->inherits_from != bs) {
3756 continue;
3759 /* Check if the options contain a child reference */
3760 if (qdict_haskey(options, child->name)) {
3761 const char *childref = qdict_get_try_str(options, child->name);
3763 * The current child must not be reopened if the child
3764 * reference is null or points to a different node.
3766 if (g_strcmp0(childref, child->bs->node_name)) {
3767 continue;
3770 * If the child reference points to the current child then
3771 * reopen it with its existing set of options (note that
3772 * it can still inherit new options from the parent).
3774 child_keep_old = true;
3775 } else {
3776 /* Extract child options ("child-name.*") */
3777 char *child_key_dot = g_strdup_printf("%s.", child->name);
3778 qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3779 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3780 g_free(child_key_dot);
3783 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3784 child->klass, child->role, bs->drv->is_format,
3785 options, flags, child_keep_old);
3788 return bs_queue;
3791 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3792 BlockDriverState *bs,
3793 QDict *options, bool keep_old_opts)
3795 return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
3796 NULL, 0, keep_old_opts);
3800 * Reopen multiple BlockDriverStates atomically & transactionally.
3802 * The queue passed in (bs_queue) must have been built up previous
3803 * via bdrv_reopen_queue().
3805 * Reopens all BDS specified in the queue, with the appropriate
3806 * flags. All devices are prepared for reopen, and failure of any
3807 * device will cause all device changes to be abandoned, and intermediate
3808 * data cleaned up.
3810 * If all devices prepare successfully, then the changes are committed
3811 * to all devices.
3813 * All affected nodes must be drained between bdrv_reopen_queue() and
3814 * bdrv_reopen_multiple().
3816 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3818 int ret = -1;
3819 BlockReopenQueueEntry *bs_entry, *next;
3821 assert(bs_queue != NULL);
3823 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3824 assert(bs_entry->state.bs->quiesce_counter > 0);
3825 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3826 goto cleanup;
3828 bs_entry->prepared = true;
3831 QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3832 BDRVReopenState *state = &bs_entry->state;
3833 ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3834 state->shared_perm, NULL, errp);
3835 if (ret < 0) {
3836 goto cleanup_perm;
3838 /* Check if new_backing_bs would accept the new permissions */
3839 if (state->replace_backing_bs && state->new_backing_bs) {
3840 uint64_t nperm, nshared;
3841 bdrv_child_perm(state->bs, state->new_backing_bs,
3842 NULL, bdrv_backing_role(state->bs),
3843 bs_queue, state->perm, state->shared_perm,
3844 &nperm, &nshared);
3845 ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3846 nperm, nshared, NULL, errp);
3847 if (ret < 0) {
3848 goto cleanup_perm;
3851 bs_entry->perms_checked = true;
3855 * If we reach this point, we have success and just need to apply the
3856 * changes.
3858 * Reverse order is used to comfort qcow2 driver: on commit it need to write
3859 * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3860 * children are usually goes after parents in reopen-queue, so go from last
3861 * to first element.
3863 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3864 bdrv_reopen_commit(&bs_entry->state);
3867 ret = 0;
3868 cleanup_perm:
3869 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3870 BDRVReopenState *state = &bs_entry->state;
3872 if (!bs_entry->perms_checked) {
3873 continue;
3876 if (ret == 0) {
3877 uint64_t perm, shared;
3879 bdrv_get_cumulative_perm(state->bs, &perm, &shared);
3880 assert(perm == state->perm);
3881 assert(shared == state->shared_perm);
3883 bdrv_set_perm(state->bs);
3884 } else {
3885 bdrv_abort_perm_update(state->bs);
3886 if (state->replace_backing_bs && state->new_backing_bs) {
3887 bdrv_abort_perm_update(state->new_backing_bs);
3892 if (ret == 0) {
3893 QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3894 BlockDriverState *bs = bs_entry->state.bs;
3896 if (bs->drv->bdrv_reopen_commit_post)
3897 bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
3900 cleanup:
3901 QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3902 if (ret) {
3903 if (bs_entry->prepared) {
3904 bdrv_reopen_abort(&bs_entry->state);
3906 qobject_unref(bs_entry->state.explicit_options);
3907 qobject_unref(bs_entry->state.options);
3909 if (bs_entry->state.new_backing_bs) {
3910 bdrv_unref(bs_entry->state.new_backing_bs);
3912 g_free(bs_entry);
3914 g_free(bs_queue);
3916 return ret;
3919 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3920 Error **errp)
3922 int ret;
3923 BlockReopenQueue *queue;
3924 QDict *opts = qdict_new();
3926 qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3928 bdrv_subtree_drained_begin(bs);
3929 queue = bdrv_reopen_queue(NULL, bs, opts, true);
3930 ret = bdrv_reopen_multiple(queue, errp);
3931 bdrv_subtree_drained_end(bs);
3933 return ret;
3936 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3937 BdrvChild *c)
3939 BlockReopenQueueEntry *entry;
3941 QTAILQ_FOREACH(entry, q, entry) {
3942 BlockDriverState *bs = entry->state.bs;
3943 BdrvChild *child;
3945 QLIST_FOREACH(child, &bs->children, next) {
3946 if (child == c) {
3947 return entry;
3952 return NULL;
3955 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3956 uint64_t *perm, uint64_t *shared)
3958 BdrvChild *c;
3959 BlockReopenQueueEntry *parent;
3960 uint64_t cumulative_perms = 0;
3961 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3963 QLIST_FOREACH(c, &bs->parents, next_parent) {
3964 parent = find_parent_in_reopen_queue(q, c);
3965 if (!parent) {
3966 cumulative_perms |= c->perm;
3967 cumulative_shared_perms &= c->shared_perm;
3968 } else {
3969 uint64_t nperm, nshared;
3971 bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3972 parent->state.perm, parent->state.shared_perm,
3973 &nperm, &nshared);
3975 cumulative_perms |= nperm;
3976 cumulative_shared_perms &= nshared;
3979 *perm = cumulative_perms;
3980 *shared = cumulative_shared_perms;
3983 static bool bdrv_reopen_can_attach(BlockDriverState *parent,
3984 BdrvChild *child,
3985 BlockDriverState *new_child,
3986 Error **errp)
3988 AioContext *parent_ctx = bdrv_get_aio_context(parent);
3989 AioContext *child_ctx = bdrv_get_aio_context(new_child);
3990 GSList *ignore;
3991 bool ret;
3993 ignore = g_slist_prepend(NULL, child);
3994 ret = bdrv_can_set_aio_context(new_child, parent_ctx, &ignore, NULL);
3995 g_slist_free(ignore);
3996 if (ret) {
3997 return ret;
4000 ignore = g_slist_prepend(NULL, child);
4001 ret = bdrv_can_set_aio_context(parent, child_ctx, &ignore, errp);
4002 g_slist_free(ignore);
4003 return ret;
4007 * Take a BDRVReopenState and check if the value of 'backing' in the
4008 * reopen_state->options QDict is valid or not.
4010 * If 'backing' is missing from the QDict then return 0.
4012 * If 'backing' contains the node name of the backing file of
4013 * reopen_state->bs then return 0.
4015 * If 'backing' contains a different node name (or is null) then check
4016 * whether the current backing file can be replaced with the new one.
4017 * If that's the case then reopen_state->replace_backing_bs is set to
4018 * true and reopen_state->new_backing_bs contains a pointer to the new
4019 * backing BlockDriverState (or NULL).
4021 * Return 0 on success, otherwise return < 0 and set @errp.
4023 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
4024 Error **errp)
4026 BlockDriverState *bs = reopen_state->bs;
4027 BlockDriverState *overlay_bs, *below_bs, *new_backing_bs;
4028 QObject *value;
4029 const char *str;
4031 value = qdict_get(reopen_state->options, "backing");
4032 if (value == NULL) {
4033 return 0;
4036 switch (qobject_type(value)) {
4037 case QTYPE_QNULL:
4038 new_backing_bs = NULL;
4039 break;
4040 case QTYPE_QSTRING:
4041 str = qstring_get_str(qobject_to(QString, value));
4042 new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
4043 if (new_backing_bs == NULL) {
4044 return -EINVAL;
4045 } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
4046 error_setg(errp, "Making '%s' a backing file of '%s' "
4047 "would create a cycle", str, bs->node_name);
4048 return -EINVAL;
4050 break;
4051 default:
4052 /* 'backing' does not allow any other data type */
4053 g_assert_not_reached();
4057 * Check AioContext compatibility so that the bdrv_set_backing_hd() call in
4058 * bdrv_reopen_commit() won't fail.
4060 if (new_backing_bs) {
4061 if (!bdrv_reopen_can_attach(bs, bs->backing, new_backing_bs, errp)) {
4062 return -EINVAL;
4067 * Ensure that @bs can really handle backing files, because we are
4068 * about to give it one (or swap the existing one)
4070 if (bs->drv->is_filter) {
4071 /* Filters always have a file or a backing child */
4072 if (!bs->backing) {
4073 error_setg(errp, "'%s' is a %s filter node that does not support a "
4074 "backing child", bs->node_name, bs->drv->format_name);
4075 return -EINVAL;
4077 } else if (!bs->drv->supports_backing) {
4078 error_setg(errp, "Driver '%s' of node '%s' does not support backing "
4079 "files", bs->drv->format_name, bs->node_name);
4080 return -EINVAL;
4084 * Find the "actual" backing file by skipping all links that point
4085 * to an implicit node, if any (e.g. a commit filter node).
4086 * We cannot use any of the bdrv_skip_*() functions here because
4087 * those return the first explicit node, while we are looking for
4088 * its overlay here.
4090 overlay_bs = bs;
4091 for (below_bs = bdrv_filter_or_cow_bs(overlay_bs);
4092 below_bs && below_bs->implicit;
4093 below_bs = bdrv_filter_or_cow_bs(overlay_bs))
4095 overlay_bs = below_bs;
4098 /* If we want to replace the backing file we need some extra checks */
4099 if (new_backing_bs != bdrv_filter_or_cow_bs(overlay_bs)) {
4100 /* Check for implicit nodes between bs and its backing file */
4101 if (bs != overlay_bs) {
4102 error_setg(errp, "Cannot change backing link if '%s' has "
4103 "an implicit backing file", bs->node_name);
4104 return -EPERM;
4107 * Check if the backing link that we want to replace is frozen.
4108 * Note that
4109 * bdrv_filter_or_cow_child(overlay_bs) == overlay_bs->backing,
4110 * because we know that overlay_bs == bs, and that @bs
4111 * either is a filter that uses ->backing or a COW format BDS
4112 * with bs->drv->supports_backing == true.
4114 if (bdrv_is_backing_chain_frozen(overlay_bs,
4115 child_bs(overlay_bs->backing), errp))
4117 return -EPERM;
4119 reopen_state->replace_backing_bs = true;
4120 if (new_backing_bs) {
4121 bdrv_ref(new_backing_bs);
4122 reopen_state->new_backing_bs = new_backing_bs;
4126 return 0;
4130 * Prepares a BlockDriverState for reopen. All changes are staged in the
4131 * 'opaque' field of the BDRVReopenState, which is used and allocated by
4132 * the block driver layer .bdrv_reopen_prepare()
4134 * bs is the BlockDriverState to reopen
4135 * flags are the new open flags
4136 * queue is the reopen queue
4138 * Returns 0 on success, non-zero on error. On error errp will be set
4139 * as well.
4141 * On failure, bdrv_reopen_abort() will be called to clean up any data.
4142 * It is the responsibility of the caller to then call the abort() or
4143 * commit() for any other BDS that have been left in a prepare() state
4146 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4147 Error **errp)
4149 int ret = -1;
4150 int old_flags;
4151 Error *local_err = NULL;
4152 BlockDriver *drv;
4153 QemuOpts *opts;
4154 QDict *orig_reopen_opts;
4155 char *discard = NULL;
4156 bool read_only;
4157 bool drv_prepared = false;
4159 assert(reopen_state != NULL);
4160 assert(reopen_state->bs->drv != NULL);
4161 drv = reopen_state->bs->drv;
4163 /* This function and each driver's bdrv_reopen_prepare() remove
4164 * entries from reopen_state->options as they are processed, so
4165 * we need to make a copy of the original QDict. */
4166 orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4168 /* Process generic block layer options */
4169 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4170 if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4171 ret = -EINVAL;
4172 goto error;
4175 /* This was already called in bdrv_reopen_queue_child() so the flags
4176 * are up-to-date. This time we simply want to remove the options from
4177 * QemuOpts in order to indicate that they have been processed. */
4178 old_flags = reopen_state->flags;
4179 update_flags_from_options(&reopen_state->flags, opts);
4180 assert(old_flags == reopen_state->flags);
4182 discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4183 if (discard != NULL) {
4184 if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4185 error_setg(errp, "Invalid discard option");
4186 ret = -EINVAL;
4187 goto error;
4191 reopen_state->detect_zeroes =
4192 bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4193 if (local_err) {
4194 error_propagate(errp, local_err);
4195 ret = -EINVAL;
4196 goto error;
4199 /* All other options (including node-name and driver) must be unchanged.
4200 * Put them back into the QDict, so that they are checked at the end
4201 * of this function. */
4202 qemu_opts_to_qdict(opts, reopen_state->options);
4204 /* If we are to stay read-only, do not allow permission change
4205 * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4206 * not set, or if the BDS still has copy_on_read enabled */
4207 read_only = !(reopen_state->flags & BDRV_O_RDWR);
4208 ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4209 if (local_err) {
4210 error_propagate(errp, local_err);
4211 goto error;
4214 /* Calculate required permissions after reopening */
4215 bdrv_reopen_perm(queue, reopen_state->bs,
4216 &reopen_state->perm, &reopen_state->shared_perm);
4218 ret = bdrv_flush(reopen_state->bs);
4219 if (ret) {
4220 error_setg_errno(errp, -ret, "Error flushing drive");
4221 goto error;
4224 if (drv->bdrv_reopen_prepare) {
4226 * If a driver-specific option is missing, it means that we
4227 * should reset it to its default value.
4228 * But not all options allow that, so we need to check it first.
4230 ret = bdrv_reset_options_allowed(reopen_state->bs,
4231 reopen_state->options, errp);
4232 if (ret) {
4233 goto error;
4236 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4237 if (ret) {
4238 if (local_err != NULL) {
4239 error_propagate(errp, local_err);
4240 } else {
4241 bdrv_refresh_filename(reopen_state->bs);
4242 error_setg(errp, "failed while preparing to reopen image '%s'",
4243 reopen_state->bs->filename);
4245 goto error;
4247 } else {
4248 /* It is currently mandatory to have a bdrv_reopen_prepare()
4249 * handler for each supported drv. */
4250 error_setg(errp, "Block format '%s' used by node '%s' "
4251 "does not support reopening files", drv->format_name,
4252 bdrv_get_device_or_node_name(reopen_state->bs));
4253 ret = -1;
4254 goto error;
4257 drv_prepared = true;