block: do not set BDS read_only if copy_on_read enabled
[qemu/ar7.git] / block.c
blob67ae35a47acf9b35f1559a28e08e2d9d3313cc98
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.
24 #include "qemu/osdep.h"
25 #include "block/trace.h"
26 #include "block/block_int.h"
27 #include "block/blockjob.h"
28 #include "block/nbd.h"
29 #include "qemu/error-report.h"
30 #include "module_block.h"
31 #include "qemu/module.h"
32 #include "qapi/qmp/qerror.h"
33 #include "qapi/qmp/qbool.h"
34 #include "qapi/qmp/qjson.h"
35 #include "sysemu/block-backend.h"
36 #include "sysemu/sysemu.h"
37 #include "qemu/notify.h"
38 #include "qemu/coroutine.h"
39 #include "block/qapi.h"
40 #include "qmp-commands.h"
41 #include "qemu/timer.h"
42 #include "qapi-event.h"
43 #include "qemu/cutils.h"
44 #include "qemu/id.h"
45 #include "qapi/util.h"
47 #ifdef CONFIG_BSD
48 #include <sys/ioctl.h>
49 #include <sys/queue.h>
50 #ifndef __DragonFly__
51 #include <sys/disk.h>
52 #endif
53 #endif
55 #ifdef _WIN32
56 #include <windows.h>
57 #endif
59 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
61 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
62 QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
64 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
65 QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
67 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
68 QLIST_HEAD_INITIALIZER(bdrv_drivers);
70 static BlockDriverState *bdrv_open_inherit(const char *filename,
71 const char *reference,
72 QDict *options, int flags,
73 BlockDriverState *parent,
74 const BdrvChildRole *child_role,
75 Error **errp);
77 /* If non-zero, use only whitelisted block drivers */
78 static int use_bdrv_whitelist;
80 #ifdef _WIN32
81 static int is_windows_drive_prefix(const char *filename)
83 return (((filename[0] >= 'a' && filename[0] <= 'z') ||
84 (filename[0] >= 'A' && filename[0] <= 'Z')) &&
85 filename[1] == ':');
88 int is_windows_drive(const char *filename)
90 if (is_windows_drive_prefix(filename) &&
91 filename[2] == '\0')
92 return 1;
93 if (strstart(filename, "\\\\.\\", NULL) ||
94 strstart(filename, "//./", NULL))
95 return 1;
96 return 0;
98 #endif
100 size_t bdrv_opt_mem_align(BlockDriverState *bs)
102 if (!bs || !bs->drv) {
103 /* page size or 4k (hdd sector size) should be on the safe side */
104 return MAX(4096, getpagesize());
107 return bs->bl.opt_mem_alignment;
110 size_t bdrv_min_mem_align(BlockDriverState *bs)
112 if (!bs || !bs->drv) {
113 /* page size or 4k (hdd sector size) should be on the safe side */
114 return MAX(4096, getpagesize());
117 return bs->bl.min_mem_alignment;
120 /* check if the path starts with "<protocol>:" */
121 int path_has_protocol(const char *path)
123 const char *p;
125 #ifdef _WIN32
126 if (is_windows_drive(path) ||
127 is_windows_drive_prefix(path)) {
128 return 0;
130 p = path + strcspn(path, ":/\\");
131 #else
132 p = path + strcspn(path, ":/");
133 #endif
135 return *p == ':';
138 int path_is_absolute(const char *path)
140 #ifdef _WIN32
141 /* specific case for names like: "\\.\d:" */
142 if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
143 return 1;
145 return (*path == '/' || *path == '\\');
146 #else
147 return (*path == '/');
148 #endif
151 /* if filename is absolute, just copy it to dest. Otherwise, build a
152 path to it by considering it is relative to base_path. URL are
153 supported. */
154 void path_combine(char *dest, int dest_size,
155 const char *base_path,
156 const char *filename)
158 const char *p, *p1;
159 int len;
161 if (dest_size <= 0)
162 return;
163 if (path_is_absolute(filename)) {
164 pstrcpy(dest, dest_size, filename);
165 } else {
166 p = strchr(base_path, ':');
167 if (p)
168 p++;
169 else
170 p = base_path;
171 p1 = strrchr(base_path, '/');
172 #ifdef _WIN32
174 const char *p2;
175 p2 = strrchr(base_path, '\\');
176 if (!p1 || p2 > p1)
177 p1 = p2;
179 #endif
180 if (p1)
181 p1++;
182 else
183 p1 = base_path;
184 if (p1 > p)
185 p = p1;
186 len = p - base_path;
187 if (len > dest_size - 1)
188 len = dest_size - 1;
189 memcpy(dest, base_path, len);
190 dest[len] = '\0';
191 pstrcat(dest, dest_size, filename);
195 int bdrv_set_read_only(BlockDriverState *bs, bool read_only, Error **errp)
197 /* Do not set read_only if copy_on_read is enabled */
198 if (bs->copy_on_read && read_only) {
199 error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
200 bdrv_get_device_or_node_name(bs));
201 return -EINVAL;
204 bs->read_only = read_only;
205 return 0;
208 void bdrv_get_full_backing_filename_from_filename(const char *backed,
209 const char *backing,
210 char *dest, size_t sz,
211 Error **errp)
213 if (backing[0] == '\0' || path_has_protocol(backing) ||
214 path_is_absolute(backing))
216 pstrcpy(dest, sz, backing);
217 } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
218 error_setg(errp, "Cannot use relative backing file names for '%s'",
219 backed);
220 } else {
221 path_combine(dest, sz, backed, backing);
225 void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
226 Error **errp)
228 char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
230 bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
231 dest, sz, errp);
234 void bdrv_register(BlockDriver *bdrv)
236 QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
239 BlockDriverState *bdrv_new(void)
241 BlockDriverState *bs;
242 int i;
244 bs = g_new0(BlockDriverState, 1);
245 QLIST_INIT(&bs->dirty_bitmaps);
246 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
247 QLIST_INIT(&bs->op_blockers[i]);
249 notifier_with_return_list_init(&bs->before_write_notifiers);
250 bs->refcnt = 1;
251 bs->aio_context = qemu_get_aio_context();
253 qemu_co_queue_init(&bs->flush_queue);
255 QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
257 return bs;
260 static BlockDriver *bdrv_do_find_format(const char *format_name)
262 BlockDriver *drv1;
264 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
265 if (!strcmp(drv1->format_name, format_name)) {
266 return drv1;
270 return NULL;
273 BlockDriver *bdrv_find_format(const char *format_name)
275 BlockDriver *drv1;
276 int i;
278 drv1 = bdrv_do_find_format(format_name);
279 if (drv1) {
280 return drv1;
283 /* The driver isn't registered, maybe we need to load a module */
284 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
285 if (!strcmp(block_driver_modules[i].format_name, format_name)) {
286 block_module_load_one(block_driver_modules[i].library_name);
287 break;
291 return bdrv_do_find_format(format_name);
294 static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
296 static const char *whitelist_rw[] = {
297 CONFIG_BDRV_RW_WHITELIST
299 static const char *whitelist_ro[] = {
300 CONFIG_BDRV_RO_WHITELIST
302 const char **p;
304 if (!whitelist_rw[0] && !whitelist_ro[0]) {
305 return 1; /* no whitelist, anything goes */
308 for (p = whitelist_rw; *p; p++) {
309 if (!strcmp(drv->format_name, *p)) {
310 return 1;
313 if (read_only) {
314 for (p = whitelist_ro; *p; p++) {
315 if (!strcmp(drv->format_name, *p)) {
316 return 1;
320 return 0;
323 bool bdrv_uses_whitelist(void)
325 return use_bdrv_whitelist;
328 typedef struct CreateCo {
329 BlockDriver *drv;
330 char *filename;
331 QemuOpts *opts;
332 int ret;
333 Error *err;
334 } CreateCo;
336 static void coroutine_fn bdrv_create_co_entry(void *opaque)
338 Error *local_err = NULL;
339 int ret;
341 CreateCo *cco = opaque;
342 assert(cco->drv);
344 ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
345 error_propagate(&cco->err, local_err);
346 cco->ret = ret;
349 int bdrv_create(BlockDriver *drv, const char* filename,
350 QemuOpts *opts, Error **errp)
352 int ret;
354 Coroutine *co;
355 CreateCo cco = {
356 .drv = drv,
357 .filename = g_strdup(filename),
358 .opts = opts,
359 .ret = NOT_DONE,
360 .err = NULL,
363 if (!drv->bdrv_create) {
364 error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
365 ret = -ENOTSUP;
366 goto out;
369 if (qemu_in_coroutine()) {
370 /* Fast-path if already in coroutine context */
371 bdrv_create_co_entry(&cco);
372 } else {
373 co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
374 qemu_coroutine_enter(co);
375 while (cco.ret == NOT_DONE) {
376 aio_poll(qemu_get_aio_context(), true);
380 ret = cco.ret;
381 if (ret < 0) {
382 if (cco.err) {
383 error_propagate(errp, cco.err);
384 } else {
385 error_setg_errno(errp, -ret, "Could not create image");
389 out:
390 g_free(cco.filename);
391 return ret;
394 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
396 BlockDriver *drv;
397 Error *local_err = NULL;
398 int ret;
400 drv = bdrv_find_protocol(filename, true, errp);
401 if (drv == NULL) {
402 return -ENOENT;
405 ret = bdrv_create(drv, filename, opts, &local_err);
406 error_propagate(errp, local_err);
407 return ret;
411 * Try to get @bs's logical and physical block size.
412 * On success, store them in @bsz struct and return 0.
413 * On failure return -errno.
414 * @bs must not be empty.
416 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
418 BlockDriver *drv = bs->drv;
420 if (drv && drv->bdrv_probe_blocksizes) {
421 return drv->bdrv_probe_blocksizes(bs, bsz);
424 return -ENOTSUP;
428 * Try to get @bs's geometry (cyls, heads, sectors).
429 * On success, store them in @geo struct and return 0.
430 * On failure return -errno.
431 * @bs must not be empty.
433 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
435 BlockDriver *drv = bs->drv;
437 if (drv && drv->bdrv_probe_geometry) {
438 return drv->bdrv_probe_geometry(bs, geo);
441 return -ENOTSUP;
445 * Create a uniquely-named empty temporary file.
446 * Return 0 upon success, otherwise a negative errno value.
448 int get_tmp_filename(char *filename, int size)
450 #ifdef _WIN32
451 char temp_dir[MAX_PATH];
452 /* GetTempFileName requires that its output buffer (4th param)
453 have length MAX_PATH or greater. */
454 assert(size >= MAX_PATH);
455 return (GetTempPath(MAX_PATH, temp_dir)
456 && GetTempFileName(temp_dir, "qem", 0, filename)
457 ? 0 : -GetLastError());
458 #else
459 int fd;
460 const char *tmpdir;
461 tmpdir = getenv("TMPDIR");
462 if (!tmpdir) {
463 tmpdir = "/var/tmp";
465 if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
466 return -EOVERFLOW;
468 fd = mkstemp(filename);
469 if (fd < 0) {
470 return -errno;
472 if (close(fd) != 0) {
473 unlink(filename);
474 return -errno;
476 return 0;
477 #endif
481 * Detect host devices. By convention, /dev/cdrom[N] is always
482 * recognized as a host CDROM.
484 static BlockDriver *find_hdev_driver(const char *filename)
486 int score_max = 0, score;
487 BlockDriver *drv = NULL, *d;
489 QLIST_FOREACH(d, &bdrv_drivers, list) {
490 if (d->bdrv_probe_device) {
491 score = d->bdrv_probe_device(filename);
492 if (score > score_max) {
493 score_max = score;
494 drv = d;
499 return drv;
502 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
504 BlockDriver *drv1;
506 QLIST_FOREACH(drv1, &bdrv_drivers, list) {
507 if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
508 return drv1;
512 return NULL;
515 BlockDriver *bdrv_find_protocol(const char *filename,
516 bool allow_protocol_prefix,
517 Error **errp)
519 BlockDriver *drv1;
520 char protocol[128];
521 int len;
522 const char *p;
523 int i;
525 /* TODO Drivers without bdrv_file_open must be specified explicitly */
528 * XXX(hch): we really should not let host device detection
529 * override an explicit protocol specification, but moving this
530 * later breaks access to device names with colons in them.
531 * Thanks to the brain-dead persistent naming schemes on udev-
532 * based Linux systems those actually are quite common.
534 drv1 = find_hdev_driver(filename);
535 if (drv1) {
536 return drv1;
539 if (!path_has_protocol(filename) || !allow_protocol_prefix) {
540 return &bdrv_file;
543 p = strchr(filename, ':');
544 assert(p != NULL);
545 len = p - filename;
546 if (len > sizeof(protocol) - 1)
547 len = sizeof(protocol) - 1;
548 memcpy(protocol, filename, len);
549 protocol[len] = '\0';
551 drv1 = bdrv_do_find_protocol(protocol);
552 if (drv1) {
553 return drv1;
556 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
557 if (block_driver_modules[i].protocol_name &&
558 !strcmp(block_driver_modules[i].protocol_name, protocol)) {
559 block_module_load_one(block_driver_modules[i].library_name);
560 break;
564 drv1 = bdrv_do_find_protocol(protocol);
565 if (!drv1) {
566 error_setg(errp, "Unknown protocol '%s'", protocol);
568 return drv1;
572 * Guess image format by probing its contents.
573 * This is not a good idea when your image is raw (CVE-2008-2004), but
574 * we do it anyway for backward compatibility.
576 * @buf contains the image's first @buf_size bytes.
577 * @buf_size is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
578 * but can be smaller if the image file is smaller)
579 * @filename is its filename.
581 * For all block drivers, call the bdrv_probe() method to get its
582 * probing score.
583 * Return the first block driver with the highest probing score.
585 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
586 const char *filename)
588 int score_max = 0, score;
589 BlockDriver *drv = NULL, *d;
591 QLIST_FOREACH(d, &bdrv_drivers, list) {
592 if (d->bdrv_probe) {
593 score = d->bdrv_probe(buf, buf_size, filename);
594 if (score > score_max) {
595 score_max = score;
596 drv = d;
601 return drv;
604 static int find_image_format(BlockBackend *file, const char *filename,
605 BlockDriver **pdrv, Error **errp)
607 BlockDriver *drv;
608 uint8_t buf[BLOCK_PROBE_BUF_SIZE];
609 int ret = 0;
611 /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
612 if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
613 *pdrv = &bdrv_raw;
614 return ret;
617 ret = blk_pread(file, 0, buf, sizeof(buf));
618 if (ret < 0) {
619 error_setg_errno(errp, -ret, "Could not read image for determining its "
620 "format");
621 *pdrv = NULL;
622 return ret;
625 drv = bdrv_probe_all(buf, ret, filename);
626 if (!drv) {
627 error_setg(errp, "Could not determine image format: No compatible "
628 "driver found");
629 ret = -ENOENT;
631 *pdrv = drv;
632 return ret;
636 * Set the current 'total_sectors' value
637 * Return 0 on success, -errno on error.
639 static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
641 BlockDriver *drv = bs->drv;
643 /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
644 if (bdrv_is_sg(bs))
645 return 0;
647 /* query actual device if possible, otherwise just trust the hint */
648 if (drv->bdrv_getlength) {
649 int64_t length = drv->bdrv_getlength(bs);
650 if (length < 0) {
651 return length;
653 hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
656 bs->total_sectors = hint;
657 return 0;
661 * Combines a QDict of new block driver @options with any missing options taken
662 * from @old_options, so that leaving out an option defaults to its old value.
664 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
665 QDict *old_options)
667 if (bs->drv && bs->drv->bdrv_join_options) {
668 bs->drv->bdrv_join_options(options, old_options);
669 } else {
670 qdict_join(options, old_options, false);
675 * Set open flags for a given discard mode
677 * Return 0 on success, -1 if the discard mode was invalid.
679 int bdrv_parse_discard_flags(const char *mode, int *flags)
681 *flags &= ~BDRV_O_UNMAP;
683 if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
684 /* do nothing */
685 } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
686 *flags |= BDRV_O_UNMAP;
687 } else {
688 return -1;
691 return 0;
695 * Set open flags for a given cache mode
697 * Return 0 on success, -1 if the cache mode was invalid.
699 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
701 *flags &= ~BDRV_O_CACHE_MASK;
703 if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
704 *writethrough = false;
705 *flags |= BDRV_O_NOCACHE;
706 } else if (!strcmp(mode, "directsync")) {
707 *writethrough = true;
708 *flags |= BDRV_O_NOCACHE;
709 } else if (!strcmp(mode, "writeback")) {
710 *writethrough = false;
711 } else if (!strcmp(mode, "unsafe")) {
712 *writethrough = false;
713 *flags |= BDRV_O_NO_FLUSH;
714 } else if (!strcmp(mode, "writethrough")) {
715 *writethrough = true;
716 } else {
717 return -1;
720 return 0;
723 static char *bdrv_child_get_parent_desc(BdrvChild *c)
725 BlockDriverState *parent = c->opaque;
726 return g_strdup(bdrv_get_device_or_node_name(parent));
729 static void bdrv_child_cb_drained_begin(BdrvChild *child)
731 BlockDriverState *bs = child->opaque;
732 bdrv_drained_begin(bs);
735 static void bdrv_child_cb_drained_end(BdrvChild *child)
737 BlockDriverState *bs = child->opaque;
738 bdrv_drained_end(bs);
742 * Returns the options and flags that a temporary snapshot should get, based on
743 * the originally requested flags (the originally requested image will have
744 * flags like a backing file)
746 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
747 int parent_flags, QDict *parent_options)
749 *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
751 /* For temporary files, unconditional cache=unsafe is fine */
752 qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
753 qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
755 /* Copy the read-only option from the parent */
756 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
758 /* aio=native doesn't work for cache.direct=off, so disable it for the
759 * temporary snapshot */
760 *child_flags &= ~BDRV_O_NATIVE_AIO;
764 * Returns the options and flags that bs->file should get if a protocol driver
765 * is expected, based on the given options and flags for the parent BDS
767 static void bdrv_inherited_options(int *child_flags, QDict *child_options,
768 int parent_flags, QDict *parent_options)
770 int flags = parent_flags;
772 /* Enable protocol handling, disable format probing for bs->file */
773 flags |= BDRV_O_PROTOCOL;
775 /* If the cache mode isn't explicitly set, inherit direct and no-flush from
776 * the parent. */
777 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
778 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
780 /* Inherit the read-only option from the parent if it's not set */
781 qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
783 /* Our block drivers take care to send flushes and respect unmap policy,
784 * so we can default to enable both on lower layers regardless of the
785 * corresponding parent options. */
786 qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
788 /* Clear flags that only apply to the top layer */
789 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
790 BDRV_O_NO_IO);
792 *child_flags = flags;
795 const BdrvChildRole child_file = {
796 .get_parent_desc = bdrv_child_get_parent_desc,
797 .inherit_options = bdrv_inherited_options,
798 .drained_begin = bdrv_child_cb_drained_begin,
799 .drained_end = bdrv_child_cb_drained_end,
803 * Returns the options and flags that bs->file should get if the use of formats
804 * (and not only protocols) is permitted for it, based on the given options and
805 * flags for the parent BDS
807 static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
808 int parent_flags, QDict *parent_options)
810 child_file.inherit_options(child_flags, child_options,
811 parent_flags, parent_options);
813 *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
816 const BdrvChildRole child_format = {
817 .get_parent_desc = bdrv_child_get_parent_desc,
818 .inherit_options = bdrv_inherited_fmt_options,
819 .drained_begin = bdrv_child_cb_drained_begin,
820 .drained_end = bdrv_child_cb_drained_end,
823 static void bdrv_backing_attach(BdrvChild *c)
825 BlockDriverState *parent = c->opaque;
826 BlockDriverState *backing_hd = c->bs;
828 assert(!parent->backing_blocker);
829 error_setg(&parent->backing_blocker,
830 "node is used as backing hd of '%s'",
831 bdrv_get_device_or_node_name(parent));
833 parent->open_flags &= ~BDRV_O_NO_BACKING;
834 pstrcpy(parent->backing_file, sizeof(parent->backing_file),
835 backing_hd->filename);
836 pstrcpy(parent->backing_format, sizeof(parent->backing_format),
837 backing_hd->drv ? backing_hd->drv->format_name : "");
839 bdrv_op_block_all(backing_hd, parent->backing_blocker);
840 /* Otherwise we won't be able to commit or stream */
841 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
842 parent->backing_blocker);
843 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
844 parent->backing_blocker);
846 * We do backup in 3 ways:
847 * 1. drive backup
848 * The target bs is new opened, and the source is top BDS
849 * 2. blockdev backup
850 * Both the source and the target are top BDSes.
851 * 3. internal backup(used for block replication)
852 * Both the source and the target are backing file
854 * In case 1 and 2, neither the source nor the target is the backing file.
855 * In case 3, we will block the top BDS, so there is only one block job
856 * for the top BDS and its backing chain.
858 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
859 parent->backing_blocker);
860 bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
861 parent->backing_blocker);
864 static void bdrv_backing_detach(BdrvChild *c)
866 BlockDriverState *parent = c->opaque;
868 assert(parent->backing_blocker);
869 bdrv_op_unblock_all(c->bs, parent->backing_blocker);
870 error_free(parent->backing_blocker);
871 parent->backing_blocker = NULL;
875 * Returns the options and flags that bs->backing should get, based on the
876 * given options and flags for the parent BDS
878 static void bdrv_backing_options(int *child_flags, QDict *child_options,
879 int parent_flags, QDict *parent_options)
881 int flags = parent_flags;
883 /* The cache mode is inherited unmodified for backing files; except WCE,
884 * which is only applied on the top level (BlockBackend) */
885 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
886 qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
888 /* backing files always opened read-only */
889 qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
890 flags &= ~BDRV_O_COPY_ON_READ;
892 /* snapshot=on is handled on the top layer */
893 flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
895 *child_flags = flags;
898 const BdrvChildRole child_backing = {
899 .get_parent_desc = bdrv_child_get_parent_desc,
900 .attach = bdrv_backing_attach,
901 .detach = bdrv_backing_detach,
902 .inherit_options = bdrv_backing_options,
903 .drained_begin = bdrv_child_cb_drained_begin,
904 .drained_end = bdrv_child_cb_drained_end,
907 static int bdrv_open_flags(BlockDriverState *bs, int flags)
909 int open_flags = flags;
912 * Clear flags that are internal to the block layer before opening the
913 * image.
915 open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
918 * Snapshots should be writable.
920 if (flags & BDRV_O_TEMPORARY) {
921 open_flags |= BDRV_O_RDWR;
924 return open_flags;
927 static void update_flags_from_options(int *flags, QemuOpts *opts)
929 *flags &= ~BDRV_O_CACHE_MASK;
931 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
932 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
933 *flags |= BDRV_O_NO_FLUSH;
936 assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
937 if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
938 *flags |= BDRV_O_NOCACHE;
941 *flags &= ~BDRV_O_RDWR;
943 assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
944 if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
945 *flags |= BDRV_O_RDWR;
950 static void update_options_from_flags(QDict *options, int flags)
952 if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
953 qdict_put(options, BDRV_OPT_CACHE_DIRECT,
954 qbool_from_bool(flags & BDRV_O_NOCACHE));
956 if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
957 qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
958 qbool_from_bool(flags & BDRV_O_NO_FLUSH));
960 if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
961 qdict_put(options, BDRV_OPT_READ_ONLY,
962 qbool_from_bool(!(flags & BDRV_O_RDWR)));
966 static void bdrv_assign_node_name(BlockDriverState *bs,
967 const char *node_name,
968 Error **errp)
970 char *gen_node_name = NULL;
972 if (!node_name) {
973 node_name = gen_node_name = id_generate(ID_BLOCK);
974 } else if (!id_wellformed(node_name)) {
976 * Check for empty string or invalid characters, but not if it is
977 * generated (generated names use characters not available to the user)
979 error_setg(errp, "Invalid node name");
980 return;
983 /* takes care of avoiding namespaces collisions */
984 if (blk_by_name(node_name)) {
985 error_setg(errp, "node-name=%s is conflicting with a device id",
986 node_name);
987 goto out;
990 /* takes care of avoiding duplicates node names */
991 if (bdrv_find_node(node_name)) {
992 error_setg(errp, "Duplicate node name");
993 goto out;
996 /* copy node name into the bs and insert it into the graph list */
997 pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
998 QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
999 out:
1000 g_free(gen_node_name);
1003 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1004 const char *node_name, QDict *options,
1005 int open_flags, Error **errp)
1007 Error *local_err = NULL;
1008 int ret;
1010 bdrv_assign_node_name(bs, node_name, &local_err);
1011 if (local_err) {
1012 error_propagate(errp, local_err);
1013 return -EINVAL;
1016 bs->drv = drv;
1017 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1018 bs->opaque = g_malloc0(drv->instance_size);
1020 if (drv->bdrv_file_open) {
1021 assert(!drv->bdrv_needs_filename || bs->filename[0]);
1022 ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1023 } else if (drv->bdrv_open) {
1024 ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1025 } else {
1026 ret = 0;
1029 if (ret < 0) {
1030 if (local_err) {
1031 error_propagate(errp, local_err);
1032 } else if (bs->filename[0]) {
1033 error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1034 } else {
1035 error_setg_errno(errp, -ret, "Could not open image");
1037 goto free_and_fail;
1040 ret = refresh_total_sectors(bs, bs->total_sectors);
1041 if (ret < 0) {
1042 error_setg_errno(errp, -ret, "Could not refresh total sector count");
1043 goto free_and_fail;
1046 bdrv_refresh_limits(bs, &local_err);
1047 if (local_err) {
1048 error_propagate(errp, local_err);
1049 ret = -EINVAL;
1050 goto free_and_fail;
1053 assert(bdrv_opt_mem_align(bs) != 0);
1054 assert(bdrv_min_mem_align(bs) != 0);
1055 assert(is_power_of_2(bs->bl.request_alignment));
1057 return 0;
1059 free_and_fail:
1060 /* FIXME Close bs first if already opened*/
1061 g_free(bs->opaque);
1062 bs->opaque = NULL;
1063 bs->drv = NULL;
1064 return ret;
1067 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1068 int flags, Error **errp)
1070 BlockDriverState *bs;
1071 int ret;
1073 bs = bdrv_new();
1074 bs->open_flags = flags;
1075 bs->explicit_options = qdict_new();
1076 bs->options = qdict_new();
1077 bs->opaque = NULL;
1079 update_options_from_flags(bs->options, flags);
1081 ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1082 if (ret < 0) {
1083 QDECREF(bs->explicit_options);
1084 QDECREF(bs->options);
1085 bdrv_unref(bs);
1086 return NULL;
1089 return bs;
1092 QemuOptsList bdrv_runtime_opts = {
1093 .name = "bdrv_common",
1094 .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1095 .desc = {
1097 .name = "node-name",
1098 .type = QEMU_OPT_STRING,
1099 .help = "Node name of the block device node",
1102 .name = "driver",
1103 .type = QEMU_OPT_STRING,
1104 .help = "Block driver to use for the node",
1107 .name = BDRV_OPT_CACHE_DIRECT,
1108 .type = QEMU_OPT_BOOL,
1109 .help = "Bypass software writeback cache on the host",
1112 .name = BDRV_OPT_CACHE_NO_FLUSH,
1113 .type = QEMU_OPT_BOOL,
1114 .help = "Ignore flush requests",
1117 .name = BDRV_OPT_READ_ONLY,
1118 .type = QEMU_OPT_BOOL,
1119 .help = "Node is opened in read-only mode",
1122 .name = "detect-zeroes",
1123 .type = QEMU_OPT_STRING,
1124 .help = "try to optimize zero writes (off, on, unmap)",
1127 .name = "discard",
1128 .type = QEMU_OPT_STRING,
1129 .help = "discard operation (ignore/off, unmap/on)",
1131 { /* end of list */ }
1136 * Common part for opening disk images and files
1138 * Removes all processed options from *options.
1140 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1141 QDict *options, Error **errp)
1143 int ret, open_flags;
1144 const char *filename;
1145 const char *driver_name = NULL;
1146 const char *node_name = NULL;
1147 const char *discard;
1148 const char *detect_zeroes;
1149 QemuOpts *opts;
1150 BlockDriver *drv;
1151 Error *local_err = NULL;
1153 assert(bs->file == NULL);
1154 assert(options != NULL && bs->options != options);
1156 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1157 qemu_opts_absorb_qdict(opts, options, &local_err);
1158 if (local_err) {
1159 error_propagate(errp, local_err);
1160 ret = -EINVAL;
1161 goto fail_opts;
1164 update_flags_from_options(&bs->open_flags, opts);
1166 driver_name = qemu_opt_get(opts, "driver");
1167 drv = bdrv_find_format(driver_name);
1168 assert(drv != NULL);
1170 if (file != NULL) {
1171 filename = blk_bs(file)->filename;
1172 } else {
1174 * Caution: while qdict_get_try_str() is fine, getting
1175 * non-string types would require more care. When @options
1176 * come from -blockdev or blockdev_add, its members are typed
1177 * according to the QAPI schema, but when they come from
1178 * -drive, they're all QString.
1180 filename = qdict_get_try_str(options, "filename");
1183 if (drv->bdrv_needs_filename && !filename) {
1184 error_setg(errp, "The '%s' block driver requires a file name",
1185 drv->format_name);
1186 ret = -EINVAL;
1187 goto fail_opts;
1190 trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1191 drv->format_name);
1193 bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1195 if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1196 error_setg(errp,
1197 !bs->read_only && bdrv_is_whitelisted(drv, true)
1198 ? "Driver '%s' can only be used for read-only devices"
1199 : "Driver '%s' is not whitelisted",
1200 drv->format_name);
1201 ret = -ENOTSUP;
1202 goto fail_opts;
1205 assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
1206 if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1207 if (!bs->read_only) {
1208 bdrv_enable_copy_on_read(bs);
1209 } else {
1210 error_setg(errp, "Can't use copy-on-read on read-only device");
1211 ret = -EINVAL;
1212 goto fail_opts;
1216 discard = qemu_opt_get(opts, "discard");
1217 if (discard != NULL) {
1218 if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1219 error_setg(errp, "Invalid discard option");
1220 ret = -EINVAL;
1221 goto fail_opts;
1225 detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
1226 if (detect_zeroes) {
1227 BlockdevDetectZeroesOptions value =
1228 qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
1229 detect_zeroes,
1230 BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
1231 BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
1232 &local_err);
1233 if (local_err) {
1234 error_propagate(errp, local_err);
1235 ret = -EINVAL;
1236 goto fail_opts;
1239 if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1240 !(bs->open_flags & BDRV_O_UNMAP))
1242 error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1243 "without setting discard operation to unmap");
1244 ret = -EINVAL;
1245 goto fail_opts;
1248 bs->detect_zeroes = value;
1251 if (filename != NULL) {
1252 pstrcpy(bs->filename, sizeof(bs->filename), filename);
1253 } else {
1254 bs->filename[0] = '\0';
1256 pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1258 /* Open the image, either directly or using a protocol */
1259 open_flags = bdrv_open_flags(bs, bs->open_flags);
1260 node_name = qemu_opt_get(opts, "node-name");
1262 assert(!drv->bdrv_file_open || file == NULL);
1263 ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1264 if (ret < 0) {
1265 goto fail_opts;
1268 qemu_opts_del(opts);
1269 return 0;
1271 fail_opts:
1272 qemu_opts_del(opts);
1273 return ret;
1276 static QDict *parse_json_filename(const char *filename, Error **errp)
1278 QObject *options_obj;
1279 QDict *options;
1280 int ret;
1282 ret = strstart(filename, "json:", &filename);
1283 assert(ret);
1285 options_obj = qobject_from_json(filename, errp);
1286 if (!options_obj) {
1287 /* Work around qobject_from_json() lossage TODO fix that */
1288 if (errp && !*errp) {
1289 error_setg(errp, "Could not parse the JSON options");
1290 return NULL;
1292 error_prepend(errp, "Could not parse the JSON options: ");
1293 return NULL;
1296 options = qobject_to_qdict(options_obj);
1297 if (!options) {
1298 qobject_decref(options_obj);
1299 error_setg(errp, "Invalid JSON object given");
1300 return NULL;
1303 qdict_flatten(options);
1305 return options;
1308 static void parse_json_protocol(QDict *options, const char **pfilename,
1309 Error **errp)
1311 QDict *json_options;
1312 Error *local_err = NULL;
1314 /* Parse json: pseudo-protocol */
1315 if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1316 return;
1319 json_options = parse_json_filename(*pfilename, &local_err);
1320 if (local_err) {
1321 error_propagate(errp, local_err);
1322 return;
1325 /* Options given in the filename have lower priority than options
1326 * specified directly */
1327 qdict_join(options, json_options, false);
1328 QDECREF(json_options);
1329 *pfilename = NULL;
1333 * Fills in default options for opening images and converts the legacy
1334 * filename/flags pair to option QDict entries.
1335 * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1336 * block driver has been specified explicitly.
1338 static int bdrv_fill_options(QDict **options, const char *filename,
1339 int *flags, Error **errp)
1341 const char *drvname;
1342 bool protocol = *flags & BDRV_O_PROTOCOL;
1343 bool parse_filename = false;
1344 BlockDriver *drv = NULL;
1345 Error *local_err = NULL;
1348 * Caution: while qdict_get_try_str() is fine, getting non-string
1349 * types would require more care. When @options come from
1350 * -blockdev or blockdev_add, its members are typed according to
1351 * the QAPI schema, but when they come from -drive, they're all
1352 * QString.
1354 drvname = qdict_get_try_str(*options, "driver");
1355 if (drvname) {
1356 drv = bdrv_find_format(drvname);
1357 if (!drv) {
1358 error_setg(errp, "Unknown driver '%s'", drvname);
1359 return -ENOENT;
1361 /* If the user has explicitly specified the driver, this choice should
1362 * override the BDRV_O_PROTOCOL flag */
1363 protocol = drv->bdrv_file_open;
1366 if (protocol) {
1367 *flags |= BDRV_O_PROTOCOL;
1368 } else {
1369 *flags &= ~BDRV_O_PROTOCOL;
1372 /* Translate cache options from flags into options */
1373 update_options_from_flags(*options, *flags);
1375 /* Fetch the file name from the options QDict if necessary */
1376 if (protocol && filename) {
1377 if (!qdict_haskey(*options, "filename")) {
1378 qdict_put(*options, "filename", qstring_from_str(filename));
1379 parse_filename = true;
1380 } else {
1381 error_setg(errp, "Can't specify 'file' and 'filename' options at "
1382 "the same time");
1383 return -EINVAL;
1387 /* Find the right block driver */
1388 /* See cautionary note on accessing @options above */
1389 filename = qdict_get_try_str(*options, "filename");
1391 if (!drvname && protocol) {
1392 if (filename) {
1393 drv = bdrv_find_protocol(filename, parse_filename, errp);
1394 if (!drv) {
1395 return -EINVAL;
1398 drvname = drv->format_name;
1399 qdict_put(*options, "driver", qstring_from_str(drvname));
1400 } else {
1401 error_setg(errp, "Must specify either driver or file");
1402 return -EINVAL;
1406 assert(drv || !protocol);
1408 /* Driver-specific filename parsing */
1409 if (drv && drv->bdrv_parse_filename && parse_filename) {
1410 drv->bdrv_parse_filename(filename, *options, &local_err);
1411 if (local_err) {
1412 error_propagate(errp, local_err);
1413 return -EINVAL;
1416 if (!drv->bdrv_needs_filename) {
1417 qdict_del(*options, "filename");
1421 return 0;
1424 static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1425 GSList *ignore_children, Error **errp);
1426 static void bdrv_child_abort_perm_update(BdrvChild *c);
1427 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1430 * Check whether permissions on this node can be changed in a way that
1431 * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1432 * permissions of all its parents. This involves checking whether all necessary
1433 * permission changes to child nodes can be performed.
1435 * A call to this function must always be followed by a call to bdrv_set_perm()
1436 * or bdrv_abort_perm_update().
1438 static int bdrv_check_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1439 uint64_t cumulative_shared_perms,
1440 GSList *ignore_children, Error **errp)
1442 BlockDriver *drv = bs->drv;
1443 BdrvChild *c;
1444 int ret;
1446 /* Write permissions never work with read-only images */
1447 if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
1448 bdrv_is_read_only(bs))
1450 error_setg(errp, "Block node is read-only");
1451 return -EPERM;
1454 /* Check this node */
1455 if (!drv) {
1456 return 0;
1459 if (drv->bdrv_check_perm) {
1460 return drv->bdrv_check_perm(bs, cumulative_perms,
1461 cumulative_shared_perms, errp);
1464 /* Drivers that never have children can omit .bdrv_child_perm() */
1465 if (!drv->bdrv_child_perm) {
1466 assert(QLIST_EMPTY(&bs->children));
1467 return 0;
1470 /* Check all children */
1471 QLIST_FOREACH(c, &bs->children, next) {
1472 uint64_t cur_perm, cur_shared;
1473 drv->bdrv_child_perm(bs, c, c->role,
1474 cumulative_perms, cumulative_shared_perms,
1475 &cur_perm, &cur_shared);
1476 ret = bdrv_child_check_perm(c, cur_perm, cur_shared, ignore_children,
1477 errp);
1478 if (ret < 0) {
1479 return ret;
1483 return 0;
1487 * Notifies drivers that after a previous bdrv_check_perm() call, the
1488 * permission update is not performed and any preparations made for it (e.g.
1489 * taken file locks) need to be undone.
1491 * This function recursively notifies all child nodes.
1493 static void bdrv_abort_perm_update(BlockDriverState *bs)
1495 BlockDriver *drv = bs->drv;
1496 BdrvChild *c;
1498 if (!drv) {
1499 return;
1502 if (drv->bdrv_abort_perm_update) {
1503 drv->bdrv_abort_perm_update(bs);
1506 QLIST_FOREACH(c, &bs->children, next) {
1507 bdrv_child_abort_perm_update(c);
1511 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1512 uint64_t cumulative_shared_perms)
1514 BlockDriver *drv = bs->drv;
1515 BdrvChild *c;
1517 if (!drv) {
1518 return;
1521 /* Update this node */
1522 if (drv->bdrv_set_perm) {
1523 drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1526 /* Drivers that never have children can omit .bdrv_child_perm() */
1527 if (!drv->bdrv_child_perm) {
1528 assert(QLIST_EMPTY(&bs->children));
1529 return;
1532 /* Update all children */
1533 QLIST_FOREACH(c, &bs->children, next) {
1534 uint64_t cur_perm, cur_shared;
1535 drv->bdrv_child_perm(bs, c, c->role,
1536 cumulative_perms, cumulative_shared_perms,
1537 &cur_perm, &cur_shared);
1538 bdrv_child_set_perm(c, cur_perm, cur_shared);
1542 static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1543 uint64_t *shared_perm)
1545 BdrvChild *c;
1546 uint64_t cumulative_perms = 0;
1547 uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1549 QLIST_FOREACH(c, &bs->parents, next_parent) {
1550 cumulative_perms |= c->perm;
1551 cumulative_shared_perms &= c->shared_perm;
1554 *perm = cumulative_perms;
1555 *shared_perm = cumulative_shared_perms;
1558 static char *bdrv_child_user_desc(BdrvChild *c)
1560 if (c->role->get_parent_desc) {
1561 return c->role->get_parent_desc(c);
1564 return g_strdup("another user");
1567 static char *bdrv_perm_names(uint64_t perm)
1569 struct perm_name {
1570 uint64_t perm;
1571 const char *name;
1572 } permissions[] = {
1573 { BLK_PERM_CONSISTENT_READ, "consistent read" },
1574 { BLK_PERM_WRITE, "write" },
1575 { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1576 { BLK_PERM_RESIZE, "resize" },
1577 { BLK_PERM_GRAPH_MOD, "change children" },
1578 { 0, NULL }
1581 char *result = g_strdup("");
1582 struct perm_name *p;
1584 for (p = permissions; p->name; p++) {
1585 if (perm & p->perm) {
1586 char *old = result;
1587 result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
1588 g_free(old);
1592 return result;
1596 * Checks whether a new reference to @bs can be added if the new user requires
1597 * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
1598 * set, the BdrvChild objects in this list are ignored in the calculations;
1599 * this allows checking permission updates for an existing reference.
1601 * Needs to be followed by a call to either bdrv_set_perm() or
1602 * bdrv_abort_perm_update(). */
1603 static int bdrv_check_update_perm(BlockDriverState *bs, uint64_t new_used_perm,
1604 uint64_t new_shared_perm,
1605 GSList *ignore_children, Error **errp)
1607 BdrvChild *c;
1608 uint64_t cumulative_perms = new_used_perm;
1609 uint64_t cumulative_shared_perms = new_shared_perm;
1611 /* There is no reason why anyone couldn't tolerate write_unchanged */
1612 assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
1614 QLIST_FOREACH(c, &bs->parents, next_parent) {
1615 if (g_slist_find(ignore_children, c)) {
1616 continue;
1619 if ((new_used_perm & c->shared_perm) != new_used_perm) {
1620 char *user = bdrv_child_user_desc(c);
1621 char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
1622 error_setg(errp, "Conflicts with use by %s as '%s', which does not "
1623 "allow '%s' on %s",
1624 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1625 g_free(user);
1626 g_free(perm_names);
1627 return -EPERM;
1630 if ((c->perm & new_shared_perm) != c->perm) {
1631 char *user = bdrv_child_user_desc(c);
1632 char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
1633 error_setg(errp, "Conflicts with use by %s as '%s', which uses "
1634 "'%s' on %s",
1635 user, c->name, perm_names, bdrv_get_node_name(c->bs));
1636 g_free(user);
1637 g_free(perm_names);
1638 return -EPERM;
1641 cumulative_perms |= c->perm;
1642 cumulative_shared_perms &= c->shared_perm;
1645 return bdrv_check_perm(bs, cumulative_perms, cumulative_shared_perms,
1646 ignore_children, errp);
1649 /* Needs to be followed by a call to either bdrv_child_set_perm() or
1650 * bdrv_child_abort_perm_update(). */
1651 static int bdrv_child_check_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1652 GSList *ignore_children, Error **errp)
1654 int ret;
1656 ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
1657 ret = bdrv_check_update_perm(c->bs, perm, shared, ignore_children, errp);
1658 g_slist_free(ignore_children);
1660 return ret;
1663 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
1665 uint64_t cumulative_perms, cumulative_shared_perms;
1667 c->perm = perm;
1668 c->shared_perm = shared;
1670 bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
1671 &cumulative_shared_perms);
1672 bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
1675 static void bdrv_child_abort_perm_update(BdrvChild *c)
1677 bdrv_abort_perm_update(c->bs);
1680 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
1681 Error **errp)
1683 int ret;
1685 ret = bdrv_child_check_perm(c, perm, shared, NULL, errp);
1686 if (ret < 0) {
1687 bdrv_child_abort_perm_update(c);
1688 return ret;
1691 bdrv_child_set_perm(c, perm, shared);
1693 return 0;
1696 #define DEFAULT_PERM_PASSTHROUGH (BLK_PERM_CONSISTENT_READ \
1697 | BLK_PERM_WRITE \
1698 | BLK_PERM_WRITE_UNCHANGED \
1699 | BLK_PERM_RESIZE)
1700 #define DEFAULT_PERM_UNCHANGED (BLK_PERM_ALL & ~DEFAULT_PERM_PASSTHROUGH)
1702 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
1703 const BdrvChildRole *role,
1704 uint64_t perm, uint64_t shared,
1705 uint64_t *nperm, uint64_t *nshared)
1707 if (c == NULL) {
1708 *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
1709 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
1710 return;
1713 *nperm = (perm & DEFAULT_PERM_PASSTHROUGH) |
1714 (c->perm & DEFAULT_PERM_UNCHANGED);
1715 *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) |
1716 (c->shared_perm & DEFAULT_PERM_UNCHANGED);
1719 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
1720 const BdrvChildRole *role,
1721 uint64_t perm, uint64_t shared,
1722 uint64_t *nperm, uint64_t *nshared)
1724 bool backing = (role == &child_backing);
1725 assert(role == &child_backing || role == &child_file);
1727 if (!backing) {
1728 /* Apart from the modifications below, the same permissions are
1729 * forwarded and left alone as for filters */
1730 bdrv_filter_default_perms(bs, c, role, perm, shared, &perm, &shared);
1732 /* Format drivers may touch metadata even if the guest doesn't write */
1733 if (!bdrv_is_read_only(bs)) {
1734 perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
1737 /* bs->file always needs to be consistent because of the metadata. We
1738 * can never allow other users to resize or write to it. */
1739 perm |= BLK_PERM_CONSISTENT_READ;
1740 shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
1741 } else {
1742 /* We want consistent read from backing files if the parent needs it.
1743 * No other operations are performed on backing files. */
1744 perm &= BLK_PERM_CONSISTENT_READ;
1746 /* If the parent can deal with changing data, we're okay with a
1747 * writable and resizable backing file. */
1748 /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
1749 if (shared & BLK_PERM_WRITE) {
1750 shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
1751 } else {
1752 shared = 0;
1755 shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
1756 BLK_PERM_WRITE_UNCHANGED;
1759 *nperm = perm;
1760 *nshared = shared;
1763 static void bdrv_replace_child_noperm(BdrvChild *child,
1764 BlockDriverState *new_bs)
1766 BlockDriverState *old_bs = child->bs;
1768 if (old_bs && new_bs) {
1769 assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
1771 if (old_bs) {
1772 if (old_bs->quiesce_counter && child->role->drained_end) {
1773 child->role->drained_end(child);
1775 if (child->role->detach) {
1776 child->role->detach(child);
1778 QLIST_REMOVE(child, next_parent);
1781 child->bs = new_bs;
1783 if (new_bs) {
1784 QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
1785 if (new_bs->quiesce_counter && child->role->drained_begin) {
1786 child->role->drained_begin(child);
1789 if (child->role->attach) {
1790 child->role->attach(child);
1796 * Updates @child to change its reference to point to @new_bs, including
1797 * checking and applying the necessary permisson updates both to the old node
1798 * and to @new_bs.
1800 * NULL is passed as @new_bs for removing the reference before freeing @child.
1802 * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
1803 * function uses bdrv_set_perm() to update the permissions according to the new
1804 * reference that @new_bs gets.
1806 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
1808 BlockDriverState *old_bs = child->bs;
1809 uint64_t perm, shared_perm;
1811 if (old_bs) {
1812 /* Update permissions for old node. This is guaranteed to succeed
1813 * because we're just taking a parent away, so we're loosening
1814 * restrictions. */
1815 bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
1816 bdrv_check_perm(old_bs, perm, shared_perm, NULL, &error_abort);
1817 bdrv_set_perm(old_bs, perm, shared_perm);
1820 bdrv_replace_child_noperm(child, new_bs);
1822 if (new_bs) {
1823 bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
1824 bdrv_set_perm(new_bs, perm, shared_perm);
1828 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1829 const char *child_name,
1830 const BdrvChildRole *child_role,
1831 uint64_t perm, uint64_t shared_perm,
1832 void *opaque, Error **errp)
1834 BdrvChild *child;
1835 int ret;
1837 ret = bdrv_check_update_perm(child_bs, perm, shared_perm, NULL, errp);
1838 if (ret < 0) {
1839 bdrv_abort_perm_update(child_bs);
1840 return NULL;
1843 child = g_new(BdrvChild, 1);
1844 *child = (BdrvChild) {
1845 .bs = NULL,
1846 .name = g_strdup(child_name),
1847 .role = child_role,
1848 .perm = perm,
1849 .shared_perm = shared_perm,
1850 .opaque = opaque,
1853 /* This performs the matching bdrv_set_perm() for the above check. */
1854 bdrv_replace_child(child, child_bs);
1856 return child;
1859 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1860 BlockDriverState *child_bs,
1861 const char *child_name,
1862 const BdrvChildRole *child_role,
1863 Error **errp)
1865 BdrvChild *child;
1866 uint64_t perm, shared_perm;
1868 bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
1870 assert(parent_bs->drv);
1871 assert(bdrv_get_aio_context(parent_bs) == bdrv_get_aio_context(child_bs));
1872 parent_bs->drv->bdrv_child_perm(parent_bs, NULL, child_role,
1873 perm, shared_perm, &perm, &shared_perm);
1875 child = bdrv_root_attach_child(child_bs, child_name, child_role,
1876 perm, shared_perm, parent_bs, errp);
1877 if (child == NULL) {
1878 return NULL;
1881 QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1882 return child;
1885 static void bdrv_detach_child(BdrvChild *child)
1887 if (child->next.le_prev) {
1888 QLIST_REMOVE(child, next);
1889 child->next.le_prev = NULL;
1892 bdrv_replace_child(child, NULL);
1894 g_free(child->name);
1895 g_free(child);
1898 void bdrv_root_unref_child(BdrvChild *child)
1900 BlockDriverState *child_bs;
1902 child_bs = child->bs;
1903 bdrv_detach_child(child);
1904 bdrv_unref(child_bs);
1907 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1909 if (child == NULL) {
1910 return;
1913 if (child->bs->inherits_from == parent) {
1914 BdrvChild *c;
1916 /* Remove inherits_from only when the last reference between parent and
1917 * child->bs goes away. */
1918 QLIST_FOREACH(c, &parent->children, next) {
1919 if (c != child && c->bs == child->bs) {
1920 break;
1923 if (c == NULL) {
1924 child->bs->inherits_from = NULL;
1928 bdrv_root_unref_child(child);
1932 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
1934 BdrvChild *c;
1935 QLIST_FOREACH(c, &bs->parents, next_parent) {
1936 if (c->role->change_media) {
1937 c->role->change_media(c, load);
1942 static void bdrv_parent_cb_resize(BlockDriverState *bs)
1944 BdrvChild *c;
1945 QLIST_FOREACH(c, &bs->parents, next_parent) {
1946 if (c->role->resize) {
1947 c->role->resize(c);
1953 * Sets the backing file link of a BDS. A new reference is created; callers
1954 * which don't need their own reference any more must call bdrv_unref().
1956 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
1957 Error **errp)
1959 if (backing_hd) {
1960 bdrv_ref(backing_hd);
1963 if (bs->backing) {
1964 bdrv_unref_child(bs, bs->backing);
1967 if (!backing_hd) {
1968 bs->backing = NULL;
1969 goto out;
1972 bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
1973 errp);
1974 if (!bs->backing) {
1975 bdrv_unref(backing_hd);
1978 bdrv_refresh_filename(bs);
1980 out:
1981 bdrv_refresh_limits(bs, NULL);
1985 * Opens the backing file for a BlockDriverState if not yet open
1987 * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1988 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1989 * itself, all options starting with "${bdref_key}." are considered part of the
1990 * BlockdevRef.
1992 * TODO Can this be unified with bdrv_open_image()?
1994 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1995 const char *bdref_key, Error **errp)
1997 char *backing_filename = g_malloc0(PATH_MAX);
1998 char *bdref_key_dot;
1999 const char *reference = NULL;
2000 int ret = 0;
2001 BlockDriverState *backing_hd;
2002 QDict *options;
2003 QDict *tmp_parent_options = NULL;
2004 Error *local_err = NULL;
2006 if (bs->backing != NULL) {
2007 goto free_exit;
2010 /* NULL means an empty set of options */
2011 if (parent_options == NULL) {
2012 tmp_parent_options = qdict_new();
2013 parent_options = tmp_parent_options;
2016 bs->open_flags &= ~BDRV_O_NO_BACKING;
2018 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2019 qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2020 g_free(bdref_key_dot);
2023 * Caution: while qdict_get_try_str() is fine, getting non-string
2024 * types would require more care. When @parent_options come from
2025 * -blockdev or blockdev_add, its members are typed according to
2026 * the QAPI schema, but when they come from -drive, they're all
2027 * QString.
2029 reference = qdict_get_try_str(parent_options, bdref_key);
2030 if (reference || qdict_haskey(options, "file.filename")) {
2031 backing_filename[0] = '\0';
2032 } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2033 QDECREF(options);
2034 goto free_exit;
2035 } else {
2036 bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
2037 &local_err);
2038 if (local_err) {
2039 ret = -EINVAL;
2040 error_propagate(errp, local_err);
2041 QDECREF(options);
2042 goto free_exit;
2046 if (!bs->drv || !bs->drv->supports_backing) {
2047 ret = -EINVAL;
2048 error_setg(errp, "Driver doesn't support backing files");
2049 QDECREF(options);
2050 goto free_exit;
2053 if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2054 qdict_put(options, "driver", qstring_from_str(bs->backing_format));
2057 backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
2058 reference, options, 0, bs, &child_backing,
2059 errp);
2060 if (!backing_hd) {
2061 bs->open_flags |= BDRV_O_NO_BACKING;
2062 error_prepend(errp, "Could not open backing file: ");
2063 ret = -EINVAL;
2064 goto free_exit;
2067 /* Hook up the backing file link; drop our reference, bs owns the
2068 * backing_hd reference now */
2069 bdrv_set_backing_hd(bs, backing_hd, &local_err);
2070 bdrv_unref(backing_hd);
2071 if (local_err) {
2072 error_propagate(errp, local_err);
2073 ret = -EINVAL;
2074 goto free_exit;
2077 qdict_del(parent_options, bdref_key);
2079 free_exit:
2080 g_free(backing_filename);
2081 QDECREF(tmp_parent_options);
2082 return ret;
2085 static BlockDriverState *
2086 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2087 BlockDriverState *parent, const BdrvChildRole *child_role,
2088 bool allow_none, Error **errp)
2090 BlockDriverState *bs = NULL;
2091 QDict *image_options;
2092 char *bdref_key_dot;
2093 const char *reference;
2095 assert(child_role != NULL);
2097 bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2098 qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2099 g_free(bdref_key_dot);
2102 * Caution: while qdict_get_try_str() is fine, getting non-string
2103 * types would require more care. When @options come from
2104 * -blockdev or blockdev_add, its members are typed according to
2105 * the QAPI schema, but when they come from -drive, they're all
2106 * QString.
2108 reference = qdict_get_try_str(options, bdref_key);
2109 if (!filename && !reference && !qdict_size(image_options)) {
2110 if (!allow_none) {
2111 error_setg(errp, "A block device must be specified for \"%s\"",
2112 bdref_key);
2114 QDECREF(image_options);
2115 goto done;
2118 bs = bdrv_open_inherit(filename, reference, image_options, 0,
2119 parent, child_role, errp);
2120 if (!bs) {
2121 goto done;
2124 done:
2125 qdict_del(options, bdref_key);
2126 return bs;
2130 * Opens a disk image whose options are given as BlockdevRef in another block
2131 * device's options.
2133 * If allow_none is true, no image will be opened if filename is false and no
2134 * BlockdevRef is given. NULL will be returned, but errp remains unset.
2136 * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2137 * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2138 * itself, all options starting with "${bdref_key}." are considered part of the
2139 * BlockdevRef.
2141 * The BlockdevRef will be removed from the options QDict.
2143 BdrvChild *bdrv_open_child(const char *filename,
2144 QDict *options, const char *bdref_key,
2145 BlockDriverState *parent,
2146 const BdrvChildRole *child_role,
2147 bool allow_none, Error **errp)
2149 BdrvChild *c;
2150 BlockDriverState *bs;
2152 bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2153 allow_none, errp);
2154 if (bs == NULL) {
2155 return NULL;
2158 c = bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2159 if (!c) {
2160 bdrv_unref(bs);
2161 return NULL;
2164 return c;
2167 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2168 int flags,
2169 QDict *snapshot_options,
2170 Error **errp)
2172 /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
2173 char *tmp_filename = g_malloc0(PATH_MAX + 1);
2174 int64_t total_size;
2175 QemuOpts *opts = NULL;
2176 BlockDriverState *bs_snapshot;
2177 Error *local_err = NULL;
2178 int ret;
2180 /* if snapshot, we create a temporary backing file and open it
2181 instead of opening 'filename' directly */
2183 /* Get the required size from the image */
2184 total_size = bdrv_getlength(bs);
2185 if (total_size < 0) {
2186 error_setg_errno(errp, -total_size, "Could not get image size");
2187 goto out;
2190 /* Create the temporary image */
2191 ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
2192 if (ret < 0) {
2193 error_setg_errno(errp, -ret, "Could not get temporary filename");
2194 goto out;
2197 opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
2198 &error_abort);
2199 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
2200 ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
2201 qemu_opts_del(opts);
2202 if (ret < 0) {
2203 error_prepend(errp, "Could not create temporary overlay '%s': ",
2204 tmp_filename);
2205 goto out;
2208 /* Prepare options QDict for the temporary file */
2209 qdict_put(snapshot_options, "file.driver",
2210 qstring_from_str("file"));
2211 qdict_put(snapshot_options, "file.filename",
2212 qstring_from_str(tmp_filename));
2213 qdict_put(snapshot_options, "driver",
2214 qstring_from_str("qcow2"));
2216 bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
2217 snapshot_options = NULL;
2218 if (!bs_snapshot) {
2219 ret = -EINVAL;
2220 goto out;
2223 /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
2224 * call bdrv_unref() on it), so in order to be able to return one, we have
2225 * to increase bs_snapshot's refcount here */
2226 bdrv_ref(bs_snapshot);
2227 bdrv_append(bs_snapshot, bs, &local_err);
2228 if (local_err) {
2229 error_propagate(errp, local_err);
2230 ret = -EINVAL;
2231 goto out;
2234 g_free(tmp_filename);
2235 return bs_snapshot;
2237 out:
2238 QDECREF(snapshot_options);
2239 g_free(tmp_filename);
2240 return NULL;
2244 * Opens a disk image (raw, qcow2, vmdk, ...)
2246 * options is a QDict of options to pass to the block drivers, or NULL for an
2247 * empty set of options. The reference to the QDict belongs to the block layer
2248 * after the call (even on failure), so if the caller intends to reuse the
2249 * dictionary, it needs to use QINCREF() before calling bdrv_open.
2251 * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2252 * If it is not NULL, the referenced BDS will be reused.
2254 * The reference parameter may be used to specify an existing block device which
2255 * should be opened. If specified, neither options nor a filename may be given,
2256 * nor can an existing BDS be reused (that is, *pbs has to be NULL).
2258 static BlockDriverState *bdrv_open_inherit(const char *filename,
2259 const char *reference,
2260 QDict *options, int flags,
2261 BlockDriverState *parent,
2262 const BdrvChildRole *child_role,
2263 Error **errp)
2265 int ret;
2266 BlockBackend *file = NULL;
2267 BlockDriverState *bs;
2268 BlockDriver *drv = NULL;
2269 const char *drvname;
2270 const char *backing;
2271 Error *local_err = NULL;
2272 QDict *snapshot_options = NULL;
2273 int snapshot_flags = 0;
2275 assert(!child_role || !flags);
2276 assert(!child_role == !parent);
2278 if (reference) {
2279 bool options_non_empty = options ? qdict_size(options) : false;
2280 QDECREF(options);
2282 if (filename || options_non_empty) {
2283 error_setg(errp, "Cannot reference an existing block device with "
2284 "additional options or a new filename");
2285 return NULL;
2288 bs = bdrv_lookup_bs(reference, reference, errp);
2289 if (!bs) {
2290 return NULL;
2293 bdrv_ref(bs);
2294 return bs;
2297 bs = bdrv_new();
2299 /* NULL means an empty set of options */
2300 if (options == NULL) {
2301 options = qdict_new();
2304 /* json: syntax counts as explicit options, as if in the QDict */
2305 parse_json_protocol(options, &filename, &local_err);
2306 if (local_err) {
2307 goto fail;
2310 bs->explicit_options = qdict_clone_shallow(options);
2312 if (child_role) {
2313 bs->inherits_from = parent;
2314 child_role->inherit_options(&flags, options,
2315 parent->open_flags, parent->options);
2318 ret = bdrv_fill_options(&options, filename, &flags, &local_err);
2319 if (local_err) {
2320 goto fail;
2324 * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
2325 * Caution: getting a boolean member of @options requires care.
2326 * When @options come from -blockdev or blockdev_add, members are
2327 * typed according to the QAPI schema, but when they come from
2328 * -drive, they're all QString.
2330 if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
2331 !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
2332 flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
2333 } else {
2334 flags &= ~BDRV_O_RDWR;
2337 if (flags & BDRV_O_SNAPSHOT) {
2338 snapshot_options = qdict_new();
2339 bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
2340 flags, options);
2341 /* Let bdrv_backing_options() override "read-only" */
2342 qdict_del(options, BDRV_OPT_READ_ONLY);
2343 bdrv_backing_options(&flags, options, flags, options);
2346 bs->open_flags = flags;
2347 bs->options = options;
2348 options = qdict_clone_shallow(options);
2350 /* Find the right image format driver */
2351 /* See cautionary note on accessing @options above */
2352 drvname = qdict_get_try_str(options, "driver");
2353 if (drvname) {
2354 drv = bdrv_find_format(drvname);
2355 if (!drv) {
2356 error_setg(errp, "Unknown driver: '%s'", drvname);
2357 goto fail;
2361 assert(drvname || !(flags & BDRV_O_PROTOCOL));
2363 /* See cautionary note on accessing @options above */
2364 backing = qdict_get_try_str(options, "backing");
2365 if (backing && *backing == '\0') {
2366 flags |= BDRV_O_NO_BACKING;
2367 qdict_del(options, "backing");
2370 /* Open image file without format layer. This BlockBackend is only used for
2371 * probing, the block drivers will do their own bdrv_open_child() for the
2372 * same BDS, which is why we put the node name back into options. */
2373 if ((flags & BDRV_O_PROTOCOL) == 0) {
2374 BlockDriverState *file_bs;
2376 file_bs = bdrv_open_child_bs(filename, options, "file", bs,
2377 &child_file, true, &local_err);
2378 if (local_err) {
2379 goto fail;
2381 if (file_bs != NULL) {
2382 file = blk_new(BLK_PERM_CONSISTENT_READ, BLK_PERM_ALL);
2383 blk_insert_bs(file, file_bs, &local_err);
2384 bdrv_unref(file_bs);
2385 if (local_err) {
2386 goto fail;
2389 qdict_put(options, "file",
2390 qstring_from_str(bdrv_get_node_name(file_bs)));
2394 /* Image format probing */
2395 bs->probed = !drv;
2396 if (!drv && file) {
2397 ret = find_image_format(file, filename, &drv, &local_err);
2398 if (ret < 0) {
2399 goto fail;
2402 * This option update would logically belong in bdrv_fill_options(),
2403 * but we first need to open bs->file for the probing to work, while
2404 * opening bs->file already requires the (mostly) final set of options
2405 * so that cache mode etc. can be inherited.
2407 * Adding the driver later is somewhat ugly, but it's not an option
2408 * that would ever be inherited, so it's correct. We just need to make
2409 * sure to update both bs->options (which has the full effective
2410 * options for bs) and options (which has file.* already removed).
2412 qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
2413 qdict_put(options, "driver", qstring_from_str(drv->format_name));
2414 } else if (!drv) {
2415 error_setg(errp, "Must specify either driver or file");
2416 goto fail;
2419 /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
2420 assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
2421 /* file must be NULL if a protocol BDS is about to be created
2422 * (the inverse results in an error message from bdrv_open_common()) */
2423 assert(!(flags & BDRV_O_PROTOCOL) || !file);
2425 /* Open the image */
2426 ret = bdrv_open_common(bs, file, options, &local_err);
2427 if (ret < 0) {
2428 goto fail;
2431 if (file) {
2432 blk_unref(file);
2433 file = NULL;
2436 /* If there is a backing file, use it */
2437 if ((flags & BDRV_O_NO_BACKING) == 0) {
2438 ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
2439 if (ret < 0) {
2440 goto close_and_fail;
2444 bdrv_refresh_filename(bs);
2446 /* Check if any unknown options were used */
2447 if (qdict_size(options) != 0) {
2448 const QDictEntry *entry = qdict_first(options);
2449 if (flags & BDRV_O_PROTOCOL) {
2450 error_setg(errp, "Block protocol '%s' doesn't support the option "
2451 "'%s'", drv->format_name, entry->key);
2452 } else {
2453 error_setg(errp,
2454 "Block format '%s' does not support the option '%s'",
2455 drv->format_name, entry->key);
2458 goto close_and_fail;
2461 if (!bdrv_key_required(bs)) {
2462 bdrv_parent_cb_change_media(bs, true);
2463 } else if (!runstate_check(RUN_STATE_PRELAUNCH)
2464 && !runstate_check(RUN_STATE_INMIGRATE)
2465 && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
2466 error_setg(errp,
2467 "Guest must be stopped for opening of encrypted image");
2468 goto close_and_fail;
2471 QDECREF(options);
2473 /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
2474 * temporary snapshot afterwards. */
2475 if (snapshot_flags) {
2476 BlockDriverState *snapshot_bs;
2477 snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
2478 snapshot_options, &local_err);
2479 snapshot_options = NULL;
2480 if (local_err) {
2481 goto close_and_fail;
2483 /* We are not going to return bs but the overlay on top of it
2484 * (snapshot_bs); thus, we have to drop the strong reference to bs
2485 * (which we obtained by calling bdrv_new()). bs will not be deleted,
2486 * though, because the overlay still has a reference to it. */
2487 bdrv_unref(bs);
2488 bs = snapshot_bs;
2491 return bs;
2493 fail:
2494 blk_unref(file);
2495 if (bs->file != NULL) {
2496 bdrv_unref_child(bs, bs->file);
2498 QDECREF(snapshot_options);
2499 QDECREF(bs->explicit_options);
2500 QDECREF(bs->options);
2501 QDECREF(options);
2502 bs->options = NULL;
2503 bdrv_unref(bs);
2504 error_propagate(errp, local_err);
2505 return NULL;
2507 close_and_fail:
2508 bdrv_unref(bs);
2509 QDECREF(snapshot_options);
2510 QDECREF(options);
2511 error_propagate(errp, local_err);
2512 return NULL;
2515 BlockDriverState *bdrv_open(const char *filename, const char *reference,
2516 QDict *options, int flags, Error **errp)
2518 return bdrv_open_inherit(filename, reference, options, flags, NULL,
2519 NULL, errp);
2522 typedef struct BlockReopenQueueEntry {
2523 bool prepared;
2524 BDRVReopenState state;
2525 QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
2526 } BlockReopenQueueEntry;
2529 * Adds a BlockDriverState to a simple queue for an atomic, transactional
2530 * reopen of multiple devices.
2532 * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
2533 * already performed, or alternatively may be NULL a new BlockReopenQueue will
2534 * be created and initialized. This newly created BlockReopenQueue should be
2535 * passed back in for subsequent calls that are intended to be of the same
2536 * atomic 'set'.
2538 * bs is the BlockDriverState to add to the reopen queue.
2540 * options contains the changed options for the associated bs
2541 * (the BlockReopenQueue takes ownership)
2543 * flags contains the open flags for the associated bs
2545 * returns a pointer to bs_queue, which is either the newly allocated
2546 * bs_queue, or the existing bs_queue being used.
2549 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
2550 BlockDriverState *bs,
2551 QDict *options,
2552 int flags,
2553 const BdrvChildRole *role,
2554 QDict *parent_options,
2555 int parent_flags)
2557 assert(bs != NULL);
2559 BlockReopenQueueEntry *bs_entry;
2560 BdrvChild *child;
2561 QDict *old_options, *explicit_options;
2563 if (bs_queue == NULL) {
2564 bs_queue = g_new0(BlockReopenQueue, 1);
2565 QSIMPLEQ_INIT(bs_queue);
2568 if (!options) {
2569 options = qdict_new();
2572 /* Check if this BlockDriverState is already in the queue */
2573 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2574 if (bs == bs_entry->state.bs) {
2575 break;
2580 * Precedence of options:
2581 * 1. Explicitly passed in options (highest)
2582 * 2. Set in flags (only for top level)
2583 * 3. Retained from explicitly set options of bs
2584 * 4. Inherited from parent node
2585 * 5. Retained from effective options of bs
2588 if (!parent_options) {
2590 * Any setting represented by flags is always updated. If the
2591 * corresponding QDict option is set, it takes precedence. Otherwise
2592 * the flag is translated into a QDict option. The old setting of bs is
2593 * not considered.
2595 update_options_from_flags(options, flags);
2598 /* Old explicitly set values (don't overwrite by inherited value) */
2599 if (bs_entry) {
2600 old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
2601 } else {
2602 old_options = qdict_clone_shallow(bs->explicit_options);
2604 bdrv_join_options(bs, options, old_options);
2605 QDECREF(old_options);
2607 explicit_options = qdict_clone_shallow(options);
2609 /* Inherit from parent node */
2610 if (parent_options) {
2611 assert(!flags);
2612 role->inherit_options(&flags, options, parent_flags, parent_options);
2615 /* Old values are used for options that aren't set yet */
2616 old_options = qdict_clone_shallow(bs->options);
2617 bdrv_join_options(bs, options, old_options);
2618 QDECREF(old_options);
2620 /* bdrv_open() masks this flag out */
2621 flags &= ~BDRV_O_PROTOCOL;
2623 QLIST_FOREACH(child, &bs->children, next) {
2624 QDict *new_child_options;
2625 char *child_key_dot;
2627 /* reopen can only change the options of block devices that were
2628 * implicitly created and inherited options. For other (referenced)
2629 * block devices, a syntax like "backing.foo" results in an error. */
2630 if (child->bs->inherits_from != bs) {
2631 continue;
2634 child_key_dot = g_strdup_printf("%s.", child->name);
2635 qdict_extract_subqdict(options, &new_child_options, child_key_dot);
2636 g_free(child_key_dot);
2638 bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
2639 child->role, options, flags);
2642 if (!bs_entry) {
2643 bs_entry = g_new0(BlockReopenQueueEntry, 1);
2644 QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
2645 } else {
2646 QDECREF(bs_entry->state.options);
2647 QDECREF(bs_entry->state.explicit_options);
2650 bs_entry->state.bs = bs;
2651 bs_entry->state.options = options;
2652 bs_entry->state.explicit_options = explicit_options;
2653 bs_entry->state.flags = flags;
2655 return bs_queue;
2658 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
2659 BlockDriverState *bs,
2660 QDict *options, int flags)
2662 return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
2663 NULL, NULL, 0);
2667 * Reopen multiple BlockDriverStates atomically & transactionally.
2669 * The queue passed in (bs_queue) must have been built up previous
2670 * via bdrv_reopen_queue().
2672 * Reopens all BDS specified in the queue, with the appropriate
2673 * flags. All devices are prepared for reopen, and failure of any
2674 * device will cause all device changes to be abandonded, and intermediate
2675 * data cleaned up.
2677 * If all devices prepare successfully, then the changes are committed
2678 * to all devices.
2681 int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
2683 int ret = -1;
2684 BlockReopenQueueEntry *bs_entry, *next;
2685 Error *local_err = NULL;
2687 assert(bs_queue != NULL);
2689 aio_context_release(ctx);
2690 bdrv_drain_all_begin();
2691 aio_context_acquire(ctx);
2693 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2694 if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
2695 error_propagate(errp, local_err);
2696 goto cleanup;
2698 bs_entry->prepared = true;
2701 /* If we reach this point, we have success and just need to apply the
2702 * changes
2704 QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2705 bdrv_reopen_commit(&bs_entry->state);
2708 ret = 0;
2710 cleanup:
2711 QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
2712 if (ret && bs_entry->prepared) {
2713 bdrv_reopen_abort(&bs_entry->state);
2714 } else if (ret) {
2715 QDECREF(bs_entry->state.explicit_options);
2717 QDECREF(bs_entry->state.options);
2718 g_free(bs_entry);
2720 g_free(bs_queue);
2722 bdrv_drain_all_end();
2724 return ret;
2728 /* Reopen a single BlockDriverState with the specified flags. */
2729 int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
2731 int ret = -1;
2732 Error *local_err = NULL;
2733 BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
2735 ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
2736 if (local_err != NULL) {
2737 error_propagate(errp, local_err);
2739 return ret;
2744 * Prepares a BlockDriverState for reopen. All changes are staged in the
2745 * 'opaque' field of the BDRVReopenState, which is used and allocated by
2746 * the block driver layer .bdrv_reopen_prepare()
2748 * bs is the BlockDriverState to reopen
2749 * flags are the new open flags
2750 * queue is the reopen queue
2752 * Returns 0 on success, non-zero on error. On error errp will be set
2753 * as well.
2755 * On failure, bdrv_reopen_abort() will be called to clean up any data.
2756 * It is the responsibility of the caller to then call the abort() or
2757 * commit() for any other BDS that have been left in a prepare() state
2760 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2761 Error **errp)
2763 int ret = -1;
2764 Error *local_err = NULL;
2765 BlockDriver *drv;
2766 QemuOpts *opts;
2767 const char *value;
2769 assert(reopen_state != NULL);
2770 assert(reopen_state->bs->drv != NULL);
2771 drv = reopen_state->bs->drv;
2773 /* Process generic block layer options */
2774 opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2775 qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2776 if (local_err) {
2777 error_propagate(errp, local_err);
2778 ret = -EINVAL;
2779 goto error;
2782 update_flags_from_options(&reopen_state->flags, opts);
2784 /* node-name and driver must be unchanged. Put them back into the QDict, so
2785 * that they are checked at the end of this function. */
2786 value = qemu_opt_get(opts, "node-name");
2787 if (value) {
2788 qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2791 value = qemu_opt_get(opts, "driver");
2792 if (value) {
2793 qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2796 /* if we are to stay read-only, do not allow permission change
2797 * to r/w */
2798 if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2799 reopen_state->flags & BDRV_O_RDWR) {
2800 error_setg(errp, "Node '%s' is read only",
2801 bdrv_get_device_or_node_name(reopen_state->bs));
2802 goto error;
2806 ret = bdrv_flush(reopen_state->bs);
2807 if (ret) {
2808 error_setg_errno(errp, -ret, "Error flushing drive");
2809 goto error;
2812 if (drv->bdrv_reopen_prepare) {
2813 ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2814 if (ret) {
2815 if (local_err != NULL) {
2816 error_propagate(errp, local_err);
2817 } else {
2818 error_setg(errp, "failed while preparing to reopen image '%s'",
2819 reopen_state->bs->filename);
2821 goto error;
2823 } else {
2824 /* It is currently mandatory to have a bdrv_reopen_prepare()
2825 * handler for each supported drv. */
2826 error_setg(errp, "Block format '%s' used by node '%s' "
2827 "does not support reopening files", drv->format_name,
2828 bdrv_get_device_or_node_name(reopen_state->bs));
2829 ret = -1;
2830 goto error;
2833 /* Options that are not handled are only okay if they are unchanged
2834 * compared to the old state. It is expected that some options are only
2835 * used for the initial open, but not reopen (e.g. filename) */
2836 if (qdict_size(reopen_state->options)) {
2837 const QDictEntry *entry = qdict_first(reopen_state->options);
2839 do {
2840 QString *new_obj = qobject_to_qstring(entry->value);
2841 const char *new = qstring_get_str(new_obj);
2843 * Caution: while qdict_get_try_str() is fine, getting
2844 * non-string types would require more care. When
2845 * bs->options come from -blockdev or blockdev_add, its
2846 * members are typed according to the QAPI schema, but
2847 * when they come from -drive, they're all QString.
2849 const char *old = qdict_get_try_str(reopen_state->bs->options,
2850 entry->key);
2852 if (!old || strcmp(new, old)) {
2853 error_setg(errp, "Cannot change the option '%s'", entry->key);
2854 ret = -EINVAL;
2855 goto error;
2857 } while ((entry = qdict_next(reopen_state->options, entry)));
2860 ret = 0;
2862 error:
2863 qemu_opts_del(opts);
2864 return ret;
2868 * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2869 * makes them final by swapping the staging BlockDriverState contents into
2870 * the active BlockDriverState contents.
2872 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2874 BlockDriver *drv;
2876 assert(reopen_state != NULL);
2877 drv = reopen_state->bs->drv;
2878 assert(drv != NULL);
2880 /* If there are any driver level actions to take */
2881 if (drv->bdrv_reopen_commit) {
2882 drv->bdrv_reopen_commit(reopen_state);
2885 /* set BDS specific flags now */
2886 QDECREF(reopen_state->bs->explicit_options);
2888 reopen_state->bs->explicit_options = reopen_state->explicit_options;
2889 reopen_state->bs->open_flags = reopen_state->flags;
2890 reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2892 bdrv_refresh_limits(reopen_state->bs, NULL);
2896 * Abort the reopen, and delete and free the staged changes in
2897 * reopen_state
2899 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2901 BlockDriver *drv;
2903 assert(reopen_state != NULL);
2904 drv = reopen_state->bs->drv;
2905 assert(drv != NULL);
2907 if (drv->bdrv_reopen_abort) {
2908 drv->bdrv_reopen_abort(reopen_state);
2911 QDECREF(reopen_state->explicit_options);
2915 static void bdrv_close(BlockDriverState *bs)
2917 BdrvAioNotifier *ban, *ban_next;
2919 assert(!bs->job);
2920 assert(!bs->refcnt);
2922 bdrv_drained_begin(bs); /* complete I/O */
2923 bdrv_flush(bs);
2924 bdrv_drain(bs); /* in case flush left pending I/O */
2926 bdrv_release_named_dirty_bitmaps(bs);
2927 assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2929 if (bs->drv) {
2930 BdrvChild *child, *next;
2932 bs->drv->bdrv_close(bs);
2933 bs->drv = NULL;
2935 bdrv_set_backing_hd(bs, NULL, &error_abort);
2937 if (bs->file != NULL) {
2938 bdrv_unref_child(bs, bs->file);
2939 bs->file = NULL;
2942 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
2943 /* TODO Remove bdrv_unref() from drivers' close function and use
2944 * bdrv_unref_child() here */
2945 if (child->bs->inherits_from == bs) {
2946 child->bs->inherits_from = NULL;
2948 bdrv_detach_child(child);
2951 g_free(bs->opaque);
2952 bs->opaque = NULL;
2953 bs->copy_on_read = 0;
2954 bs->backing_file[0] = '\0';
2955 bs->backing_format[0] = '\0';
2956 bs->total_sectors = 0;
2957 bs->encrypted = false;
2958 bs->valid_key = false;
2959 bs->sg = false;
2960 QDECREF(bs->options);
2961 QDECREF(bs->explicit_options);
2962 bs->options = NULL;
2963 QDECREF(bs->full_open_options);
2964 bs->full_open_options = NULL;
2967 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
2968 g_free(ban);
2970 QLIST_INIT(&bs->aio_notifiers);
2971 bdrv_drained_end(bs);
2974 void bdrv_close_all(void)
2976 block_job_cancel_sync_all();
2977 nbd_export_close_all();
2979 /* Drop references from requests still in flight, such as canceled block
2980 * jobs whose AIO context has not been polled yet */
2981 bdrv_drain_all();
2983 blk_remove_all_bs();
2984 blockdev_close_all_bdrv_states();
2986 assert(QTAILQ_EMPTY(&all_bdrv_states));
2989 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
2991 BdrvChild *to_c;
2993 if (c->role->stay_at_node) {
2994 return false;
2997 if (c->role == &child_backing) {
2998 /* If @from is a backing file of @to, ignore the child to avoid
2999 * creating a loop. We only want to change the pointer of other
3000 * parents. */
3001 QLIST_FOREACH(to_c, &to->children, next) {
3002 if (to_c == c) {
3003 break;
3006 if (to_c) {
3007 return false;
3011 return true;
3014 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
3015 Error **errp)
3017 BdrvChild *c, *next;
3018 GSList *list = NULL, *p;
3019 uint64_t old_perm, old_shared;
3020 uint64_t perm = 0, shared = BLK_PERM_ALL;
3021 int ret;
3023 assert(!atomic_read(&from->in_flight));
3024 assert(!atomic_read(&to->in_flight));
3026 /* Make sure that @from doesn't go away until we have successfully attached
3027 * all of its parents to @to. */
3028 bdrv_ref(from);
3030 /* Put all parents into @list and calculate their cumulative permissions */
3031 QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
3032 if (!should_update_child(c, to)) {
3033 continue;
3035 list = g_slist_prepend(list, c);
3036 perm |= c->perm;
3037 shared &= c->shared_perm;
3040 /* Check whether the required permissions can be granted on @to, ignoring
3041 * all BdrvChild in @list so that they can't block themselves. */
3042 ret = bdrv_check_update_perm(to, perm, shared, list, errp);
3043 if (ret < 0) {
3044 bdrv_abort_perm_update(to);
3045 goto out;
3048 /* Now actually perform the change. We performed the permission check for
3049 * all elements of @list at once, so set the permissions all at once at the
3050 * very end. */
3051 for (p = list; p != NULL; p = p->next) {
3052 c = p->data;
3054 bdrv_ref(to);
3055 bdrv_replace_child_noperm(c, to);
3056 bdrv_unref(from);
3059 bdrv_get_cumulative_perm(to, &old_perm, &old_shared);
3060 bdrv_set_perm(to, old_perm | perm, old_shared | shared);
3062 out:
3063 g_slist_free(list);
3064 bdrv_unref(from);
3068 * Add new bs contents at the top of an image chain while the chain is
3069 * live, while keeping required fields on the top layer.
3071 * This will modify the BlockDriverState fields, and swap contents
3072 * between bs_new and bs_top. Both bs_new and bs_top are modified.
3074 * bs_new must not be attached to a BlockBackend.
3076 * This function does not create any image files.
3078 * bdrv_append() takes ownership of a bs_new reference and unrefs it because
3079 * that's what the callers commonly need. bs_new will be referenced by the old
3080 * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
3081 * reference of its own, it must call bdrv_ref().
3083 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
3084 Error **errp)
3086 Error *local_err = NULL;
3088 bdrv_set_backing_hd(bs_new, bs_top, &local_err);
3089 if (local_err) {
3090 error_propagate(errp, local_err);
3091 goto out;
3094 bdrv_replace_node(bs_top, bs_new, &local_err);
3095 if (local_err) {
3096 error_propagate(errp, local_err);
3097 bdrv_set_backing_hd(bs_new, NULL, &error_abort);
3098 goto out;
3101 /* bs_new is now referenced by its new parents, we don't need the
3102 * additional reference any more. */
3103 out:
3104 bdrv_unref(bs_new);
3107 static void bdrv_delete(BlockDriverState *bs)
3109 assert(!bs->job);
3110 assert(bdrv_op_blocker_is_empty(bs));
3111 assert(!bs->refcnt);
3113 bdrv_close(bs);
3115 /* remove from list, if necessary */
3116 if (bs->node_name[0] != '\0') {
3117 QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
3119 QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
3121 g_free(bs);
3125 * Run consistency checks on an image
3127 * Returns 0 if the check could be completed (it doesn't mean that the image is
3128 * free of errors) or -errno when an internal error occurred. The results of the
3129 * check are stored in res.
3131 int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
3133 if (bs->drv == NULL) {
3134 return -ENOMEDIUM;
3136 if (bs->drv->bdrv_check == NULL) {
3137 return -ENOTSUP;
3140 memset(res, 0, sizeof(*res));
3141 return bs->drv->bdrv_check(bs, res, fix);
3145 * Return values:
3146 * 0 - success
3147 * -EINVAL - backing format specified, but no file
3148 * -ENOSPC - can't update the backing file because no space is left in the
3149 * image file header
3150 * -ENOTSUP - format driver doesn't support changing the backing file
3152 int bdrv_change_backing_file(BlockDriverState *bs,
3153 const char *backing_file, const char *backing_fmt)
3155 BlockDriver *drv = bs->drv;
3156 int ret;
3158 /* Backing file format doesn't make sense without a backing file */
3159 if (backing_fmt && !backing_file) {
3160 return -EINVAL;
3163 if (drv->bdrv_change_backing_file != NULL) {
3164 ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
3165 } else {
3166 ret = -ENOTSUP;
3169 if (ret == 0) {
3170 pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
3171 pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
3173 return ret;
3177 * Finds the image layer in the chain that has 'bs' as its backing file.
3179 * active is the current topmost image.
3181 * Returns NULL if bs is not found in active's image chain,
3182 * or if active == bs.
3184 * Returns the bottommost base image if bs == NULL.
3186 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
3187 BlockDriverState *bs)
3189 while (active && bs != backing_bs(active)) {
3190 active = backing_bs(active);
3193 return active;
3196 /* Given a BDS, searches for the base layer. */
3197 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
3199 return bdrv_find_overlay(bs, NULL);
3203 * Drops images above 'base' up to and including 'top', and sets the image
3204 * above 'top' to have base as its backing file.
3206 * Requires that the overlay to 'top' is opened r/w, so that the backing file
3207 * information in 'bs' can be properly updated.
3209 * E.g., this will convert the following chain:
3210 * bottom <- base <- intermediate <- top <- active
3212 * to
3214 * bottom <- base <- active
3216 * It is allowed for bottom==base, in which case it converts:
3218 * base <- intermediate <- top <- active
3220 * to
3222 * base <- active
3224 * If backing_file_str is non-NULL, it will be used when modifying top's
3225 * overlay image metadata.
3227 * Error conditions:
3228 * if active == top, that is considered an error
3231 int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
3232 BlockDriverState *base, const char *backing_file_str)
3234 BlockDriverState *new_top_bs = NULL;
3235 Error *local_err = NULL;
3236 int ret = -EIO;
3238 if (!top->drv || !base->drv) {
3239 goto exit;
3242 new_top_bs = bdrv_find_overlay(active, top);
3244 if (new_top_bs == NULL) {
3245 /* we could not find the image above 'top', this is an error */
3246 goto exit;
3249 /* special case of new_top_bs->backing->bs already pointing to base - nothing
3250 * to do, no intermediate images */
3251 if (backing_bs(new_top_bs) == base) {
3252 ret = 0;
3253 goto exit;
3256 /* Make sure that base is in the backing chain of top */
3257 if (!bdrv_chain_contains(top, base)) {
3258 goto exit;
3261 /* success - we can delete the intermediate states, and link top->base */
3262 backing_file_str = backing_file_str ? backing_file_str : base->filename;
3263 ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
3264 base->drv ? base->drv->format_name : "");
3265 if (ret) {
3266 goto exit;
3269 bdrv_set_backing_hd(new_top_bs, base, &local_err);
3270 if (local_err) {
3271 ret = -EPERM;
3272 error_report_err(local_err);
3273 goto exit;
3276 ret = 0;
3277 exit:
3278 return ret;
3282 * Truncate file to 'offset' bytes (needed only for file protocols)
3284 int bdrv_truncate(BdrvChild *child, int64_t offset)
3286 BlockDriverState *bs = child->bs;
3287 BlockDriver *drv = bs->drv;
3288 int ret;
3290 /* FIXME: Some format block drivers use this function instead of implicitly
3291 * growing their file by writing beyond its end.
3292 * See bdrv_aligned_pwritev() for an explanation why we currently
3293 * cannot assert this permission in that case. */
3294 // assert(child->perm & BLK_PERM_RESIZE);
3296 if (!drv)
3297 return -ENOMEDIUM;
3298 if (!drv->bdrv_truncate)
3299 return -ENOTSUP;
3300 if (bs->read_only)
3301 return -EACCES;
3303 ret = drv->bdrv_truncate(bs, offset);
3304 if (ret == 0) {
3305 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3306 bdrv_dirty_bitmap_truncate(bs);
3307 bdrv_parent_cb_resize(bs);
3308 ++bs->write_gen;
3310 return ret;
3314 * Length of a allocated file in bytes. Sparse files are counted by actual
3315 * allocated space. Return < 0 if error or unknown.
3317 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
3319 BlockDriver *drv = bs->drv;
3320 if (!drv) {
3321 return -ENOMEDIUM;
3323 if (drv->bdrv_get_allocated_file_size) {
3324 return drv->bdrv_get_allocated_file_size(bs);
3326 if (bs->file) {
3327 return bdrv_get_allocated_file_size(bs->file->bs);
3329 return -ENOTSUP;
3333 * Return number of sectors on success, -errno on error.
3335 int64_t bdrv_nb_sectors(BlockDriverState *bs)
3337 BlockDriver *drv = bs->drv;
3339 if (!drv)
3340 return -ENOMEDIUM;
3342 if (drv->has_variable_length) {
3343 int ret = refresh_total_sectors(bs, bs->total_sectors);
3344 if (ret < 0) {
3345 return ret;
3348 return bs->total_sectors;
3352 * Return length in bytes on success, -errno on error.
3353 * The length is always a multiple of BDRV_SECTOR_SIZE.
3355 int64_t bdrv_getlength(BlockDriverState *bs)
3357 int64_t ret = bdrv_nb_sectors(bs);
3359 ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
3360 return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
3363 /* return 0 as number of sectors if no device present or error */
3364 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3366 int64_t nb_sectors = bdrv_nb_sectors(bs);
3368 *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
3371 bool bdrv_is_read_only(BlockDriverState *bs)
3373 return bs->read_only;
3376 bool bdrv_is_sg(BlockDriverState *bs)
3378 return bs->sg;
3381 bool bdrv_is_encrypted(BlockDriverState *bs)
3383 if (bs->backing && bs->backing->bs->encrypted) {
3384 return true;
3386 return bs->encrypted;
3389 bool bdrv_key_required(BlockDriverState *bs)
3391 BdrvChild *backing = bs->backing;
3393 if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
3394 return true;
3396 return (bs->encrypted && !bs->valid_key);
3399 int bdrv_set_key(BlockDriverState *bs, const char *key)
3401 int ret;
3402 if (bs->backing && bs->backing->bs->encrypted) {
3403 ret = bdrv_set_key(bs->backing->bs, key);
3404 if (ret < 0)
3405 return ret;
3406 if (!bs->encrypted)
3407 return 0;
3409 if (!bs->encrypted) {
3410 return -EINVAL;
3411 } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3412 return -ENOMEDIUM;
3414 ret = bs->drv->bdrv_set_key(bs, key);
3415 if (ret < 0) {
3416 bs->valid_key = false;
3417 } else if (!bs->valid_key) {
3418 /* call the change callback now, we skipped it on open */
3419 bs->valid_key = true;
3420 bdrv_parent_cb_change_media(bs, true);
3422 return ret;
3426 * Provide an encryption key for @bs.
3427 * If @key is non-null:
3428 * If @bs is not encrypted, fail.
3429 * Else if the key is invalid, fail.
3430 * Else set @bs's key to @key, replacing the existing key, if any.
3431 * If @key is null:
3432 * If @bs is encrypted and still lacks a key, fail.
3433 * Else do nothing.
3434 * On failure, store an error object through @errp if non-null.
3436 void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
3438 if (key) {
3439 if (!bdrv_is_encrypted(bs)) {
3440 error_setg(errp, "Node '%s' is not encrypted",
3441 bdrv_get_device_or_node_name(bs));
3442 } else if (bdrv_set_key(bs, key) < 0) {
3443 error_setg(errp, QERR_INVALID_PASSWORD);
3445 } else {
3446 if (bdrv_key_required(bs)) {
3447 error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
3448 "'%s' (%s) is encrypted",
3449 bdrv_get_device_or_node_name(bs),
3450 bdrv_get_encrypted_filename(bs));
3455 const char *bdrv_get_format_name(BlockDriverState *bs)
3457 return bs->drv ? bs->drv->format_name : NULL;
3460 static int qsort_strcmp(const void *a, const void *b)
3462 return strcmp(*(char *const *)a, *(char *const *)b);
3465 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3466 void *opaque)
3468 BlockDriver *drv;
3469 int count = 0;
3470 int i;
3471 const char **formats = NULL;
3473 QLIST_FOREACH(drv, &bdrv_drivers, list) {
3474 if (drv->format_name) {
3475 bool found = false;
3476 int i = count;
3477 while (formats && i && !found) {
3478 found = !strcmp(formats[--i], drv->format_name);
3481 if (!found) {
3482 formats = g_renew(const char *, formats, count + 1);
3483 formats[count++] = drv->format_name;
3488 for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
3489 const char *format_name = block_driver_modules[i].format_name;
3491 if (format_name) {
3492 bool found = false;
3493 int j = count;
3495 while (formats && j && !found) {
3496 found = !strcmp(formats[--j], format_name);
3499 if (!found) {
3500 formats = g_renew(const char *, formats, count + 1);
3501 formats[count++] = format_name;
3506 qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3508 for (i = 0; i < count; i++) {
3509 it(opaque, formats[i]);
3512 g_free(formats);
3515 /* This function is to find a node in the bs graph */
3516 BlockDriverState *bdrv_find_node(const char *node_name)
3518 BlockDriverState *bs;
3520 assert(node_name);
3522 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3523 if (!strcmp(node_name, bs->node_name)) {
3524 return bs;
3527 return NULL;
3530 /* Put this QMP function here so it can access the static graph_bdrv_states. */
3531 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
3533 BlockDeviceInfoList *list, *entry;
3534 BlockDriverState *bs;
3536 list = NULL;
3537 QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3538 BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
3539 if (!info) {
3540 qapi_free_BlockDeviceInfoList(list);
3541 return NULL;
3543 entry = g_malloc0(sizeof(*entry));
3544 entry->value = info;
3545 entry->next = list;
3546 list = entry;
3549 return list;
3552 BlockDriverState *bdrv_lookup_bs(const char *device,
3553 const char *node_name,
3554 Error **errp)
3556 BlockBackend *blk;
3557 BlockDriverState *bs;
3559 if (device) {
3560 blk = blk_by_name(device);
3562 if (blk) {
3563 bs = blk_bs(blk);
3564 if (!bs) {
3565 error_setg(errp, "Device '%s' has no medium", device);
3568 return bs;
3572 if (node_name) {
3573 bs = bdrv_find_node(node_name);
3575 if (bs) {
3576 return bs;
3580 error_setg(errp, "Cannot find device=%s nor node_name=%s",
3581 device ? device : "",
3582 node_name ? node_name : "");
3583 return NULL;
3586 /* If 'base' is in the same chain as 'top', return true. Otherwise,
3587 * return false. If either argument is NULL, return false. */
3588 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
3590 while (top && top != base) {
3591 top = backing_bs(top);
3594 return top != NULL;
3597 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
3599 if (!bs) {
3600 return QTAILQ_FIRST(&graph_bdrv_states);
3602 return QTAILQ_NEXT(bs, node_list);
3605 const char *bdrv_get_node_name(const BlockDriverState *bs)
3607 return bs->node_name;
3610 const char *bdrv_get_parent_name(const BlockDriverState *bs)
3612 BdrvChild *c;
3613 const char *name;
3615 /* If multiple parents have a name, just pick the first one. */
3616 QLIST_FOREACH(c, &bs->parents, next_parent) {
3617 if (c->role->get_name) {
3618 name = c->role->get_name(c);
3619 if (name && *name) {
3620 return name;
3625 return NULL;
3628 /* TODO check what callers really want: bs->node_name or blk_name() */
3629 const char *bdrv_get_device_name(const BlockDriverState *bs)
3631 return bdrv_get_parent_name(bs) ?: "";
3634 /* This can be used to identify nodes that might not have a device
3635 * name associated. Since node and device names live in the same
3636 * namespace, the result is unambiguous. The exception is if both are
3637 * absent, then this returns an empty (non-null) string. */
3638 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
3640 return bdrv_get_parent_name(bs) ?: bs->node_name;
3643 int bdrv_get_flags(BlockDriverState *bs)
3645 return bs->open_flags;
3648 int bdrv_has_zero_init_1(BlockDriverState *bs)
3650 return 1;
3653 int bdrv_has_zero_init(BlockDriverState *bs)
3655 assert(bs->drv);
3657 /* If BS is a copy on write image, it is initialized to
3658 the contents of the base image, which may not be zeroes. */
3659 if (bs->backing) {
3660 return 0;
3662 if (bs->drv->bdrv_has_zero_init) {
3663 return bs->drv->bdrv_has_zero_init(bs);
3666 /* safe default */
3667 return 0;
3670 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
3672 BlockDriverInfo bdi;
3674 if (bs->backing) {
3675 return false;
3678 if (bdrv_get_info(bs, &bdi) == 0) {
3679 return bdi.unallocated_blocks_are_zero;
3682 return false;
3685 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
3687 BlockDriverInfo bdi;
3689 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3690 return false;
3693 if (bdrv_get_info(bs, &bdi) == 0) {
3694 return bdi.can_write_zeroes_with_unmap;
3697 return false;
3700 const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3702 if (bs->backing && bs->backing->bs->encrypted)
3703 return bs->backing_file;
3704 else if (bs->encrypted)
3705 return bs->filename;
3706 else
3707 return NULL;
3710 void bdrv_get_backing_filename(BlockDriverState *bs,
3711 char *filename, int filename_size)
3713 pstrcpy(filename, filename_size, bs->backing_file);
3716 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3718 BlockDriver *drv = bs->drv;
3719 if (!drv)
3720 return -ENOMEDIUM;
3721 if (!drv->bdrv_get_info)
3722 return -ENOTSUP;
3723 memset(bdi, 0, sizeof(*bdi));
3724 return drv->bdrv_get_info(bs, bdi);
3727 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3729 BlockDriver *drv = bs->drv;
3730 if (drv && drv->bdrv_get_specific_info) {
3731 return drv->bdrv_get_specific_info(bs);
3733 return NULL;
3736 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
3738 if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
3739 return;
3742 bs->drv->bdrv_debug_event(bs, event);
3745 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
3746 const char *tag)
3748 while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
3749 bs = bs->file ? bs->file->bs : NULL;
3752 if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
3753 return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
3756 return -ENOTSUP;
3759 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
3761 while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
3762 bs = bs->file ? bs->file->bs : NULL;
3765 if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
3766 return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
3769 return -ENOTSUP;
3772 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
3774 while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
3775 bs = bs->file ? bs->file->bs : NULL;
3778 if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
3779 return bs->drv->bdrv_debug_resume(bs, tag);
3782 return -ENOTSUP;
3785 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
3787 while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
3788 bs = bs->file ? bs->file->bs : NULL;
3791 if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
3792 return bs->drv->bdrv_debug_is_suspended(bs, tag);
3795 return false;
3798 /* backing_file can either be relative, or absolute, or a protocol. If it is
3799 * relative, it must be relative to the chain. So, passing in bs->filename
3800 * from a BDS as backing_file should not be done, as that may be relative to
3801 * the CWD rather than the chain. */
3802 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3803 const char *backing_file)
3805 char *filename_full = NULL;
3806 char *backing_file_full = NULL;
3807 char *filename_tmp = NULL;
3808 int is_protocol = 0;
3809 BlockDriverState *curr_bs = NULL;
3810 BlockDriverState *retval = NULL;
3811 Error *local_error = NULL;
3813 if (!bs || !bs->drv || !backing_file) {
3814 return NULL;
3817 filename_full = g_malloc(PATH_MAX);
3818 backing_file_full = g_malloc(PATH_MAX);
3819 filename_tmp = g_malloc(PATH_MAX);
3821 is_protocol = path_has_protocol(backing_file);
3823 for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3825 /* If either of the filename paths is actually a protocol, then
3826 * compare unmodified paths; otherwise make paths relative */
3827 if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3828 if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3829 retval = curr_bs->backing->bs;
3830 break;
3832 /* Also check against the full backing filename for the image */
3833 bdrv_get_full_backing_filename(curr_bs, backing_file_full, PATH_MAX,
3834 &local_error);
3835 if (local_error == NULL) {
3836 if (strcmp(backing_file, backing_file_full) == 0) {
3837 retval = curr_bs->backing->bs;
3838 break;
3840 } else {
3841 error_free(local_error);
3842 local_error = NULL;
3844 } else {
3845 /* If not an absolute filename path, make it relative to the current
3846 * image's filename path */
3847 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3848 backing_file);
3850 /* We are going to compare absolute pathnames */
3851 if (!realpath(filename_tmp, filename_full)) {
3852 continue;
3855 /* We need to make sure the backing filename we are comparing against
3856 * is relative to the current image filename (or absolute) */
3857 path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3858 curr_bs->backing_file);
3860 if (!realpath(filename_tmp, backing_file_full)) {
3861 continue;
3864 if (strcmp(backing_file_full, filename_full) == 0) {
3865 retval = curr_bs->backing->bs;
3866 break;
3871 g_free(filename_full);
3872 g_free(backing_file_full);
3873 g_free(filename_tmp);
3874 return retval;
3877 int bdrv_get_backing_file_depth(BlockDriverState *bs)
3879 if (!bs->drv) {
3880 return 0;
3883 if (!bs->backing) {
3884 return 0;
3887 return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3890 void bdrv_init(void)
3892 module_call_init(MODULE_INIT_BLOCK);
3895 void bdrv_init_with_whitelist(void)
3897 use_bdrv_whitelist = 1;
3898 bdrv_init();
3901 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
3903 BdrvChild *child;
3904 Error *local_err = NULL;
3905 int ret;
3907 if (!bs->drv) {
3908 return;
3911 if (!(bs->open_flags & BDRV_O_INACTIVE)) {
3912 return;
3915 QLIST_FOREACH(child, &bs->children, next) {
3916 bdrv_invalidate_cache(child->bs, &local_err);
3917 if (local_err) {
3918 error_propagate(errp, local_err);
3919 return;
3923 bs->open_flags &= ~BDRV_O_INACTIVE;
3924 if (bs->drv->bdrv_invalidate_cache) {
3925 bs->drv->bdrv_invalidate_cache(bs, &local_err);
3926 if (local_err) {
3927 bs->open_flags |= BDRV_O_INACTIVE;
3928 error_propagate(errp, local_err);
3929 return;
3933 ret = refresh_total_sectors(bs, bs->total_sectors);
3934 if (ret < 0) {
3935 bs->open_flags |= BDRV_O_INACTIVE;
3936 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3937 return;
3941 void bdrv_invalidate_cache_all(Error **errp)
3943 BlockDriverState *bs;
3944 Error *local_err = NULL;
3945 BdrvNextIterator it;
3947 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3948 AioContext *aio_context = bdrv_get_aio_context(bs);
3950 aio_context_acquire(aio_context);
3951 bdrv_invalidate_cache(bs, &local_err);
3952 aio_context_release(aio_context);
3953 if (local_err) {
3954 error_propagate(errp, local_err);
3955 return;
3960 static int bdrv_inactivate_recurse(BlockDriverState *bs,
3961 bool setting_flag)
3963 BdrvChild *child;
3964 int ret;
3966 if (!setting_flag && bs->drv->bdrv_inactivate) {
3967 ret = bs->drv->bdrv_inactivate(bs);
3968 if (ret < 0) {
3969 return ret;
3973 QLIST_FOREACH(child, &bs->children, next) {
3974 ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3975 if (ret < 0) {
3976 return ret;
3980 if (setting_flag) {
3981 bs->open_flags |= BDRV_O_INACTIVE;
3983 return 0;
3986 int bdrv_inactivate_all(void)
3988 BlockDriverState *bs = NULL;
3989 BdrvNextIterator it;
3990 int ret = 0;
3991 int pass;
3993 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3994 aio_context_acquire(bdrv_get_aio_context(bs));
3997 /* We do two passes of inactivation. The first pass calls to drivers'
3998 * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3999 * the second pass sets the BDRV_O_INACTIVE flag so that no further write
4000 * is allowed. */
4001 for (pass = 0; pass < 2; pass++) {
4002 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4003 ret = bdrv_inactivate_recurse(bs, pass);
4004 if (ret < 0) {
4005 goto out;
4010 out:
4011 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4012 aio_context_release(bdrv_get_aio_context(bs));
4015 return ret;
4018 /**************************************************************/
4019 /* removable device support */
4022 * Return TRUE if the media is present
4024 bool bdrv_is_inserted(BlockDriverState *bs)
4026 BlockDriver *drv = bs->drv;
4027 BdrvChild *child;
4029 if (!drv) {
4030 return false;
4032 if (drv->bdrv_is_inserted) {
4033 return drv->bdrv_is_inserted(bs);
4035 QLIST_FOREACH(child, &bs->children, next) {
4036 if (!bdrv_is_inserted(child->bs)) {
4037 return false;
4040 return true;
4044 * Return whether the media changed since the last call to this
4045 * function, or -ENOTSUP if we don't know. Most drivers don't know.
4047 int bdrv_media_changed(BlockDriverState *bs)
4049 BlockDriver *drv = bs->drv;
4051 if (drv && drv->bdrv_media_changed) {
4052 return drv->bdrv_media_changed(bs);
4054 return -ENOTSUP;
4058 * If eject_flag is TRUE, eject the media. Otherwise, close the tray
4060 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
4062 BlockDriver *drv = bs->drv;
4064 if (drv && drv->bdrv_eject) {
4065 drv->bdrv_eject(bs, eject_flag);
4070 * Lock or unlock the media (if it is locked, the user won't be able
4071 * to eject it manually).
4073 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
4075 BlockDriver *drv = bs->drv;
4077 trace_bdrv_lock_medium(bs, locked);
4079 if (drv && drv->bdrv_lock_medium) {
4080 drv->bdrv_lock_medium(bs, locked);
4084 /* Get a reference to bs */
4085 void bdrv_ref(BlockDriverState *bs)
4087 bs->refcnt++;
4090 /* Release a previously grabbed reference to bs.
4091 * If after releasing, reference count is zero, the BlockDriverState is
4092 * deleted. */
4093 void bdrv_unref(BlockDriverState *bs)
4095 if (!bs) {
4096 return;
4098 assert(bs->refcnt > 0);
4099 if (--bs->refcnt == 0) {
4100 bdrv_delete(bs);
4104 struct BdrvOpBlocker {
4105 Error *reason;
4106 QLIST_ENTRY(BdrvOpBlocker) list;
4109 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
4111 BdrvOpBlocker *blocker;
4112 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4113 if (!QLIST_EMPTY(&bs->op_blockers[op])) {
4114 blocker = QLIST_FIRST(&bs->op_blockers[op]);
4115 if (errp) {
4116 *errp = error_copy(blocker->reason);
4117 error_prepend(errp, "Node '%s' is busy: ",
4118 bdrv_get_device_or_node_name(bs));
4120 return true;
4122 return false;
4125 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
4127 BdrvOpBlocker *blocker;
4128 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4130 blocker = g_new0(BdrvOpBlocker, 1);
4131 blocker->reason = reason;
4132 QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
4135 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
4137 BdrvOpBlocker *blocker, *next;
4138 assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
4139 QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
4140 if (blocker->reason == reason) {
4141 QLIST_REMOVE(blocker, list);
4142 g_free(blocker);
4147 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
4149 int i;
4150 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4151 bdrv_op_block(bs, i, reason);
4155 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
4157 int i;
4158 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4159 bdrv_op_unblock(bs, i, reason);
4163 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
4165 int i;
4167 for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
4168 if (!QLIST_EMPTY(&bs->op_blockers[i])) {
4169 return false;
4172 return true;
4175 void bdrv_img_create(const char *filename, const char *fmt,
4176 const char *base_filename, const char *base_fmt,
4177 char *options, uint64_t img_size, int flags, bool quiet,
4178 Error **errp)
4180 QemuOptsList *create_opts = NULL;
4181 QemuOpts *opts = NULL;
4182 const char *backing_fmt, *backing_file;
4183 int64_t size;
4184 BlockDriver *drv, *proto_drv;
4185 Error *local_err = NULL;
4186 int ret = 0;
4188 /* Find driver and parse its options */
4189 drv = bdrv_find_format(fmt);
4190 if (!drv) {
4191 error_setg(errp, "Unknown file format '%s'", fmt);
4192 return;
4195 proto_drv = bdrv_find_protocol(filename, true, errp);
4196 if (!proto_drv) {
4197 return;
4200 if (!drv->create_opts) {
4201 error_setg(errp, "Format driver '%s' does not support image creation",
4202 drv->format_name);
4203 return;
4206 if (!proto_drv->create_opts) {
4207 error_setg(errp, "Protocol driver '%s' does not support image creation",
4208 proto_drv->format_name);
4209 return;
4212 create_opts = qemu_opts_append(create_opts, drv->create_opts);
4213 create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
4215 /* Create parameter list with default values */
4216 opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
4217 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
4219 /* Parse -o options */
4220 if (options) {
4221 qemu_opts_do_parse(opts, options, NULL, &local_err);
4222 if (local_err) {
4223 error_report_err(local_err);
4224 local_err = NULL;
4225 error_setg(errp, "Invalid options for file format '%s'", fmt);
4226 goto out;
4230 if (base_filename) {
4231 qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
4232 if (local_err) {
4233 error_setg(errp, "Backing file not supported for file format '%s'",
4234 fmt);
4235 goto out;
4239 if (base_fmt) {
4240 qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
4241 if (local_err) {
4242 error_setg(errp, "Backing file format not supported for file "
4243 "format '%s'", fmt);
4244 goto out;
4248 backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
4249 if (backing_file) {
4250 if (!strcmp(filename, backing_file)) {
4251 error_setg(errp, "Error: Trying to create an image with the "
4252 "same filename as the backing file");
4253 goto out;
4257 backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
4259 // The size for the image must always be specified, with one exception:
4260 // If we are using a backing file, we can obtain the size from there
4261 size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
4262 if (size == -1) {
4263 if (backing_file) {
4264 BlockDriverState *bs;
4265 char *full_backing = g_new0(char, PATH_MAX);
4266 int64_t size;
4267 int back_flags;
4268 QDict *backing_options = NULL;
4270 bdrv_get_full_backing_filename_from_filename(filename, backing_file,
4271 full_backing, PATH_MAX,
4272 &local_err);
4273 if (local_err) {
4274 g_free(full_backing);
4275 goto out;
4278 /* backing files always opened read-only */
4279 back_flags = flags;
4280 back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
4282 if (backing_fmt) {
4283 backing_options = qdict_new();
4284 qdict_put(backing_options, "driver",
4285 qstring_from_str(backing_fmt));
4288 bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
4289 &local_err);
4290 g_free(full_backing);
4291 if (!bs) {
4292 goto out;
4294 size = bdrv_getlength(bs);
4295 if (size < 0) {
4296 error_setg_errno(errp, -size, "Could not get size of '%s'",
4297 backing_file);
4298 bdrv_unref(bs);
4299 goto out;
4302 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
4304 bdrv_unref(bs);
4305 } else {
4306 error_setg(errp, "Image creation needs a size parameter");
4307 goto out;
4311 if (!quiet) {
4312 printf("Formatting '%s', fmt=%s ", filename, fmt);
4313 qemu_opts_print(opts, " ");
4314 puts("");
4317 ret = bdrv_create(drv, filename, opts, &local_err);
4319 if (ret == -EFBIG) {
4320 /* This is generally a better message than whatever the driver would
4321 * deliver (especially because of the cluster_size_hint), since that
4322 * is most probably not much different from "image too large". */
4323 const char *cluster_size_hint = "";
4324 if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
4325 cluster_size_hint = " (try using a larger cluster size)";
4327 error_setg(errp, "The image size is too large for file format '%s'"
4328 "%s", fmt, cluster_size_hint);
4329 error_free(local_err);
4330 local_err = NULL;
4333 out:
4334 qemu_opts_del(opts);
4335 qemu_opts_free(create_opts);
4336 error_propagate(errp, local_err);
4339 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
4341 return bs->aio_context;
4344 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
4346 aio_co_enter(bdrv_get_aio_context(bs), co);
4349 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
4351 QLIST_REMOVE(ban, list);
4352 g_free(ban);
4355 void bdrv_detach_aio_context(BlockDriverState *bs)
4357 BdrvAioNotifier *baf, *baf_tmp;
4358 BdrvChild *child;
4360 if (!bs->drv) {
4361 return;
4364 assert(!bs->walking_aio_notifiers);
4365 bs->walking_aio_notifiers = true;
4366 QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
4367 if (baf->deleted) {
4368 bdrv_do_remove_aio_context_notifier(baf);
4369 } else {
4370 baf->detach_aio_context(baf->opaque);
4373 /* Never mind iterating again to check for ->deleted. bdrv_close() will
4374 * remove remaining aio notifiers if we aren't called again.
4376 bs->walking_aio_notifiers = false;
4378 if (bs->drv->bdrv_detach_aio_context) {
4379 bs->drv->bdrv_detach_aio_context(bs);
4381 QLIST_FOREACH(child, &bs->children, next) {
4382 bdrv_detach_aio_context(child->bs);
4385 bs->aio_context = NULL;
4388 void bdrv_attach_aio_context(BlockDriverState *bs,
4389 AioContext *new_context)
4391 BdrvAioNotifier *ban, *ban_tmp;
4392 BdrvChild *child;
4394 if (!bs->drv) {
4395 return;
4398 bs->aio_context = new_context;
4400 QLIST_FOREACH(child, &bs->children, next) {
4401 bdrv_attach_aio_context(child->bs, new_context);
4403 if (bs->drv->bdrv_attach_aio_context) {
4404 bs->drv->bdrv_attach_aio_context(bs, new_context);
4407 assert(!bs->walking_aio_notifiers);
4408 bs->walking_aio_notifiers = true;
4409 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
4410 if (ban->deleted) {
4411 bdrv_do_remove_aio_context_notifier(ban);
4412 } else {
4413 ban->attached_aio_context(new_context, ban->opaque);
4416 bs->walking_aio_notifiers = false;
4419 void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
4421 AioContext *ctx = bdrv_get_aio_context(bs);
4423 aio_disable_external(ctx);
4424 bdrv_parent_drained_begin(bs);
4425 bdrv_drain(bs); /* ensure there are no in-flight requests */
4427 while (aio_poll(ctx, false)) {
4428 /* wait for all bottom halves to execute */
4431 bdrv_detach_aio_context(bs);
4433 /* This function executes in the old AioContext so acquire the new one in
4434 * case it runs in a different thread.
4436 aio_context_acquire(new_context);
4437 bdrv_attach_aio_context(bs, new_context);
4438 bdrv_parent_drained_end(bs);
4439 aio_enable_external(ctx);
4440 aio_context_release(new_context);
4443 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
4444 void (*attached_aio_context)(AioContext *new_context, void *opaque),
4445 void (*detach_aio_context)(void *opaque), void *opaque)
4447 BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
4448 *ban = (BdrvAioNotifier){
4449 .attached_aio_context = attached_aio_context,
4450 .detach_aio_context = detach_aio_context,
4451 .opaque = opaque
4454 QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
4457 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
4458 void (*attached_aio_context)(AioContext *,
4459 void *),
4460 void (*detach_aio_context)(void *),
4461 void *opaque)
4463 BdrvAioNotifier *ban, *ban_next;
4465 QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4466 if (ban->attached_aio_context == attached_aio_context &&
4467 ban->detach_aio_context == detach_aio_context &&
4468 ban->opaque == opaque &&
4469 ban->deleted == false)
4471 if (bs->walking_aio_notifiers) {
4472 ban->deleted = true;
4473 } else {
4474 bdrv_do_remove_aio_context_notifier(ban);
4476 return;
4480 abort();
4483 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
4484 BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
4486 if (!bs->drv->bdrv_amend_options) {
4487 return -ENOTSUP;
4489 return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
4492 /* This function will be called by the bdrv_recurse_is_first_non_filter method
4493 * of block filter and by bdrv_is_first_non_filter.
4494 * It is used to test if the given bs is the candidate or recurse more in the
4495 * node graph.
4497 bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
4498 BlockDriverState *candidate)
4500 /* return false if basic checks fails */
4501 if (!bs || !bs->drv) {
4502 return false;
4505 /* the code reached a non block filter driver -> check if the bs is
4506 * the same as the candidate. It's the recursion termination condition.
4508 if (!bs->drv->is_filter) {
4509 return bs == candidate;
4511 /* Down this path the driver is a block filter driver */
4513 /* If the block filter recursion method is defined use it to recurse down
4514 * the node graph.
4516 if (bs->drv->bdrv_recurse_is_first_non_filter) {
4517 return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4520 /* the driver is a block filter but don't allow to recurse -> return false
4522 return false;
4525 /* This function checks if the candidate is the first non filter bs down it's
4526 * bs chain. Since we don't have pointers to parents it explore all bs chains
4527 * from the top. Some filters can choose not to pass down the recursion.
4529 bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4531 BlockDriverState *bs;
4532 BdrvNextIterator it;
4534 /* walk down the bs forest recursively */
4535 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
4536 bool perm;
4538 /* try to recurse in this top level bs */
4539 perm = bdrv_recurse_is_first_non_filter(bs, candidate);
4541 /* candidate is the first non filter */
4542 if (perm) {
4543 return true;
4547 return false;
4550 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4551 const char *node_name, Error **errp)
4553 BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
4554 AioContext *aio_context;
4556 if (!to_replace_bs) {
4557 error_setg(errp, "Node name '%s' not found", node_name);
4558 return NULL;
4561 aio_context = bdrv_get_aio_context(to_replace_bs);
4562 aio_context_acquire(aio_context);
4564 if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
4565 to_replace_bs = NULL;
4566 goto out;
4569 /* We don't want arbitrary node of the BDS chain to be replaced only the top
4570 * most non filter in order to prevent data corruption.
4571 * Another benefit is that this tests exclude backing files which are
4572 * blocked by the backing blockers.
4574 if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
4575 error_setg(errp, "Only top most non filter can be replaced");
4576 to_replace_bs = NULL;
4577 goto out;
4580 out:
4581 aio_context_release(aio_context);
4582 return to_replace_bs;
4585 static bool append_open_options(QDict *d, BlockDriverState *bs)
4587 const QDictEntry *entry;
4588 QemuOptDesc *desc;
4589 BdrvChild *child;
4590 bool found_any = false;
4591 const char *p;
4593 for (entry = qdict_first(bs->options); entry;
4594 entry = qdict_next(bs->options, entry))
4596 /* Exclude options for children */
4597 QLIST_FOREACH(child, &bs->children, next) {
4598 if (strstart(qdict_entry_key(entry), child->name, &p)
4599 && (!*p || *p == '.'))
4601 break;
4604 if (child) {
4605 continue;
4608 /* And exclude all non-driver-specific options */
4609 for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
4610 if (!strcmp(qdict_entry_key(entry), desc->name)) {
4611 break;
4614 if (desc->name) {
4615 continue;
4618 qobject_incref(qdict_entry_value(entry));
4619 qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
4620 found_any = true;
4623 return found_any;
4626 /* Updates the following BDS fields:
4627 * - exact_filename: A filename which may be used for opening a block device
4628 * which (mostly) equals the given BDS (even without any
4629 * other options; so reading and writing must return the same
4630 * results, but caching etc. may be different)
4631 * - full_open_options: Options which, when given when opening a block device
4632 * (without a filename), result in a BDS (mostly)
4633 * equalling the given one
4634 * - filename: If exact_filename is set, it is copied here. Otherwise,
4635 * full_open_options is converted to a JSON object, prefixed with
4636 * "json:" (for use through the JSON pseudo protocol) and put here.
4638 void bdrv_refresh_filename(BlockDriverState *bs)
4640 BlockDriver *drv = bs->drv;
4641 QDict *opts;
4643 if (!drv) {
4644 return;
4647 /* This BDS's file name will most probably depend on its file's name, so
4648 * refresh that first */
4649 if (bs->file) {
4650 bdrv_refresh_filename(bs->file->bs);
4653 if (drv->bdrv_refresh_filename) {
4654 /* Obsolete information is of no use here, so drop the old file name
4655 * information before refreshing it */
4656 bs->exact_filename[0] = '\0';
4657 if (bs->full_open_options) {
4658 QDECREF(bs->full_open_options);
4659 bs->full_open_options = NULL;
4662 opts = qdict_new();
4663 append_open_options(opts, bs);
4664 drv->bdrv_refresh_filename(bs, opts);
4665 QDECREF(opts);
4666 } else if (bs->file) {
4667 /* Try to reconstruct valid information from the underlying file */
4668 bool has_open_options;
4670 bs->exact_filename[0] = '\0';
4671 if (bs->full_open_options) {
4672 QDECREF(bs->full_open_options);
4673 bs->full_open_options = NULL;
4676 opts = qdict_new();
4677 has_open_options = append_open_options(opts, bs);
4679 /* If no specific options have been given for this BDS, the filename of
4680 * the underlying file should suffice for this one as well */
4681 if (bs->file->bs->exact_filename[0] && !has_open_options) {
4682 strcpy(bs->exact_filename, bs->file->bs->exact_filename);
4684 /* Reconstructing the full options QDict is simple for most format block
4685 * drivers, as long as the full options are known for the underlying
4686 * file BDS. The full options QDict of that file BDS should somehow
4687 * contain a representation of the filename, therefore the following
4688 * suffices without querying the (exact_)filename of this BDS. */
4689 if (bs->file->bs->full_open_options) {
4690 qdict_put_obj(opts, "driver",
4691 QOBJECT(qstring_from_str(drv->format_name)));
4692 QINCREF(bs->file->bs->full_open_options);
4693 qdict_put_obj(opts, "file",
4694 QOBJECT(bs->file->bs->full_open_options));
4696 bs->full_open_options = opts;
4697 } else {
4698 QDECREF(opts);
4700 } else if (!bs->full_open_options && qdict_size(bs->options)) {
4701 /* There is no underlying file BDS (at least referenced by BDS.file),
4702 * so the full options QDict should be equal to the options given
4703 * specifically for this block device when it was opened (plus the
4704 * driver specification).
4705 * Because those options don't change, there is no need to update
4706 * full_open_options when it's already set. */
4708 opts = qdict_new();
4709 append_open_options(opts, bs);
4710 qdict_put_obj(opts, "driver",
4711 QOBJECT(qstring_from_str(drv->format_name)));
4713 if (bs->exact_filename[0]) {
4714 /* This may not work for all block protocol drivers (some may
4715 * require this filename to be parsed), but we have to find some
4716 * default solution here, so just include it. If some block driver
4717 * does not support pure options without any filename at all or
4718 * needs some special format of the options QDict, it needs to
4719 * implement the driver-specific bdrv_refresh_filename() function.
4721 qdict_put_obj(opts, "filename",
4722 QOBJECT(qstring_from_str(bs->exact_filename)));
4725 bs->full_open_options = opts;
4728 if (bs->exact_filename[0]) {
4729 pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
4730 } else if (bs->full_open_options) {
4731 QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
4732 snprintf(bs->filename, sizeof(bs->filename), "json:%s",
4733 qstring_get_str(json));
4734 QDECREF(json);
4739 * Hot add/remove a BDS's child. So the user can take a child offline when
4740 * it is broken and take a new child online
4742 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
4743 Error **errp)
4746 if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
4747 error_setg(errp, "The node %s does not support adding a child",
4748 bdrv_get_device_or_node_name(parent_bs));
4749 return;
4752 if (!QLIST_EMPTY(&child_bs->parents)) {
4753 error_setg(errp, "The node %s already has a parent",
4754 child_bs->node_name);
4755 return;
4758 parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
4761 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
4763 BdrvChild *tmp;
4765 if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
4766 error_setg(errp, "The node %s does not support removing a child",
4767 bdrv_get_device_or_node_name(parent_bs));
4768 return;
4771 QLIST_FOREACH(tmp, &parent_bs->children, next) {
4772 if (tmp == child) {
4773 break;
4777 if (!tmp) {
4778 error_setg(errp, "The node %s does not have a child named %s",
4779 bdrv_get_device_or_node_name(parent_bs),
4780 bdrv_get_device_or_node_name(child->bs));
4781 return;
4784 parent_bs->drv->bdrv_del_child(parent_bs, child, errp);