xref: /openbmc/qemu/block.c (revision a2c37a30422328fe2391bd1ff342f8941c7681bc)
1 /*
2  * QEMU System Emulator block driver
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  * Copyright (c) 2020 Virtuozzo International GmbH.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #include "qemu/osdep.h"
27 #include "block/trace.h"
28 #include "block/block_int.h"
29 #include "block/blockjob.h"
30 #include "block/fuse.h"
31 #include "block/nbd.h"
32 #include "block/qdict.h"
33 #include "qemu/error-report.h"
34 #include "block/module_block.h"
35 #include "qemu/main-loop.h"
36 #include "qemu/module.h"
37 #include "qapi/error.h"
38 #include "qapi/qmp/qdict.h"
39 #include "qapi/qmp/qjson.h"
40 #include "qapi/qmp/qnull.h"
41 #include "qapi/qmp/qstring.h"
42 #include "qapi/qobject-output-visitor.h"
43 #include "qapi/qapi-visit-block-core.h"
44 #include "sysemu/block-backend.h"
45 #include "qemu/notify.h"
46 #include "qemu/option.h"
47 #include "qemu/coroutine.h"
48 #include "block/qapi.h"
49 #include "qemu/timer.h"
50 #include "qemu/cutils.h"
51 #include "qemu/id.h"
52 #include "qemu/range.h"
53 #include "qemu/rcu.h"
54 #include "block/coroutines.h"
55 
56 #ifdef CONFIG_BSD
57 #include <sys/ioctl.h>
58 #include <sys/queue.h>
59 #if defined(HAVE_SYS_DISK_H)
60 #include <sys/disk.h>
61 #endif
62 #endif
63 
64 #ifdef _WIN32
65 #include <windows.h>
66 #endif
67 
68 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
69 
70 /* Protected by BQL */
71 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
72     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
73 
74 /* Protected by BQL */
75 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
76     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
77 
78 /* Protected by BQL */
79 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
80     QLIST_HEAD_INITIALIZER(bdrv_drivers);
81 
82 static BlockDriverState *bdrv_open_inherit(const char *filename,
83                                            const char *reference,
84                                            QDict *options, int flags,
85                                            BlockDriverState *parent,
86                                            const BdrvChildClass *child_class,
87                                            BdrvChildRole child_role,
88                                            Error **errp);
89 
90 static bool bdrv_recurse_has_child(BlockDriverState *bs,
91                                    BlockDriverState *child);
92 
93 static void bdrv_replace_child_noperm(BdrvChild **child,
94                                       BlockDriverState *new_bs);
95 static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
96                                               BdrvChild *child,
97                                               Transaction *tran);
98 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
99                                             Transaction *tran);
100 
101 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
102                                BlockReopenQueue *queue,
103                                Transaction *change_child_tran, Error **errp);
104 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
105 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
106 
107 static bool bdrv_backing_overridden(BlockDriverState *bs);
108 
109 /* If non-zero, use only whitelisted block drivers */
110 static int use_bdrv_whitelist;
111 
112 #ifdef _WIN32
113 static int is_windows_drive_prefix(const char *filename)
114 {
115     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
116              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
117             filename[1] == ':');
118 }
119 
120 int is_windows_drive(const char *filename)
121 {
122     if (is_windows_drive_prefix(filename) &&
123         filename[2] == '\0')
124         return 1;
125     if (strstart(filename, "\\\\.\\", NULL) ||
126         strstart(filename, "//./", NULL))
127         return 1;
128     return 0;
129 }
130 #endif
131 
132 size_t bdrv_opt_mem_align(BlockDriverState *bs)
133 {
134     if (!bs || !bs->drv) {
135         /* page size or 4k (hdd sector size) should be on the safe side */
136         return MAX(4096, qemu_real_host_page_size());
137     }
138     IO_CODE();
139 
140     return bs->bl.opt_mem_alignment;
141 }
142 
143 size_t bdrv_min_mem_align(BlockDriverState *bs)
144 {
145     if (!bs || !bs->drv) {
146         /* page size or 4k (hdd sector size) should be on the safe side */
147         return MAX(4096, qemu_real_host_page_size());
148     }
149     IO_CODE();
150 
151     return bs->bl.min_mem_alignment;
152 }
153 
154 /* check if the path starts with "<protocol>:" */
155 int path_has_protocol(const char *path)
156 {
157     const char *p;
158 
159 #ifdef _WIN32
160     if (is_windows_drive(path) ||
161         is_windows_drive_prefix(path)) {
162         return 0;
163     }
164     p = path + strcspn(path, ":/\\");
165 #else
166     p = path + strcspn(path, ":/");
167 #endif
168 
169     return *p == ':';
170 }
171 
172 int path_is_absolute(const char *path)
173 {
174 #ifdef _WIN32
175     /* specific case for names like: "\\.\d:" */
176     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
177         return 1;
178     }
179     return (*path == '/' || *path == '\\');
180 #else
181     return (*path == '/');
182 #endif
183 }
184 
185 /* if filename is absolute, just return its duplicate. Otherwise, build a
186    path to it by considering it is relative to base_path. URL are
187    supported. */
188 char *path_combine(const char *base_path, const char *filename)
189 {
190     const char *protocol_stripped = NULL;
191     const char *p, *p1;
192     char *result;
193     int len;
194 
195     if (path_is_absolute(filename)) {
196         return g_strdup(filename);
197     }
198 
199     if (path_has_protocol(base_path)) {
200         protocol_stripped = strchr(base_path, ':');
201         if (protocol_stripped) {
202             protocol_stripped++;
203         }
204     }
205     p = protocol_stripped ?: base_path;
206 
207     p1 = strrchr(base_path, '/');
208 #ifdef _WIN32
209     {
210         const char *p2;
211         p2 = strrchr(base_path, '\\');
212         if (!p1 || p2 > p1) {
213             p1 = p2;
214         }
215     }
216 #endif
217     if (p1) {
218         p1++;
219     } else {
220         p1 = base_path;
221     }
222     if (p1 > p) {
223         p = p1;
224     }
225     len = p - base_path;
226 
227     result = g_malloc(len + strlen(filename) + 1);
228     memcpy(result, base_path, len);
229     strcpy(result + len, filename);
230 
231     return result;
232 }
233 
234 /*
235  * Helper function for bdrv_parse_filename() implementations to remove optional
236  * protocol prefixes (especially "file:") from a filename and for putting the
237  * stripped filename into the options QDict if there is such a prefix.
238  */
239 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
240                                       QDict *options)
241 {
242     if (strstart(filename, prefix, &filename)) {
243         /* Stripping the explicit protocol prefix may result in a protocol
244          * prefix being (wrongly) detected (if the filename contains a colon) */
245         if (path_has_protocol(filename)) {
246             GString *fat_filename;
247 
248             /* This means there is some colon before the first slash; therefore,
249              * this cannot be an absolute path */
250             assert(!path_is_absolute(filename));
251 
252             /* And we can thus fix the protocol detection issue by prefixing it
253              * by "./" */
254             fat_filename = g_string_new("./");
255             g_string_append(fat_filename, filename);
256 
257             assert(!path_has_protocol(fat_filename->str));
258 
259             qdict_put(options, "filename",
260                       qstring_from_gstring(fat_filename));
261         } else {
262             /* If no protocol prefix was detected, we can use the shortened
263              * filename as-is */
264             qdict_put_str(options, "filename", filename);
265         }
266     }
267 }
268 
269 
270 /* Returns whether the image file is opened as read-only. Note that this can
271  * return false and writing to the image file is still not possible because the
272  * image is inactivated. */
273 bool bdrv_is_read_only(BlockDriverState *bs)
274 {
275     IO_CODE();
276     return !(bs->open_flags & BDRV_O_RDWR);
277 }
278 
279 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
280                            bool ignore_allow_rdw, Error **errp)
281 {
282     IO_CODE();
283 
284     /* Do not set read_only if copy_on_read is enabled */
285     if (bs->copy_on_read && read_only) {
286         error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
287                    bdrv_get_device_or_node_name(bs));
288         return -EINVAL;
289     }
290 
291     /* Do not clear read_only if it is prohibited */
292     if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
293         !ignore_allow_rdw)
294     {
295         error_setg(errp, "Node '%s' is read only",
296                    bdrv_get_device_or_node_name(bs));
297         return -EPERM;
298     }
299 
300     return 0;
301 }
302 
303 /*
304  * Called by a driver that can only provide a read-only image.
305  *
306  * Returns 0 if the node is already read-only or it could switch the node to
307  * read-only because BDRV_O_AUTO_RDONLY is set.
308  *
309  * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
310  * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
311  * is not NULL, it is used as the error message for the Error object.
312  */
313 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
314                               Error **errp)
315 {
316     int ret = 0;
317     IO_CODE();
318 
319     if (!(bs->open_flags & BDRV_O_RDWR)) {
320         return 0;
321     }
322     if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
323         goto fail;
324     }
325 
326     ret = bdrv_can_set_read_only(bs, true, false, NULL);
327     if (ret < 0) {
328         goto fail;
329     }
330 
331     bs->open_flags &= ~BDRV_O_RDWR;
332 
333     return 0;
334 
335 fail:
336     error_setg(errp, "%s", errmsg ?: "Image is read-only");
337     return -EACCES;
338 }
339 
340 /*
341  * If @backing is empty, this function returns NULL without setting
342  * @errp.  In all other cases, NULL will only be returned with @errp
343  * set.
344  *
345  * Therefore, a return value of NULL without @errp set means that
346  * there is no backing file; if @errp is set, there is one but its
347  * absolute filename cannot be generated.
348  */
349 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
350                                                    const char *backing,
351                                                    Error **errp)
352 {
353     if (backing[0] == '\0') {
354         return NULL;
355     } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
356         return g_strdup(backing);
357     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
358         error_setg(errp, "Cannot use relative backing file names for '%s'",
359                    backed);
360         return NULL;
361     } else {
362         return path_combine(backed, backing);
363     }
364 }
365 
366 /*
367  * If @filename is empty or NULL, this function returns NULL without
368  * setting @errp.  In all other cases, NULL will only be returned with
369  * @errp set.
370  */
371 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
372                                          const char *filename, Error **errp)
373 {
374     char *dir, *full_name;
375 
376     if (!filename || filename[0] == '\0') {
377         return NULL;
378     } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
379         return g_strdup(filename);
380     }
381 
382     dir = bdrv_dirname(relative_to, errp);
383     if (!dir) {
384         return NULL;
385     }
386 
387     full_name = g_strconcat(dir, filename, NULL);
388     g_free(dir);
389     return full_name;
390 }
391 
392 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
393 {
394     GLOBAL_STATE_CODE();
395     return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
396 }
397 
398 void bdrv_register(BlockDriver *bdrv)
399 {
400     assert(bdrv->format_name);
401     GLOBAL_STATE_CODE();
402     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
403 }
404 
405 BlockDriverState *bdrv_new(void)
406 {
407     BlockDriverState *bs;
408     int i;
409 
410     GLOBAL_STATE_CODE();
411 
412     bs = g_new0(BlockDriverState, 1);
413     QLIST_INIT(&bs->dirty_bitmaps);
414     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
415         QLIST_INIT(&bs->op_blockers[i]);
416     }
417     qemu_co_mutex_init(&bs->reqs_lock);
418     qemu_mutex_init(&bs->dirty_bitmap_mutex);
419     bs->refcnt = 1;
420     bs->aio_context = qemu_get_aio_context();
421 
422     qemu_co_queue_init(&bs->flush_queue);
423 
424     qemu_co_mutex_init(&bs->bsc_modify_lock);
425     bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
426 
427     for (i = 0; i < bdrv_drain_all_count; i++) {
428         bdrv_drained_begin(bs);
429     }
430 
431     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
432 
433     return bs;
434 }
435 
436 static BlockDriver *bdrv_do_find_format(const char *format_name)
437 {
438     BlockDriver *drv1;
439     GLOBAL_STATE_CODE();
440 
441     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
442         if (!strcmp(drv1->format_name, format_name)) {
443             return drv1;
444         }
445     }
446 
447     return NULL;
448 }
449 
450 BlockDriver *bdrv_find_format(const char *format_name)
451 {
452     BlockDriver *drv1;
453     int i;
454 
455     GLOBAL_STATE_CODE();
456 
457     drv1 = bdrv_do_find_format(format_name);
458     if (drv1) {
459         return drv1;
460     }
461 
462     /* The driver isn't registered, maybe we need to load a module */
463     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
464         if (!strcmp(block_driver_modules[i].format_name, format_name)) {
465             block_module_load_one(block_driver_modules[i].library_name);
466             break;
467         }
468     }
469 
470     return bdrv_do_find_format(format_name);
471 }
472 
473 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
474 {
475     static const char *whitelist_rw[] = {
476         CONFIG_BDRV_RW_WHITELIST
477         NULL
478     };
479     static const char *whitelist_ro[] = {
480         CONFIG_BDRV_RO_WHITELIST
481         NULL
482     };
483     const char **p;
484 
485     if (!whitelist_rw[0] && !whitelist_ro[0]) {
486         return 1;               /* no whitelist, anything goes */
487     }
488 
489     for (p = whitelist_rw; *p; p++) {
490         if (!strcmp(format_name, *p)) {
491             return 1;
492         }
493     }
494     if (read_only) {
495         for (p = whitelist_ro; *p; p++) {
496             if (!strcmp(format_name, *p)) {
497                 return 1;
498             }
499         }
500     }
501     return 0;
502 }
503 
504 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
505 {
506     GLOBAL_STATE_CODE();
507     return bdrv_format_is_whitelisted(drv->format_name, read_only);
508 }
509 
510 bool bdrv_uses_whitelist(void)
511 {
512     return use_bdrv_whitelist;
513 }
514 
515 typedef struct CreateCo {
516     BlockDriver *drv;
517     char *filename;
518     QemuOpts *opts;
519     int ret;
520     Error *err;
521 } CreateCo;
522 
523 static void coroutine_fn bdrv_create_co_entry(void *opaque)
524 {
525     Error *local_err = NULL;
526     int ret;
527 
528     CreateCo *cco = opaque;
529     assert(cco->drv);
530     GLOBAL_STATE_CODE();
531 
532     ret = cco->drv->bdrv_co_create_opts(cco->drv,
533                                         cco->filename, cco->opts, &local_err);
534     error_propagate(&cco->err, local_err);
535     cco->ret = ret;
536 }
537 
538 int bdrv_create(BlockDriver *drv, const char* filename,
539                 QemuOpts *opts, Error **errp)
540 {
541     int ret;
542 
543     GLOBAL_STATE_CODE();
544 
545     Coroutine *co;
546     CreateCo cco = {
547         .drv = drv,
548         .filename = g_strdup(filename),
549         .opts = opts,
550         .ret = NOT_DONE,
551         .err = NULL,
552     };
553 
554     if (!drv->bdrv_co_create_opts) {
555         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
556         ret = -ENOTSUP;
557         goto out;
558     }
559 
560     if (qemu_in_coroutine()) {
561         /* Fast-path if already in coroutine context */
562         bdrv_create_co_entry(&cco);
563     } else {
564         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
565         qemu_coroutine_enter(co);
566         while (cco.ret == NOT_DONE) {
567             aio_poll(qemu_get_aio_context(), true);
568         }
569     }
570 
571     ret = cco.ret;
572     if (ret < 0) {
573         if (cco.err) {
574             error_propagate(errp, cco.err);
575         } else {
576             error_setg_errno(errp, -ret, "Could not create image");
577         }
578     }
579 
580 out:
581     g_free(cco.filename);
582     return ret;
583 }
584 
585 /**
586  * Helper function for bdrv_create_file_fallback(): Resize @blk to at
587  * least the given @minimum_size.
588  *
589  * On success, return @blk's actual length.
590  * Otherwise, return -errno.
591  */
592 static int64_t create_file_fallback_truncate(BlockBackend *blk,
593                                              int64_t minimum_size, Error **errp)
594 {
595     Error *local_err = NULL;
596     int64_t size;
597     int ret;
598 
599     GLOBAL_STATE_CODE();
600 
601     ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
602                        &local_err);
603     if (ret < 0 && ret != -ENOTSUP) {
604         error_propagate(errp, local_err);
605         return ret;
606     }
607 
608     size = blk_getlength(blk);
609     if (size < 0) {
610         error_free(local_err);
611         error_setg_errno(errp, -size,
612                          "Failed to inquire the new image file's length");
613         return size;
614     }
615 
616     if (size < minimum_size) {
617         /* Need to grow the image, but we failed to do that */
618         error_propagate(errp, local_err);
619         return -ENOTSUP;
620     }
621 
622     error_free(local_err);
623     local_err = NULL;
624 
625     return size;
626 }
627 
628 /**
629  * Helper function for bdrv_create_file_fallback(): Zero the first
630  * sector to remove any potentially pre-existing image header.
631  */
632 static int coroutine_fn
633 create_file_fallback_zero_first_sector(BlockBackend *blk,
634                                        int64_t current_size,
635                                        Error **errp)
636 {
637     int64_t bytes_to_clear;
638     int ret;
639 
640     GLOBAL_STATE_CODE();
641 
642     bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
643     if (bytes_to_clear) {
644         ret = blk_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
645         if (ret < 0) {
646             error_setg_errno(errp, -ret,
647                              "Failed to clear the new image's first sector");
648             return ret;
649         }
650     }
651 
652     return 0;
653 }
654 
655 /**
656  * Simple implementation of bdrv_co_create_opts for protocol drivers
657  * which only support creation via opening a file
658  * (usually existing raw storage device)
659  */
660 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
661                                             const char *filename,
662                                             QemuOpts *opts,
663                                             Error **errp)
664 {
665     BlockBackend *blk;
666     QDict *options;
667     int64_t size = 0;
668     char *buf = NULL;
669     PreallocMode prealloc;
670     Error *local_err = NULL;
671     int ret;
672 
673     GLOBAL_STATE_CODE();
674 
675     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
676     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
677     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
678                                PREALLOC_MODE_OFF, &local_err);
679     g_free(buf);
680     if (local_err) {
681         error_propagate(errp, local_err);
682         return -EINVAL;
683     }
684 
685     if (prealloc != PREALLOC_MODE_OFF) {
686         error_setg(errp, "Unsupported preallocation mode '%s'",
687                    PreallocMode_str(prealloc));
688         return -ENOTSUP;
689     }
690 
691     options = qdict_new();
692     qdict_put_str(options, "driver", drv->format_name);
693 
694     blk = blk_new_open(filename, NULL, options,
695                        BDRV_O_RDWR | BDRV_O_RESIZE, errp);
696     if (!blk) {
697         error_prepend(errp, "Protocol driver '%s' does not support image "
698                       "creation, and opening the image failed: ",
699                       drv->format_name);
700         return -EINVAL;
701     }
702 
703     size = create_file_fallback_truncate(blk, size, errp);
704     if (size < 0) {
705         ret = size;
706         goto out;
707     }
708 
709     ret = create_file_fallback_zero_first_sector(blk, size, errp);
710     if (ret < 0) {
711         goto out;
712     }
713 
714     ret = 0;
715 out:
716     blk_unref(blk);
717     return ret;
718 }
719 
720 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
721 {
722     QemuOpts *protocol_opts;
723     BlockDriver *drv;
724     QDict *qdict;
725     int ret;
726 
727     GLOBAL_STATE_CODE();
728 
729     drv = bdrv_find_protocol(filename, true, errp);
730     if (drv == NULL) {
731         return -ENOENT;
732     }
733 
734     if (!drv->create_opts) {
735         error_setg(errp, "Driver '%s' does not support image creation",
736                    drv->format_name);
737         return -ENOTSUP;
738     }
739 
740     /*
741      * 'opts' contains a QemuOptsList with a combination of format and protocol
742      * default values.
743      *
744      * The format properly removes its options, but the default values remain
745      * in 'opts->list'.  So if the protocol has options with the same name
746      * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
747      * of the format, since for overlapping options, the format wins.
748      *
749      * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
750      * only the set options, and then convert it back to QemuOpts, using the
751      * create_opts of the protocol. So the new QemuOpts, will contain only the
752      * protocol defaults.
753      */
754     qdict = qemu_opts_to_qdict(opts, NULL);
755     protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
756     if (protocol_opts == NULL) {
757         ret = -EINVAL;
758         goto out;
759     }
760 
761     ret = bdrv_create(drv, filename, protocol_opts, errp);
762 out:
763     qemu_opts_del(protocol_opts);
764     qobject_unref(qdict);
765     return ret;
766 }
767 
768 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
769 {
770     Error *local_err = NULL;
771     int ret;
772 
773     IO_CODE();
774     assert(bs != NULL);
775 
776     if (!bs->drv) {
777         error_setg(errp, "Block node '%s' is not opened", bs->filename);
778         return -ENOMEDIUM;
779     }
780 
781     if (!bs->drv->bdrv_co_delete_file) {
782         error_setg(errp, "Driver '%s' does not support image deletion",
783                    bs->drv->format_name);
784         return -ENOTSUP;
785     }
786 
787     ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
788     if (ret < 0) {
789         error_propagate(errp, local_err);
790     }
791 
792     return ret;
793 }
794 
795 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
796 {
797     Error *local_err = NULL;
798     int ret;
799     IO_CODE();
800 
801     if (!bs) {
802         return;
803     }
804 
805     ret = bdrv_co_delete_file(bs, &local_err);
806     /*
807      * ENOTSUP will happen if the block driver doesn't support
808      * the 'bdrv_co_delete_file' interface. This is a predictable
809      * scenario and shouldn't be reported back to the user.
810      */
811     if (ret == -ENOTSUP) {
812         error_free(local_err);
813     } else if (ret < 0) {
814         error_report_err(local_err);
815     }
816 }
817 
818 /**
819  * Try to get @bs's logical and physical block size.
820  * On success, store them in @bsz struct and return 0.
821  * On failure return -errno.
822  * @bs must not be empty.
823  */
824 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
825 {
826     BlockDriver *drv = bs->drv;
827     BlockDriverState *filtered = bdrv_filter_bs(bs);
828     GLOBAL_STATE_CODE();
829 
830     if (drv && drv->bdrv_probe_blocksizes) {
831         return drv->bdrv_probe_blocksizes(bs, bsz);
832     } else if (filtered) {
833         return bdrv_probe_blocksizes(filtered, bsz);
834     }
835 
836     return -ENOTSUP;
837 }
838 
839 /**
840  * Try to get @bs's geometry (cyls, heads, sectors).
841  * On success, store them in @geo struct and return 0.
842  * On failure return -errno.
843  * @bs must not be empty.
844  */
845 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
846 {
847     BlockDriver *drv = bs->drv;
848     BlockDriverState *filtered = bdrv_filter_bs(bs);
849     GLOBAL_STATE_CODE();
850 
851     if (drv && drv->bdrv_probe_geometry) {
852         return drv->bdrv_probe_geometry(bs, geo);
853     } else if (filtered) {
854         return bdrv_probe_geometry(filtered, geo);
855     }
856 
857     return -ENOTSUP;
858 }
859 
860 /*
861  * Create a uniquely-named empty temporary file.
862  * Return the actual file name used upon success, otherwise NULL.
863  * This string should be freed with g_free() when not needed any longer.
864  *
865  * Note: creating a temporary file for the caller to (re)open is
866  * inherently racy. Use g_file_open_tmp() instead whenever practical.
867  */
868 char *create_tmp_file(Error **errp)
869 {
870     int fd;
871     const char *tmpdir;
872     g_autofree char *filename = NULL;
873 
874     tmpdir = g_get_tmp_dir();
875 #ifndef _WIN32
876     /*
877      * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
878      *
879      * This function is used to create temporary disk images (like -snapshot),
880      * so the files can become very large. /tmp is often a tmpfs where as
881      * /var/tmp is usually on a disk, so more appropriate for disk images.
882      */
883     if (!g_strcmp0(tmpdir, "/tmp")) {
884         tmpdir = "/var/tmp";
885     }
886 #endif
887 
888     filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
889     fd = g_mkstemp(filename);
890     if (fd < 0) {
891         error_setg_errno(errp, errno, "Could not open temporary file '%s'",
892                          filename);
893         return NULL;
894     }
895     close(fd);
896 
897     return g_steal_pointer(&filename);
898 }
899 
900 /*
901  * Detect host devices. By convention, /dev/cdrom[N] is always
902  * recognized as a host CDROM.
903  */
904 static BlockDriver *find_hdev_driver(const char *filename)
905 {
906     int score_max = 0, score;
907     BlockDriver *drv = NULL, *d;
908     GLOBAL_STATE_CODE();
909 
910     QLIST_FOREACH(d, &bdrv_drivers, list) {
911         if (d->bdrv_probe_device) {
912             score = d->bdrv_probe_device(filename);
913             if (score > score_max) {
914                 score_max = score;
915                 drv = d;
916             }
917         }
918     }
919 
920     return drv;
921 }
922 
923 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
924 {
925     BlockDriver *drv1;
926     GLOBAL_STATE_CODE();
927 
928     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
929         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
930             return drv1;
931         }
932     }
933 
934     return NULL;
935 }
936 
937 BlockDriver *bdrv_find_protocol(const char *filename,
938                                 bool allow_protocol_prefix,
939                                 Error **errp)
940 {
941     BlockDriver *drv1;
942     char protocol[128];
943     int len;
944     const char *p;
945     int i;
946 
947     GLOBAL_STATE_CODE();
948     /* TODO Drivers without bdrv_file_open must be specified explicitly */
949 
950     /*
951      * XXX(hch): we really should not let host device detection
952      * override an explicit protocol specification, but moving this
953      * later breaks access to device names with colons in them.
954      * Thanks to the brain-dead persistent naming schemes on udev-
955      * based Linux systems those actually are quite common.
956      */
957     drv1 = find_hdev_driver(filename);
958     if (drv1) {
959         return drv1;
960     }
961 
962     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
963         return &bdrv_file;
964     }
965 
966     p = strchr(filename, ':');
967     assert(p != NULL);
968     len = p - filename;
969     if (len > sizeof(protocol) - 1)
970         len = sizeof(protocol) - 1;
971     memcpy(protocol, filename, len);
972     protocol[len] = '\0';
973 
974     drv1 = bdrv_do_find_protocol(protocol);
975     if (drv1) {
976         return drv1;
977     }
978 
979     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
980         if (block_driver_modules[i].protocol_name &&
981             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
982             block_module_load_one(block_driver_modules[i].library_name);
983             break;
984         }
985     }
986 
987     drv1 = bdrv_do_find_protocol(protocol);
988     if (!drv1) {
989         error_setg(errp, "Unknown protocol '%s'", protocol);
990     }
991     return drv1;
992 }
993 
994 /*
995  * Guess image format by probing its contents.
996  * This is not a good idea when your image is raw (CVE-2008-2004), but
997  * we do it anyway for backward compatibility.
998  *
999  * @buf         contains the image's first @buf_size bytes.
1000  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1001  *              but can be smaller if the image file is smaller)
1002  * @filename    is its filename.
1003  *
1004  * For all block drivers, call the bdrv_probe() method to get its
1005  * probing score.
1006  * Return the first block driver with the highest probing score.
1007  */
1008 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1009                             const char *filename)
1010 {
1011     int score_max = 0, score;
1012     BlockDriver *drv = NULL, *d;
1013     IO_CODE();
1014 
1015     QLIST_FOREACH(d, &bdrv_drivers, list) {
1016         if (d->bdrv_probe) {
1017             score = d->bdrv_probe(buf, buf_size, filename);
1018             if (score > score_max) {
1019                 score_max = score;
1020                 drv = d;
1021             }
1022         }
1023     }
1024 
1025     return drv;
1026 }
1027 
1028 static int find_image_format(BlockBackend *file, const char *filename,
1029                              BlockDriver **pdrv, Error **errp)
1030 {
1031     BlockDriver *drv;
1032     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1033     int ret = 0;
1034 
1035     GLOBAL_STATE_CODE();
1036 
1037     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1038     if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1039         *pdrv = &bdrv_raw;
1040         return ret;
1041     }
1042 
1043     ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1044     if (ret < 0) {
1045         error_setg_errno(errp, -ret, "Could not read image for determining its "
1046                          "format");
1047         *pdrv = NULL;
1048         return ret;
1049     }
1050 
1051     drv = bdrv_probe_all(buf, sizeof(buf), filename);
1052     if (!drv) {
1053         error_setg(errp, "Could not determine image format: No compatible "
1054                    "driver found");
1055         *pdrv = NULL;
1056         return -ENOENT;
1057     }
1058 
1059     *pdrv = drv;
1060     return 0;
1061 }
1062 
1063 /**
1064  * Set the current 'total_sectors' value
1065  * Return 0 on success, -errno on error.
1066  */
1067 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1068 {
1069     BlockDriver *drv = bs->drv;
1070     IO_CODE();
1071 
1072     if (!drv) {
1073         return -ENOMEDIUM;
1074     }
1075 
1076     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1077     if (bdrv_is_sg(bs))
1078         return 0;
1079 
1080     /* query actual device if possible, otherwise just trust the hint */
1081     if (drv->bdrv_getlength) {
1082         int64_t length = drv->bdrv_getlength(bs);
1083         if (length < 0) {
1084             return length;
1085         }
1086         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1087     }
1088 
1089     bs->total_sectors = hint;
1090 
1091     if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1092         return -EFBIG;
1093     }
1094 
1095     return 0;
1096 }
1097 
1098 /**
1099  * Combines a QDict of new block driver @options with any missing options taken
1100  * from @old_options, so that leaving out an option defaults to its old value.
1101  */
1102 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1103                               QDict *old_options)
1104 {
1105     GLOBAL_STATE_CODE();
1106     if (bs->drv && bs->drv->bdrv_join_options) {
1107         bs->drv->bdrv_join_options(options, old_options);
1108     } else {
1109         qdict_join(options, old_options, false);
1110     }
1111 }
1112 
1113 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1114                                                             int open_flags,
1115                                                             Error **errp)
1116 {
1117     Error *local_err = NULL;
1118     char *value = qemu_opt_get_del(opts, "detect-zeroes");
1119     BlockdevDetectZeroesOptions detect_zeroes =
1120         qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1121                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1122     GLOBAL_STATE_CODE();
1123     g_free(value);
1124     if (local_err) {
1125         error_propagate(errp, local_err);
1126         return detect_zeroes;
1127     }
1128 
1129     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1130         !(open_flags & BDRV_O_UNMAP))
1131     {
1132         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1133                    "without setting discard operation to unmap");
1134     }
1135 
1136     return detect_zeroes;
1137 }
1138 
1139 /**
1140  * Set open flags for aio engine
1141  *
1142  * Return 0 on success, -1 if the engine specified is invalid
1143  */
1144 int bdrv_parse_aio(const char *mode, int *flags)
1145 {
1146     if (!strcmp(mode, "threads")) {
1147         /* do nothing, default */
1148     } else if (!strcmp(mode, "native")) {
1149         *flags |= BDRV_O_NATIVE_AIO;
1150 #ifdef CONFIG_LINUX_IO_URING
1151     } else if (!strcmp(mode, "io_uring")) {
1152         *flags |= BDRV_O_IO_URING;
1153 #endif
1154     } else {
1155         return -1;
1156     }
1157 
1158     return 0;
1159 }
1160 
1161 /**
1162  * Set open flags for a given discard mode
1163  *
1164  * Return 0 on success, -1 if the discard mode was invalid.
1165  */
1166 int bdrv_parse_discard_flags(const char *mode, int *flags)
1167 {
1168     *flags &= ~BDRV_O_UNMAP;
1169 
1170     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1171         /* do nothing */
1172     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1173         *flags |= BDRV_O_UNMAP;
1174     } else {
1175         return -1;
1176     }
1177 
1178     return 0;
1179 }
1180 
1181 /**
1182  * Set open flags for a given cache mode
1183  *
1184  * Return 0 on success, -1 if the cache mode was invalid.
1185  */
1186 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1187 {
1188     *flags &= ~BDRV_O_CACHE_MASK;
1189 
1190     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1191         *writethrough = false;
1192         *flags |= BDRV_O_NOCACHE;
1193     } else if (!strcmp(mode, "directsync")) {
1194         *writethrough = true;
1195         *flags |= BDRV_O_NOCACHE;
1196     } else if (!strcmp(mode, "writeback")) {
1197         *writethrough = false;
1198     } else if (!strcmp(mode, "unsafe")) {
1199         *writethrough = false;
1200         *flags |= BDRV_O_NO_FLUSH;
1201     } else if (!strcmp(mode, "writethrough")) {
1202         *writethrough = true;
1203     } else {
1204         return -1;
1205     }
1206 
1207     return 0;
1208 }
1209 
1210 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1211 {
1212     BlockDriverState *parent = c->opaque;
1213     return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1214 }
1215 
1216 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1217 {
1218     BlockDriverState *bs = child->opaque;
1219     bdrv_do_drained_begin_quiesce(bs, NULL, false);
1220 }
1221 
1222 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1223 {
1224     BlockDriverState *bs = child->opaque;
1225     return bdrv_drain_poll(bs, false, NULL, false);
1226 }
1227 
1228 static void bdrv_child_cb_drained_end(BdrvChild *child,
1229                                       int *drained_end_counter)
1230 {
1231     BlockDriverState *bs = child->opaque;
1232     bdrv_drained_end_no_poll(bs, drained_end_counter);
1233 }
1234 
1235 static int bdrv_child_cb_inactivate(BdrvChild *child)
1236 {
1237     BlockDriverState *bs = child->opaque;
1238     GLOBAL_STATE_CODE();
1239     assert(bs->open_flags & BDRV_O_INACTIVE);
1240     return 0;
1241 }
1242 
1243 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1244                                           GSList **ignore, Error **errp)
1245 {
1246     BlockDriverState *bs = child->opaque;
1247     return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
1248 }
1249 
1250 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
1251                                       GSList **ignore)
1252 {
1253     BlockDriverState *bs = child->opaque;
1254     return bdrv_set_aio_context_ignore(bs, ctx, ignore);
1255 }
1256 
1257 /*
1258  * Returns the options and flags that a temporary snapshot should get, based on
1259  * the originally requested flags (the originally requested image will have
1260  * flags like a backing file)
1261  */
1262 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1263                                        int parent_flags, QDict *parent_options)
1264 {
1265     GLOBAL_STATE_CODE();
1266     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1267 
1268     /* For temporary files, unconditional cache=unsafe is fine */
1269     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1270     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1271 
1272     /* Copy the read-only and discard options from the parent */
1273     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1274     qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1275 
1276     /* aio=native doesn't work for cache.direct=off, so disable it for the
1277      * temporary snapshot */
1278     *child_flags &= ~BDRV_O_NATIVE_AIO;
1279 }
1280 
1281 static void bdrv_backing_attach(BdrvChild *c)
1282 {
1283     BlockDriverState *parent = c->opaque;
1284     BlockDriverState *backing_hd = c->bs;
1285 
1286     GLOBAL_STATE_CODE();
1287     assert(!parent->backing_blocker);
1288     error_setg(&parent->backing_blocker,
1289                "node is used as backing hd of '%s'",
1290                bdrv_get_device_or_node_name(parent));
1291 
1292     bdrv_refresh_filename(backing_hd);
1293 
1294     parent->open_flags &= ~BDRV_O_NO_BACKING;
1295 
1296     bdrv_op_block_all(backing_hd, parent->backing_blocker);
1297     /* Otherwise we won't be able to commit or stream */
1298     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1299                     parent->backing_blocker);
1300     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1301                     parent->backing_blocker);
1302     /*
1303      * We do backup in 3 ways:
1304      * 1. drive backup
1305      *    The target bs is new opened, and the source is top BDS
1306      * 2. blockdev backup
1307      *    Both the source and the target are top BDSes.
1308      * 3. internal backup(used for block replication)
1309      *    Both the source and the target are backing file
1310      *
1311      * In case 1 and 2, neither the source nor the target is the backing file.
1312      * In case 3, we will block the top BDS, so there is only one block job
1313      * for the top BDS and its backing chain.
1314      */
1315     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1316                     parent->backing_blocker);
1317     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1318                     parent->backing_blocker);
1319 }
1320 
1321 static void bdrv_backing_detach(BdrvChild *c)
1322 {
1323     BlockDriverState *parent = c->opaque;
1324 
1325     GLOBAL_STATE_CODE();
1326     assert(parent->backing_blocker);
1327     bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1328     error_free(parent->backing_blocker);
1329     parent->backing_blocker = NULL;
1330 }
1331 
1332 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1333                                         const char *filename, Error **errp)
1334 {
1335     BlockDriverState *parent = c->opaque;
1336     bool read_only = bdrv_is_read_only(parent);
1337     int ret;
1338     GLOBAL_STATE_CODE();
1339 
1340     if (read_only) {
1341         ret = bdrv_reopen_set_read_only(parent, false, errp);
1342         if (ret < 0) {
1343             return ret;
1344         }
1345     }
1346 
1347     ret = bdrv_change_backing_file(parent, filename,
1348                                    base->drv ? base->drv->format_name : "",
1349                                    false);
1350     if (ret < 0) {
1351         error_setg_errno(errp, -ret, "Could not update backing file link");
1352     }
1353 
1354     if (read_only) {
1355         bdrv_reopen_set_read_only(parent, true, NULL);
1356     }
1357 
1358     return ret;
1359 }
1360 
1361 /*
1362  * Returns the options and flags that a generic child of a BDS should
1363  * get, based on the given options and flags for the parent BDS.
1364  */
1365 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1366                                    int *child_flags, QDict *child_options,
1367                                    int parent_flags, QDict *parent_options)
1368 {
1369     int flags = parent_flags;
1370     GLOBAL_STATE_CODE();
1371 
1372     /*
1373      * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1374      * Generally, the question to answer is: Should this child be
1375      * format-probed by default?
1376      */
1377 
1378     /*
1379      * Pure and non-filtered data children of non-format nodes should
1380      * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1381      * set).  This only affects a very limited set of drivers (namely
1382      * quorum and blkverify when this comment was written).
1383      * Force-clear BDRV_O_PROTOCOL then.
1384      */
1385     if (!parent_is_format &&
1386         (role & BDRV_CHILD_DATA) &&
1387         !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1388     {
1389         flags &= ~BDRV_O_PROTOCOL;
1390     }
1391 
1392     /*
1393      * All children of format nodes (except for COW children) and all
1394      * metadata children in general should never be format-probed.
1395      * Force-set BDRV_O_PROTOCOL then.
1396      */
1397     if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1398         (role & BDRV_CHILD_METADATA))
1399     {
1400         flags |= BDRV_O_PROTOCOL;
1401     }
1402 
1403     /*
1404      * If the cache mode isn't explicitly set, inherit direct and no-flush from
1405      * the parent.
1406      */
1407     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1408     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1409     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1410 
1411     if (role & BDRV_CHILD_COW) {
1412         /* backing files are opened read-only by default */
1413         qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1414         qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1415     } else {
1416         /* Inherit the read-only option from the parent if it's not set */
1417         qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1418         qdict_copy_default(child_options, parent_options,
1419                            BDRV_OPT_AUTO_READ_ONLY);
1420     }
1421 
1422     /*
1423      * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1424      * can default to enable it on lower layers regardless of the
1425      * parent option.
1426      */
1427     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1428 
1429     /* Clear flags that only apply to the top layer */
1430     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1431 
1432     if (role & BDRV_CHILD_METADATA) {
1433         flags &= ~BDRV_O_NO_IO;
1434     }
1435     if (role & BDRV_CHILD_COW) {
1436         flags &= ~BDRV_O_TEMPORARY;
1437     }
1438 
1439     *child_flags = flags;
1440 }
1441 
1442 static void bdrv_child_cb_attach(BdrvChild *child)
1443 {
1444     BlockDriverState *bs = child->opaque;
1445 
1446     assert_bdrv_graph_writable(bs);
1447     QLIST_INSERT_HEAD(&bs->children, child, next);
1448 
1449     if (child->role & BDRV_CHILD_COW) {
1450         bdrv_backing_attach(child);
1451     }
1452 
1453     bdrv_apply_subtree_drain(child, bs);
1454 }
1455 
1456 static void bdrv_child_cb_detach(BdrvChild *child)
1457 {
1458     BlockDriverState *bs = child->opaque;
1459 
1460     if (child->role & BDRV_CHILD_COW) {
1461         bdrv_backing_detach(child);
1462     }
1463 
1464     bdrv_unapply_subtree_drain(child, bs);
1465 
1466     assert_bdrv_graph_writable(bs);
1467     QLIST_REMOVE(child, next);
1468 }
1469 
1470 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1471                                          const char *filename, Error **errp)
1472 {
1473     if (c->role & BDRV_CHILD_COW) {
1474         return bdrv_backing_update_filename(c, base, filename, errp);
1475     }
1476     return 0;
1477 }
1478 
1479 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1480 {
1481     BlockDriverState *bs = c->opaque;
1482     IO_CODE();
1483 
1484     return bdrv_get_aio_context(bs);
1485 }
1486 
1487 const BdrvChildClass child_of_bds = {
1488     .parent_is_bds   = true,
1489     .get_parent_desc = bdrv_child_get_parent_desc,
1490     .inherit_options = bdrv_inherited_options,
1491     .drained_begin   = bdrv_child_cb_drained_begin,
1492     .drained_poll    = bdrv_child_cb_drained_poll,
1493     .drained_end     = bdrv_child_cb_drained_end,
1494     .attach          = bdrv_child_cb_attach,
1495     .detach          = bdrv_child_cb_detach,
1496     .inactivate      = bdrv_child_cb_inactivate,
1497     .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1498     .set_aio_ctx     = bdrv_child_cb_set_aio_ctx,
1499     .update_filename = bdrv_child_cb_update_filename,
1500     .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1501 };
1502 
1503 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1504 {
1505     GLOBAL_STATE_CODE();
1506     return c->klass->get_parent_aio_context(c);
1507 }
1508 
1509 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1510 {
1511     int open_flags = flags;
1512     GLOBAL_STATE_CODE();
1513 
1514     /*
1515      * Clear flags that are internal to the block layer before opening the
1516      * image.
1517      */
1518     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1519 
1520     return open_flags;
1521 }
1522 
1523 static void update_flags_from_options(int *flags, QemuOpts *opts)
1524 {
1525     GLOBAL_STATE_CODE();
1526 
1527     *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1528 
1529     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1530         *flags |= BDRV_O_NO_FLUSH;
1531     }
1532 
1533     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1534         *flags |= BDRV_O_NOCACHE;
1535     }
1536 
1537     if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1538         *flags |= BDRV_O_RDWR;
1539     }
1540 
1541     if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1542         *flags |= BDRV_O_AUTO_RDONLY;
1543     }
1544 }
1545 
1546 static void update_options_from_flags(QDict *options, int flags)
1547 {
1548     GLOBAL_STATE_CODE();
1549     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1550         qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1551     }
1552     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1553         qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1554                        flags & BDRV_O_NO_FLUSH);
1555     }
1556     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1557         qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1558     }
1559     if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1560         qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1561                        flags & BDRV_O_AUTO_RDONLY);
1562     }
1563 }
1564 
1565 static void bdrv_assign_node_name(BlockDriverState *bs,
1566                                   const char *node_name,
1567                                   Error **errp)
1568 {
1569     char *gen_node_name = NULL;
1570     GLOBAL_STATE_CODE();
1571 
1572     if (!node_name) {
1573         node_name = gen_node_name = id_generate(ID_BLOCK);
1574     } else if (!id_wellformed(node_name)) {
1575         /*
1576          * Check for empty string or invalid characters, but not if it is
1577          * generated (generated names use characters not available to the user)
1578          */
1579         error_setg(errp, "Invalid node-name: '%s'", node_name);
1580         return;
1581     }
1582 
1583     /* takes care of avoiding namespaces collisions */
1584     if (blk_by_name(node_name)) {
1585         error_setg(errp, "node-name=%s is conflicting with a device id",
1586                    node_name);
1587         goto out;
1588     }
1589 
1590     /* takes care of avoiding duplicates node names */
1591     if (bdrv_find_node(node_name)) {
1592         error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1593         goto out;
1594     }
1595 
1596     /* Make sure that the node name isn't truncated */
1597     if (strlen(node_name) >= sizeof(bs->node_name)) {
1598         error_setg(errp, "Node name too long");
1599         goto out;
1600     }
1601 
1602     /* copy node name into the bs and insert it into the graph list */
1603     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1604     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1605 out:
1606     g_free(gen_node_name);
1607 }
1608 
1609 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1610                             const char *node_name, QDict *options,
1611                             int open_flags, Error **errp)
1612 {
1613     Error *local_err = NULL;
1614     int i, ret;
1615     GLOBAL_STATE_CODE();
1616 
1617     bdrv_assign_node_name(bs, node_name, &local_err);
1618     if (local_err) {
1619         error_propagate(errp, local_err);
1620         return -EINVAL;
1621     }
1622 
1623     bs->drv = drv;
1624     bs->opaque = g_malloc0(drv->instance_size);
1625 
1626     if (drv->bdrv_file_open) {
1627         assert(!drv->bdrv_needs_filename || bs->filename[0]);
1628         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1629     } else if (drv->bdrv_open) {
1630         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1631     } else {
1632         ret = 0;
1633     }
1634 
1635     if (ret < 0) {
1636         if (local_err) {
1637             error_propagate(errp, local_err);
1638         } else if (bs->filename[0]) {
1639             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1640         } else {
1641             error_setg_errno(errp, -ret, "Could not open image");
1642         }
1643         goto open_failed;
1644     }
1645 
1646     ret = refresh_total_sectors(bs, bs->total_sectors);
1647     if (ret < 0) {
1648         error_setg_errno(errp, -ret, "Could not refresh total sector count");
1649         return ret;
1650     }
1651 
1652     bdrv_refresh_limits(bs, NULL, &local_err);
1653     if (local_err) {
1654         error_propagate(errp, local_err);
1655         return -EINVAL;
1656     }
1657 
1658     assert(bdrv_opt_mem_align(bs) != 0);
1659     assert(bdrv_min_mem_align(bs) != 0);
1660     assert(is_power_of_2(bs->bl.request_alignment));
1661 
1662     for (i = 0; i < bs->quiesce_counter; i++) {
1663         if (drv->bdrv_co_drain_begin) {
1664             drv->bdrv_co_drain_begin(bs);
1665         }
1666     }
1667 
1668     return 0;
1669 open_failed:
1670     bs->drv = NULL;
1671     if (bs->file != NULL) {
1672         bdrv_unref_child(bs, bs->file);
1673         bs->file = NULL;
1674     }
1675     g_free(bs->opaque);
1676     bs->opaque = NULL;
1677     return ret;
1678 }
1679 
1680 /*
1681  * Create and open a block node.
1682  *
1683  * @options is a QDict of options to pass to the block drivers, or NULL for an
1684  * empty set of options. The reference to the QDict belongs to the block layer
1685  * after the call (even on failure), so if the caller intends to reuse the
1686  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1687  */
1688 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1689                                             const char *node_name,
1690                                             QDict *options, int flags,
1691                                             Error **errp)
1692 {
1693     BlockDriverState *bs;
1694     int ret;
1695 
1696     GLOBAL_STATE_CODE();
1697 
1698     bs = bdrv_new();
1699     bs->open_flags = flags;
1700     bs->options = options ?: qdict_new();
1701     bs->explicit_options = qdict_clone_shallow(bs->options);
1702     bs->opaque = NULL;
1703 
1704     update_options_from_flags(bs->options, flags);
1705 
1706     ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1707     if (ret < 0) {
1708         qobject_unref(bs->explicit_options);
1709         bs->explicit_options = NULL;
1710         qobject_unref(bs->options);
1711         bs->options = NULL;
1712         bdrv_unref(bs);
1713         return NULL;
1714     }
1715 
1716     return bs;
1717 }
1718 
1719 /* Create and open a block node. */
1720 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1721                                        int flags, Error **errp)
1722 {
1723     GLOBAL_STATE_CODE();
1724     return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1725 }
1726 
1727 QemuOptsList bdrv_runtime_opts = {
1728     .name = "bdrv_common",
1729     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1730     .desc = {
1731         {
1732             .name = "node-name",
1733             .type = QEMU_OPT_STRING,
1734             .help = "Node name of the block device node",
1735         },
1736         {
1737             .name = "driver",
1738             .type = QEMU_OPT_STRING,
1739             .help = "Block driver to use for the node",
1740         },
1741         {
1742             .name = BDRV_OPT_CACHE_DIRECT,
1743             .type = QEMU_OPT_BOOL,
1744             .help = "Bypass software writeback cache on the host",
1745         },
1746         {
1747             .name = BDRV_OPT_CACHE_NO_FLUSH,
1748             .type = QEMU_OPT_BOOL,
1749             .help = "Ignore flush requests",
1750         },
1751         {
1752             .name = BDRV_OPT_READ_ONLY,
1753             .type = QEMU_OPT_BOOL,
1754             .help = "Node is opened in read-only mode",
1755         },
1756         {
1757             .name = BDRV_OPT_AUTO_READ_ONLY,
1758             .type = QEMU_OPT_BOOL,
1759             .help = "Node can become read-only if opening read-write fails",
1760         },
1761         {
1762             .name = "detect-zeroes",
1763             .type = QEMU_OPT_STRING,
1764             .help = "try to optimize zero writes (off, on, unmap)",
1765         },
1766         {
1767             .name = BDRV_OPT_DISCARD,
1768             .type = QEMU_OPT_STRING,
1769             .help = "discard operation (ignore/off, unmap/on)",
1770         },
1771         {
1772             .name = BDRV_OPT_FORCE_SHARE,
1773             .type = QEMU_OPT_BOOL,
1774             .help = "always accept other writers (default: off)",
1775         },
1776         { /* end of list */ }
1777     },
1778 };
1779 
1780 QemuOptsList bdrv_create_opts_simple = {
1781     .name = "simple-create-opts",
1782     .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1783     .desc = {
1784         {
1785             .name = BLOCK_OPT_SIZE,
1786             .type = QEMU_OPT_SIZE,
1787             .help = "Virtual disk size"
1788         },
1789         {
1790             .name = BLOCK_OPT_PREALLOC,
1791             .type = QEMU_OPT_STRING,
1792             .help = "Preallocation mode (allowed values: off)"
1793         },
1794         { /* end of list */ }
1795     }
1796 };
1797 
1798 /*
1799  * Common part for opening disk images and files
1800  *
1801  * Removes all processed options from *options.
1802  */
1803 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1804                             QDict *options, Error **errp)
1805 {
1806     int ret, open_flags;
1807     const char *filename;
1808     const char *driver_name = NULL;
1809     const char *node_name = NULL;
1810     const char *discard;
1811     QemuOpts *opts;
1812     BlockDriver *drv;
1813     Error *local_err = NULL;
1814     bool ro;
1815 
1816     assert(bs->file == NULL);
1817     assert(options != NULL && bs->options != options);
1818     GLOBAL_STATE_CODE();
1819 
1820     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1821     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1822         ret = -EINVAL;
1823         goto fail_opts;
1824     }
1825 
1826     update_flags_from_options(&bs->open_flags, opts);
1827 
1828     driver_name = qemu_opt_get(opts, "driver");
1829     drv = bdrv_find_format(driver_name);
1830     assert(drv != NULL);
1831 
1832     bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1833 
1834     if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1835         error_setg(errp,
1836                    BDRV_OPT_FORCE_SHARE
1837                    "=on can only be used with read-only images");
1838         ret = -EINVAL;
1839         goto fail_opts;
1840     }
1841 
1842     if (file != NULL) {
1843         bdrv_refresh_filename(blk_bs(file));
1844         filename = blk_bs(file)->filename;
1845     } else {
1846         /*
1847          * Caution: while qdict_get_try_str() is fine, getting
1848          * non-string types would require more care.  When @options
1849          * come from -blockdev or blockdev_add, its members are typed
1850          * according to the QAPI schema, but when they come from
1851          * -drive, they're all QString.
1852          */
1853         filename = qdict_get_try_str(options, "filename");
1854     }
1855 
1856     if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1857         error_setg(errp, "The '%s' block driver requires a file name",
1858                    drv->format_name);
1859         ret = -EINVAL;
1860         goto fail_opts;
1861     }
1862 
1863     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1864                            drv->format_name);
1865 
1866     ro = bdrv_is_read_only(bs);
1867 
1868     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1869         if (!ro && bdrv_is_whitelisted(drv, true)) {
1870             ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1871         } else {
1872             ret = -ENOTSUP;
1873         }
1874         if (ret < 0) {
1875             error_setg(errp,
1876                        !ro && bdrv_is_whitelisted(drv, true)
1877                        ? "Driver '%s' can only be used for read-only devices"
1878                        : "Driver '%s' is not whitelisted",
1879                        drv->format_name);
1880             goto fail_opts;
1881         }
1882     }
1883 
1884     /* bdrv_new() and bdrv_close() make it so */
1885     assert(qatomic_read(&bs->copy_on_read) == 0);
1886 
1887     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1888         if (!ro) {
1889             bdrv_enable_copy_on_read(bs);
1890         } else {
1891             error_setg(errp, "Can't use copy-on-read on read-only device");
1892             ret = -EINVAL;
1893             goto fail_opts;
1894         }
1895     }
1896 
1897     discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1898     if (discard != NULL) {
1899         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1900             error_setg(errp, "Invalid discard option");
1901             ret = -EINVAL;
1902             goto fail_opts;
1903         }
1904     }
1905 
1906     bs->detect_zeroes =
1907         bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1908     if (local_err) {
1909         error_propagate(errp, local_err);
1910         ret = -EINVAL;
1911         goto fail_opts;
1912     }
1913 
1914     if (filename != NULL) {
1915         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1916     } else {
1917         bs->filename[0] = '\0';
1918     }
1919     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1920 
1921     /* Open the image, either directly or using a protocol */
1922     open_flags = bdrv_open_flags(bs, bs->open_flags);
1923     node_name = qemu_opt_get(opts, "node-name");
1924 
1925     assert(!drv->bdrv_file_open || file == NULL);
1926     ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1927     if (ret < 0) {
1928         goto fail_opts;
1929     }
1930 
1931     qemu_opts_del(opts);
1932     return 0;
1933 
1934 fail_opts:
1935     qemu_opts_del(opts);
1936     return ret;
1937 }
1938 
1939 static QDict *parse_json_filename(const char *filename, Error **errp)
1940 {
1941     QObject *options_obj;
1942     QDict *options;
1943     int ret;
1944     GLOBAL_STATE_CODE();
1945 
1946     ret = strstart(filename, "json:", &filename);
1947     assert(ret);
1948 
1949     options_obj = qobject_from_json(filename, errp);
1950     if (!options_obj) {
1951         error_prepend(errp, "Could not parse the JSON options: ");
1952         return NULL;
1953     }
1954 
1955     options = qobject_to(QDict, options_obj);
1956     if (!options) {
1957         qobject_unref(options_obj);
1958         error_setg(errp, "Invalid JSON object given");
1959         return NULL;
1960     }
1961 
1962     qdict_flatten(options);
1963 
1964     return options;
1965 }
1966 
1967 static void parse_json_protocol(QDict *options, const char **pfilename,
1968                                 Error **errp)
1969 {
1970     QDict *json_options;
1971     Error *local_err = NULL;
1972     GLOBAL_STATE_CODE();
1973 
1974     /* Parse json: pseudo-protocol */
1975     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1976         return;
1977     }
1978 
1979     json_options = parse_json_filename(*pfilename, &local_err);
1980     if (local_err) {
1981         error_propagate(errp, local_err);
1982         return;
1983     }
1984 
1985     /* Options given in the filename have lower priority than options
1986      * specified directly */
1987     qdict_join(options, json_options, false);
1988     qobject_unref(json_options);
1989     *pfilename = NULL;
1990 }
1991 
1992 /*
1993  * Fills in default options for opening images and converts the legacy
1994  * filename/flags pair to option QDict entries.
1995  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1996  * block driver has been specified explicitly.
1997  */
1998 static int bdrv_fill_options(QDict **options, const char *filename,
1999                              int *flags, Error **errp)
2000 {
2001     const char *drvname;
2002     bool protocol = *flags & BDRV_O_PROTOCOL;
2003     bool parse_filename = false;
2004     BlockDriver *drv = NULL;
2005     Error *local_err = NULL;
2006 
2007     GLOBAL_STATE_CODE();
2008 
2009     /*
2010      * Caution: while qdict_get_try_str() is fine, getting non-string
2011      * types would require more care.  When @options come from
2012      * -blockdev or blockdev_add, its members are typed according to
2013      * the QAPI schema, but when they come from -drive, they're all
2014      * QString.
2015      */
2016     drvname = qdict_get_try_str(*options, "driver");
2017     if (drvname) {
2018         drv = bdrv_find_format(drvname);
2019         if (!drv) {
2020             error_setg(errp, "Unknown driver '%s'", drvname);
2021             return -ENOENT;
2022         }
2023         /* If the user has explicitly specified the driver, this choice should
2024          * override the BDRV_O_PROTOCOL flag */
2025         protocol = drv->bdrv_file_open;
2026     }
2027 
2028     if (protocol) {
2029         *flags |= BDRV_O_PROTOCOL;
2030     } else {
2031         *flags &= ~BDRV_O_PROTOCOL;
2032     }
2033 
2034     /* Translate cache options from flags into options */
2035     update_options_from_flags(*options, *flags);
2036 
2037     /* Fetch the file name from the options QDict if necessary */
2038     if (protocol && filename) {
2039         if (!qdict_haskey(*options, "filename")) {
2040             qdict_put_str(*options, "filename", filename);
2041             parse_filename = true;
2042         } else {
2043             error_setg(errp, "Can't specify 'file' and 'filename' options at "
2044                              "the same time");
2045             return -EINVAL;
2046         }
2047     }
2048 
2049     /* Find the right block driver */
2050     /* See cautionary note on accessing @options above */
2051     filename = qdict_get_try_str(*options, "filename");
2052 
2053     if (!drvname && protocol) {
2054         if (filename) {
2055             drv = bdrv_find_protocol(filename, parse_filename, errp);
2056             if (!drv) {
2057                 return -EINVAL;
2058             }
2059 
2060             drvname = drv->format_name;
2061             qdict_put_str(*options, "driver", drvname);
2062         } else {
2063             error_setg(errp, "Must specify either driver or file");
2064             return -EINVAL;
2065         }
2066     }
2067 
2068     assert(drv || !protocol);
2069 
2070     /* Driver-specific filename parsing */
2071     if (drv && drv->bdrv_parse_filename && parse_filename) {
2072         drv->bdrv_parse_filename(filename, *options, &local_err);
2073         if (local_err) {
2074             error_propagate(errp, local_err);
2075             return -EINVAL;
2076         }
2077 
2078         if (!drv->bdrv_needs_filename) {
2079             qdict_del(*options, "filename");
2080         }
2081     }
2082 
2083     return 0;
2084 }
2085 
2086 typedef struct BlockReopenQueueEntry {
2087      bool prepared;
2088      bool perms_checked;
2089      BDRVReopenState state;
2090      QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2091 } BlockReopenQueueEntry;
2092 
2093 /*
2094  * Return the flags that @bs will have after the reopens in @q have
2095  * successfully completed. If @q is NULL (or @bs is not contained in @q),
2096  * return the current flags.
2097  */
2098 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2099 {
2100     BlockReopenQueueEntry *entry;
2101 
2102     if (q != NULL) {
2103         QTAILQ_FOREACH(entry, q, entry) {
2104             if (entry->state.bs == bs) {
2105                 return entry->state.flags;
2106             }
2107         }
2108     }
2109 
2110     return bs->open_flags;
2111 }
2112 
2113 /* Returns whether the image file can be written to after the reopen queue @q
2114  * has been successfully applied, or right now if @q is NULL. */
2115 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2116                                           BlockReopenQueue *q)
2117 {
2118     int flags = bdrv_reopen_get_flags(q, bs);
2119 
2120     return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2121 }
2122 
2123 /*
2124  * Return whether the BDS can be written to.  This is not necessarily
2125  * the same as !bdrv_is_read_only(bs), as inactivated images may not
2126  * be written to but do not count as read-only images.
2127  */
2128 bool bdrv_is_writable(BlockDriverState *bs)
2129 {
2130     IO_CODE();
2131     return bdrv_is_writable_after_reopen(bs, NULL);
2132 }
2133 
2134 static char *bdrv_child_user_desc(BdrvChild *c)
2135 {
2136     GLOBAL_STATE_CODE();
2137     return c->klass->get_parent_desc(c);
2138 }
2139 
2140 /*
2141  * Check that @a allows everything that @b needs. @a and @b must reference same
2142  * child node.
2143  */
2144 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2145 {
2146     const char *child_bs_name;
2147     g_autofree char *a_user = NULL;
2148     g_autofree char *b_user = NULL;
2149     g_autofree char *perms = NULL;
2150 
2151     assert(a->bs);
2152     assert(a->bs == b->bs);
2153     GLOBAL_STATE_CODE();
2154 
2155     if ((b->perm & a->shared_perm) == b->perm) {
2156         return true;
2157     }
2158 
2159     child_bs_name = bdrv_get_node_name(b->bs);
2160     a_user = bdrv_child_user_desc(a);
2161     b_user = bdrv_child_user_desc(b);
2162     perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2163 
2164     error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2165                "both required by %s (uses node '%s' as '%s' child) and "
2166                "unshared by %s (uses node '%s' as '%s' child).",
2167                child_bs_name, perms,
2168                b_user, child_bs_name, b->name,
2169                a_user, child_bs_name, a->name);
2170 
2171     return false;
2172 }
2173 
2174 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2175 {
2176     BdrvChild *a, *b;
2177     GLOBAL_STATE_CODE();
2178 
2179     /*
2180      * During the loop we'll look at each pair twice. That's correct because
2181      * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2182      * directions.
2183      */
2184     QLIST_FOREACH(a, &bs->parents, next_parent) {
2185         QLIST_FOREACH(b, &bs->parents, next_parent) {
2186             if (a == b) {
2187                 continue;
2188             }
2189 
2190             if (!bdrv_a_allow_b(a, b, errp)) {
2191                 return true;
2192             }
2193         }
2194     }
2195 
2196     return false;
2197 }
2198 
2199 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2200                             BdrvChild *c, BdrvChildRole role,
2201                             BlockReopenQueue *reopen_queue,
2202                             uint64_t parent_perm, uint64_t parent_shared,
2203                             uint64_t *nperm, uint64_t *nshared)
2204 {
2205     assert(bs->drv && bs->drv->bdrv_child_perm);
2206     GLOBAL_STATE_CODE();
2207     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2208                              parent_perm, parent_shared,
2209                              nperm, nshared);
2210     /* TODO Take force_share from reopen_queue */
2211     if (child_bs && child_bs->force_share) {
2212         *nshared = BLK_PERM_ALL;
2213     }
2214 }
2215 
2216 /*
2217  * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2218  * nodes that are already in the @list, of course) so that final list is
2219  * topologically sorted. Return the result (GSList @list object is updated, so
2220  * don't use old reference after function call).
2221  *
2222  * On function start @list must be already topologically sorted and for any node
2223  * in the @list the whole subtree of the node must be in the @list as well. The
2224  * simplest way to satisfy this criteria: use only result of
2225  * bdrv_topological_dfs() or NULL as @list parameter.
2226  */
2227 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2228                                     BlockDriverState *bs)
2229 {
2230     BdrvChild *child;
2231     g_autoptr(GHashTable) local_found = NULL;
2232 
2233     GLOBAL_STATE_CODE();
2234 
2235     if (!found) {
2236         assert(!list);
2237         found = local_found = g_hash_table_new(NULL, NULL);
2238     }
2239 
2240     if (g_hash_table_contains(found, bs)) {
2241         return list;
2242     }
2243     g_hash_table_add(found, bs);
2244 
2245     QLIST_FOREACH(child, &bs->children, next) {
2246         list = bdrv_topological_dfs(list, found, child->bs);
2247     }
2248 
2249     return g_slist_prepend(list, bs);
2250 }
2251 
2252 typedef struct BdrvChildSetPermState {
2253     BdrvChild *child;
2254     uint64_t old_perm;
2255     uint64_t old_shared_perm;
2256 } BdrvChildSetPermState;
2257 
2258 static void bdrv_child_set_perm_abort(void *opaque)
2259 {
2260     BdrvChildSetPermState *s = opaque;
2261 
2262     GLOBAL_STATE_CODE();
2263 
2264     s->child->perm = s->old_perm;
2265     s->child->shared_perm = s->old_shared_perm;
2266 }
2267 
2268 static TransactionActionDrv bdrv_child_set_pem_drv = {
2269     .abort = bdrv_child_set_perm_abort,
2270     .clean = g_free,
2271 };
2272 
2273 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2274                                 uint64_t shared, Transaction *tran)
2275 {
2276     BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2277     GLOBAL_STATE_CODE();
2278 
2279     *s = (BdrvChildSetPermState) {
2280         .child = c,
2281         .old_perm = c->perm,
2282         .old_shared_perm = c->shared_perm,
2283     };
2284 
2285     c->perm = perm;
2286     c->shared_perm = shared;
2287 
2288     tran_add(tran, &bdrv_child_set_pem_drv, s);
2289 }
2290 
2291 static void bdrv_drv_set_perm_commit(void *opaque)
2292 {
2293     BlockDriverState *bs = opaque;
2294     uint64_t cumulative_perms, cumulative_shared_perms;
2295     GLOBAL_STATE_CODE();
2296 
2297     if (bs->drv->bdrv_set_perm) {
2298         bdrv_get_cumulative_perm(bs, &cumulative_perms,
2299                                  &cumulative_shared_perms);
2300         bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2301     }
2302 }
2303 
2304 static void bdrv_drv_set_perm_abort(void *opaque)
2305 {
2306     BlockDriverState *bs = opaque;
2307     GLOBAL_STATE_CODE();
2308 
2309     if (bs->drv->bdrv_abort_perm_update) {
2310         bs->drv->bdrv_abort_perm_update(bs);
2311     }
2312 }
2313 
2314 TransactionActionDrv bdrv_drv_set_perm_drv = {
2315     .abort = bdrv_drv_set_perm_abort,
2316     .commit = bdrv_drv_set_perm_commit,
2317 };
2318 
2319 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2320                              uint64_t shared_perm, Transaction *tran,
2321                              Error **errp)
2322 {
2323     GLOBAL_STATE_CODE();
2324     if (!bs->drv) {
2325         return 0;
2326     }
2327 
2328     if (bs->drv->bdrv_check_perm) {
2329         int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2330         if (ret < 0) {
2331             return ret;
2332         }
2333     }
2334 
2335     if (tran) {
2336         tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2337     }
2338 
2339     return 0;
2340 }
2341 
2342 typedef struct BdrvReplaceChildState {
2343     BdrvChild *child;
2344     BlockDriverState *old_bs;
2345 } BdrvReplaceChildState;
2346 
2347 static void bdrv_replace_child_commit(void *opaque)
2348 {
2349     BdrvReplaceChildState *s = opaque;
2350     GLOBAL_STATE_CODE();
2351 
2352     bdrv_unref(s->old_bs);
2353 }
2354 
2355 static void bdrv_replace_child_abort(void *opaque)
2356 {
2357     BdrvReplaceChildState *s = opaque;
2358     BlockDriverState *new_bs = s->child->bs;
2359 
2360     GLOBAL_STATE_CODE();
2361     /* old_bs reference is transparently moved from @s to @s->child */
2362     bdrv_replace_child_noperm(&s->child, s->old_bs);
2363     bdrv_unref(new_bs);
2364 }
2365 
2366 static TransactionActionDrv bdrv_replace_child_drv = {
2367     .commit = bdrv_replace_child_commit,
2368     .abort = bdrv_replace_child_abort,
2369     .clean = g_free,
2370 };
2371 
2372 /*
2373  * bdrv_replace_child_tran
2374  *
2375  * Note: real unref of old_bs is done only on commit.
2376  *
2377  * The function doesn't update permissions, caller is responsible for this.
2378  */
2379 static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2380                                     Transaction *tran)
2381 {
2382     BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2383     *s = (BdrvReplaceChildState) {
2384         .child = child,
2385         .old_bs = child->bs,
2386     };
2387     tran_add(tran, &bdrv_replace_child_drv, s);
2388 
2389     if (new_bs) {
2390         bdrv_ref(new_bs);
2391     }
2392     bdrv_replace_child_noperm(&child, new_bs);
2393     /* old_bs reference is transparently moved from @child to @s */
2394 }
2395 
2396 /*
2397  * Refresh permissions in @bs subtree. The function is intended to be called
2398  * after some graph modification that was done without permission update.
2399  */
2400 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2401                                   Transaction *tran, Error **errp)
2402 {
2403     BlockDriver *drv = bs->drv;
2404     BdrvChild *c;
2405     int ret;
2406     uint64_t cumulative_perms, cumulative_shared_perms;
2407     GLOBAL_STATE_CODE();
2408 
2409     bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2410 
2411     /* Write permissions never work with read-only images */
2412     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2413         !bdrv_is_writable_after_reopen(bs, q))
2414     {
2415         if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2416             error_setg(errp, "Block node is read-only");
2417         } else {
2418             error_setg(errp, "Read-only block node '%s' cannot support "
2419                        "read-write users", bdrv_get_node_name(bs));
2420         }
2421 
2422         return -EPERM;
2423     }
2424 
2425     /*
2426      * Unaligned requests will automatically be aligned to bl.request_alignment
2427      * and without RESIZE we can't extend requests to write to space beyond the
2428      * end of the image, so it's required that the image size is aligned.
2429      */
2430     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2431         !(cumulative_perms & BLK_PERM_RESIZE))
2432     {
2433         if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2434             error_setg(errp, "Cannot get 'write' permission without 'resize': "
2435                              "Image size is not a multiple of request "
2436                              "alignment");
2437             return -EPERM;
2438         }
2439     }
2440 
2441     /* Check this node */
2442     if (!drv) {
2443         return 0;
2444     }
2445 
2446     ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2447                             errp);
2448     if (ret < 0) {
2449         return ret;
2450     }
2451 
2452     /* Drivers that never have children can omit .bdrv_child_perm() */
2453     if (!drv->bdrv_child_perm) {
2454         assert(QLIST_EMPTY(&bs->children));
2455         return 0;
2456     }
2457 
2458     /* Check all children */
2459     QLIST_FOREACH(c, &bs->children, next) {
2460         uint64_t cur_perm, cur_shared;
2461 
2462         bdrv_child_perm(bs, c->bs, c, c->role, q,
2463                         cumulative_perms, cumulative_shared_perms,
2464                         &cur_perm, &cur_shared);
2465         bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2466     }
2467 
2468     return 0;
2469 }
2470 
2471 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2472                                    Transaction *tran, Error **errp)
2473 {
2474     int ret;
2475     BlockDriverState *bs;
2476     GLOBAL_STATE_CODE();
2477 
2478     for ( ; list; list = list->next) {
2479         bs = list->data;
2480 
2481         if (bdrv_parent_perms_conflict(bs, errp)) {
2482             return -EINVAL;
2483         }
2484 
2485         ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2486         if (ret < 0) {
2487             return ret;
2488         }
2489     }
2490 
2491     return 0;
2492 }
2493 
2494 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2495                               uint64_t *shared_perm)
2496 {
2497     BdrvChild *c;
2498     uint64_t cumulative_perms = 0;
2499     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2500 
2501     GLOBAL_STATE_CODE();
2502 
2503     QLIST_FOREACH(c, &bs->parents, next_parent) {
2504         cumulative_perms |= c->perm;
2505         cumulative_shared_perms &= c->shared_perm;
2506     }
2507 
2508     *perm = cumulative_perms;
2509     *shared_perm = cumulative_shared_perms;
2510 }
2511 
2512 char *bdrv_perm_names(uint64_t perm)
2513 {
2514     struct perm_name {
2515         uint64_t perm;
2516         const char *name;
2517     } permissions[] = {
2518         { BLK_PERM_CONSISTENT_READ, "consistent read" },
2519         { BLK_PERM_WRITE,           "write" },
2520         { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2521         { BLK_PERM_RESIZE,          "resize" },
2522         { 0, NULL }
2523     };
2524 
2525     GString *result = g_string_sized_new(30);
2526     struct perm_name *p;
2527 
2528     for (p = permissions; p->name; p++) {
2529         if (perm & p->perm) {
2530             if (result->len > 0) {
2531                 g_string_append(result, ", ");
2532             }
2533             g_string_append(result, p->name);
2534         }
2535     }
2536 
2537     return g_string_free(result, FALSE);
2538 }
2539 
2540 
2541 static int bdrv_refresh_perms(BlockDriverState *bs, Error **errp)
2542 {
2543     int ret;
2544     Transaction *tran = tran_new();
2545     g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2546     GLOBAL_STATE_CODE();
2547 
2548     ret = bdrv_list_refresh_perms(list, NULL, tran, errp);
2549     tran_finalize(tran, ret);
2550 
2551     return ret;
2552 }
2553 
2554 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2555                             Error **errp)
2556 {
2557     Error *local_err = NULL;
2558     Transaction *tran = tran_new();
2559     int ret;
2560 
2561     GLOBAL_STATE_CODE();
2562 
2563     bdrv_child_set_perm(c, perm, shared, tran);
2564 
2565     ret = bdrv_refresh_perms(c->bs, &local_err);
2566 
2567     tran_finalize(tran, ret);
2568 
2569     if (ret < 0) {
2570         if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2571             /* tighten permissions */
2572             error_propagate(errp, local_err);
2573         } else {
2574             /*
2575              * Our caller may intend to only loosen restrictions and
2576              * does not expect this function to fail.  Errors are not
2577              * fatal in such a case, so we can just hide them from our
2578              * caller.
2579              */
2580             error_free(local_err);
2581             ret = 0;
2582         }
2583     }
2584 
2585     return ret;
2586 }
2587 
2588 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2589 {
2590     uint64_t parent_perms, parent_shared;
2591     uint64_t perms, shared;
2592 
2593     GLOBAL_STATE_CODE();
2594 
2595     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2596     bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2597                     parent_perms, parent_shared, &perms, &shared);
2598 
2599     return bdrv_child_try_set_perm(c, perms, shared, errp);
2600 }
2601 
2602 /*
2603  * Default implementation for .bdrv_child_perm() for block filters:
2604  * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2605  * filtered child.
2606  */
2607 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2608                                       BdrvChildRole role,
2609                                       BlockReopenQueue *reopen_queue,
2610                                       uint64_t perm, uint64_t shared,
2611                                       uint64_t *nperm, uint64_t *nshared)
2612 {
2613     GLOBAL_STATE_CODE();
2614     *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2615     *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2616 }
2617 
2618 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2619                                        BdrvChildRole role,
2620                                        BlockReopenQueue *reopen_queue,
2621                                        uint64_t perm, uint64_t shared,
2622                                        uint64_t *nperm, uint64_t *nshared)
2623 {
2624     assert(role & BDRV_CHILD_COW);
2625     GLOBAL_STATE_CODE();
2626 
2627     /*
2628      * We want consistent read from backing files if the parent needs it.
2629      * No other operations are performed on backing files.
2630      */
2631     perm &= BLK_PERM_CONSISTENT_READ;
2632 
2633     /*
2634      * If the parent can deal with changing data, we're okay with a
2635      * writable and resizable backing file.
2636      * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2637      */
2638     if (shared & BLK_PERM_WRITE) {
2639         shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2640     } else {
2641         shared = 0;
2642     }
2643 
2644     shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2645 
2646     if (bs->open_flags & BDRV_O_INACTIVE) {
2647         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2648     }
2649 
2650     *nperm = perm;
2651     *nshared = shared;
2652 }
2653 
2654 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2655                                            BdrvChildRole role,
2656                                            BlockReopenQueue *reopen_queue,
2657                                            uint64_t perm, uint64_t shared,
2658                                            uint64_t *nperm, uint64_t *nshared)
2659 {
2660     int flags;
2661 
2662     GLOBAL_STATE_CODE();
2663     assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2664 
2665     flags = bdrv_reopen_get_flags(reopen_queue, bs);
2666 
2667     /*
2668      * Apart from the modifications below, the same permissions are
2669      * forwarded and left alone as for filters
2670      */
2671     bdrv_filter_default_perms(bs, c, role, reopen_queue,
2672                               perm, shared, &perm, &shared);
2673 
2674     if (role & BDRV_CHILD_METADATA) {
2675         /* Format drivers may touch metadata even if the guest doesn't write */
2676         if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2677             perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2678         }
2679 
2680         /*
2681          * bs->file always needs to be consistent because of the
2682          * metadata. We can never allow other users to resize or write
2683          * to it.
2684          */
2685         if (!(flags & BDRV_O_NO_IO)) {
2686             perm |= BLK_PERM_CONSISTENT_READ;
2687         }
2688         shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2689     }
2690 
2691     if (role & BDRV_CHILD_DATA) {
2692         /*
2693          * Technically, everything in this block is a subset of the
2694          * BDRV_CHILD_METADATA path taken above, and so this could
2695          * be an "else if" branch.  However, that is not obvious, and
2696          * this function is not performance critical, therefore we let
2697          * this be an independent "if".
2698          */
2699 
2700         /*
2701          * We cannot allow other users to resize the file because the
2702          * format driver might have some assumptions about the size
2703          * (e.g. because it is stored in metadata, or because the file
2704          * is split into fixed-size data files).
2705          */
2706         shared &= ~BLK_PERM_RESIZE;
2707 
2708         /*
2709          * WRITE_UNCHANGED often cannot be performed as such on the
2710          * data file.  For example, the qcow2 driver may still need to
2711          * write copied clusters on copy-on-read.
2712          */
2713         if (perm & BLK_PERM_WRITE_UNCHANGED) {
2714             perm |= BLK_PERM_WRITE;
2715         }
2716 
2717         /*
2718          * If the data file is written to, the format driver may
2719          * expect to be able to resize it by writing beyond the EOF.
2720          */
2721         if (perm & BLK_PERM_WRITE) {
2722             perm |= BLK_PERM_RESIZE;
2723         }
2724     }
2725 
2726     if (bs->open_flags & BDRV_O_INACTIVE) {
2727         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2728     }
2729 
2730     *nperm = perm;
2731     *nshared = shared;
2732 }
2733 
2734 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2735                         BdrvChildRole role, BlockReopenQueue *reopen_queue,
2736                         uint64_t perm, uint64_t shared,
2737                         uint64_t *nperm, uint64_t *nshared)
2738 {
2739     GLOBAL_STATE_CODE();
2740     if (role & BDRV_CHILD_FILTERED) {
2741         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2742                          BDRV_CHILD_COW)));
2743         bdrv_filter_default_perms(bs, c, role, reopen_queue,
2744                                   perm, shared, nperm, nshared);
2745     } else if (role & BDRV_CHILD_COW) {
2746         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2747         bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2748                                    perm, shared, nperm, nshared);
2749     } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2750         bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2751                                        perm, shared, nperm, nshared);
2752     } else {
2753         g_assert_not_reached();
2754     }
2755 }
2756 
2757 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2758 {
2759     static const uint64_t permissions[] = {
2760         [BLOCK_PERMISSION_CONSISTENT_READ]  = BLK_PERM_CONSISTENT_READ,
2761         [BLOCK_PERMISSION_WRITE]            = BLK_PERM_WRITE,
2762         [BLOCK_PERMISSION_WRITE_UNCHANGED]  = BLK_PERM_WRITE_UNCHANGED,
2763         [BLOCK_PERMISSION_RESIZE]           = BLK_PERM_RESIZE,
2764     };
2765 
2766     QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2767     QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2768 
2769     assert(qapi_perm < BLOCK_PERMISSION__MAX);
2770 
2771     return permissions[qapi_perm];
2772 }
2773 
2774 static void bdrv_replace_child_noperm(BdrvChild **childp,
2775                                       BlockDriverState *new_bs)
2776 {
2777     BdrvChild *child = *childp;
2778     BlockDriverState *old_bs = child->bs;
2779     int new_bs_quiesce_counter;
2780     int drain_saldo;
2781 
2782     assert(!child->frozen);
2783     assert(old_bs != new_bs);
2784     GLOBAL_STATE_CODE();
2785 
2786     if (old_bs && new_bs) {
2787         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2788     }
2789 
2790     new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2791     drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2792 
2793     /*
2794      * If the new child node is drained but the old one was not, flush
2795      * all outstanding requests to the old child node.
2796      */
2797     while (drain_saldo > 0 && child->klass->drained_begin) {
2798         bdrv_parent_drained_begin_single(child, true);
2799         drain_saldo--;
2800     }
2801 
2802     if (old_bs) {
2803         /* Detach first so that the recursive drain sections coming from @child
2804          * are already gone and we only end the drain sections that came from
2805          * elsewhere. */
2806         if (child->klass->detach) {
2807             child->klass->detach(child);
2808         }
2809         assert_bdrv_graph_writable(old_bs);
2810         QLIST_REMOVE(child, next_parent);
2811     }
2812 
2813     child->bs = new_bs;
2814 
2815     if (new_bs) {
2816         assert_bdrv_graph_writable(new_bs);
2817         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2818 
2819         /*
2820          * Detaching the old node may have led to the new node's
2821          * quiesce_counter having been decreased.  Not a problem, we
2822          * just need to recognize this here and then invoke
2823          * drained_end appropriately more often.
2824          */
2825         assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2826         drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2827 
2828         /* Attach only after starting new drained sections, so that recursive
2829          * drain sections coming from @child don't get an extra .drained_begin
2830          * callback. */
2831         if (child->klass->attach) {
2832             child->klass->attach(child);
2833         }
2834     }
2835 
2836     /*
2837      * If the old child node was drained but the new one is not, allow
2838      * requests to come in only after the new node has been attached.
2839      */
2840     while (drain_saldo < 0 && child->klass->drained_end) {
2841         bdrv_parent_drained_end_single(child);
2842         drain_saldo++;
2843     }
2844 }
2845 
2846 /**
2847  * Free the given @child.
2848  *
2849  * The child must be empty (i.e. `child->bs == NULL`) and it must be
2850  * unused (i.e. not in a children list).
2851  */
2852 static void bdrv_child_free(BdrvChild *child)
2853 {
2854     assert(!child->bs);
2855     GLOBAL_STATE_CODE();
2856     assert(!child->next.le_prev); /* not in children list */
2857 
2858     g_free(child->name);
2859     g_free(child);
2860 }
2861 
2862 typedef struct BdrvAttachChildCommonState {
2863     BdrvChild **child;
2864     AioContext *old_parent_ctx;
2865     AioContext *old_child_ctx;
2866 } BdrvAttachChildCommonState;
2867 
2868 static void bdrv_attach_child_common_abort(void *opaque)
2869 {
2870     BdrvAttachChildCommonState *s = opaque;
2871     BdrvChild *child = *s->child;
2872     BlockDriverState *bs = child->bs;
2873 
2874     GLOBAL_STATE_CODE();
2875     bdrv_replace_child_noperm(s->child, NULL);
2876 
2877     if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2878         bdrv_try_set_aio_context(bs, s->old_child_ctx, &error_abort);
2879     }
2880 
2881     if (bdrv_child_get_parent_aio_context(child) != s->old_parent_ctx) {
2882         GSList *ignore;
2883 
2884         /* No need to ignore `child`, because it has been detached already */
2885         ignore = NULL;
2886         child->klass->can_set_aio_ctx(child, s->old_parent_ctx, &ignore,
2887                                       &error_abort);
2888         g_slist_free(ignore);
2889 
2890         ignore = NULL;
2891         child->klass->set_aio_ctx(child, s->old_parent_ctx, &ignore);
2892         g_slist_free(ignore);
2893     }
2894 
2895     bdrv_unref(bs);
2896     bdrv_child_free(child);
2897     *s->child = NULL;
2898 }
2899 
2900 static TransactionActionDrv bdrv_attach_child_common_drv = {
2901     .abort = bdrv_attach_child_common_abort,
2902     .clean = g_free,
2903 };
2904 
2905 /*
2906  * Common part of attaching bdrv child to bs or to blk or to job
2907  *
2908  * Resulting new child is returned through @child.
2909  * At start *@child must be NULL.
2910  * @child is saved to a new entry of @tran, so that *@child could be reverted to
2911  * NULL on abort(). So referenced variable must live at least until transaction
2912  * end.
2913  *
2914  * Function doesn't update permissions, caller is responsible for this.
2915  */
2916 static int bdrv_attach_child_common(BlockDriverState *child_bs,
2917                                     const char *child_name,
2918                                     const BdrvChildClass *child_class,
2919                                     BdrvChildRole child_role,
2920                                     uint64_t perm, uint64_t shared_perm,
2921                                     void *opaque, BdrvChild **child,
2922                                     Transaction *tran, Error **errp)
2923 {
2924     BdrvChild *new_child;
2925     AioContext *parent_ctx;
2926     AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2927 
2928     assert(child);
2929     assert(*child == NULL);
2930     assert(child_class->get_parent_desc);
2931     GLOBAL_STATE_CODE();
2932 
2933     new_child = g_new(BdrvChild, 1);
2934     *new_child = (BdrvChild) {
2935         .bs             = NULL,
2936         .name           = g_strdup(child_name),
2937         .klass          = child_class,
2938         .role           = child_role,
2939         .perm           = perm,
2940         .shared_perm    = shared_perm,
2941         .opaque         = opaque,
2942     };
2943 
2944     /*
2945      * If the AioContexts don't match, first try to move the subtree of
2946      * child_bs into the AioContext of the new parent. If this doesn't work,
2947      * try moving the parent into the AioContext of child_bs instead.
2948      */
2949     parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2950     if (child_ctx != parent_ctx) {
2951         Error *local_err = NULL;
2952         int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2953 
2954         if (ret < 0 && child_class->can_set_aio_ctx) {
2955             GSList *ignore = g_slist_prepend(NULL, new_child);
2956             if (child_class->can_set_aio_ctx(new_child, child_ctx, &ignore,
2957                                              NULL))
2958             {
2959                 error_free(local_err);
2960                 ret = 0;
2961                 g_slist_free(ignore);
2962                 ignore = g_slist_prepend(NULL, new_child);
2963                 child_class->set_aio_ctx(new_child, child_ctx, &ignore);
2964             }
2965             g_slist_free(ignore);
2966         }
2967 
2968         if (ret < 0) {
2969             error_propagate(errp, local_err);
2970             bdrv_child_free(new_child);
2971             return ret;
2972         }
2973     }
2974 
2975     bdrv_ref(child_bs);
2976     bdrv_replace_child_noperm(&new_child, child_bs);
2977 
2978     *child = new_child;
2979 
2980     BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
2981     *s = (BdrvAttachChildCommonState) {
2982         .child = child,
2983         .old_parent_ctx = parent_ctx,
2984         .old_child_ctx = child_ctx,
2985     };
2986     tran_add(tran, &bdrv_attach_child_common_drv, s);
2987 
2988     return 0;
2989 }
2990 
2991 /*
2992  * Variable referenced by @child must live at least until transaction end.
2993  * (see bdrv_attach_child_common() doc for details)
2994  *
2995  * Function doesn't update permissions, caller is responsible for this.
2996  */
2997 static int bdrv_attach_child_noperm(BlockDriverState *parent_bs,
2998                                     BlockDriverState *child_bs,
2999                                     const char *child_name,
3000                                     const BdrvChildClass *child_class,
3001                                     BdrvChildRole child_role,
3002                                     BdrvChild **child,
3003                                     Transaction *tran,
3004                                     Error **errp)
3005 {
3006     int ret;
3007     uint64_t perm, shared_perm;
3008 
3009     assert(parent_bs->drv);
3010     GLOBAL_STATE_CODE();
3011 
3012     if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3013         error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3014                    child_bs->node_name, child_name, parent_bs->node_name);
3015         return -EINVAL;
3016     }
3017 
3018     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3019     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3020                     perm, shared_perm, &perm, &shared_perm);
3021 
3022     ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3023                                    child_role, perm, shared_perm, parent_bs,
3024                                    child, tran, errp);
3025     if (ret < 0) {
3026         return ret;
3027     }
3028 
3029     return 0;
3030 }
3031 
3032 static void bdrv_detach_child(BdrvChild **childp)
3033 {
3034     BlockDriverState *old_bs = (*childp)->bs;
3035 
3036     GLOBAL_STATE_CODE();
3037     bdrv_replace_child_noperm(childp, NULL);
3038     bdrv_child_free(*childp);
3039 
3040     if (old_bs) {
3041         /*
3042          * Update permissions for old node. We're just taking a parent away, so
3043          * we're loosening restrictions. Errors of permission update are not
3044          * fatal in this case, ignore them.
3045          */
3046         bdrv_refresh_perms(old_bs, NULL);
3047 
3048         /*
3049          * When the parent requiring a non-default AioContext is removed, the
3050          * node moves back to the main AioContext
3051          */
3052         bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3053     }
3054 }
3055 
3056 /*
3057  * This function steals the reference to child_bs from the caller.
3058  * That reference is later dropped by bdrv_root_unref_child().
3059  *
3060  * On failure NULL is returned, errp is set and the reference to
3061  * child_bs is also dropped.
3062  *
3063  * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3064  * (unless @child_bs is already in @ctx).
3065  */
3066 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3067                                   const char *child_name,
3068                                   const BdrvChildClass *child_class,
3069                                   BdrvChildRole child_role,
3070                                   uint64_t perm, uint64_t shared_perm,
3071                                   void *opaque, Error **errp)
3072 {
3073     int ret;
3074     BdrvChild *child = NULL;
3075     Transaction *tran = tran_new();
3076 
3077     GLOBAL_STATE_CODE();
3078 
3079     ret = bdrv_attach_child_common(child_bs, child_name, child_class,
3080                                    child_role, perm, shared_perm, opaque,
3081                                    &child, tran, errp);
3082     if (ret < 0) {
3083         goto out;
3084     }
3085 
3086     ret = bdrv_refresh_perms(child_bs, errp);
3087 
3088 out:
3089     tran_finalize(tran, ret);
3090     /* child is unset on failure by bdrv_attach_child_common_abort() */
3091     assert((ret < 0) == !child);
3092 
3093     bdrv_unref(child_bs);
3094     return child;
3095 }
3096 
3097 /*
3098  * This function transfers the reference to child_bs from the caller
3099  * to parent_bs. That reference is later dropped by parent_bs on
3100  * bdrv_close() or if someone calls bdrv_unref_child().
3101  *
3102  * On failure NULL is returned, errp is set and the reference to
3103  * child_bs is also dropped.
3104  *
3105  * If @parent_bs and @child_bs are in different AioContexts, the caller must
3106  * hold the AioContext lock for @child_bs, but not for @parent_bs.
3107  */
3108 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3109                              BlockDriverState *child_bs,
3110                              const char *child_name,
3111                              const BdrvChildClass *child_class,
3112                              BdrvChildRole child_role,
3113                              Error **errp)
3114 {
3115     int ret;
3116     BdrvChild *child = NULL;
3117     Transaction *tran = tran_new();
3118 
3119     GLOBAL_STATE_CODE();
3120 
3121     ret = bdrv_attach_child_noperm(parent_bs, child_bs, child_name, child_class,
3122                                    child_role, &child, tran, errp);
3123     if (ret < 0) {
3124         goto out;
3125     }
3126 
3127     ret = bdrv_refresh_perms(parent_bs, errp);
3128     if (ret < 0) {
3129         goto out;
3130     }
3131 
3132 out:
3133     tran_finalize(tran, ret);
3134     /* child is unset on failure by bdrv_attach_child_common_abort() */
3135     assert((ret < 0) == !child);
3136 
3137     bdrv_unref(child_bs);
3138 
3139     return child;
3140 }
3141 
3142 /* Callers must ensure that child->frozen is false. */
3143 void bdrv_root_unref_child(BdrvChild *child)
3144 {
3145     BlockDriverState *child_bs;
3146 
3147     GLOBAL_STATE_CODE();
3148 
3149     child_bs = child->bs;
3150     bdrv_detach_child(&child);
3151     bdrv_unref(child_bs);
3152 }
3153 
3154 typedef struct BdrvSetInheritsFrom {
3155     BlockDriverState *bs;
3156     BlockDriverState *old_inherits_from;
3157 } BdrvSetInheritsFrom;
3158 
3159 static void bdrv_set_inherits_from_abort(void *opaque)
3160 {
3161     BdrvSetInheritsFrom *s = opaque;
3162 
3163     s->bs->inherits_from = s->old_inherits_from;
3164 }
3165 
3166 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3167     .abort = bdrv_set_inherits_from_abort,
3168     .clean = g_free,
3169 };
3170 
3171 /* @tran is allowed to be NULL. In this case no rollback is possible */
3172 static void bdrv_set_inherits_from(BlockDriverState *bs,
3173                                    BlockDriverState *new_inherits_from,
3174                                    Transaction *tran)
3175 {
3176     if (tran) {
3177         BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3178 
3179         *s = (BdrvSetInheritsFrom) {
3180             .bs = bs,
3181             .old_inherits_from = bs->inherits_from,
3182         };
3183 
3184         tran_add(tran, &bdrv_set_inherits_from_drv, s);
3185     }
3186 
3187     bs->inherits_from = new_inherits_from;
3188 }
3189 
3190 /**
3191  * Clear all inherits_from pointers from children and grandchildren of
3192  * @root that point to @root, where necessary.
3193  * @tran is allowed to be NULL. In this case no rollback is possible
3194  */
3195 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3196                                      Transaction *tran)
3197 {
3198     BdrvChild *c;
3199 
3200     if (child->bs->inherits_from == root) {
3201         /*
3202          * Remove inherits_from only when the last reference between root and
3203          * child->bs goes away.
3204          */
3205         QLIST_FOREACH(c, &root->children, next) {
3206             if (c != child && c->bs == child->bs) {
3207                 break;
3208             }
3209         }
3210         if (c == NULL) {
3211             bdrv_set_inherits_from(child->bs, NULL, tran);
3212         }
3213     }
3214 
3215     QLIST_FOREACH(c, &child->bs->children, next) {
3216         bdrv_unset_inherits_from(root, c, tran);
3217     }
3218 }
3219 
3220 /* Callers must ensure that child->frozen is false. */
3221 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3222 {
3223     GLOBAL_STATE_CODE();
3224     if (child == NULL) {
3225         return;
3226     }
3227 
3228     bdrv_unset_inherits_from(parent, child, NULL);
3229     bdrv_root_unref_child(child);
3230 }
3231 
3232 
3233 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3234 {
3235     BdrvChild *c;
3236     GLOBAL_STATE_CODE();
3237     QLIST_FOREACH(c, &bs->parents, next_parent) {
3238         if (c->klass->change_media) {
3239             c->klass->change_media(c, load);
3240         }
3241     }
3242 }
3243 
3244 /* Return true if you can reach parent going through child->inherits_from
3245  * recursively. If parent or child are NULL, return false */
3246 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3247                                          BlockDriverState *parent)
3248 {
3249     while (child && child != parent) {
3250         child = child->inherits_from;
3251     }
3252 
3253     return child != NULL;
3254 }
3255 
3256 /*
3257  * Return the BdrvChildRole for @bs's backing child.  bs->backing is
3258  * mostly used for COW backing children (role = COW), but also for
3259  * filtered children (role = FILTERED | PRIMARY).
3260  */
3261 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3262 {
3263     if (bs->drv && bs->drv->is_filter) {
3264         return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3265     } else {
3266         return BDRV_CHILD_COW;
3267     }
3268 }
3269 
3270 /*
3271  * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3272  * callers which don't need their own reference any more must call bdrv_unref().
3273  *
3274  * Function doesn't update permissions, caller is responsible for this.
3275  */
3276 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3277                                            BlockDriverState *child_bs,
3278                                            bool is_backing,
3279                                            Transaction *tran, Error **errp)
3280 {
3281     int ret = 0;
3282     bool update_inherits_from =
3283         bdrv_inherits_from_recursive(child_bs, parent_bs);
3284     BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3285     BdrvChildRole role;
3286 
3287     GLOBAL_STATE_CODE();
3288 
3289     if (!parent_bs->drv) {
3290         /*
3291          * Node without drv is an object without a class :/. TODO: finally fix
3292          * qcow2 driver to never clear bs->drv and implement format corruption
3293          * handling in other way.
3294          */
3295         error_setg(errp, "Node corrupted");
3296         return -EINVAL;
3297     }
3298 
3299     if (child && child->frozen) {
3300         error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3301                    child->name, parent_bs->node_name, child->bs->node_name);
3302         return -EPERM;
3303     }
3304 
3305     if (is_backing && !parent_bs->drv->is_filter &&
3306         !parent_bs->drv->supports_backing)
3307     {
3308         error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3309                    "files", parent_bs->drv->format_name, parent_bs->node_name);
3310         return -EINVAL;
3311     }
3312 
3313     if (parent_bs->drv->is_filter) {
3314         role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3315     } else if (is_backing) {
3316         role = BDRV_CHILD_COW;
3317     } else {
3318         /*
3319          * We only can use same role as it is in existing child. We don't have
3320          * infrastructure to determine role of file child in generic way
3321          */
3322         if (!child) {
3323             error_setg(errp, "Cannot set file child to format node without "
3324                        "file child");
3325             return -EINVAL;
3326         }
3327         role = child->role;
3328     }
3329 
3330     if (child) {
3331         bdrv_unset_inherits_from(parent_bs, child, tran);
3332         bdrv_remove_file_or_backing_child(parent_bs, child, tran);
3333     }
3334 
3335     if (!child_bs) {
3336         goto out;
3337     }
3338 
3339     ret = bdrv_attach_child_noperm(parent_bs, child_bs,
3340                                    is_backing ? "backing" : "file",
3341                                    &child_of_bds, role,
3342                                    is_backing ? &parent_bs->backing :
3343                                                 &parent_bs->file,
3344                                    tran, errp);
3345     if (ret < 0) {
3346         return ret;
3347     }
3348 
3349 
3350     /*
3351      * If inherits_from pointed recursively to bs then let's update it to
3352      * point directly to bs (else it will become NULL).
3353      */
3354     if (update_inherits_from) {
3355         bdrv_set_inherits_from(child_bs, parent_bs, tran);
3356     }
3357 
3358 out:
3359     bdrv_refresh_limits(parent_bs, tran, NULL);
3360 
3361     return 0;
3362 }
3363 
3364 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3365                                    BlockDriverState *backing_hd,
3366                                    Transaction *tran, Error **errp)
3367 {
3368     GLOBAL_STATE_CODE();
3369     return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3370 }
3371 
3372 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3373                         Error **errp)
3374 {
3375     int ret;
3376     Transaction *tran = tran_new();
3377 
3378     GLOBAL_STATE_CODE();
3379     bdrv_drained_begin(bs);
3380 
3381     ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3382     if (ret < 0) {
3383         goto out;
3384     }
3385 
3386     ret = bdrv_refresh_perms(bs, errp);
3387 out:
3388     tran_finalize(tran, ret);
3389 
3390     bdrv_drained_end(bs);
3391 
3392     return ret;
3393 }
3394 
3395 /*
3396  * Opens the backing file for a BlockDriverState if not yet open
3397  *
3398  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3399  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3400  * itself, all options starting with "${bdref_key}." are considered part of the
3401  * BlockdevRef.
3402  *
3403  * TODO Can this be unified with bdrv_open_image()?
3404  */
3405 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3406                            const char *bdref_key, Error **errp)
3407 {
3408     char *backing_filename = NULL;
3409     char *bdref_key_dot;
3410     const char *reference = NULL;
3411     int ret = 0;
3412     bool implicit_backing = false;
3413     BlockDriverState *backing_hd;
3414     QDict *options;
3415     QDict *tmp_parent_options = NULL;
3416     Error *local_err = NULL;
3417 
3418     GLOBAL_STATE_CODE();
3419 
3420     if (bs->backing != NULL) {
3421         goto free_exit;
3422     }
3423 
3424     /* NULL means an empty set of options */
3425     if (parent_options == NULL) {
3426         tmp_parent_options = qdict_new();
3427         parent_options = tmp_parent_options;
3428     }
3429 
3430     bs->open_flags &= ~BDRV_O_NO_BACKING;
3431 
3432     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3433     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3434     g_free(bdref_key_dot);
3435 
3436     /*
3437      * Caution: while qdict_get_try_str() is fine, getting non-string
3438      * types would require more care.  When @parent_options come from
3439      * -blockdev or blockdev_add, its members are typed according to
3440      * the QAPI schema, but when they come from -drive, they're all
3441      * QString.
3442      */
3443     reference = qdict_get_try_str(parent_options, bdref_key);
3444     if (reference || qdict_haskey(options, "file.filename")) {
3445         /* keep backing_filename NULL */
3446     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3447         qobject_unref(options);
3448         goto free_exit;
3449     } else {
3450         if (qdict_size(options) == 0) {
3451             /* If the user specifies options that do not modify the
3452              * backing file's behavior, we might still consider it the
3453              * implicit backing file.  But it's easier this way, and
3454              * just specifying some of the backing BDS's options is
3455              * only possible with -drive anyway (otherwise the QAPI
3456              * schema forces the user to specify everything). */
3457             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3458         }
3459 
3460         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3461         if (local_err) {
3462             ret = -EINVAL;
3463             error_propagate(errp, local_err);
3464             qobject_unref(options);
3465             goto free_exit;
3466         }
3467     }
3468 
3469     if (!bs->drv || !bs->drv->supports_backing) {
3470         ret = -EINVAL;
3471         error_setg(errp, "Driver doesn't support backing files");
3472         qobject_unref(options);
3473         goto free_exit;
3474     }
3475 
3476     if (!reference &&
3477         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3478         qdict_put_str(options, "driver", bs->backing_format);
3479     }
3480 
3481     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3482                                    &child_of_bds, bdrv_backing_role(bs), errp);
3483     if (!backing_hd) {
3484         bs->open_flags |= BDRV_O_NO_BACKING;
3485         error_prepend(errp, "Could not open backing file: ");
3486         ret = -EINVAL;
3487         goto free_exit;
3488     }
3489 
3490     if (implicit_backing) {
3491         bdrv_refresh_filename(backing_hd);
3492         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3493                 backing_hd->filename);
3494     }
3495 
3496     /* Hook up the backing file link; drop our reference, bs owns the
3497      * backing_hd reference now */
3498     ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3499     bdrv_unref(backing_hd);
3500     if (ret < 0) {
3501         goto free_exit;
3502     }
3503 
3504     qdict_del(parent_options, bdref_key);
3505 
3506 free_exit:
3507     g_free(backing_filename);
3508     qobject_unref(tmp_parent_options);
3509     return ret;
3510 }
3511 
3512 static BlockDriverState *
3513 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3514                    BlockDriverState *parent, const BdrvChildClass *child_class,
3515                    BdrvChildRole child_role, bool allow_none, Error **errp)
3516 {
3517     BlockDriverState *bs = NULL;
3518     QDict *image_options;
3519     char *bdref_key_dot;
3520     const char *reference;
3521 
3522     assert(child_class != NULL);
3523 
3524     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3525     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3526     g_free(bdref_key_dot);
3527 
3528     /*
3529      * Caution: while qdict_get_try_str() is fine, getting non-string
3530      * types would require more care.  When @options come from
3531      * -blockdev or blockdev_add, its members are typed according to
3532      * the QAPI schema, but when they come from -drive, they're all
3533      * QString.
3534      */
3535     reference = qdict_get_try_str(options, bdref_key);
3536     if (!filename && !reference && !qdict_size(image_options)) {
3537         if (!allow_none) {
3538             error_setg(errp, "A block device must be specified for \"%s\"",
3539                        bdref_key);
3540         }
3541         qobject_unref(image_options);
3542         goto done;
3543     }
3544 
3545     bs = bdrv_open_inherit(filename, reference, image_options, 0,
3546                            parent, child_class, child_role, errp);
3547     if (!bs) {
3548         goto done;
3549     }
3550 
3551 done:
3552     qdict_del(options, bdref_key);
3553     return bs;
3554 }
3555 
3556 /*
3557  * Opens a disk image whose options are given as BlockdevRef in another block
3558  * device's options.
3559  *
3560  * If allow_none is true, no image will be opened if filename is false and no
3561  * BlockdevRef is given. NULL will be returned, but errp remains unset.
3562  *
3563  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3564  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3565  * itself, all options starting with "${bdref_key}." are considered part of the
3566  * BlockdevRef.
3567  *
3568  * The BlockdevRef will be removed from the options QDict.
3569  */
3570 BdrvChild *bdrv_open_child(const char *filename,
3571                            QDict *options, const char *bdref_key,
3572                            BlockDriverState *parent,
3573                            const BdrvChildClass *child_class,
3574                            BdrvChildRole child_role,
3575                            bool allow_none, Error **errp)
3576 {
3577     BlockDriverState *bs;
3578 
3579     GLOBAL_STATE_CODE();
3580 
3581     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3582                             child_role, allow_none, errp);
3583     if (bs == NULL) {
3584         return NULL;
3585     }
3586 
3587     return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3588                              errp);
3589 }
3590 
3591 /*
3592  * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3593  */
3594 int bdrv_open_file_child(const char *filename,
3595                          QDict *options, const char *bdref_key,
3596                          BlockDriverState *parent, Error **errp)
3597 {
3598     BdrvChildRole role;
3599 
3600     /* commit_top and mirror_top don't use this function */
3601     assert(!parent->drv->filtered_child_is_backing);
3602 
3603     role = parent->drv->is_filter ?
3604         (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3605 
3606     parent->file = bdrv_open_child(filename, options, bdref_key, parent,
3607                                    &child_of_bds, role, false, errp);
3608 
3609     return parent->file ? 0 : -EINVAL;
3610 }
3611 
3612 /*
3613  * TODO Future callers may need to specify parent/child_class in order for
3614  * option inheritance to work. Existing callers use it for the root node.
3615  */
3616 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3617 {
3618     BlockDriverState *bs = NULL;
3619     QObject *obj = NULL;
3620     QDict *qdict = NULL;
3621     const char *reference = NULL;
3622     Visitor *v = NULL;
3623 
3624     GLOBAL_STATE_CODE();
3625 
3626     if (ref->type == QTYPE_QSTRING) {
3627         reference = ref->u.reference;
3628     } else {
3629         BlockdevOptions *options = &ref->u.definition;
3630         assert(ref->type == QTYPE_QDICT);
3631 
3632         v = qobject_output_visitor_new(&obj);
3633         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3634         visit_complete(v, &obj);
3635 
3636         qdict = qobject_to(QDict, obj);
3637         qdict_flatten(qdict);
3638 
3639         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3640          * compatibility with other callers) rather than what we want as the
3641          * real defaults. Apply the defaults here instead. */
3642         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3643         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3644         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3645         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3646 
3647     }
3648 
3649     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3650     obj = NULL;
3651     qobject_unref(obj);
3652     visit_free(v);
3653     return bs;
3654 }
3655 
3656 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3657                                                    int flags,
3658                                                    QDict *snapshot_options,
3659                                                    Error **errp)
3660 {
3661     g_autofree char *tmp_filename = NULL;
3662     int64_t total_size;
3663     QemuOpts *opts = NULL;
3664     BlockDriverState *bs_snapshot = NULL;
3665     int ret;
3666 
3667     GLOBAL_STATE_CODE();
3668 
3669     /* if snapshot, we create a temporary backing file and open it
3670        instead of opening 'filename' directly */
3671 
3672     /* Get the required size from the image */
3673     total_size = bdrv_getlength(bs);
3674     if (total_size < 0) {
3675         error_setg_errno(errp, -total_size, "Could not get image size");
3676         goto out;
3677     }
3678 
3679     /* Create the temporary image */
3680     tmp_filename = create_tmp_file(errp);
3681     if (!tmp_filename) {
3682         goto out;
3683     }
3684 
3685     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3686                             &error_abort);
3687     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3688     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3689     qemu_opts_del(opts);
3690     if (ret < 0) {
3691         error_prepend(errp, "Could not create temporary overlay '%s': ",
3692                       tmp_filename);
3693         goto out;
3694     }
3695 
3696     /* Prepare options QDict for the temporary file */
3697     qdict_put_str(snapshot_options, "file.driver", "file");
3698     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3699     qdict_put_str(snapshot_options, "driver", "qcow2");
3700 
3701     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3702     snapshot_options = NULL;
3703     if (!bs_snapshot) {
3704         goto out;
3705     }
3706 
3707     ret = bdrv_append(bs_snapshot, bs, errp);
3708     if (ret < 0) {
3709         bs_snapshot = NULL;
3710         goto out;
3711     }
3712 
3713 out:
3714     qobject_unref(snapshot_options);
3715     return bs_snapshot;
3716 }
3717 
3718 /*
3719  * Opens a disk image (raw, qcow2, vmdk, ...)
3720  *
3721  * options is a QDict of options to pass to the block drivers, or NULL for an
3722  * empty set of options. The reference to the QDict belongs to the block layer
3723  * after the call (even on failure), so if the caller intends to reuse the
3724  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3725  *
3726  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3727  * If it is not NULL, the referenced BDS will be reused.
3728  *
3729  * The reference parameter may be used to specify an existing block device which
3730  * should be opened. If specified, neither options nor a filename may be given,
3731  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3732  */
3733 static BlockDriverState *bdrv_open_inherit(const char *filename,
3734                                            const char *reference,
3735                                            QDict *options, int flags,
3736                                            BlockDriverState *parent,
3737                                            const BdrvChildClass *child_class,
3738                                            BdrvChildRole child_role,
3739                                            Error **errp)
3740 {
3741     int ret;
3742     BlockBackend *file = NULL;
3743     BlockDriverState *bs;
3744     BlockDriver *drv = NULL;
3745     BdrvChild *child;
3746     const char *drvname;
3747     const char *backing;
3748     Error *local_err = NULL;
3749     QDict *snapshot_options = NULL;
3750     int snapshot_flags = 0;
3751 
3752     assert(!child_class || !flags);
3753     assert(!child_class == !parent);
3754     GLOBAL_STATE_CODE();
3755 
3756     if (reference) {
3757         bool options_non_empty = options ? qdict_size(options) : false;
3758         qobject_unref(options);
3759 
3760         if (filename || options_non_empty) {
3761             error_setg(errp, "Cannot reference an existing block device with "
3762                        "additional options or a new filename");
3763             return NULL;
3764         }
3765 
3766         bs = bdrv_lookup_bs(reference, reference, errp);
3767         if (!bs) {
3768             return NULL;
3769         }
3770 
3771         bdrv_ref(bs);
3772         return bs;
3773     }
3774 
3775     bs = bdrv_new();
3776 
3777     /* NULL means an empty set of options */
3778     if (options == NULL) {
3779         options = qdict_new();
3780     }
3781 
3782     /* json: syntax counts as explicit options, as if in the QDict */
3783     parse_json_protocol(options, &filename, &local_err);
3784     if (local_err) {
3785         goto fail;
3786     }
3787 
3788     bs->explicit_options = qdict_clone_shallow(options);
3789 
3790     if (child_class) {
3791         bool parent_is_format;
3792 
3793         if (parent->drv) {
3794             parent_is_format = parent->drv->is_format;
3795         } else {
3796             /*
3797              * parent->drv is not set yet because this node is opened for
3798              * (potential) format probing.  That means that @parent is going
3799              * to be a format node.
3800              */
3801             parent_is_format = true;
3802         }
3803 
3804         bs->inherits_from = parent;
3805         child_class->inherit_options(child_role, parent_is_format,
3806                                      &flags, options,
3807                                      parent->open_flags, parent->options);
3808     }
3809 
3810     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3811     if (ret < 0) {
3812         goto fail;
3813     }
3814 
3815     /*
3816      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3817      * Caution: getting a boolean member of @options requires care.
3818      * When @options come from -blockdev or blockdev_add, members are
3819      * typed according to the QAPI schema, but when they come from
3820      * -drive, they're all QString.
3821      */
3822     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3823         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3824         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3825     } else {
3826         flags &= ~BDRV_O_RDWR;
3827     }
3828 
3829     if (flags & BDRV_O_SNAPSHOT) {
3830         snapshot_options = qdict_new();
3831         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3832                                    flags, options);
3833         /* Let bdrv_backing_options() override "read-only" */
3834         qdict_del(options, BDRV_OPT_READ_ONLY);
3835         bdrv_inherited_options(BDRV_CHILD_COW, true,
3836                                &flags, options, flags, options);
3837     }
3838 
3839     bs->open_flags = flags;
3840     bs->options = options;
3841     options = qdict_clone_shallow(options);
3842 
3843     /* Find the right image format driver */
3844     /* See cautionary note on accessing @options above */
3845     drvname = qdict_get_try_str(options, "driver");
3846     if (drvname) {
3847         drv = bdrv_find_format(drvname);
3848         if (!drv) {
3849             error_setg(errp, "Unknown driver: '%s'", drvname);
3850             goto fail;
3851         }
3852     }
3853 
3854     assert(drvname || !(flags & BDRV_O_PROTOCOL));
3855 
3856     /* See cautionary note on accessing @options above */
3857     backing = qdict_get_try_str(options, "backing");
3858     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3859         (backing && *backing == '\0'))
3860     {
3861         if (backing) {
3862             warn_report("Use of \"backing\": \"\" is deprecated; "
3863                         "use \"backing\": null instead");
3864         }
3865         flags |= BDRV_O_NO_BACKING;
3866         qdict_del(bs->explicit_options, "backing");
3867         qdict_del(bs->options, "backing");
3868         qdict_del(options, "backing");
3869     }
3870 
3871     /* Open image file without format layer. This BlockBackend is only used for
3872      * probing, the block drivers will do their own bdrv_open_child() for the
3873      * same BDS, which is why we put the node name back into options. */
3874     if ((flags & BDRV_O_PROTOCOL) == 0) {
3875         BlockDriverState *file_bs;
3876 
3877         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3878                                      &child_of_bds, BDRV_CHILD_IMAGE,
3879                                      true, &local_err);
3880         if (local_err) {
3881             goto fail;
3882         }
3883         if (file_bs != NULL) {
3884             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3885              * looking at the header to guess the image format. This works even
3886              * in cases where a guest would not see a consistent state. */
3887             file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3888             blk_insert_bs(file, file_bs, &local_err);
3889             bdrv_unref(file_bs);
3890             if (local_err) {
3891                 goto fail;
3892             }
3893 
3894             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3895         }
3896     }
3897 
3898     /* Image format probing */
3899     bs->probed = !drv;
3900     if (!drv && file) {
3901         ret = find_image_format(file, filename, &drv, &local_err);
3902         if (ret < 0) {
3903             goto fail;
3904         }
3905         /*
3906          * This option update would logically belong in bdrv_fill_options(),
3907          * but we first need to open bs->file for the probing to work, while
3908          * opening bs->file already requires the (mostly) final set of options
3909          * so that cache mode etc. can be inherited.
3910          *
3911          * Adding the driver later is somewhat ugly, but it's not an option
3912          * that would ever be inherited, so it's correct. We just need to make
3913          * sure to update both bs->options (which has the full effective
3914          * options for bs) and options (which has file.* already removed).
3915          */
3916         qdict_put_str(bs->options, "driver", drv->format_name);
3917         qdict_put_str(options, "driver", drv->format_name);
3918     } else if (!drv) {
3919         error_setg(errp, "Must specify either driver or file");
3920         goto fail;
3921     }
3922 
3923     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3924     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3925     /* file must be NULL if a protocol BDS is about to be created
3926      * (the inverse results in an error message from bdrv_open_common()) */
3927     assert(!(flags & BDRV_O_PROTOCOL) || !file);
3928 
3929     /* Open the image */
3930     ret = bdrv_open_common(bs, file, options, &local_err);
3931     if (ret < 0) {
3932         goto fail;
3933     }
3934 
3935     if (file) {
3936         blk_unref(file);
3937         file = NULL;
3938     }
3939 
3940     /* If there is a backing file, use it */
3941     if ((flags & BDRV_O_NO_BACKING) == 0) {
3942         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3943         if (ret < 0) {
3944             goto close_and_fail;
3945         }
3946     }
3947 
3948     /* Remove all children options and references
3949      * from bs->options and bs->explicit_options */
3950     QLIST_FOREACH(child, &bs->children, next) {
3951         char *child_key_dot;
3952         child_key_dot = g_strdup_printf("%s.", child->name);
3953         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3954         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3955         qdict_del(bs->explicit_options, child->name);
3956         qdict_del(bs->options, child->name);
3957         g_free(child_key_dot);
3958     }
3959 
3960     /* Check if any unknown options were used */
3961     if (qdict_size(options) != 0) {
3962         const QDictEntry *entry = qdict_first(options);
3963         if (flags & BDRV_O_PROTOCOL) {
3964             error_setg(errp, "Block protocol '%s' doesn't support the option "
3965                        "'%s'", drv->format_name, entry->key);
3966         } else {
3967             error_setg(errp,
3968                        "Block format '%s' does not support the option '%s'",
3969                        drv->format_name, entry->key);
3970         }
3971 
3972         goto close_and_fail;
3973     }
3974 
3975     bdrv_parent_cb_change_media(bs, true);
3976 
3977     qobject_unref(options);
3978     options = NULL;
3979 
3980     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3981      * temporary snapshot afterwards. */
3982     if (snapshot_flags) {
3983         BlockDriverState *snapshot_bs;
3984         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3985                                                 snapshot_options, &local_err);
3986         snapshot_options = NULL;
3987         if (local_err) {
3988             goto close_and_fail;
3989         }
3990         /* We are not going to return bs but the overlay on top of it
3991          * (snapshot_bs); thus, we have to drop the strong reference to bs
3992          * (which we obtained by calling bdrv_new()). bs will not be deleted,
3993          * though, because the overlay still has a reference to it. */
3994         bdrv_unref(bs);
3995         bs = snapshot_bs;
3996     }
3997 
3998     return bs;
3999 
4000 fail:
4001     blk_unref(file);
4002     qobject_unref(snapshot_options);
4003     qobject_unref(bs->explicit_options);
4004     qobject_unref(bs->options);
4005     qobject_unref(options);
4006     bs->options = NULL;
4007     bs->explicit_options = NULL;
4008     bdrv_unref(bs);
4009     error_propagate(errp, local_err);
4010     return NULL;
4011 
4012 close_and_fail:
4013     bdrv_unref(bs);
4014     qobject_unref(snapshot_options);
4015     qobject_unref(options);
4016     error_propagate(errp, local_err);
4017     return NULL;
4018 }
4019 
4020 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4021                             QDict *options, int flags, Error **errp)
4022 {
4023     GLOBAL_STATE_CODE();
4024 
4025     return bdrv_open_inherit(filename, reference, options, flags, NULL,
4026                              NULL, 0, errp);
4027 }
4028 
4029 /* Return true if the NULL-terminated @list contains @str */
4030 static bool is_str_in_list(const char *str, const char *const *list)
4031 {
4032     if (str && list) {
4033         int i;
4034         for (i = 0; list[i] != NULL; i++) {
4035             if (!strcmp(str, list[i])) {
4036                 return true;
4037             }
4038         }
4039     }
4040     return false;
4041 }
4042 
4043 /*
4044  * Check that every option set in @bs->options is also set in
4045  * @new_opts.
4046  *
4047  * Options listed in the common_options list and in
4048  * @bs->drv->mutable_opts are skipped.
4049  *
4050  * Return 0 on success, otherwise return -EINVAL and set @errp.
4051  */
4052 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4053                                       const QDict *new_opts, Error **errp)
4054 {
4055     const QDictEntry *e;
4056     /* These options are common to all block drivers and are handled
4057      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4058     const char *const common_options[] = {
4059         "node-name", "discard", "cache.direct", "cache.no-flush",
4060         "read-only", "auto-read-only", "detect-zeroes", NULL
4061     };
4062 
4063     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4064         if (!qdict_haskey(new_opts, e->key) &&
4065             !is_str_in_list(e->key, common_options) &&
4066             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4067             error_setg(errp, "Option '%s' cannot be reset "
4068                        "to its default value", e->key);
4069             return -EINVAL;
4070         }
4071     }
4072 
4073     return 0;
4074 }
4075 
4076 /*
4077  * Returns true if @child can be reached recursively from @bs
4078  */
4079 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4080                                    BlockDriverState *child)
4081 {
4082     BdrvChild *c;
4083 
4084     if (bs == child) {
4085         return true;
4086     }
4087 
4088     QLIST_FOREACH(c, &bs->children, next) {
4089         if (bdrv_recurse_has_child(c->bs, child)) {
4090             return true;
4091         }
4092     }
4093 
4094     return false;
4095 }
4096 
4097 /*
4098  * Adds a BlockDriverState to a simple queue for an atomic, transactional
4099  * reopen of multiple devices.
4100  *
4101  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4102  * already performed, or alternatively may be NULL a new BlockReopenQueue will
4103  * be created and initialized. This newly created BlockReopenQueue should be
4104  * passed back in for subsequent calls that are intended to be of the same
4105  * atomic 'set'.
4106  *
4107  * bs is the BlockDriverState to add to the reopen queue.
4108  *
4109  * options contains the changed options for the associated bs
4110  * (the BlockReopenQueue takes ownership)
4111  *
4112  * flags contains the open flags for the associated bs
4113  *
4114  * returns a pointer to bs_queue, which is either the newly allocated
4115  * bs_queue, or the existing bs_queue being used.
4116  *
4117  * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4118  */
4119 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4120                                                  BlockDriverState *bs,
4121                                                  QDict *options,
4122                                                  const BdrvChildClass *klass,
4123                                                  BdrvChildRole role,
4124                                                  bool parent_is_format,
4125                                                  QDict *parent_options,
4126                                                  int parent_flags,
4127                                                  bool keep_old_opts)
4128 {
4129     assert(bs != NULL);
4130 
4131     BlockReopenQueueEntry *bs_entry;
4132     BdrvChild *child;
4133     QDict *old_options, *explicit_options, *options_copy;
4134     int flags;
4135     QemuOpts *opts;
4136 
4137     /* Make sure that the caller remembered to use a drained section. This is
4138      * important to avoid graph changes between the recursive queuing here and
4139      * bdrv_reopen_multiple(). */
4140     assert(bs->quiesce_counter > 0);
4141     GLOBAL_STATE_CODE();
4142 
4143     if (bs_queue == NULL) {
4144         bs_queue = g_new0(BlockReopenQueue, 1);
4145         QTAILQ_INIT(bs_queue);
4146     }
4147 
4148     if (!options) {
4149         options = qdict_new();
4150     }
4151 
4152     /* Check if this BlockDriverState is already in the queue */
4153     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4154         if (bs == bs_entry->state.bs) {
4155             break;
4156         }
4157     }
4158 
4159     /*
4160      * Precedence of options:
4161      * 1. Explicitly passed in options (highest)
4162      * 2. Retained from explicitly set options of bs
4163      * 3. Inherited from parent node
4164      * 4. Retained from effective options of bs
4165      */
4166 
4167     /* Old explicitly set values (don't overwrite by inherited value) */
4168     if (bs_entry || keep_old_opts) {
4169         old_options = qdict_clone_shallow(bs_entry ?
4170                                           bs_entry->state.explicit_options :
4171                                           bs->explicit_options);
4172         bdrv_join_options(bs, options, old_options);
4173         qobject_unref(old_options);
4174     }
4175 
4176     explicit_options = qdict_clone_shallow(options);
4177 
4178     /* Inherit from parent node */
4179     if (parent_options) {
4180         flags = 0;
4181         klass->inherit_options(role, parent_is_format, &flags, options,
4182                                parent_flags, parent_options);
4183     } else {
4184         flags = bdrv_get_flags(bs);
4185     }
4186 
4187     if (keep_old_opts) {
4188         /* Old values are used for options that aren't set yet */
4189         old_options = qdict_clone_shallow(bs->options);
4190         bdrv_join_options(bs, options, old_options);
4191         qobject_unref(old_options);
4192     }
4193 
4194     /* We have the final set of options so let's update the flags */
4195     options_copy = qdict_clone_shallow(options);
4196     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4197     qemu_opts_absorb_qdict(opts, options_copy, NULL);
4198     update_flags_from_options(&flags, opts);
4199     qemu_opts_del(opts);
4200     qobject_unref(options_copy);
4201 
4202     /* bdrv_open_inherit() sets and clears some additional flags internally */
4203     flags &= ~BDRV_O_PROTOCOL;
4204     if (flags & BDRV_O_RDWR) {
4205         flags |= BDRV_O_ALLOW_RDWR;
4206     }
4207 
4208     if (!bs_entry) {
4209         bs_entry = g_new0(BlockReopenQueueEntry, 1);
4210         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4211     } else {
4212         qobject_unref(bs_entry->state.options);
4213         qobject_unref(bs_entry->state.explicit_options);
4214     }
4215 
4216     bs_entry->state.bs = bs;
4217     bs_entry->state.options = options;
4218     bs_entry->state.explicit_options = explicit_options;
4219     bs_entry->state.flags = flags;
4220 
4221     /*
4222      * If keep_old_opts is false then it means that unspecified
4223      * options must be reset to their original value. We don't allow
4224      * resetting 'backing' but we need to know if the option is
4225      * missing in order to decide if we have to return an error.
4226      */
4227     if (!keep_old_opts) {
4228         bs_entry->state.backing_missing =
4229             !qdict_haskey(options, "backing") &&
4230             !qdict_haskey(options, "backing.driver");
4231     }
4232 
4233     QLIST_FOREACH(child, &bs->children, next) {
4234         QDict *new_child_options = NULL;
4235         bool child_keep_old = keep_old_opts;
4236 
4237         /* reopen can only change the options of block devices that were
4238          * implicitly created and inherited options. For other (referenced)
4239          * block devices, a syntax like "backing.foo" results in an error. */
4240         if (child->bs->inherits_from != bs) {
4241             continue;
4242         }
4243 
4244         /* Check if the options contain a child reference */
4245         if (qdict_haskey(options, child->name)) {
4246             const char *childref = qdict_get_try_str(options, child->name);
4247             /*
4248              * The current child must not be reopened if the child
4249              * reference is null or points to a different node.
4250              */
4251             if (g_strcmp0(childref, child->bs->node_name)) {
4252                 continue;
4253             }
4254             /*
4255              * If the child reference points to the current child then
4256              * reopen it with its existing set of options (note that
4257              * it can still inherit new options from the parent).
4258              */
4259             child_keep_old = true;
4260         } else {
4261             /* Extract child options ("child-name.*") */
4262             char *child_key_dot = g_strdup_printf("%s.", child->name);
4263             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4264             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4265             g_free(child_key_dot);
4266         }
4267 
4268         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4269                                 child->klass, child->role, bs->drv->is_format,
4270                                 options, flags, child_keep_old);
4271     }
4272 
4273     return bs_queue;
4274 }
4275 
4276 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4277                                     BlockDriverState *bs,
4278                                     QDict *options, bool keep_old_opts)
4279 {
4280     GLOBAL_STATE_CODE();
4281 
4282     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4283                                    NULL, 0, keep_old_opts);
4284 }
4285 
4286 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4287 {
4288     GLOBAL_STATE_CODE();
4289     if (bs_queue) {
4290         BlockReopenQueueEntry *bs_entry, *next;
4291         QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4292             qobject_unref(bs_entry->state.explicit_options);
4293             qobject_unref(bs_entry->state.options);
4294             g_free(bs_entry);
4295         }
4296         g_free(bs_queue);
4297     }
4298 }
4299 
4300 /*
4301  * Reopen multiple BlockDriverStates atomically & transactionally.
4302  *
4303  * The queue passed in (bs_queue) must have been built up previous
4304  * via bdrv_reopen_queue().
4305  *
4306  * Reopens all BDS specified in the queue, with the appropriate
4307  * flags.  All devices are prepared for reopen, and failure of any
4308  * device will cause all device changes to be abandoned, and intermediate
4309  * data cleaned up.
4310  *
4311  * If all devices prepare successfully, then the changes are committed
4312  * to all devices.
4313  *
4314  * All affected nodes must be drained between bdrv_reopen_queue() and
4315  * bdrv_reopen_multiple().
4316  *
4317  * To be called from the main thread, with all other AioContexts unlocked.
4318  */
4319 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4320 {
4321     int ret = -1;
4322     BlockReopenQueueEntry *bs_entry, *next;
4323     AioContext *ctx;
4324     Transaction *tran = tran_new();
4325     g_autoptr(GHashTable) found = NULL;
4326     g_autoptr(GSList) refresh_list = NULL;
4327 
4328     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4329     assert(bs_queue != NULL);
4330     GLOBAL_STATE_CODE();
4331 
4332     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4333         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4334         aio_context_acquire(ctx);
4335         ret = bdrv_flush(bs_entry->state.bs);
4336         aio_context_release(ctx);
4337         if (ret < 0) {
4338             error_setg_errno(errp, -ret, "Error flushing drive");
4339             goto abort;
4340         }
4341     }
4342 
4343     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4344         assert(bs_entry->state.bs->quiesce_counter > 0);
4345         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4346         aio_context_acquire(ctx);
4347         ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4348         aio_context_release(ctx);
4349         if (ret < 0) {
4350             goto abort;
4351         }
4352         bs_entry->prepared = true;
4353     }
4354 
4355     found = g_hash_table_new(NULL, NULL);
4356     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4357         BDRVReopenState *state = &bs_entry->state;
4358 
4359         refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4360         if (state->old_backing_bs) {
4361             refresh_list = bdrv_topological_dfs(refresh_list, found,
4362                                                 state->old_backing_bs);
4363         }
4364         if (state->old_file_bs) {
4365             refresh_list = bdrv_topological_dfs(refresh_list, found,
4366                                                 state->old_file_bs);
4367         }
4368     }
4369 
4370     /*
4371      * Note that file-posix driver rely on permission update done during reopen
4372      * (even if no permission changed), because it wants "new" permissions for
4373      * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4374      * in raw_reopen_prepare() which is called with "old" permissions.
4375      */
4376     ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4377     if (ret < 0) {
4378         goto abort;
4379     }
4380 
4381     /*
4382      * If we reach this point, we have success and just need to apply the
4383      * changes.
4384      *
4385      * Reverse order is used to comfort qcow2 driver: on commit it need to write
4386      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4387      * children are usually goes after parents in reopen-queue, so go from last
4388      * to first element.
4389      */
4390     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4391         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4392         aio_context_acquire(ctx);
4393         bdrv_reopen_commit(&bs_entry->state);
4394         aio_context_release(ctx);
4395     }
4396 
4397     tran_commit(tran);
4398 
4399     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4400         BlockDriverState *bs = bs_entry->state.bs;
4401 
4402         if (bs->drv->bdrv_reopen_commit_post) {
4403             ctx = bdrv_get_aio_context(bs);
4404             aio_context_acquire(ctx);
4405             bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4406             aio_context_release(ctx);
4407         }
4408     }
4409 
4410     ret = 0;
4411     goto cleanup;
4412 
4413 abort:
4414     tran_abort(tran);
4415     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4416         if (bs_entry->prepared) {
4417             ctx = bdrv_get_aio_context(bs_entry->state.bs);
4418             aio_context_acquire(ctx);
4419             bdrv_reopen_abort(&bs_entry->state);
4420             aio_context_release(ctx);
4421         }
4422     }
4423 
4424 cleanup:
4425     bdrv_reopen_queue_free(bs_queue);
4426 
4427     return ret;
4428 }
4429 
4430 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4431                 Error **errp)
4432 {
4433     AioContext *ctx = bdrv_get_aio_context(bs);
4434     BlockReopenQueue *queue;
4435     int ret;
4436 
4437     GLOBAL_STATE_CODE();
4438 
4439     bdrv_subtree_drained_begin(bs);
4440     if (ctx != qemu_get_aio_context()) {
4441         aio_context_release(ctx);
4442     }
4443 
4444     queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4445     ret = bdrv_reopen_multiple(queue, errp);
4446 
4447     if (ctx != qemu_get_aio_context()) {
4448         aio_context_acquire(ctx);
4449     }
4450     bdrv_subtree_drained_end(bs);
4451 
4452     return ret;
4453 }
4454 
4455 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4456                               Error **errp)
4457 {
4458     QDict *opts = qdict_new();
4459 
4460     GLOBAL_STATE_CODE();
4461 
4462     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4463 
4464     return bdrv_reopen(bs, opts, true, errp);
4465 }
4466 
4467 /*
4468  * Take a BDRVReopenState and check if the value of 'backing' in the
4469  * reopen_state->options QDict is valid or not.
4470  *
4471  * If 'backing' is missing from the QDict then return 0.
4472  *
4473  * If 'backing' contains the node name of the backing file of
4474  * reopen_state->bs then return 0.
4475  *
4476  * If 'backing' contains a different node name (or is null) then check
4477  * whether the current backing file can be replaced with the new one.
4478  * If that's the case then reopen_state->replace_backing_bs is set to
4479  * true and reopen_state->new_backing_bs contains a pointer to the new
4480  * backing BlockDriverState (or NULL).
4481  *
4482  * Return 0 on success, otherwise return < 0 and set @errp.
4483  */
4484 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4485                                              bool is_backing, Transaction *tran,
4486                                              Error **errp)
4487 {
4488     BlockDriverState *bs = reopen_state->bs;
4489     BlockDriverState *new_child_bs;
4490     BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4491                                                   child_bs(bs->file);
4492     const char *child_name = is_backing ? "backing" : "file";
4493     QObject *value;
4494     const char *str;
4495 
4496     GLOBAL_STATE_CODE();
4497 
4498     value = qdict_get(reopen_state->options, child_name);
4499     if (value == NULL) {
4500         return 0;
4501     }
4502 
4503     switch (qobject_type(value)) {
4504     case QTYPE_QNULL:
4505         assert(is_backing); /* The 'file' option does not allow a null value */
4506         new_child_bs = NULL;
4507         break;
4508     case QTYPE_QSTRING:
4509         str = qstring_get_str(qobject_to(QString, value));
4510         new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4511         if (new_child_bs == NULL) {
4512             return -EINVAL;
4513         } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4514             error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4515                        "cycle", str, child_name, bs->node_name);
4516             return -EINVAL;
4517         }
4518         break;
4519     default:
4520         /*
4521          * The options QDict has been flattened, so 'backing' and 'file'
4522          * do not allow any other data type here.
4523          */
4524         g_assert_not_reached();
4525     }
4526 
4527     if (old_child_bs == new_child_bs) {
4528         return 0;
4529     }
4530 
4531     if (old_child_bs) {
4532         if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4533             return 0;
4534         }
4535 
4536         if (old_child_bs->implicit) {
4537             error_setg(errp, "Cannot replace implicit %s child of %s",
4538                        child_name, bs->node_name);
4539             return -EPERM;
4540         }
4541     }
4542 
4543     if (bs->drv->is_filter && !old_child_bs) {
4544         /*
4545          * Filters always have a file or a backing child, so we are trying to
4546          * change wrong child
4547          */
4548         error_setg(errp, "'%s' is a %s filter node that does not support a "
4549                    "%s child", bs->node_name, bs->drv->format_name, child_name);
4550         return -EINVAL;
4551     }
4552 
4553     if (is_backing) {
4554         reopen_state->old_backing_bs = old_child_bs;
4555     } else {
4556         reopen_state->old_file_bs = old_child_bs;
4557     }
4558 
4559     return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4560                                            tran, errp);
4561 }
4562 
4563 /*
4564  * Prepares a BlockDriverState for reopen. All changes are staged in the
4565  * 'opaque' field of the BDRVReopenState, which is used and allocated by
4566  * the block driver layer .bdrv_reopen_prepare()
4567  *
4568  * bs is the BlockDriverState to reopen
4569  * flags are the new open flags
4570  * queue is the reopen queue
4571  *
4572  * Returns 0 on success, non-zero on error.  On error errp will be set
4573  * as well.
4574  *
4575  * On failure, bdrv_reopen_abort() will be called to clean up any data.
4576  * It is the responsibility of the caller to then call the abort() or
4577  * commit() for any other BDS that have been left in a prepare() state
4578  *
4579  */
4580 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4581                                BlockReopenQueue *queue,
4582                                Transaction *change_child_tran, Error **errp)
4583 {
4584     int ret = -1;
4585     int old_flags;
4586     Error *local_err = NULL;
4587     BlockDriver *drv;
4588     QemuOpts *opts;
4589     QDict *orig_reopen_opts;
4590     char *discard = NULL;
4591     bool read_only;
4592     bool drv_prepared = false;
4593 
4594     assert(reopen_state != NULL);
4595     assert(reopen_state->bs->drv != NULL);
4596     GLOBAL_STATE_CODE();
4597     drv = reopen_state->bs->drv;
4598 
4599     /* This function and each driver's bdrv_reopen_prepare() remove
4600      * entries from reopen_state->options as they are processed, so
4601      * we need to make a copy of the original QDict. */
4602     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4603 
4604     /* Process generic block layer options */
4605     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4606     if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4607         ret = -EINVAL;
4608         goto error;
4609     }
4610 
4611     /* This was already called in bdrv_reopen_queue_child() so the flags
4612      * are up-to-date. This time we simply want to remove the options from
4613      * QemuOpts in order to indicate that they have been processed. */
4614     old_flags = reopen_state->flags;
4615     update_flags_from_options(&reopen_state->flags, opts);
4616     assert(old_flags == reopen_state->flags);
4617 
4618     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4619     if (discard != NULL) {
4620         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4621             error_setg(errp, "Invalid discard option");
4622             ret = -EINVAL;
4623             goto error;
4624         }
4625     }
4626 
4627     reopen_state->detect_zeroes =
4628         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4629     if (local_err) {
4630         error_propagate(errp, local_err);
4631         ret = -EINVAL;
4632         goto error;
4633     }
4634 
4635     /* All other options (including node-name and driver) must be unchanged.
4636      * Put them back into the QDict, so that they are checked at the end
4637      * of this function. */
4638     qemu_opts_to_qdict(opts, reopen_state->options);
4639 
4640     /* If we are to stay read-only, do not allow permission change
4641      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4642      * not set, or if the BDS still has copy_on_read enabled */
4643     read_only = !(reopen_state->flags & BDRV_O_RDWR);
4644     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4645     if (local_err) {
4646         error_propagate(errp, local_err);
4647         goto error;
4648     }
4649 
4650     if (drv->bdrv_reopen_prepare) {
4651         /*
4652          * If a driver-specific option is missing, it means that we
4653          * should reset it to its default value.
4654          * But not all options allow that, so we need to check it first.
4655          */
4656         ret = bdrv_reset_options_allowed(reopen_state->bs,
4657                                          reopen_state->options, errp);
4658         if (ret) {
4659             goto error;
4660         }
4661 
4662         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4663         if (ret) {
4664             if (local_err != NULL) {
4665                 error_propagate(errp, local_err);
4666             } else {
4667                 bdrv_refresh_filename(reopen_state->bs);
4668                 error_setg(errp, "failed while preparing to reopen image '%s'",
4669                            reopen_state->bs->filename);
4670             }
4671             goto error;
4672         }
4673     } else {
4674         /* It is currently mandatory to have a bdrv_reopen_prepare()
4675          * handler for each supported drv. */
4676         error_setg(errp, "Block format '%s' used by node '%s' "
4677                    "does not support reopening files", drv->format_name,
4678                    bdrv_get_device_or_node_name(reopen_state->bs));
4679         ret = -1;
4680         goto error;
4681     }
4682 
4683     drv_prepared = true;
4684 
4685     /*
4686      * We must provide the 'backing' option if the BDS has a backing
4687      * file or if the image file has a backing file name as part of
4688      * its metadata. Otherwise the 'backing' option can be omitted.
4689      */
4690     if (drv->supports_backing && reopen_state->backing_missing &&
4691         (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4692         error_setg(errp, "backing is missing for '%s'",
4693                    reopen_state->bs->node_name);
4694         ret = -EINVAL;
4695         goto error;
4696     }
4697 
4698     /*
4699      * Allow changing the 'backing' option. The new value can be
4700      * either a reference to an existing node (using its node name)
4701      * or NULL to simply detach the current backing file.
4702      */
4703     ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4704                                             change_child_tran, errp);
4705     if (ret < 0) {
4706         goto error;
4707     }
4708     qdict_del(reopen_state->options, "backing");
4709 
4710     /* Allow changing the 'file' option. In this case NULL is not allowed */
4711     ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4712                                             change_child_tran, errp);
4713     if (ret < 0) {
4714         goto error;
4715     }
4716     qdict_del(reopen_state->options, "file");
4717 
4718     /* Options that are not handled are only okay if they are unchanged
4719      * compared to the old state. It is expected that some options are only
4720      * used for the initial open, but not reopen (e.g. filename) */
4721     if (qdict_size(reopen_state->options)) {
4722         const QDictEntry *entry = qdict_first(reopen_state->options);
4723 
4724         do {
4725             QObject *new = entry->value;
4726             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4727 
4728             /* Allow child references (child_name=node_name) as long as they
4729              * point to the current child (i.e. everything stays the same). */
4730             if (qobject_type(new) == QTYPE_QSTRING) {
4731                 BdrvChild *child;
4732                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4733                     if (!strcmp(child->name, entry->key)) {
4734                         break;
4735                     }
4736                 }
4737 
4738                 if (child) {
4739                     if (!strcmp(child->bs->node_name,
4740                                 qstring_get_str(qobject_to(QString, new)))) {
4741                         continue; /* Found child with this name, skip option */
4742                     }
4743                 }
4744             }
4745 
4746             /*
4747              * TODO: When using -drive to specify blockdev options, all values
4748              * will be strings; however, when using -blockdev, blockdev-add or
4749              * filenames using the json:{} pseudo-protocol, they will be
4750              * correctly typed.
4751              * In contrast, reopening options are (currently) always strings
4752              * (because you can only specify them through qemu-io; all other
4753              * callers do not specify any options).
4754              * Therefore, when using anything other than -drive to create a BDS,
4755              * this cannot detect non-string options as unchanged, because
4756              * qobject_is_equal() always returns false for objects of different
4757              * type.  In the future, this should be remedied by correctly typing
4758              * all options.  For now, this is not too big of an issue because
4759              * the user can simply omit options which cannot be changed anyway,
4760              * so they will stay unchanged.
4761              */
4762             if (!qobject_is_equal(new, old)) {
4763                 error_setg(errp, "Cannot change the option '%s'", entry->key);
4764                 ret = -EINVAL;
4765                 goto error;
4766             }
4767         } while ((entry = qdict_next(reopen_state->options, entry)));
4768     }
4769 
4770     ret = 0;
4771 
4772     /* Restore the original reopen_state->options QDict */
4773     qobject_unref(reopen_state->options);
4774     reopen_state->options = qobject_ref(orig_reopen_opts);
4775 
4776 error:
4777     if (ret < 0 && drv_prepared) {
4778         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4779          * call drv->bdrv_reopen_abort() before signaling an error
4780          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4781          * when the respective bdrv_reopen_prepare() has failed) */
4782         if (drv->bdrv_reopen_abort) {
4783             drv->bdrv_reopen_abort(reopen_state);
4784         }
4785     }
4786     qemu_opts_del(opts);
4787     qobject_unref(orig_reopen_opts);
4788     g_free(discard);
4789     return ret;
4790 }
4791 
4792 /*
4793  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4794  * makes them final by swapping the staging BlockDriverState contents into
4795  * the active BlockDriverState contents.
4796  */
4797 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4798 {
4799     BlockDriver *drv;
4800     BlockDriverState *bs;
4801     BdrvChild *child;
4802 
4803     assert(reopen_state != NULL);
4804     bs = reopen_state->bs;
4805     drv = bs->drv;
4806     assert(drv != NULL);
4807     GLOBAL_STATE_CODE();
4808 
4809     /* If there are any driver level actions to take */
4810     if (drv->bdrv_reopen_commit) {
4811         drv->bdrv_reopen_commit(reopen_state);
4812     }
4813 
4814     /* set BDS specific flags now */
4815     qobject_unref(bs->explicit_options);
4816     qobject_unref(bs->options);
4817     qobject_ref(reopen_state->explicit_options);
4818     qobject_ref(reopen_state->options);
4819 
4820     bs->explicit_options   = reopen_state->explicit_options;
4821     bs->options            = reopen_state->options;
4822     bs->open_flags         = reopen_state->flags;
4823     bs->detect_zeroes      = reopen_state->detect_zeroes;
4824 
4825     /* Remove child references from bs->options and bs->explicit_options.
4826      * Child options were already removed in bdrv_reopen_queue_child() */
4827     QLIST_FOREACH(child, &bs->children, next) {
4828         qdict_del(bs->explicit_options, child->name);
4829         qdict_del(bs->options, child->name);
4830     }
4831     /* backing is probably removed, so it's not handled by previous loop */
4832     qdict_del(bs->explicit_options, "backing");
4833     qdict_del(bs->options, "backing");
4834 
4835     bdrv_refresh_limits(bs, NULL, NULL);
4836 }
4837 
4838 /*
4839  * Abort the reopen, and delete and free the staged changes in
4840  * reopen_state
4841  */
4842 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4843 {
4844     BlockDriver *drv;
4845 
4846     assert(reopen_state != NULL);
4847     drv = reopen_state->bs->drv;
4848     assert(drv != NULL);
4849     GLOBAL_STATE_CODE();
4850 
4851     if (drv->bdrv_reopen_abort) {
4852         drv->bdrv_reopen_abort(reopen_state);
4853     }
4854 }
4855 
4856 
4857 static void bdrv_close(BlockDriverState *bs)
4858 {
4859     BdrvAioNotifier *ban, *ban_next;
4860     BdrvChild *child, *next;
4861 
4862     GLOBAL_STATE_CODE();
4863     assert(!bs->refcnt);
4864 
4865     bdrv_drained_begin(bs); /* complete I/O */
4866     bdrv_flush(bs);
4867     bdrv_drain(bs); /* in case flush left pending I/O */
4868 
4869     if (bs->drv) {
4870         if (bs->drv->bdrv_close) {
4871             /* Must unfreeze all children, so bdrv_unref_child() works */
4872             bs->drv->bdrv_close(bs);
4873         }
4874         bs->drv = NULL;
4875     }
4876 
4877     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4878         bdrv_unref_child(bs, child);
4879     }
4880 
4881     bs->backing = NULL;
4882     bs->file = NULL;
4883     g_free(bs->opaque);
4884     bs->opaque = NULL;
4885     qatomic_set(&bs->copy_on_read, 0);
4886     bs->backing_file[0] = '\0';
4887     bs->backing_format[0] = '\0';
4888     bs->total_sectors = 0;
4889     bs->encrypted = false;
4890     bs->sg = false;
4891     qobject_unref(bs->options);
4892     qobject_unref(bs->explicit_options);
4893     bs->options = NULL;
4894     bs->explicit_options = NULL;
4895     qobject_unref(bs->full_open_options);
4896     bs->full_open_options = NULL;
4897     g_free(bs->block_status_cache);
4898     bs->block_status_cache = NULL;
4899 
4900     bdrv_release_named_dirty_bitmaps(bs);
4901     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4902 
4903     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4904         g_free(ban);
4905     }
4906     QLIST_INIT(&bs->aio_notifiers);
4907     bdrv_drained_end(bs);
4908 
4909     /*
4910      * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4911      * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4912      * gets called.
4913      */
4914     if (bs->quiesce_counter) {
4915         bdrv_drain_all_end_quiesce(bs);
4916     }
4917 }
4918 
4919 void bdrv_close_all(void)
4920 {
4921     GLOBAL_STATE_CODE();
4922     assert(job_next(NULL) == NULL);
4923 
4924     /* Drop references from requests still in flight, such as canceled block
4925      * jobs whose AIO context has not been polled yet */
4926     bdrv_drain_all();
4927 
4928     blk_remove_all_bs();
4929     blockdev_close_all_bdrv_states();
4930 
4931     assert(QTAILQ_EMPTY(&all_bdrv_states));
4932 }
4933 
4934 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4935 {
4936     GQueue *queue;
4937     GHashTable *found;
4938     bool ret;
4939 
4940     if (c->klass->stay_at_node) {
4941         return false;
4942     }
4943 
4944     /* If the child @c belongs to the BDS @to, replacing the current
4945      * c->bs by @to would mean to create a loop.
4946      *
4947      * Such a case occurs when appending a BDS to a backing chain.
4948      * For instance, imagine the following chain:
4949      *
4950      *   guest device -> node A -> further backing chain...
4951      *
4952      * Now we create a new BDS B which we want to put on top of this
4953      * chain, so we first attach A as its backing node:
4954      *
4955      *                   node B
4956      *                     |
4957      *                     v
4958      *   guest device -> node A -> further backing chain...
4959      *
4960      * Finally we want to replace A by B.  When doing that, we want to
4961      * replace all pointers to A by pointers to B -- except for the
4962      * pointer from B because (1) that would create a loop, and (2)
4963      * that pointer should simply stay intact:
4964      *
4965      *   guest device -> node B
4966      *                     |
4967      *                     v
4968      *                   node A -> further backing chain...
4969      *
4970      * In general, when replacing a node A (c->bs) by a node B (@to),
4971      * if A is a child of B, that means we cannot replace A by B there
4972      * because that would create a loop.  Silently detaching A from B
4973      * is also not really an option.  So overall just leaving A in
4974      * place there is the most sensible choice.
4975      *
4976      * We would also create a loop in any cases where @c is only
4977      * indirectly referenced by @to. Prevent this by returning false
4978      * if @c is found (by breadth-first search) anywhere in the whole
4979      * subtree of @to.
4980      */
4981 
4982     ret = true;
4983     found = g_hash_table_new(NULL, NULL);
4984     g_hash_table_add(found, to);
4985     queue = g_queue_new();
4986     g_queue_push_tail(queue, to);
4987 
4988     while (!g_queue_is_empty(queue)) {
4989         BlockDriverState *v = g_queue_pop_head(queue);
4990         BdrvChild *c2;
4991 
4992         QLIST_FOREACH(c2, &v->children, next) {
4993             if (c2 == c) {
4994                 ret = false;
4995                 break;
4996             }
4997 
4998             if (g_hash_table_contains(found, c2->bs)) {
4999                 continue;
5000             }
5001 
5002             g_queue_push_tail(queue, c2->bs);
5003             g_hash_table_add(found, c2->bs);
5004         }
5005     }
5006 
5007     g_queue_free(queue);
5008     g_hash_table_destroy(found);
5009 
5010     return ret;
5011 }
5012 
5013 typedef struct BdrvRemoveFilterOrCowChild {
5014     BdrvChild *child;
5015     bool is_backing;
5016 } BdrvRemoveFilterOrCowChild;
5017 
5018 static void bdrv_remove_filter_or_cow_child_abort(void *opaque)
5019 {
5020     BdrvRemoveFilterOrCowChild *s = opaque;
5021     BlockDriverState *parent_bs = s->child->opaque;
5022 
5023     if (s->is_backing) {
5024         parent_bs->backing = s->child;
5025     } else {
5026         parent_bs->file = s->child;
5027     }
5028 
5029     /*
5030      * We don't have to restore child->bs here to undo bdrv_replace_child_tran()
5031      * because that function is transactionable and it registered own completion
5032      * entries in @tran, so .abort() for bdrv_replace_child_safe() will be
5033      * called automatically.
5034      */
5035 }
5036 
5037 static void bdrv_remove_filter_or_cow_child_commit(void *opaque)
5038 {
5039     BdrvRemoveFilterOrCowChild *s = opaque;
5040     GLOBAL_STATE_CODE();
5041     bdrv_child_free(s->child);
5042 }
5043 
5044 static TransactionActionDrv bdrv_remove_filter_or_cow_child_drv = {
5045     .abort = bdrv_remove_filter_or_cow_child_abort,
5046     .commit = bdrv_remove_filter_or_cow_child_commit,
5047     .clean = g_free,
5048 };
5049 
5050 /*
5051  * A function to remove backing or file child of @bs.
5052  * Function doesn't update permissions, caller is responsible for this.
5053  */
5054 static void bdrv_remove_file_or_backing_child(BlockDriverState *bs,
5055                                               BdrvChild *child,
5056                                               Transaction *tran)
5057 {
5058     BdrvRemoveFilterOrCowChild *s;
5059 
5060     assert(child == bs->backing || child == bs->file);
5061 
5062     if (!child) {
5063         return;
5064     }
5065 
5066     if (child->bs) {
5067         bdrv_replace_child_tran(child, NULL, tran);
5068     }
5069 
5070     s = g_new(BdrvRemoveFilterOrCowChild, 1);
5071     *s = (BdrvRemoveFilterOrCowChild) {
5072         .child = child,
5073         .is_backing = (child == bs->backing),
5074     };
5075     tran_add(tran, &bdrv_remove_filter_or_cow_child_drv, s);
5076 
5077     if (s->is_backing) {
5078         bs->backing = NULL;
5079     } else {
5080         bs->file = NULL;
5081     }
5082 }
5083 
5084 /*
5085  * A function to remove backing-chain child of @bs if exists: cow child for
5086  * format nodes (always .backing) and filter child for filters (may be .file or
5087  * .backing)
5088  */
5089 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5090                                             Transaction *tran)
5091 {
5092     bdrv_remove_file_or_backing_child(bs, bdrv_filter_or_cow_child(bs), tran);
5093 }
5094 
5095 static int bdrv_replace_node_noperm(BlockDriverState *from,
5096                                     BlockDriverState *to,
5097                                     bool auto_skip, Transaction *tran,
5098                                     Error **errp)
5099 {
5100     BdrvChild *c, *next;
5101 
5102     GLOBAL_STATE_CODE();
5103 
5104     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5105         assert(c->bs == from);
5106         if (!should_update_child(c, to)) {
5107             if (auto_skip) {
5108                 continue;
5109             }
5110             error_setg(errp, "Should not change '%s' link to '%s'",
5111                        c->name, from->node_name);
5112             return -EINVAL;
5113         }
5114         if (c->frozen) {
5115             error_setg(errp, "Cannot change '%s' link to '%s'",
5116                        c->name, from->node_name);
5117             return -EPERM;
5118         }
5119         bdrv_replace_child_tran(c, to, tran);
5120     }
5121 
5122     return 0;
5123 }
5124 
5125 /*
5126  * With auto_skip=true bdrv_replace_node_common skips updating from parents
5127  * if it creates a parent-child relation loop or if parent is block-job.
5128  *
5129  * With auto_skip=false the error is returned if from has a parent which should
5130  * not be updated.
5131  *
5132  * With @detach_subchain=true @to must be in a backing chain of @from. In this
5133  * case backing link of the cow-parent of @to is removed.
5134  */
5135 static int bdrv_replace_node_common(BlockDriverState *from,
5136                                     BlockDriverState *to,
5137                                     bool auto_skip, bool detach_subchain,
5138                                     Error **errp)
5139 {
5140     Transaction *tran = tran_new();
5141     g_autoptr(GHashTable) found = NULL;
5142     g_autoptr(GSList) refresh_list = NULL;
5143     BlockDriverState *to_cow_parent = NULL;
5144     int ret;
5145 
5146     GLOBAL_STATE_CODE();
5147 
5148     if (detach_subchain) {
5149         assert(bdrv_chain_contains(from, to));
5150         assert(from != to);
5151         for (to_cow_parent = from;
5152              bdrv_filter_or_cow_bs(to_cow_parent) != to;
5153              to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5154         {
5155             ;
5156         }
5157     }
5158 
5159     /* Make sure that @from doesn't go away until we have successfully attached
5160      * all of its parents to @to. */
5161     bdrv_ref(from);
5162 
5163     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5164     assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5165     bdrv_drained_begin(from);
5166 
5167     /*
5168      * Do the replacement without permission update.
5169      * Replacement may influence the permissions, we should calculate new
5170      * permissions based on new graph. If we fail, we'll roll-back the
5171      * replacement.
5172      */
5173     ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5174     if (ret < 0) {
5175         goto out;
5176     }
5177 
5178     if (detach_subchain) {
5179         bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5180     }
5181 
5182     found = g_hash_table_new(NULL, NULL);
5183 
5184     refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5185     refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5186 
5187     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5188     if (ret < 0) {
5189         goto out;
5190     }
5191 
5192     ret = 0;
5193 
5194 out:
5195     tran_finalize(tran, ret);
5196 
5197     bdrv_drained_end(from);
5198     bdrv_unref(from);
5199 
5200     return ret;
5201 }
5202 
5203 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5204                       Error **errp)
5205 {
5206     GLOBAL_STATE_CODE();
5207 
5208     return bdrv_replace_node_common(from, to, true, false, errp);
5209 }
5210 
5211 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5212 {
5213     GLOBAL_STATE_CODE();
5214 
5215     return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5216                                     errp);
5217 }
5218 
5219 /*
5220  * Add new bs contents at the top of an image chain while the chain is
5221  * live, while keeping required fields on the top layer.
5222  *
5223  * This will modify the BlockDriverState fields, and swap contents
5224  * between bs_new and bs_top. Both bs_new and bs_top are modified.
5225  *
5226  * bs_new must not be attached to a BlockBackend and must not have backing
5227  * child.
5228  *
5229  * This function does not create any image files.
5230  */
5231 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5232                 Error **errp)
5233 {
5234     int ret;
5235     Transaction *tran = tran_new();
5236 
5237     GLOBAL_STATE_CODE();
5238 
5239     assert(!bs_new->backing);
5240 
5241     ret = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5242                                    &child_of_bds, bdrv_backing_role(bs_new),
5243                                    &bs_new->backing, tran, errp);
5244     if (ret < 0) {
5245         goto out;
5246     }
5247 
5248     ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5249     if (ret < 0) {
5250         goto out;
5251     }
5252 
5253     ret = bdrv_refresh_perms(bs_new, errp);
5254 out:
5255     tran_finalize(tran, ret);
5256 
5257     bdrv_refresh_limits(bs_top, NULL, NULL);
5258 
5259     return ret;
5260 }
5261 
5262 /* Not for empty child */
5263 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5264                           Error **errp)
5265 {
5266     int ret;
5267     Transaction *tran = tran_new();
5268     g_autoptr(GHashTable) found = NULL;
5269     g_autoptr(GSList) refresh_list = NULL;
5270     BlockDriverState *old_bs = child->bs;
5271 
5272     GLOBAL_STATE_CODE();
5273 
5274     bdrv_ref(old_bs);
5275     bdrv_drained_begin(old_bs);
5276     bdrv_drained_begin(new_bs);
5277 
5278     bdrv_replace_child_tran(child, new_bs, tran);
5279 
5280     found = g_hash_table_new(NULL, NULL);
5281     refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5282     refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5283 
5284     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5285 
5286     tran_finalize(tran, ret);
5287 
5288     bdrv_drained_end(old_bs);
5289     bdrv_drained_end(new_bs);
5290     bdrv_unref(old_bs);
5291 
5292     return ret;
5293 }
5294 
5295 static void bdrv_delete(BlockDriverState *bs)
5296 {
5297     assert(bdrv_op_blocker_is_empty(bs));
5298     assert(!bs->refcnt);
5299     GLOBAL_STATE_CODE();
5300 
5301     /* remove from list, if necessary */
5302     if (bs->node_name[0] != '\0') {
5303         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5304     }
5305     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5306 
5307     bdrv_close(bs);
5308 
5309     g_free(bs);
5310 }
5311 
5312 
5313 /*
5314  * Replace @bs by newly created block node.
5315  *
5316  * @options is a QDict of options to pass to the block drivers, or NULL for an
5317  * empty set of options. The reference to the QDict belongs to the block layer
5318  * after the call (even on failure), so if the caller intends to reuse the
5319  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5320  */
5321 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5322                                    int flags, Error **errp)
5323 {
5324     ERRP_GUARD();
5325     int ret;
5326     BlockDriverState *new_node_bs = NULL;
5327     const char *drvname, *node_name;
5328     BlockDriver *drv;
5329 
5330     drvname = qdict_get_try_str(options, "driver");
5331     if (!drvname) {
5332         error_setg(errp, "driver is not specified");
5333         goto fail;
5334     }
5335 
5336     drv = bdrv_find_format(drvname);
5337     if (!drv) {
5338         error_setg(errp, "Unknown driver: '%s'", drvname);
5339         goto fail;
5340     }
5341 
5342     node_name = qdict_get_try_str(options, "node-name");
5343 
5344     GLOBAL_STATE_CODE();
5345 
5346     new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5347                                             errp);
5348     options = NULL; /* bdrv_new_open_driver() eats options */
5349     if (!new_node_bs) {
5350         error_prepend(errp, "Could not create node: ");
5351         goto fail;
5352     }
5353 
5354     bdrv_drained_begin(bs);
5355     ret = bdrv_replace_node(bs, new_node_bs, errp);
5356     bdrv_drained_end(bs);
5357 
5358     if (ret < 0) {
5359         error_prepend(errp, "Could not replace node: ");
5360         goto fail;
5361     }
5362 
5363     return new_node_bs;
5364 
5365 fail:
5366     qobject_unref(options);
5367     bdrv_unref(new_node_bs);
5368     return NULL;
5369 }
5370 
5371 /*
5372  * Run consistency checks on an image
5373  *
5374  * Returns 0 if the check could be completed (it doesn't mean that the image is
5375  * free of errors) or -errno when an internal error occurred. The results of the
5376  * check are stored in res.
5377  */
5378 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5379                                BdrvCheckResult *res, BdrvCheckMode fix)
5380 {
5381     IO_CODE();
5382     if (bs->drv == NULL) {
5383         return -ENOMEDIUM;
5384     }
5385     if (bs->drv->bdrv_co_check == NULL) {
5386         return -ENOTSUP;
5387     }
5388 
5389     memset(res, 0, sizeof(*res));
5390     return bs->drv->bdrv_co_check(bs, res, fix);
5391 }
5392 
5393 /*
5394  * Return values:
5395  * 0        - success
5396  * -EINVAL  - backing format specified, but no file
5397  * -ENOSPC  - can't update the backing file because no space is left in the
5398  *            image file header
5399  * -ENOTSUP - format driver doesn't support changing the backing file
5400  */
5401 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5402                              const char *backing_fmt, bool require)
5403 {
5404     BlockDriver *drv = bs->drv;
5405     int ret;
5406 
5407     GLOBAL_STATE_CODE();
5408 
5409     if (!drv) {
5410         return -ENOMEDIUM;
5411     }
5412 
5413     /* Backing file format doesn't make sense without a backing file */
5414     if (backing_fmt && !backing_file) {
5415         return -EINVAL;
5416     }
5417 
5418     if (require && backing_file && !backing_fmt) {
5419         return -EINVAL;
5420     }
5421 
5422     if (drv->bdrv_change_backing_file != NULL) {
5423         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5424     } else {
5425         ret = -ENOTSUP;
5426     }
5427 
5428     if (ret == 0) {
5429         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5430         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5431         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5432                 backing_file ?: "");
5433     }
5434     return ret;
5435 }
5436 
5437 /*
5438  * Finds the first non-filter node above bs in the chain between
5439  * active and bs.  The returned node is either an immediate parent of
5440  * bs, or there are only filter nodes between the two.
5441  *
5442  * Returns NULL if bs is not found in active's image chain,
5443  * or if active == bs.
5444  *
5445  * Returns the bottommost base image if bs == NULL.
5446  */
5447 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5448                                     BlockDriverState *bs)
5449 {
5450 
5451     GLOBAL_STATE_CODE();
5452 
5453     bs = bdrv_skip_filters(bs);
5454     active = bdrv_skip_filters(active);
5455 
5456     while (active) {
5457         BlockDriverState *next = bdrv_backing_chain_next(active);
5458         if (bs == next) {
5459             return active;
5460         }
5461         active = next;
5462     }
5463 
5464     return NULL;
5465 }
5466 
5467 /* Given a BDS, searches for the base layer. */
5468 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5469 {
5470     GLOBAL_STATE_CODE();
5471 
5472     return bdrv_find_overlay(bs, NULL);
5473 }
5474 
5475 /*
5476  * Return true if at least one of the COW (backing) and filter links
5477  * between @bs and @base is frozen. @errp is set if that's the case.
5478  * @base must be reachable from @bs, or NULL.
5479  */
5480 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5481                                   Error **errp)
5482 {
5483     BlockDriverState *i;
5484     BdrvChild *child;
5485 
5486     GLOBAL_STATE_CODE();
5487 
5488     for (i = bs; i != base; i = child_bs(child)) {
5489         child = bdrv_filter_or_cow_child(i);
5490 
5491         if (child && child->frozen) {
5492             error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5493                        child->name, i->node_name, child->bs->node_name);
5494             return true;
5495         }
5496     }
5497 
5498     return false;
5499 }
5500 
5501 /*
5502  * Freeze all COW (backing) and filter links between @bs and @base.
5503  * If any of the links is already frozen the operation is aborted and
5504  * none of the links are modified.
5505  * @base must be reachable from @bs, or NULL.
5506  * Returns 0 on success. On failure returns < 0 and sets @errp.
5507  */
5508 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5509                               Error **errp)
5510 {
5511     BlockDriverState *i;
5512     BdrvChild *child;
5513 
5514     GLOBAL_STATE_CODE();
5515 
5516     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5517         return -EPERM;
5518     }
5519 
5520     for (i = bs; i != base; i = child_bs(child)) {
5521         child = bdrv_filter_or_cow_child(i);
5522         if (child && child->bs->never_freeze) {
5523             error_setg(errp, "Cannot freeze '%s' link to '%s'",
5524                        child->name, child->bs->node_name);
5525             return -EPERM;
5526         }
5527     }
5528 
5529     for (i = bs; i != base; i = child_bs(child)) {
5530         child = bdrv_filter_or_cow_child(i);
5531         if (child) {
5532             child->frozen = true;
5533         }
5534     }
5535 
5536     return 0;
5537 }
5538 
5539 /*
5540  * Unfreeze all COW (backing) and filter links between @bs and @base.
5541  * The caller must ensure that all links are frozen before using this
5542  * function.
5543  * @base must be reachable from @bs, or NULL.
5544  */
5545 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5546 {
5547     BlockDriverState *i;
5548     BdrvChild *child;
5549 
5550     GLOBAL_STATE_CODE();
5551 
5552     for (i = bs; i != base; i = child_bs(child)) {
5553         child = bdrv_filter_or_cow_child(i);
5554         if (child) {
5555             assert(child->frozen);
5556             child->frozen = false;
5557         }
5558     }
5559 }
5560 
5561 /*
5562  * Drops images above 'base' up to and including 'top', and sets the image
5563  * above 'top' to have base as its backing file.
5564  *
5565  * Requires that the overlay to 'top' is opened r/w, so that the backing file
5566  * information in 'bs' can be properly updated.
5567  *
5568  * E.g., this will convert the following chain:
5569  * bottom <- base <- intermediate <- top <- active
5570  *
5571  * to
5572  *
5573  * bottom <- base <- active
5574  *
5575  * It is allowed for bottom==base, in which case it converts:
5576  *
5577  * base <- intermediate <- top <- active
5578  *
5579  * to
5580  *
5581  * base <- active
5582  *
5583  * If backing_file_str is non-NULL, it will be used when modifying top's
5584  * overlay image metadata.
5585  *
5586  * Error conditions:
5587  *  if active == top, that is considered an error
5588  *
5589  */
5590 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5591                            const char *backing_file_str)
5592 {
5593     BlockDriverState *explicit_top = top;
5594     bool update_inherits_from;
5595     BdrvChild *c;
5596     Error *local_err = NULL;
5597     int ret = -EIO;
5598     g_autoptr(GSList) updated_children = NULL;
5599     GSList *p;
5600 
5601     GLOBAL_STATE_CODE();
5602 
5603     bdrv_ref(top);
5604     bdrv_subtree_drained_begin(top);
5605 
5606     if (!top->drv || !base->drv) {
5607         goto exit;
5608     }
5609 
5610     /* Make sure that base is in the backing chain of top */
5611     if (!bdrv_chain_contains(top, base)) {
5612         goto exit;
5613     }
5614 
5615     /* If 'base' recursively inherits from 'top' then we should set
5616      * base->inherits_from to top->inherits_from after 'top' and all
5617      * other intermediate nodes have been dropped.
5618      * If 'top' is an implicit node (e.g. "commit_top") we should skip
5619      * it because no one inherits from it. We use explicit_top for that. */
5620     explicit_top = bdrv_skip_implicit_filters(explicit_top);
5621     update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5622 
5623     /* success - we can delete the intermediate states, and link top->base */
5624     if (!backing_file_str) {
5625         bdrv_refresh_filename(base);
5626         backing_file_str = base->filename;
5627     }
5628 
5629     QLIST_FOREACH(c, &top->parents, next_parent) {
5630         updated_children = g_slist_prepend(updated_children, c);
5631     }
5632 
5633     /*
5634      * It seems correct to pass detach_subchain=true here, but it triggers
5635      * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5636      * another drained section, which modify the graph (for example, removing
5637      * the child, which we keep in updated_children list). So, it's a TODO.
5638      *
5639      * Note, bug triggered if pass detach_subchain=true here and run
5640      * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5641      * That's a FIXME.
5642      */
5643     bdrv_replace_node_common(top, base, false, false, &local_err);
5644     if (local_err) {
5645         error_report_err(local_err);
5646         goto exit;
5647     }
5648 
5649     for (p = updated_children; p; p = p->next) {
5650         c = p->data;
5651 
5652         if (c->klass->update_filename) {
5653             ret = c->klass->update_filename(c, base, backing_file_str,
5654                                             &local_err);
5655             if (ret < 0) {
5656                 /*
5657                  * TODO: Actually, we want to rollback all previous iterations
5658                  * of this loop, and (which is almost impossible) previous
5659                  * bdrv_replace_node()...
5660                  *
5661                  * Note, that c->klass->update_filename may lead to permission
5662                  * update, so it's a bad idea to call it inside permission
5663                  * update transaction of bdrv_replace_node.
5664                  */
5665                 error_report_err(local_err);
5666                 goto exit;
5667             }
5668         }
5669     }
5670 
5671     if (update_inherits_from) {
5672         base->inherits_from = explicit_top->inherits_from;
5673     }
5674 
5675     ret = 0;
5676 exit:
5677     bdrv_subtree_drained_end(top);
5678     bdrv_unref(top);
5679     return ret;
5680 }
5681 
5682 /**
5683  * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5684  * sums the size of all data-bearing children.  (This excludes backing
5685  * children.)
5686  */
5687 static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5688 {
5689     BdrvChild *child;
5690     int64_t child_size, sum = 0;
5691 
5692     QLIST_FOREACH(child, &bs->children, next) {
5693         if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5694                            BDRV_CHILD_FILTERED))
5695         {
5696             child_size = bdrv_get_allocated_file_size(child->bs);
5697             if (child_size < 0) {
5698                 return child_size;
5699             }
5700             sum += child_size;
5701         }
5702     }
5703 
5704     return sum;
5705 }
5706 
5707 /**
5708  * Length of a allocated file in bytes. Sparse files are counted by actual
5709  * allocated space. Return < 0 if error or unknown.
5710  */
5711 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5712 {
5713     BlockDriver *drv = bs->drv;
5714     IO_CODE();
5715 
5716     if (!drv) {
5717         return -ENOMEDIUM;
5718     }
5719     if (drv->bdrv_get_allocated_file_size) {
5720         return drv->bdrv_get_allocated_file_size(bs);
5721     }
5722 
5723     if (drv->bdrv_file_open) {
5724         /*
5725          * Protocol drivers default to -ENOTSUP (most of their data is
5726          * not stored in any of their children (if they even have any),
5727          * so there is no generic way to figure it out).
5728          */
5729         return -ENOTSUP;
5730     } else if (drv->is_filter) {
5731         /* Filter drivers default to the size of their filtered child */
5732         return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5733     } else {
5734         /* Other drivers default to summing their children's sizes */
5735         return bdrv_sum_allocated_file_size(bs);
5736     }
5737 }
5738 
5739 /*
5740  * bdrv_measure:
5741  * @drv: Format driver
5742  * @opts: Creation options for new image
5743  * @in_bs: Existing image containing data for new image (may be NULL)
5744  * @errp: Error object
5745  * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5746  *          or NULL on error
5747  *
5748  * Calculate file size required to create a new image.
5749  *
5750  * If @in_bs is given then space for allocated clusters and zero clusters
5751  * from that image are included in the calculation.  If @opts contains a
5752  * backing file that is shared by @in_bs then backing clusters may be omitted
5753  * from the calculation.
5754  *
5755  * If @in_bs is NULL then the calculation includes no allocated clusters
5756  * unless a preallocation option is given in @opts.
5757  *
5758  * Note that @in_bs may use a different BlockDriver from @drv.
5759  *
5760  * If an error occurs the @errp pointer is set.
5761  */
5762 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5763                                BlockDriverState *in_bs, Error **errp)
5764 {
5765     IO_CODE();
5766     if (!drv->bdrv_measure) {
5767         error_setg(errp, "Block driver '%s' does not support size measurement",
5768                    drv->format_name);
5769         return NULL;
5770     }
5771 
5772     return drv->bdrv_measure(opts, in_bs, errp);
5773 }
5774 
5775 /**
5776  * Return number of sectors on success, -errno on error.
5777  */
5778 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5779 {
5780     BlockDriver *drv = bs->drv;
5781     IO_CODE();
5782 
5783     if (!drv)
5784         return -ENOMEDIUM;
5785 
5786     if (drv->has_variable_length) {
5787         int ret = refresh_total_sectors(bs, bs->total_sectors);
5788         if (ret < 0) {
5789             return ret;
5790         }
5791     }
5792     return bs->total_sectors;
5793 }
5794 
5795 /**
5796  * Return length in bytes on success, -errno on error.
5797  * The length is always a multiple of BDRV_SECTOR_SIZE.
5798  */
5799 int64_t bdrv_getlength(BlockDriverState *bs)
5800 {
5801     int64_t ret = bdrv_nb_sectors(bs);
5802     IO_CODE();
5803 
5804     if (ret < 0) {
5805         return ret;
5806     }
5807     if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5808         return -EFBIG;
5809     }
5810     return ret * BDRV_SECTOR_SIZE;
5811 }
5812 
5813 /* return 0 as number of sectors if no device present or error */
5814 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5815 {
5816     int64_t nb_sectors = bdrv_nb_sectors(bs);
5817     IO_CODE();
5818 
5819     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5820 }
5821 
5822 bool bdrv_is_sg(BlockDriverState *bs)
5823 {
5824     IO_CODE();
5825     return bs->sg;
5826 }
5827 
5828 /**
5829  * Return whether the given node supports compressed writes.
5830  */
5831 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5832 {
5833     BlockDriverState *filtered;
5834     IO_CODE();
5835 
5836     if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5837         return false;
5838     }
5839 
5840     filtered = bdrv_filter_bs(bs);
5841     if (filtered) {
5842         /*
5843          * Filters can only forward compressed writes, so we have to
5844          * check the child.
5845          */
5846         return bdrv_supports_compressed_writes(filtered);
5847     }
5848 
5849     return true;
5850 }
5851 
5852 const char *bdrv_get_format_name(BlockDriverState *bs)
5853 {
5854     IO_CODE();
5855     return bs->drv ? bs->drv->format_name : NULL;
5856 }
5857 
5858 static int qsort_strcmp(const void *a, const void *b)
5859 {
5860     return strcmp(*(char *const *)a, *(char *const *)b);
5861 }
5862 
5863 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5864                          void *opaque, bool read_only)
5865 {
5866     BlockDriver *drv;
5867     int count = 0;
5868     int i;
5869     const char **formats = NULL;
5870 
5871     GLOBAL_STATE_CODE();
5872 
5873     QLIST_FOREACH(drv, &bdrv_drivers, list) {
5874         if (drv->format_name) {
5875             bool found = false;
5876             int i = count;
5877 
5878             if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5879                 continue;
5880             }
5881 
5882             while (formats && i && !found) {
5883                 found = !strcmp(formats[--i], drv->format_name);
5884             }
5885 
5886             if (!found) {
5887                 formats = g_renew(const char *, formats, count + 1);
5888                 formats[count++] = drv->format_name;
5889             }
5890         }
5891     }
5892 
5893     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5894         const char *format_name = block_driver_modules[i].format_name;
5895 
5896         if (format_name) {
5897             bool found = false;
5898             int j = count;
5899 
5900             if (use_bdrv_whitelist &&
5901                 !bdrv_format_is_whitelisted(format_name, read_only)) {
5902                 continue;
5903             }
5904 
5905             while (formats && j && !found) {
5906                 found = !strcmp(formats[--j], format_name);
5907             }
5908 
5909             if (!found) {
5910                 formats = g_renew(const char *, formats, count + 1);
5911                 formats[count++] = format_name;
5912             }
5913         }
5914     }
5915 
5916     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5917 
5918     for (i = 0; i < count; i++) {
5919         it(opaque, formats[i]);
5920     }
5921 
5922     g_free(formats);
5923 }
5924 
5925 /* This function is to find a node in the bs graph */
5926 BlockDriverState *bdrv_find_node(const char *node_name)
5927 {
5928     BlockDriverState *bs;
5929 
5930     assert(node_name);
5931     GLOBAL_STATE_CODE();
5932 
5933     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5934         if (!strcmp(node_name, bs->node_name)) {
5935             return bs;
5936         }
5937     }
5938     return NULL;
5939 }
5940 
5941 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5942 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5943                                            Error **errp)
5944 {
5945     BlockDeviceInfoList *list;
5946     BlockDriverState *bs;
5947 
5948     GLOBAL_STATE_CODE();
5949 
5950     list = NULL;
5951     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5952         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5953         if (!info) {
5954             qapi_free_BlockDeviceInfoList(list);
5955             return NULL;
5956         }
5957         QAPI_LIST_PREPEND(list, info);
5958     }
5959 
5960     return list;
5961 }
5962 
5963 typedef struct XDbgBlockGraphConstructor {
5964     XDbgBlockGraph *graph;
5965     GHashTable *graph_nodes;
5966 } XDbgBlockGraphConstructor;
5967 
5968 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5969 {
5970     XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5971 
5972     gr->graph = g_new0(XDbgBlockGraph, 1);
5973     gr->graph_nodes = g_hash_table_new(NULL, NULL);
5974 
5975     return gr;
5976 }
5977 
5978 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5979 {
5980     XDbgBlockGraph *graph = gr->graph;
5981 
5982     g_hash_table_destroy(gr->graph_nodes);
5983     g_free(gr);
5984 
5985     return graph;
5986 }
5987 
5988 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5989 {
5990     uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5991 
5992     if (ret != 0) {
5993         return ret;
5994     }
5995 
5996     /*
5997      * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5998      * answer of g_hash_table_lookup.
5999      */
6000     ret = g_hash_table_size(gr->graph_nodes) + 1;
6001     g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
6002 
6003     return ret;
6004 }
6005 
6006 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
6007                                 XDbgBlockGraphNodeType type, const char *name)
6008 {
6009     XDbgBlockGraphNode *n;
6010 
6011     n = g_new0(XDbgBlockGraphNode, 1);
6012 
6013     n->id = xdbg_graph_node_num(gr, node);
6014     n->type = type;
6015     n->name = g_strdup(name);
6016 
6017     QAPI_LIST_PREPEND(gr->graph->nodes, n);
6018 }
6019 
6020 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6021                                 const BdrvChild *child)
6022 {
6023     BlockPermission qapi_perm;
6024     XDbgBlockGraphEdge *edge;
6025     GLOBAL_STATE_CODE();
6026 
6027     edge = g_new0(XDbgBlockGraphEdge, 1);
6028 
6029     edge->parent = xdbg_graph_node_num(gr, parent);
6030     edge->child = xdbg_graph_node_num(gr, child->bs);
6031     edge->name = g_strdup(child->name);
6032 
6033     for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6034         uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6035 
6036         if (flag & child->perm) {
6037             QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6038         }
6039         if (flag & child->shared_perm) {
6040             QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6041         }
6042     }
6043 
6044     QAPI_LIST_PREPEND(gr->graph->edges, edge);
6045 }
6046 
6047 
6048 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6049 {
6050     BlockBackend *blk;
6051     BlockJob *job;
6052     BlockDriverState *bs;
6053     BdrvChild *child;
6054     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6055 
6056     GLOBAL_STATE_CODE();
6057 
6058     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6059         char *allocated_name = NULL;
6060         const char *name = blk_name(blk);
6061 
6062         if (!*name) {
6063             name = allocated_name = blk_get_attached_dev_id(blk);
6064         }
6065         xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6066                            name);
6067         g_free(allocated_name);
6068         if (blk_root(blk)) {
6069             xdbg_graph_add_edge(gr, blk, blk_root(blk));
6070         }
6071     }
6072 
6073     WITH_JOB_LOCK_GUARD() {
6074         for (job = block_job_next_locked(NULL); job;
6075              job = block_job_next_locked(job)) {
6076             GSList *el;
6077 
6078             xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6079                                 job->job.id);
6080             for (el = job->nodes; el; el = el->next) {
6081                 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6082             }
6083         }
6084     }
6085 
6086     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6087         xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6088                            bs->node_name);
6089         QLIST_FOREACH(child, &bs->children, next) {
6090             xdbg_graph_add_edge(gr, bs, child);
6091         }
6092     }
6093 
6094     return xdbg_graph_finalize(gr);
6095 }
6096 
6097 BlockDriverState *bdrv_lookup_bs(const char *device,
6098                                  const char *node_name,
6099                                  Error **errp)
6100 {
6101     BlockBackend *blk;
6102     BlockDriverState *bs;
6103 
6104     GLOBAL_STATE_CODE();
6105 
6106     if (device) {
6107         blk = blk_by_name(device);
6108 
6109         if (blk) {
6110             bs = blk_bs(blk);
6111             if (!bs) {
6112                 error_setg(errp, "Device '%s' has no medium", device);
6113             }
6114 
6115             return bs;
6116         }
6117     }
6118 
6119     if (node_name) {
6120         bs = bdrv_find_node(node_name);
6121 
6122         if (bs) {
6123             return bs;
6124         }
6125     }
6126 
6127     error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6128                      device ? device : "",
6129                      node_name ? node_name : "");
6130     return NULL;
6131 }
6132 
6133 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6134  * return false.  If either argument is NULL, return false. */
6135 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6136 {
6137 
6138     GLOBAL_STATE_CODE();
6139 
6140     while (top && top != base) {
6141         top = bdrv_filter_or_cow_bs(top);
6142     }
6143 
6144     return top != NULL;
6145 }
6146 
6147 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6148 {
6149     GLOBAL_STATE_CODE();
6150     if (!bs) {
6151         return QTAILQ_FIRST(&graph_bdrv_states);
6152     }
6153     return QTAILQ_NEXT(bs, node_list);
6154 }
6155 
6156 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6157 {
6158     GLOBAL_STATE_CODE();
6159     if (!bs) {
6160         return QTAILQ_FIRST(&all_bdrv_states);
6161     }
6162     return QTAILQ_NEXT(bs, bs_list);
6163 }
6164 
6165 const char *bdrv_get_node_name(const BlockDriverState *bs)
6166 {
6167     IO_CODE();
6168     return bs->node_name;
6169 }
6170 
6171 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6172 {
6173     BdrvChild *c;
6174     const char *name;
6175     IO_CODE();
6176 
6177     /* If multiple parents have a name, just pick the first one. */
6178     QLIST_FOREACH(c, &bs->parents, next_parent) {
6179         if (c->klass->get_name) {
6180             name = c->klass->get_name(c);
6181             if (name && *name) {
6182                 return name;
6183             }
6184         }
6185     }
6186 
6187     return NULL;
6188 }
6189 
6190 /* TODO check what callers really want: bs->node_name or blk_name() */
6191 const char *bdrv_get_device_name(const BlockDriverState *bs)
6192 {
6193     IO_CODE();
6194     return bdrv_get_parent_name(bs) ?: "";
6195 }
6196 
6197 /* This can be used to identify nodes that might not have a device
6198  * name associated. Since node and device names live in the same
6199  * namespace, the result is unambiguous. The exception is if both are
6200  * absent, then this returns an empty (non-null) string. */
6201 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6202 {
6203     IO_CODE();
6204     return bdrv_get_parent_name(bs) ?: bs->node_name;
6205 }
6206 
6207 int bdrv_get_flags(BlockDriverState *bs)
6208 {
6209     IO_CODE();
6210     return bs->open_flags;
6211 }
6212 
6213 int bdrv_has_zero_init_1(BlockDriverState *bs)
6214 {
6215     GLOBAL_STATE_CODE();
6216     return 1;
6217 }
6218 
6219 int bdrv_has_zero_init(BlockDriverState *bs)
6220 {
6221     BlockDriverState *filtered;
6222     GLOBAL_STATE_CODE();
6223 
6224     if (!bs->drv) {
6225         return 0;
6226     }
6227 
6228     /* If BS is a copy on write image, it is initialized to
6229        the contents of the base image, which may not be zeroes.  */
6230     if (bdrv_cow_child(bs)) {
6231         return 0;
6232     }
6233     if (bs->drv->bdrv_has_zero_init) {
6234         return bs->drv->bdrv_has_zero_init(bs);
6235     }
6236 
6237     filtered = bdrv_filter_bs(bs);
6238     if (filtered) {
6239         return bdrv_has_zero_init(filtered);
6240     }
6241 
6242     /* safe default */
6243     return 0;
6244 }
6245 
6246 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6247 {
6248     IO_CODE();
6249     if (!(bs->open_flags & BDRV_O_UNMAP)) {
6250         return false;
6251     }
6252 
6253     return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6254 }
6255 
6256 void bdrv_get_backing_filename(BlockDriverState *bs,
6257                                char *filename, int filename_size)
6258 {
6259     IO_CODE();
6260     pstrcpy(filename, filename_size, bs->backing_file);
6261 }
6262 
6263 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6264 {
6265     int ret;
6266     BlockDriver *drv = bs->drv;
6267     IO_CODE();
6268     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6269     if (!drv) {
6270         return -ENOMEDIUM;
6271     }
6272     if (!drv->bdrv_get_info) {
6273         BlockDriverState *filtered = bdrv_filter_bs(bs);
6274         if (filtered) {
6275             return bdrv_get_info(filtered, bdi);
6276         }
6277         return -ENOTSUP;
6278     }
6279     memset(bdi, 0, sizeof(*bdi));
6280     ret = drv->bdrv_get_info(bs, bdi);
6281     if (ret < 0) {
6282         return ret;
6283     }
6284 
6285     if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6286         return -EINVAL;
6287     }
6288 
6289     return 0;
6290 }
6291 
6292 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6293                                           Error **errp)
6294 {
6295     BlockDriver *drv = bs->drv;
6296     IO_CODE();
6297     if (drv && drv->bdrv_get_specific_info) {
6298         return drv->bdrv_get_specific_info(bs, errp);
6299     }
6300     return NULL;
6301 }
6302 
6303 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6304 {
6305     BlockDriver *drv = bs->drv;
6306     IO_CODE();
6307     if (!drv || !drv->bdrv_get_specific_stats) {
6308         return NULL;
6309     }
6310     return drv->bdrv_get_specific_stats(bs);
6311 }
6312 
6313 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6314 {
6315     IO_CODE();
6316     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6317         return;
6318     }
6319 
6320     bs->drv->bdrv_debug_event(bs, event);
6321 }
6322 
6323 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
6324 {
6325     GLOBAL_STATE_CODE();
6326     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6327         bs = bdrv_primary_bs(bs);
6328     }
6329 
6330     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6331         assert(bs->drv->bdrv_debug_remove_breakpoint);
6332         return bs;
6333     }
6334 
6335     return NULL;
6336 }
6337 
6338 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6339                           const char *tag)
6340 {
6341     GLOBAL_STATE_CODE();
6342     bs = bdrv_find_debug_node(bs);
6343     if (bs) {
6344         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6345     }
6346 
6347     return -ENOTSUP;
6348 }
6349 
6350 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6351 {
6352     GLOBAL_STATE_CODE();
6353     bs = bdrv_find_debug_node(bs);
6354     if (bs) {
6355         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6356     }
6357 
6358     return -ENOTSUP;
6359 }
6360 
6361 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6362 {
6363     GLOBAL_STATE_CODE();
6364     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6365         bs = bdrv_primary_bs(bs);
6366     }
6367 
6368     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6369         return bs->drv->bdrv_debug_resume(bs, tag);
6370     }
6371 
6372     return -ENOTSUP;
6373 }
6374 
6375 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6376 {
6377     GLOBAL_STATE_CODE();
6378     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6379         bs = bdrv_primary_bs(bs);
6380     }
6381 
6382     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6383         return bs->drv->bdrv_debug_is_suspended(bs, tag);
6384     }
6385 
6386     return false;
6387 }
6388 
6389 /* backing_file can either be relative, or absolute, or a protocol.  If it is
6390  * relative, it must be relative to the chain.  So, passing in bs->filename
6391  * from a BDS as backing_file should not be done, as that may be relative to
6392  * the CWD rather than the chain. */
6393 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6394         const char *backing_file)
6395 {
6396     char *filename_full = NULL;
6397     char *backing_file_full = NULL;
6398     char *filename_tmp = NULL;
6399     int is_protocol = 0;
6400     bool filenames_refreshed = false;
6401     BlockDriverState *curr_bs = NULL;
6402     BlockDriverState *retval = NULL;
6403     BlockDriverState *bs_below;
6404 
6405     GLOBAL_STATE_CODE();
6406 
6407     if (!bs || !bs->drv || !backing_file) {
6408         return NULL;
6409     }
6410 
6411     filename_full     = g_malloc(PATH_MAX);
6412     backing_file_full = g_malloc(PATH_MAX);
6413 
6414     is_protocol = path_has_protocol(backing_file);
6415 
6416     /*
6417      * Being largely a legacy function, skip any filters here
6418      * (because filters do not have normal filenames, so they cannot
6419      * match anyway; and allowing json:{} filenames is a bit out of
6420      * scope).
6421      */
6422     for (curr_bs = bdrv_skip_filters(bs);
6423          bdrv_cow_child(curr_bs) != NULL;
6424          curr_bs = bs_below)
6425     {
6426         bs_below = bdrv_backing_chain_next(curr_bs);
6427 
6428         if (bdrv_backing_overridden(curr_bs)) {
6429             /*
6430              * If the backing file was overridden, we can only compare
6431              * directly against the backing node's filename.
6432              */
6433 
6434             if (!filenames_refreshed) {
6435                 /*
6436                  * This will automatically refresh all of the
6437                  * filenames in the rest of the backing chain, so we
6438                  * only need to do this once.
6439                  */
6440                 bdrv_refresh_filename(bs_below);
6441                 filenames_refreshed = true;
6442             }
6443 
6444             if (strcmp(backing_file, bs_below->filename) == 0) {
6445                 retval = bs_below;
6446                 break;
6447             }
6448         } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6449             /*
6450              * If either of the filename paths is actually a protocol, then
6451              * compare unmodified paths; otherwise make paths relative.
6452              */
6453             char *backing_file_full_ret;
6454 
6455             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6456                 retval = bs_below;
6457                 break;
6458             }
6459             /* Also check against the full backing filename for the image */
6460             backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6461                                                                    NULL);
6462             if (backing_file_full_ret) {
6463                 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6464                 g_free(backing_file_full_ret);
6465                 if (equal) {
6466                     retval = bs_below;
6467                     break;
6468                 }
6469             }
6470         } else {
6471             /* If not an absolute filename path, make it relative to the current
6472              * image's filename path */
6473             filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6474                                                        NULL);
6475             /* We are going to compare canonicalized absolute pathnames */
6476             if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6477                 g_free(filename_tmp);
6478                 continue;
6479             }
6480             g_free(filename_tmp);
6481 
6482             /* We need to make sure the backing filename we are comparing against
6483              * is relative to the current image filename (or absolute) */
6484             filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6485             if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6486                 g_free(filename_tmp);
6487                 continue;
6488             }
6489             g_free(filename_tmp);
6490 
6491             if (strcmp(backing_file_full, filename_full) == 0) {
6492                 retval = bs_below;
6493                 break;
6494             }
6495         }
6496     }
6497 
6498     g_free(filename_full);
6499     g_free(backing_file_full);
6500     return retval;
6501 }
6502 
6503 void bdrv_init(void)
6504 {
6505 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6506     use_bdrv_whitelist = 1;
6507 #endif
6508     module_call_init(MODULE_INIT_BLOCK);
6509 }
6510 
6511 void bdrv_init_with_whitelist(void)
6512 {
6513     use_bdrv_whitelist = 1;
6514     bdrv_init();
6515 }
6516 
6517 int bdrv_activate(BlockDriverState *bs, Error **errp)
6518 {
6519     BdrvChild *child, *parent;
6520     Error *local_err = NULL;
6521     int ret;
6522     BdrvDirtyBitmap *bm;
6523 
6524     GLOBAL_STATE_CODE();
6525 
6526     if (!bs->drv)  {
6527         return -ENOMEDIUM;
6528     }
6529 
6530     QLIST_FOREACH(child, &bs->children, next) {
6531         bdrv_activate(child->bs, &local_err);
6532         if (local_err) {
6533             error_propagate(errp, local_err);
6534             return -EINVAL;
6535         }
6536     }
6537 
6538     /*
6539      * Update permissions, they may differ for inactive nodes.
6540      *
6541      * Note that the required permissions of inactive images are always a
6542      * subset of the permissions required after activating the image. This
6543      * allows us to just get the permissions upfront without restricting
6544      * bdrv_co_invalidate_cache().
6545      *
6546      * It also means that in error cases, we don't have to try and revert to
6547      * the old permissions (which is an operation that could fail, too). We can
6548      * just keep the extended permissions for the next time that an activation
6549      * of the image is tried.
6550      */
6551     if (bs->open_flags & BDRV_O_INACTIVE) {
6552         bs->open_flags &= ~BDRV_O_INACTIVE;
6553         ret = bdrv_refresh_perms(bs, errp);
6554         if (ret < 0) {
6555             bs->open_flags |= BDRV_O_INACTIVE;
6556             return ret;
6557         }
6558 
6559         ret = bdrv_invalidate_cache(bs, errp);
6560         if (ret < 0) {
6561             bs->open_flags |= BDRV_O_INACTIVE;
6562             return ret;
6563         }
6564 
6565         FOR_EACH_DIRTY_BITMAP(bs, bm) {
6566             bdrv_dirty_bitmap_skip_store(bm, false);
6567         }
6568 
6569         ret = refresh_total_sectors(bs, bs->total_sectors);
6570         if (ret < 0) {
6571             bs->open_flags |= BDRV_O_INACTIVE;
6572             error_setg_errno(errp, -ret, "Could not refresh total sector count");
6573             return ret;
6574         }
6575     }
6576 
6577     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6578         if (parent->klass->activate) {
6579             parent->klass->activate(parent, &local_err);
6580             if (local_err) {
6581                 bs->open_flags |= BDRV_O_INACTIVE;
6582                 error_propagate(errp, local_err);
6583                 return -EINVAL;
6584             }
6585         }
6586     }
6587 
6588     return 0;
6589 }
6590 
6591 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6592 {
6593     Error *local_err = NULL;
6594     IO_CODE();
6595 
6596     assert(!(bs->open_flags & BDRV_O_INACTIVE));
6597 
6598     if (bs->drv->bdrv_co_invalidate_cache) {
6599         bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6600         if (local_err) {
6601             error_propagate(errp, local_err);
6602             return -EINVAL;
6603         }
6604     }
6605 
6606     return 0;
6607 }
6608 
6609 void bdrv_activate_all(Error **errp)
6610 {
6611     BlockDriverState *bs;
6612     BdrvNextIterator it;
6613 
6614     GLOBAL_STATE_CODE();
6615 
6616     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6617         AioContext *aio_context = bdrv_get_aio_context(bs);
6618         int ret;
6619 
6620         aio_context_acquire(aio_context);
6621         ret = bdrv_activate(bs, errp);
6622         aio_context_release(aio_context);
6623         if (ret < 0) {
6624             bdrv_next_cleanup(&it);
6625             return;
6626         }
6627     }
6628 }
6629 
6630 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6631 {
6632     BdrvChild *parent;
6633     GLOBAL_STATE_CODE();
6634 
6635     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6636         if (parent->klass->parent_is_bds) {
6637             BlockDriverState *parent_bs = parent->opaque;
6638             if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6639                 return true;
6640             }
6641         }
6642     }
6643 
6644     return false;
6645 }
6646 
6647 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6648 {
6649     BdrvChild *child, *parent;
6650     int ret;
6651     uint64_t cumulative_perms, cumulative_shared_perms;
6652 
6653     GLOBAL_STATE_CODE();
6654 
6655     if (!bs->drv) {
6656         return -ENOMEDIUM;
6657     }
6658 
6659     /* Make sure that we don't inactivate a child before its parent.
6660      * It will be covered by recursion from the yet active parent. */
6661     if (bdrv_has_bds_parent(bs, true)) {
6662         return 0;
6663     }
6664 
6665     assert(!(bs->open_flags & BDRV_O_INACTIVE));
6666 
6667     /* Inactivate this node */
6668     if (bs->drv->bdrv_inactivate) {
6669         ret = bs->drv->bdrv_inactivate(bs);
6670         if (ret < 0) {
6671             return ret;
6672         }
6673     }
6674 
6675     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6676         if (parent->klass->inactivate) {
6677             ret = parent->klass->inactivate(parent);
6678             if (ret < 0) {
6679                 return ret;
6680             }
6681         }
6682     }
6683 
6684     bdrv_get_cumulative_perm(bs, &cumulative_perms,
6685                              &cumulative_shared_perms);
6686     if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6687         /* Our inactive parents still need write access. Inactivation failed. */
6688         return -EPERM;
6689     }
6690 
6691     bs->open_flags |= BDRV_O_INACTIVE;
6692 
6693     /*
6694      * Update permissions, they may differ for inactive nodes.
6695      * We only tried to loosen restrictions, so errors are not fatal, ignore
6696      * them.
6697      */
6698     bdrv_refresh_perms(bs, NULL);
6699 
6700     /* Recursively inactivate children */
6701     QLIST_FOREACH(child, &bs->children, next) {
6702         ret = bdrv_inactivate_recurse(child->bs);
6703         if (ret < 0) {
6704             return ret;
6705         }
6706     }
6707 
6708     return 0;
6709 }
6710 
6711 int bdrv_inactivate_all(void)
6712 {
6713     BlockDriverState *bs = NULL;
6714     BdrvNextIterator it;
6715     int ret = 0;
6716     GSList *aio_ctxs = NULL, *ctx;
6717 
6718     GLOBAL_STATE_CODE();
6719 
6720     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6721         AioContext *aio_context = bdrv_get_aio_context(bs);
6722 
6723         if (!g_slist_find(aio_ctxs, aio_context)) {
6724             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6725             aio_context_acquire(aio_context);
6726         }
6727     }
6728 
6729     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6730         /* Nodes with BDS parents are covered by recursion from the last
6731          * parent that gets inactivated. Don't inactivate them a second
6732          * time if that has already happened. */
6733         if (bdrv_has_bds_parent(bs, false)) {
6734             continue;
6735         }
6736         ret = bdrv_inactivate_recurse(bs);
6737         if (ret < 0) {
6738             bdrv_next_cleanup(&it);
6739             goto out;
6740         }
6741     }
6742 
6743 out:
6744     for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6745         AioContext *aio_context = ctx->data;
6746         aio_context_release(aio_context);
6747     }
6748     g_slist_free(aio_ctxs);
6749 
6750     return ret;
6751 }
6752 
6753 /**************************************************************/
6754 /* removable device support */
6755 
6756 /**
6757  * Return TRUE if the media is present
6758  */
6759 bool bdrv_is_inserted(BlockDriverState *bs)
6760 {
6761     BlockDriver *drv = bs->drv;
6762     BdrvChild *child;
6763     IO_CODE();
6764 
6765     if (!drv) {
6766         return false;
6767     }
6768     if (drv->bdrv_is_inserted) {
6769         return drv->bdrv_is_inserted(bs);
6770     }
6771     QLIST_FOREACH(child, &bs->children, next) {
6772         if (!bdrv_is_inserted(child->bs)) {
6773             return false;
6774         }
6775     }
6776     return true;
6777 }
6778 
6779 /**
6780  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6781  */
6782 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6783 {
6784     BlockDriver *drv = bs->drv;
6785     IO_CODE();
6786 
6787     if (drv && drv->bdrv_eject) {
6788         drv->bdrv_eject(bs, eject_flag);
6789     }
6790 }
6791 
6792 /**
6793  * Lock or unlock the media (if it is locked, the user won't be able
6794  * to eject it manually).
6795  */
6796 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6797 {
6798     BlockDriver *drv = bs->drv;
6799     IO_CODE();
6800     trace_bdrv_lock_medium(bs, locked);
6801 
6802     if (drv && drv->bdrv_lock_medium) {
6803         drv->bdrv_lock_medium(bs, locked);
6804     }
6805 }
6806 
6807 /* Get a reference to bs */
6808 void bdrv_ref(BlockDriverState *bs)
6809 {
6810     GLOBAL_STATE_CODE();
6811     bs->refcnt++;
6812 }
6813 
6814 /* Release a previously grabbed reference to bs.
6815  * If after releasing, reference count is zero, the BlockDriverState is
6816  * deleted. */
6817 void bdrv_unref(BlockDriverState *bs)
6818 {
6819     GLOBAL_STATE_CODE();
6820     if (!bs) {
6821         return;
6822     }
6823     assert(bs->refcnt > 0);
6824     if (--bs->refcnt == 0) {
6825         bdrv_delete(bs);
6826     }
6827 }
6828 
6829 struct BdrvOpBlocker {
6830     Error *reason;
6831     QLIST_ENTRY(BdrvOpBlocker) list;
6832 };
6833 
6834 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6835 {
6836     BdrvOpBlocker *blocker;
6837     GLOBAL_STATE_CODE();
6838     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6839     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6840         blocker = QLIST_FIRST(&bs->op_blockers[op]);
6841         error_propagate_prepend(errp, error_copy(blocker->reason),
6842                                 "Node '%s' is busy: ",
6843                                 bdrv_get_device_or_node_name(bs));
6844         return true;
6845     }
6846     return false;
6847 }
6848 
6849 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6850 {
6851     BdrvOpBlocker *blocker;
6852     GLOBAL_STATE_CODE();
6853     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6854 
6855     blocker = g_new0(BdrvOpBlocker, 1);
6856     blocker->reason = reason;
6857     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6858 }
6859 
6860 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6861 {
6862     BdrvOpBlocker *blocker, *next;
6863     GLOBAL_STATE_CODE();
6864     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6865     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6866         if (blocker->reason == reason) {
6867             QLIST_REMOVE(blocker, list);
6868             g_free(blocker);
6869         }
6870     }
6871 }
6872 
6873 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6874 {
6875     int i;
6876     GLOBAL_STATE_CODE();
6877     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6878         bdrv_op_block(bs, i, reason);
6879     }
6880 }
6881 
6882 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6883 {
6884     int i;
6885     GLOBAL_STATE_CODE();
6886     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6887         bdrv_op_unblock(bs, i, reason);
6888     }
6889 }
6890 
6891 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6892 {
6893     int i;
6894     GLOBAL_STATE_CODE();
6895     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6896         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6897             return false;
6898         }
6899     }
6900     return true;
6901 }
6902 
6903 void bdrv_img_create(const char *filename, const char *fmt,
6904                      const char *base_filename, const char *base_fmt,
6905                      char *options, uint64_t img_size, int flags, bool quiet,
6906                      Error **errp)
6907 {
6908     QemuOptsList *create_opts = NULL;
6909     QemuOpts *opts = NULL;
6910     const char *backing_fmt, *backing_file;
6911     int64_t size;
6912     BlockDriver *drv, *proto_drv;
6913     Error *local_err = NULL;
6914     int ret = 0;
6915 
6916     GLOBAL_STATE_CODE();
6917 
6918     /* Find driver and parse its options */
6919     drv = bdrv_find_format(fmt);
6920     if (!drv) {
6921         error_setg(errp, "Unknown file format '%s'", fmt);
6922         return;
6923     }
6924 
6925     proto_drv = bdrv_find_protocol(filename, true, errp);
6926     if (!proto_drv) {
6927         return;
6928     }
6929 
6930     if (!drv->create_opts) {
6931         error_setg(errp, "Format driver '%s' does not support image creation",
6932                    drv->format_name);
6933         return;
6934     }
6935 
6936     if (!proto_drv->create_opts) {
6937         error_setg(errp, "Protocol driver '%s' does not support image creation",
6938                    proto_drv->format_name);
6939         return;
6940     }
6941 
6942     /* Create parameter list */
6943     create_opts = qemu_opts_append(create_opts, drv->create_opts);
6944     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6945 
6946     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6947 
6948     /* Parse -o options */
6949     if (options) {
6950         if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
6951             goto out;
6952         }
6953     }
6954 
6955     if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6956         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6957     } else if (img_size != UINT64_C(-1)) {
6958         error_setg(errp, "The image size must be specified only once");
6959         goto out;
6960     }
6961 
6962     if (base_filename) {
6963         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
6964                           NULL)) {
6965             error_setg(errp, "Backing file not supported for file format '%s'",
6966                        fmt);
6967             goto out;
6968         }
6969     }
6970 
6971     if (base_fmt) {
6972         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
6973             error_setg(errp, "Backing file format not supported for file "
6974                              "format '%s'", fmt);
6975             goto out;
6976         }
6977     }
6978 
6979     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6980     if (backing_file) {
6981         if (!strcmp(filename, backing_file)) {
6982             error_setg(errp, "Error: Trying to create an image with the "
6983                              "same filename as the backing file");
6984             goto out;
6985         }
6986         if (backing_file[0] == '\0') {
6987             error_setg(errp, "Expected backing file name, got empty string");
6988             goto out;
6989         }
6990     }
6991 
6992     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6993 
6994     /* The size for the image must always be specified, unless we have a backing
6995      * file and we have not been forbidden from opening it. */
6996     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6997     if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6998         BlockDriverState *bs;
6999         char *full_backing;
7000         int back_flags;
7001         QDict *backing_options = NULL;
7002 
7003         full_backing =
7004             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
7005                                                          &local_err);
7006         if (local_err) {
7007             goto out;
7008         }
7009         assert(full_backing);
7010 
7011         /*
7012          * No need to do I/O here, which allows us to open encrypted
7013          * backing images without needing the secret
7014          */
7015         back_flags = flags;
7016         back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7017         back_flags |= BDRV_O_NO_IO;
7018 
7019         backing_options = qdict_new();
7020         if (backing_fmt) {
7021             qdict_put_str(backing_options, "driver", backing_fmt);
7022         }
7023         qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7024 
7025         bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7026                        &local_err);
7027         g_free(full_backing);
7028         if (!bs) {
7029             error_append_hint(&local_err, "Could not open backing image.\n");
7030             goto out;
7031         } else {
7032             if (!backing_fmt) {
7033                 error_setg(&local_err,
7034                            "Backing file specified without backing format");
7035                 error_append_hint(&local_err, "Detected format of %s.",
7036                                   bs->drv->format_name);
7037                 goto out;
7038             }
7039             if (size == -1) {
7040                 /* Opened BS, have no size */
7041                 size = bdrv_getlength(bs);
7042                 if (size < 0) {
7043                     error_setg_errno(errp, -size, "Could not get size of '%s'",
7044                                      backing_file);
7045                     bdrv_unref(bs);
7046                     goto out;
7047                 }
7048                 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7049             }
7050             bdrv_unref(bs);
7051         }
7052         /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7053     } else if (backing_file && !backing_fmt) {
7054         error_setg(&local_err,
7055                    "Backing file specified without backing format");
7056         goto out;
7057     }
7058 
7059     if (size == -1) {
7060         error_setg(errp, "Image creation needs a size parameter");
7061         goto out;
7062     }
7063 
7064     if (!quiet) {
7065         printf("Formatting '%s', fmt=%s ", filename, fmt);
7066         qemu_opts_print(opts, " ");
7067         puts("");
7068         fflush(stdout);
7069     }
7070 
7071     ret = bdrv_create(drv, filename, opts, &local_err);
7072 
7073     if (ret == -EFBIG) {
7074         /* This is generally a better message than whatever the driver would
7075          * deliver (especially because of the cluster_size_hint), since that
7076          * is most probably not much different from "image too large". */
7077         const char *cluster_size_hint = "";
7078         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7079             cluster_size_hint = " (try using a larger cluster size)";
7080         }
7081         error_setg(errp, "The image size is too large for file format '%s'"
7082                    "%s", fmt, cluster_size_hint);
7083         error_free(local_err);
7084         local_err = NULL;
7085     }
7086 
7087 out:
7088     qemu_opts_del(opts);
7089     qemu_opts_free(create_opts);
7090     error_propagate(errp, local_err);
7091 }
7092 
7093 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7094 {
7095     IO_CODE();
7096     return bs ? bs->aio_context : qemu_get_aio_context();
7097 }
7098 
7099 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7100 {
7101     Coroutine *self = qemu_coroutine_self();
7102     AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7103     AioContext *new_ctx;
7104     IO_CODE();
7105 
7106     /*
7107      * Increase bs->in_flight to ensure that this operation is completed before
7108      * moving the node to a different AioContext. Read new_ctx only afterwards.
7109      */
7110     bdrv_inc_in_flight(bs);
7111 
7112     new_ctx = bdrv_get_aio_context(bs);
7113     aio_co_reschedule_self(new_ctx);
7114     return old_ctx;
7115 }
7116 
7117 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7118 {
7119     IO_CODE();
7120     aio_co_reschedule_self(old_ctx);
7121     bdrv_dec_in_flight(bs);
7122 }
7123 
7124 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7125 {
7126     AioContext *ctx = bdrv_get_aio_context(bs);
7127 
7128     /* In the main thread, bs->aio_context won't change concurrently */
7129     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7130 
7131     /*
7132      * We're in coroutine context, so we already hold the lock of the main
7133      * loop AioContext. Don't lock it twice to avoid deadlocks.
7134      */
7135     assert(qemu_in_coroutine());
7136     if (ctx != qemu_get_aio_context()) {
7137         aio_context_acquire(ctx);
7138     }
7139 }
7140 
7141 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7142 {
7143     AioContext *ctx = bdrv_get_aio_context(bs);
7144 
7145     assert(qemu_in_coroutine());
7146     if (ctx != qemu_get_aio_context()) {
7147         aio_context_release(ctx);
7148     }
7149 }
7150 
7151 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7152 {
7153     IO_CODE();
7154     aio_co_enter(bdrv_get_aio_context(bs), co);
7155 }
7156 
7157 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7158 {
7159     GLOBAL_STATE_CODE();
7160     QLIST_REMOVE(ban, list);
7161     g_free(ban);
7162 }
7163 
7164 static void bdrv_detach_aio_context(BlockDriverState *bs)
7165 {
7166     BdrvAioNotifier *baf, *baf_tmp;
7167 
7168     assert(!bs->walking_aio_notifiers);
7169     GLOBAL_STATE_CODE();
7170     bs->walking_aio_notifiers = true;
7171     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7172         if (baf->deleted) {
7173             bdrv_do_remove_aio_context_notifier(baf);
7174         } else {
7175             baf->detach_aio_context(baf->opaque);
7176         }
7177     }
7178     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
7179      * remove remaining aio notifiers if we aren't called again.
7180      */
7181     bs->walking_aio_notifiers = false;
7182 
7183     if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7184         bs->drv->bdrv_detach_aio_context(bs);
7185     }
7186 
7187     if (bs->quiesce_counter) {
7188         aio_enable_external(bs->aio_context);
7189     }
7190     bs->aio_context = NULL;
7191 }
7192 
7193 static void bdrv_attach_aio_context(BlockDriverState *bs,
7194                                     AioContext *new_context)
7195 {
7196     BdrvAioNotifier *ban, *ban_tmp;
7197     GLOBAL_STATE_CODE();
7198 
7199     if (bs->quiesce_counter) {
7200         aio_disable_external(new_context);
7201     }
7202 
7203     bs->aio_context = new_context;
7204 
7205     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7206         bs->drv->bdrv_attach_aio_context(bs, new_context);
7207     }
7208 
7209     assert(!bs->walking_aio_notifiers);
7210     bs->walking_aio_notifiers = true;
7211     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7212         if (ban->deleted) {
7213             bdrv_do_remove_aio_context_notifier(ban);
7214         } else {
7215             ban->attached_aio_context(new_context, ban->opaque);
7216         }
7217     }
7218     bs->walking_aio_notifiers = false;
7219 }
7220 
7221 /*
7222  * Changes the AioContext used for fd handlers, timers, and BHs by this
7223  * BlockDriverState and all its children and parents.
7224  *
7225  * Must be called from the main AioContext.
7226  *
7227  * The caller must own the AioContext lock for the old AioContext of bs, but it
7228  * must not own the AioContext lock for new_context (unless new_context is the
7229  * same as the current context of bs).
7230  *
7231  * @ignore will accumulate all visited BdrvChild object. The caller is
7232  * responsible for freeing the list afterwards.
7233  */
7234 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7235                                  AioContext *new_context, GSList **ignore)
7236 {
7237     AioContext *old_context = bdrv_get_aio_context(bs);
7238     GSList *children_to_process = NULL;
7239     GSList *parents_to_process = NULL;
7240     GSList *entry;
7241     BdrvChild *child, *parent;
7242 
7243     g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7244     GLOBAL_STATE_CODE();
7245 
7246     if (old_context == new_context) {
7247         return;
7248     }
7249 
7250     bdrv_drained_begin(bs);
7251 
7252     QLIST_FOREACH(child, &bs->children, next) {
7253         if (g_slist_find(*ignore, child)) {
7254             continue;
7255         }
7256         *ignore = g_slist_prepend(*ignore, child);
7257         children_to_process = g_slist_prepend(children_to_process, child);
7258     }
7259 
7260     QLIST_FOREACH(parent, &bs->parents, next_parent) {
7261         if (g_slist_find(*ignore, parent)) {
7262             continue;
7263         }
7264         *ignore = g_slist_prepend(*ignore, parent);
7265         parents_to_process = g_slist_prepend(parents_to_process, parent);
7266     }
7267 
7268     for (entry = children_to_process;
7269          entry != NULL;
7270          entry = g_slist_next(entry)) {
7271         child = entry->data;
7272         bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7273     }
7274     g_slist_free(children_to_process);
7275 
7276     for (entry = parents_to_process;
7277          entry != NULL;
7278          entry = g_slist_next(entry)) {
7279         parent = entry->data;
7280         assert(parent->klass->set_aio_ctx);
7281         parent->klass->set_aio_ctx(parent, new_context, ignore);
7282     }
7283     g_slist_free(parents_to_process);
7284 
7285     bdrv_detach_aio_context(bs);
7286 
7287     /* Acquire the new context, if necessary */
7288     if (qemu_get_aio_context() != new_context) {
7289         aio_context_acquire(new_context);
7290     }
7291 
7292     bdrv_attach_aio_context(bs, new_context);
7293 
7294     /*
7295      * If this function was recursively called from
7296      * bdrv_set_aio_context_ignore(), there may be nodes in the
7297      * subtree that have not yet been moved to the new AioContext.
7298      * Release the old one so bdrv_drained_end() can poll them.
7299      */
7300     if (qemu_get_aio_context() != old_context) {
7301         aio_context_release(old_context);
7302     }
7303 
7304     bdrv_drained_end(bs);
7305 
7306     if (qemu_get_aio_context() != old_context) {
7307         aio_context_acquire(old_context);
7308     }
7309     if (qemu_get_aio_context() != new_context) {
7310         aio_context_release(new_context);
7311     }
7312 }
7313 
7314 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7315                                             GSList **ignore, Error **errp)
7316 {
7317     GLOBAL_STATE_CODE();
7318     if (g_slist_find(*ignore, c)) {
7319         return true;
7320     }
7321     *ignore = g_slist_prepend(*ignore, c);
7322 
7323     /*
7324      * A BdrvChildClass that doesn't handle AioContext changes cannot
7325      * tolerate any AioContext changes
7326      */
7327     if (!c->klass->can_set_aio_ctx) {
7328         char *user = bdrv_child_user_desc(c);
7329         error_setg(errp, "Changing iothreads is not supported by %s", user);
7330         g_free(user);
7331         return false;
7332     }
7333     if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
7334         assert(!errp || *errp);
7335         return false;
7336     }
7337     return true;
7338 }
7339 
7340 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7341                                     GSList **ignore, Error **errp)
7342 {
7343     GLOBAL_STATE_CODE();
7344     if (g_slist_find(*ignore, c)) {
7345         return true;
7346     }
7347     *ignore = g_slist_prepend(*ignore, c);
7348     return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7349 }
7350 
7351 /* @ignore will accumulate all visited BdrvChild object. The caller is
7352  * responsible for freeing the list afterwards. */
7353 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7354                               GSList **ignore, Error **errp)
7355 {
7356     BdrvChild *c;
7357 
7358     if (bdrv_get_aio_context(bs) == ctx) {
7359         return true;
7360     }
7361 
7362     GLOBAL_STATE_CODE();
7363 
7364     QLIST_FOREACH(c, &bs->parents, next_parent) {
7365         if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7366             return false;
7367         }
7368     }
7369     QLIST_FOREACH(c, &bs->children, next) {
7370         if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7371             return false;
7372         }
7373     }
7374 
7375     return true;
7376 }
7377 
7378 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7379                                    BdrvChild *ignore_child, Error **errp)
7380 {
7381     GSList *ignore;
7382     bool ret;
7383 
7384     GLOBAL_STATE_CODE();
7385 
7386     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7387     ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7388     g_slist_free(ignore);
7389 
7390     if (!ret) {
7391         return -EPERM;
7392     }
7393 
7394     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7395     bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7396     g_slist_free(ignore);
7397 
7398     return 0;
7399 }
7400 
7401 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7402                              Error **errp)
7403 {
7404     GLOBAL_STATE_CODE();
7405     return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
7406 }
7407 
7408 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7409         void (*attached_aio_context)(AioContext *new_context, void *opaque),
7410         void (*detach_aio_context)(void *opaque), void *opaque)
7411 {
7412     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7413     *ban = (BdrvAioNotifier){
7414         .attached_aio_context = attached_aio_context,
7415         .detach_aio_context   = detach_aio_context,
7416         .opaque               = opaque
7417     };
7418     GLOBAL_STATE_CODE();
7419 
7420     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7421 }
7422 
7423 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7424                                       void (*attached_aio_context)(AioContext *,
7425                                                                    void *),
7426                                       void (*detach_aio_context)(void *),
7427                                       void *opaque)
7428 {
7429     BdrvAioNotifier *ban, *ban_next;
7430     GLOBAL_STATE_CODE();
7431 
7432     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7433         if (ban->attached_aio_context == attached_aio_context &&
7434             ban->detach_aio_context   == detach_aio_context   &&
7435             ban->opaque               == opaque               &&
7436             ban->deleted              == false)
7437         {
7438             if (bs->walking_aio_notifiers) {
7439                 ban->deleted = true;
7440             } else {
7441                 bdrv_do_remove_aio_context_notifier(ban);
7442             }
7443             return;
7444         }
7445     }
7446 
7447     abort();
7448 }
7449 
7450 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7451                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7452                        bool force,
7453                        Error **errp)
7454 {
7455     GLOBAL_STATE_CODE();
7456     if (!bs->drv) {
7457         error_setg(errp, "Node is ejected");
7458         return -ENOMEDIUM;
7459     }
7460     if (!bs->drv->bdrv_amend_options) {
7461         error_setg(errp, "Block driver '%s' does not support option amendment",
7462                    bs->drv->format_name);
7463         return -ENOTSUP;
7464     }
7465     return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7466                                        cb_opaque, force, errp);
7467 }
7468 
7469 /*
7470  * This function checks whether the given @to_replace is allowed to be
7471  * replaced by a node that always shows the same data as @bs.  This is
7472  * used for example to verify whether the mirror job can replace
7473  * @to_replace by the target mirrored from @bs.
7474  * To be replaceable, @bs and @to_replace may either be guaranteed to
7475  * always show the same data (because they are only connected through
7476  * filters), or some driver may allow replacing one of its children
7477  * because it can guarantee that this child's data is not visible at
7478  * all (for example, for dissenting quorum children that have no other
7479  * parents).
7480  */
7481 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7482                               BlockDriverState *to_replace)
7483 {
7484     BlockDriverState *filtered;
7485 
7486     GLOBAL_STATE_CODE();
7487 
7488     if (!bs || !bs->drv) {
7489         return false;
7490     }
7491 
7492     if (bs == to_replace) {
7493         return true;
7494     }
7495 
7496     /* See what the driver can do */
7497     if (bs->drv->bdrv_recurse_can_replace) {
7498         return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7499     }
7500 
7501     /* For filters without an own implementation, we can recurse on our own */
7502     filtered = bdrv_filter_bs(bs);
7503     if (filtered) {
7504         return bdrv_recurse_can_replace(filtered, to_replace);
7505     }
7506 
7507     /* Safe default */
7508     return false;
7509 }
7510 
7511 /*
7512  * Check whether the given @node_name can be replaced by a node that
7513  * has the same data as @parent_bs.  If so, return @node_name's BDS;
7514  * NULL otherwise.
7515  *
7516  * @node_name must be a (recursive) *child of @parent_bs (or this
7517  * function will return NULL).
7518  *
7519  * The result (whether the node can be replaced or not) is only valid
7520  * for as long as no graph or permission changes occur.
7521  */
7522 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7523                                         const char *node_name, Error **errp)
7524 {
7525     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7526     AioContext *aio_context;
7527 
7528     GLOBAL_STATE_CODE();
7529 
7530     if (!to_replace_bs) {
7531         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7532         return NULL;
7533     }
7534 
7535     aio_context = bdrv_get_aio_context(to_replace_bs);
7536     aio_context_acquire(aio_context);
7537 
7538     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7539         to_replace_bs = NULL;
7540         goto out;
7541     }
7542 
7543     /* We don't want arbitrary node of the BDS chain to be replaced only the top
7544      * most non filter in order to prevent data corruption.
7545      * Another benefit is that this tests exclude backing files which are
7546      * blocked by the backing blockers.
7547      */
7548     if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7549         error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7550                    "because it cannot be guaranteed that doing so would not "
7551                    "lead to an abrupt change of visible data",
7552                    node_name, parent_bs->node_name);
7553         to_replace_bs = NULL;
7554         goto out;
7555     }
7556 
7557 out:
7558     aio_context_release(aio_context);
7559     return to_replace_bs;
7560 }
7561 
7562 /**
7563  * Iterates through the list of runtime option keys that are said to
7564  * be "strong" for a BDS.  An option is called "strong" if it changes
7565  * a BDS's data.  For example, the null block driver's "size" and
7566  * "read-zeroes" options are strong, but its "latency-ns" option is
7567  * not.
7568  *
7569  * If a key returned by this function ends with a dot, all options
7570  * starting with that prefix are strong.
7571  */
7572 static const char *const *strong_options(BlockDriverState *bs,
7573                                          const char *const *curopt)
7574 {
7575     static const char *const global_options[] = {
7576         "driver", "filename", NULL
7577     };
7578 
7579     if (!curopt) {
7580         return &global_options[0];
7581     }
7582 
7583     curopt++;
7584     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7585         curopt = bs->drv->strong_runtime_opts;
7586     }
7587 
7588     return (curopt && *curopt) ? curopt : NULL;
7589 }
7590 
7591 /**
7592  * Copies all strong runtime options from bs->options to the given
7593  * QDict.  The set of strong option keys is determined by invoking
7594  * strong_options().
7595  *
7596  * Returns true iff any strong option was present in bs->options (and
7597  * thus copied to the target QDict) with the exception of "filename"
7598  * and "driver".  The caller is expected to use this value to decide
7599  * whether the existence of strong options prevents the generation of
7600  * a plain filename.
7601  */
7602 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7603 {
7604     bool found_any = false;
7605     const char *const *option_name = NULL;
7606 
7607     if (!bs->drv) {
7608         return false;
7609     }
7610 
7611     while ((option_name = strong_options(bs, option_name))) {
7612         bool option_given = false;
7613 
7614         assert(strlen(*option_name) > 0);
7615         if ((*option_name)[strlen(*option_name) - 1] != '.') {
7616             QObject *entry = qdict_get(bs->options, *option_name);
7617             if (!entry) {
7618                 continue;
7619             }
7620 
7621             qdict_put_obj(d, *option_name, qobject_ref(entry));
7622             option_given = true;
7623         } else {
7624             const QDictEntry *entry;
7625             for (entry = qdict_first(bs->options); entry;
7626                  entry = qdict_next(bs->options, entry))
7627             {
7628                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7629                     qdict_put_obj(d, qdict_entry_key(entry),
7630                                   qobject_ref(qdict_entry_value(entry)));
7631                     option_given = true;
7632                 }
7633             }
7634         }
7635 
7636         /* While "driver" and "filename" need to be included in a JSON filename,
7637          * their existence does not prohibit generation of a plain filename. */
7638         if (!found_any && option_given &&
7639             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7640         {
7641             found_any = true;
7642         }
7643     }
7644 
7645     if (!qdict_haskey(d, "driver")) {
7646         /* Drivers created with bdrv_new_open_driver() may not have a
7647          * @driver option.  Add it here. */
7648         qdict_put_str(d, "driver", bs->drv->format_name);
7649     }
7650 
7651     return found_any;
7652 }
7653 
7654 /* Note: This function may return false positives; it may return true
7655  * even if opening the backing file specified by bs's image header
7656  * would result in exactly bs->backing. */
7657 static bool bdrv_backing_overridden(BlockDriverState *bs)
7658 {
7659     GLOBAL_STATE_CODE();
7660     if (bs->backing) {
7661         return strcmp(bs->auto_backing_file,
7662                       bs->backing->bs->filename);
7663     } else {
7664         /* No backing BDS, so if the image header reports any backing
7665          * file, it must have been suppressed */
7666         return bs->auto_backing_file[0] != '\0';
7667     }
7668 }
7669 
7670 /* Updates the following BDS fields:
7671  *  - exact_filename: A filename which may be used for opening a block device
7672  *                    which (mostly) equals the given BDS (even without any
7673  *                    other options; so reading and writing must return the same
7674  *                    results, but caching etc. may be different)
7675  *  - full_open_options: Options which, when given when opening a block device
7676  *                       (without a filename), result in a BDS (mostly)
7677  *                       equalling the given one
7678  *  - filename: If exact_filename is set, it is copied here. Otherwise,
7679  *              full_open_options is converted to a JSON object, prefixed with
7680  *              "json:" (for use through the JSON pseudo protocol) and put here.
7681  */
7682 void bdrv_refresh_filename(BlockDriverState *bs)
7683 {
7684     BlockDriver *drv = bs->drv;
7685     BdrvChild *child;
7686     BlockDriverState *primary_child_bs;
7687     QDict *opts;
7688     bool backing_overridden;
7689     bool generate_json_filename; /* Whether our default implementation should
7690                                     fill exact_filename (false) or not (true) */
7691 
7692     GLOBAL_STATE_CODE();
7693 
7694     if (!drv) {
7695         return;
7696     }
7697 
7698     /* This BDS's file name may depend on any of its children's file names, so
7699      * refresh those first */
7700     QLIST_FOREACH(child, &bs->children, next) {
7701         bdrv_refresh_filename(child->bs);
7702     }
7703 
7704     if (bs->implicit) {
7705         /* For implicit nodes, just copy everything from the single child */
7706         child = QLIST_FIRST(&bs->children);
7707         assert(QLIST_NEXT(child, next) == NULL);
7708 
7709         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7710                 child->bs->exact_filename);
7711         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7712 
7713         qobject_unref(bs->full_open_options);
7714         bs->full_open_options = qobject_ref(child->bs->full_open_options);
7715 
7716         return;
7717     }
7718 
7719     backing_overridden = bdrv_backing_overridden(bs);
7720 
7721     if (bs->open_flags & BDRV_O_NO_IO) {
7722         /* Without I/O, the backing file does not change anything.
7723          * Therefore, in such a case (primarily qemu-img), we can
7724          * pretend the backing file has not been overridden even if
7725          * it technically has been. */
7726         backing_overridden = false;
7727     }
7728 
7729     /* Gather the options QDict */
7730     opts = qdict_new();
7731     generate_json_filename = append_strong_runtime_options(opts, bs);
7732     generate_json_filename |= backing_overridden;
7733 
7734     if (drv->bdrv_gather_child_options) {
7735         /* Some block drivers may not want to present all of their children's
7736          * options, or name them differently from BdrvChild.name */
7737         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7738     } else {
7739         QLIST_FOREACH(child, &bs->children, next) {
7740             if (child == bs->backing && !backing_overridden) {
7741                 /* We can skip the backing BDS if it has not been overridden */
7742                 continue;
7743             }
7744 
7745             qdict_put(opts, child->name,
7746                       qobject_ref(child->bs->full_open_options));
7747         }
7748 
7749         if (backing_overridden && !bs->backing) {
7750             /* Force no backing file */
7751             qdict_put_null(opts, "backing");
7752         }
7753     }
7754 
7755     qobject_unref(bs->full_open_options);
7756     bs->full_open_options = opts;
7757 
7758     primary_child_bs = bdrv_primary_bs(bs);
7759 
7760     if (drv->bdrv_refresh_filename) {
7761         /* Obsolete information is of no use here, so drop the old file name
7762          * information before refreshing it */
7763         bs->exact_filename[0] = '\0';
7764 
7765         drv->bdrv_refresh_filename(bs);
7766     } else if (primary_child_bs) {
7767         /*
7768          * Try to reconstruct valid information from the underlying
7769          * file -- this only works for format nodes (filter nodes
7770          * cannot be probed and as such must be selected by the user
7771          * either through an options dict, or through a special
7772          * filename which the filter driver must construct in its
7773          * .bdrv_refresh_filename() implementation).
7774          */
7775 
7776         bs->exact_filename[0] = '\0';
7777 
7778         /*
7779          * We can use the underlying file's filename if:
7780          * - it has a filename,
7781          * - the current BDS is not a filter,
7782          * - the file is a protocol BDS, and
7783          * - opening that file (as this BDS's format) will automatically create
7784          *   the BDS tree we have right now, that is:
7785          *   - the user did not significantly change this BDS's behavior with
7786          *     some explicit (strong) options
7787          *   - no non-file child of this BDS has been overridden by the user
7788          *   Both of these conditions are represented by generate_json_filename.
7789          */
7790         if (primary_child_bs->exact_filename[0] &&
7791             primary_child_bs->drv->bdrv_file_open &&
7792             !drv->is_filter && !generate_json_filename)
7793         {
7794             strcpy(bs->exact_filename, primary_child_bs->exact_filename);
7795         }
7796     }
7797 
7798     if (bs->exact_filename[0]) {
7799         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
7800     } else {
7801         GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
7802         if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
7803                      json->str) >= sizeof(bs->filename)) {
7804             /* Give user a hint if we truncated things. */
7805             strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7806         }
7807         g_string_free(json, true);
7808     }
7809 }
7810 
7811 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7812 {
7813     BlockDriver *drv = bs->drv;
7814     BlockDriverState *child_bs;
7815 
7816     GLOBAL_STATE_CODE();
7817 
7818     if (!drv) {
7819         error_setg(errp, "Node '%s' is ejected", bs->node_name);
7820         return NULL;
7821     }
7822 
7823     if (drv->bdrv_dirname) {
7824         return drv->bdrv_dirname(bs, errp);
7825     }
7826 
7827     child_bs = bdrv_primary_bs(bs);
7828     if (child_bs) {
7829         return bdrv_dirname(child_bs, errp);
7830     }
7831 
7832     bdrv_refresh_filename(bs);
7833     if (bs->exact_filename[0] != '\0') {
7834         return path_combine(bs->exact_filename, "");
7835     }
7836 
7837     error_setg(errp, "Cannot generate a base directory for %s nodes",
7838                drv->format_name);
7839     return NULL;
7840 }
7841 
7842 /*
7843  * Hot add/remove a BDS's child. So the user can take a child offline when
7844  * it is broken and take a new child online
7845  */
7846 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7847                     Error **errp)
7848 {
7849     GLOBAL_STATE_CODE();
7850     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7851         error_setg(errp, "The node %s does not support adding a child",
7852                    bdrv_get_device_or_node_name(parent_bs));
7853         return;
7854     }
7855 
7856     if (!QLIST_EMPTY(&child_bs->parents)) {
7857         error_setg(errp, "The node %s already has a parent",
7858                    child_bs->node_name);
7859         return;
7860     }
7861 
7862     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7863 }
7864 
7865 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7866 {
7867     BdrvChild *tmp;
7868 
7869     GLOBAL_STATE_CODE();
7870     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7871         error_setg(errp, "The node %s does not support removing a child",
7872                    bdrv_get_device_or_node_name(parent_bs));
7873         return;
7874     }
7875 
7876     QLIST_FOREACH(tmp, &parent_bs->children, next) {
7877         if (tmp == child) {
7878             break;
7879         }
7880     }
7881 
7882     if (!tmp) {
7883         error_setg(errp, "The node %s does not have a child named %s",
7884                    bdrv_get_device_or_node_name(parent_bs),
7885                    bdrv_get_device_or_node_name(child->bs));
7886         return;
7887     }
7888 
7889     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7890 }
7891 
7892 int bdrv_make_empty(BdrvChild *c, Error **errp)
7893 {
7894     BlockDriver *drv = c->bs->drv;
7895     int ret;
7896 
7897     GLOBAL_STATE_CODE();
7898     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7899 
7900     if (!drv->bdrv_make_empty) {
7901         error_setg(errp, "%s does not support emptying nodes",
7902                    drv->format_name);
7903         return -ENOTSUP;
7904     }
7905 
7906     ret = drv->bdrv_make_empty(c->bs);
7907     if (ret < 0) {
7908         error_setg_errno(errp, -ret, "Failed to empty %s",
7909                          c->bs->filename);
7910         return ret;
7911     }
7912 
7913     return 0;
7914 }
7915 
7916 /*
7917  * Return the child that @bs acts as an overlay for, and from which data may be
7918  * copied in COW or COR operations.  Usually this is the backing file.
7919  */
7920 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7921 {
7922     IO_CODE();
7923 
7924     if (!bs || !bs->drv) {
7925         return NULL;
7926     }
7927 
7928     if (bs->drv->is_filter) {
7929         return NULL;
7930     }
7931 
7932     if (!bs->backing) {
7933         return NULL;
7934     }
7935 
7936     assert(bs->backing->role & BDRV_CHILD_COW);
7937     return bs->backing;
7938 }
7939 
7940 /*
7941  * If @bs acts as a filter for exactly one of its children, return
7942  * that child.
7943  */
7944 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7945 {
7946     BdrvChild *c;
7947     IO_CODE();
7948 
7949     if (!bs || !bs->drv) {
7950         return NULL;
7951     }
7952 
7953     if (!bs->drv->is_filter) {
7954         return NULL;
7955     }
7956 
7957     /* Only one of @backing or @file may be used */
7958     assert(!(bs->backing && bs->file));
7959 
7960     c = bs->backing ?: bs->file;
7961     if (!c) {
7962         return NULL;
7963     }
7964 
7965     assert(c->role & BDRV_CHILD_FILTERED);
7966     return c;
7967 }
7968 
7969 /*
7970  * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
7971  * whichever is non-NULL.
7972  *
7973  * Return NULL if both are NULL.
7974  */
7975 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
7976 {
7977     BdrvChild *cow_child = bdrv_cow_child(bs);
7978     BdrvChild *filter_child = bdrv_filter_child(bs);
7979     IO_CODE();
7980 
7981     /* Filter nodes cannot have COW backing files */
7982     assert(!(cow_child && filter_child));
7983 
7984     return cow_child ?: filter_child;
7985 }
7986 
7987 /*
7988  * Return the primary child of this node: For filters, that is the
7989  * filtered child.  For other nodes, that is usually the child storing
7990  * metadata.
7991  * (A generally more helpful description is that this is (usually) the
7992  * child that has the same filename as @bs.)
7993  *
7994  * Drivers do not necessarily have a primary child; for example quorum
7995  * does not.
7996  */
7997 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
7998 {
7999     BdrvChild *c, *found = NULL;
8000     IO_CODE();
8001 
8002     QLIST_FOREACH(c, &bs->children, next) {
8003         if (c->role & BDRV_CHILD_PRIMARY) {
8004             assert(!found);
8005             found = c;
8006         }
8007     }
8008 
8009     return found;
8010 }
8011 
8012 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8013                                               bool stop_on_explicit_filter)
8014 {
8015     BdrvChild *c;
8016 
8017     if (!bs) {
8018         return NULL;
8019     }
8020 
8021     while (!(stop_on_explicit_filter && !bs->implicit)) {
8022         c = bdrv_filter_child(bs);
8023         if (!c) {
8024             /*
8025              * A filter that is embedded in a working block graph must
8026              * have a child.  Assert this here so this function does
8027              * not return a filter node that is not expected by the
8028              * caller.
8029              */
8030             assert(!bs->drv || !bs->drv->is_filter);
8031             break;
8032         }
8033         bs = c->bs;
8034     }
8035     /*
8036      * Note that this treats nodes with bs->drv == NULL as not being
8037      * filters (bs->drv == NULL should be replaced by something else
8038      * anyway).
8039      * The advantage of this behavior is that this function will thus
8040      * always return a non-NULL value (given a non-NULL @bs).
8041      */
8042 
8043     return bs;
8044 }
8045 
8046 /*
8047  * Return the first BDS that has not been added implicitly or that
8048  * does not have a filtered child down the chain starting from @bs
8049  * (including @bs itself).
8050  */
8051 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8052 {
8053     GLOBAL_STATE_CODE();
8054     return bdrv_do_skip_filters(bs, true);
8055 }
8056 
8057 /*
8058  * Return the first BDS that does not have a filtered child down the
8059  * chain starting from @bs (including @bs itself).
8060  */
8061 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8062 {
8063     IO_CODE();
8064     return bdrv_do_skip_filters(bs, false);
8065 }
8066 
8067 /*
8068  * For a backing chain, return the first non-filter backing image of
8069  * the first non-filter image.
8070  */
8071 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8072 {
8073     IO_CODE();
8074     return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8075 }
8076 
8077 /**
8078  * Check whether [offset, offset + bytes) overlaps with the cached
8079  * block-status data region.
8080  *
8081  * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8082  * which is what bdrv_bsc_is_data()'s interface needs.
8083  * Otherwise, *pnum is not touched.
8084  */
8085 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8086                                            int64_t offset, int64_t bytes,
8087                                            int64_t *pnum)
8088 {
8089     BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8090     bool overlaps;
8091 
8092     overlaps =
8093         qatomic_read(&bsc->valid) &&
8094         ranges_overlap(offset, bytes, bsc->data_start,
8095                        bsc->data_end - bsc->data_start);
8096 
8097     if (overlaps && pnum) {
8098         *pnum = bsc->data_end - offset;
8099     }
8100 
8101     return overlaps;
8102 }
8103 
8104 /**
8105  * See block_int.h for this function's documentation.
8106  */
8107 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8108 {
8109     IO_CODE();
8110     RCU_READ_LOCK_GUARD();
8111     return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8112 }
8113 
8114 /**
8115  * See block_int.h for this function's documentation.
8116  */
8117 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8118                                int64_t offset, int64_t bytes)
8119 {
8120     IO_CODE();
8121     RCU_READ_LOCK_GUARD();
8122 
8123     if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8124         qatomic_set(&bs->block_status_cache->valid, false);
8125     }
8126 }
8127 
8128 /**
8129  * See block_int.h for this function's documentation.
8130  */
8131 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8132 {
8133     BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8134     BdrvBlockStatusCache *old_bsc;
8135     IO_CODE();
8136 
8137     *new_bsc = (BdrvBlockStatusCache) {
8138         .valid = true,
8139         .data_start = offset,
8140         .data_end = offset + bytes,
8141     };
8142 
8143     QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8144 
8145     old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8146     qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8147     if (old_bsc) {
8148         g_free_rcu(old_bsc, rcu);
8149     }
8150 }
8151