xref: /openbmc/qemu/block.c (revision 299403aedaeb7f08d8e98aa8614b29d4e5546066)
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_child(BdrvChild *child, Transaction *tran);
96 
97 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
98                                BlockReopenQueue *queue,
99                                Transaction *change_child_tran, Error **errp);
100 static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
101 static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
102 
103 static bool bdrv_backing_overridden(BlockDriverState *bs);
104 
105 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
106                                     GHashTable *visited, Transaction *tran,
107                                     Error **errp);
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             Error *local_err = NULL;
466             int rv = block_module_load(block_driver_modules[i].library_name,
467                                        &local_err);
468             if (rv > 0) {
469                 return bdrv_do_find_format(format_name);
470             } else if (rv < 0) {
471                 error_report_err(local_err);
472             }
473             break;
474         }
475     }
476     return NULL;
477 }
478 
479 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
480 {
481     static const char *whitelist_rw[] = {
482         CONFIG_BDRV_RW_WHITELIST
483         NULL
484     };
485     static const char *whitelist_ro[] = {
486         CONFIG_BDRV_RO_WHITELIST
487         NULL
488     };
489     const char **p;
490 
491     if (!whitelist_rw[0] && !whitelist_ro[0]) {
492         return 1;               /* no whitelist, anything goes */
493     }
494 
495     for (p = whitelist_rw; *p; p++) {
496         if (!strcmp(format_name, *p)) {
497             return 1;
498         }
499     }
500     if (read_only) {
501         for (p = whitelist_ro; *p; p++) {
502             if (!strcmp(format_name, *p)) {
503                 return 1;
504             }
505         }
506     }
507     return 0;
508 }
509 
510 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
511 {
512     GLOBAL_STATE_CODE();
513     return bdrv_format_is_whitelisted(drv->format_name, read_only);
514 }
515 
516 bool bdrv_uses_whitelist(void)
517 {
518     return use_bdrv_whitelist;
519 }
520 
521 typedef struct CreateCo {
522     BlockDriver *drv;
523     char *filename;
524     QemuOpts *opts;
525     int ret;
526     Error *err;
527 } CreateCo;
528 
529 static void coroutine_fn bdrv_create_co_entry(void *opaque)
530 {
531     Error *local_err = NULL;
532     int ret;
533 
534     CreateCo *cco = opaque;
535     assert(cco->drv);
536     GLOBAL_STATE_CODE();
537 
538     ret = cco->drv->bdrv_co_create_opts(cco->drv,
539                                         cco->filename, cco->opts, &local_err);
540     error_propagate(&cco->err, local_err);
541     cco->ret = ret;
542 }
543 
544 int bdrv_create(BlockDriver *drv, const char* filename,
545                 QemuOpts *opts, Error **errp)
546 {
547     int ret;
548 
549     GLOBAL_STATE_CODE();
550 
551     Coroutine *co;
552     CreateCo cco = {
553         .drv = drv,
554         .filename = g_strdup(filename),
555         .opts = opts,
556         .ret = NOT_DONE,
557         .err = NULL,
558     };
559 
560     if (!drv->bdrv_co_create_opts) {
561         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
562         ret = -ENOTSUP;
563         goto out;
564     }
565 
566     if (qemu_in_coroutine()) {
567         /* Fast-path if already in coroutine context */
568         bdrv_create_co_entry(&cco);
569     } else {
570         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
571         qemu_coroutine_enter(co);
572         while (cco.ret == NOT_DONE) {
573             aio_poll(qemu_get_aio_context(), true);
574         }
575     }
576 
577     ret = cco.ret;
578     if (ret < 0) {
579         if (cco.err) {
580             error_propagate(errp, cco.err);
581         } else {
582             error_setg_errno(errp, -ret, "Could not create image");
583         }
584     }
585 
586 out:
587     g_free(cco.filename);
588     return ret;
589 }
590 
591 /**
592  * Helper function for bdrv_create_file_fallback(): Resize @blk to at
593  * least the given @minimum_size.
594  *
595  * On success, return @blk's actual length.
596  * Otherwise, return -errno.
597  */
598 static int64_t create_file_fallback_truncate(BlockBackend *blk,
599                                              int64_t minimum_size, Error **errp)
600 {
601     Error *local_err = NULL;
602     int64_t size;
603     int ret;
604 
605     GLOBAL_STATE_CODE();
606 
607     ret = blk_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
608                        &local_err);
609     if (ret < 0 && ret != -ENOTSUP) {
610         error_propagate(errp, local_err);
611         return ret;
612     }
613 
614     size = blk_getlength(blk);
615     if (size < 0) {
616         error_free(local_err);
617         error_setg_errno(errp, -size,
618                          "Failed to inquire the new image file's length");
619         return size;
620     }
621 
622     if (size < minimum_size) {
623         /* Need to grow the image, but we failed to do that */
624         error_propagate(errp, local_err);
625         return -ENOTSUP;
626     }
627 
628     error_free(local_err);
629     local_err = NULL;
630 
631     return size;
632 }
633 
634 /**
635  * Helper function for bdrv_create_file_fallback(): Zero the first
636  * sector to remove any potentially pre-existing image header.
637  */
638 static int coroutine_fn
639 create_file_fallback_zero_first_sector(BlockBackend *blk,
640                                        int64_t current_size,
641                                        Error **errp)
642 {
643     int64_t bytes_to_clear;
644     int ret;
645 
646     GLOBAL_STATE_CODE();
647 
648     bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
649     if (bytes_to_clear) {
650         ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
651         if (ret < 0) {
652             error_setg_errno(errp, -ret,
653                              "Failed to clear the new image's first sector");
654             return ret;
655         }
656     }
657 
658     return 0;
659 }
660 
661 /**
662  * Simple implementation of bdrv_co_create_opts for protocol drivers
663  * which only support creation via opening a file
664  * (usually existing raw storage device)
665  */
666 int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
667                                             const char *filename,
668                                             QemuOpts *opts,
669                                             Error **errp)
670 {
671     BlockBackend *blk;
672     QDict *options;
673     int64_t size = 0;
674     char *buf = NULL;
675     PreallocMode prealloc;
676     Error *local_err = NULL;
677     int ret;
678 
679     GLOBAL_STATE_CODE();
680 
681     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
682     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
683     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
684                                PREALLOC_MODE_OFF, &local_err);
685     g_free(buf);
686     if (local_err) {
687         error_propagate(errp, local_err);
688         return -EINVAL;
689     }
690 
691     if (prealloc != PREALLOC_MODE_OFF) {
692         error_setg(errp, "Unsupported preallocation mode '%s'",
693                    PreallocMode_str(prealloc));
694         return -ENOTSUP;
695     }
696 
697     options = qdict_new();
698     qdict_put_str(options, "driver", drv->format_name);
699 
700     blk = blk_new_open(filename, NULL, options,
701                        BDRV_O_RDWR | BDRV_O_RESIZE, errp);
702     if (!blk) {
703         error_prepend(errp, "Protocol driver '%s' does not support image "
704                       "creation, and opening the image failed: ",
705                       drv->format_name);
706         return -EINVAL;
707     }
708 
709     size = create_file_fallback_truncate(blk, size, errp);
710     if (size < 0) {
711         ret = size;
712         goto out;
713     }
714 
715     ret = create_file_fallback_zero_first_sector(blk, size, errp);
716     if (ret < 0) {
717         goto out;
718     }
719 
720     ret = 0;
721 out:
722     blk_unref(blk);
723     return ret;
724 }
725 
726 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
727 {
728     QemuOpts *protocol_opts;
729     BlockDriver *drv;
730     QDict *qdict;
731     int ret;
732 
733     GLOBAL_STATE_CODE();
734 
735     drv = bdrv_find_protocol(filename, true, errp);
736     if (drv == NULL) {
737         return -ENOENT;
738     }
739 
740     if (!drv->create_opts) {
741         error_setg(errp, "Driver '%s' does not support image creation",
742                    drv->format_name);
743         return -ENOTSUP;
744     }
745 
746     /*
747      * 'opts' contains a QemuOptsList with a combination of format and protocol
748      * default values.
749      *
750      * The format properly removes its options, but the default values remain
751      * in 'opts->list'.  So if the protocol has options with the same name
752      * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
753      * of the format, since for overlapping options, the format wins.
754      *
755      * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
756      * only the set options, and then convert it back to QemuOpts, using the
757      * create_opts of the protocol. So the new QemuOpts, will contain only the
758      * protocol defaults.
759      */
760     qdict = qemu_opts_to_qdict(opts, NULL);
761     protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
762     if (protocol_opts == NULL) {
763         ret = -EINVAL;
764         goto out;
765     }
766 
767     ret = bdrv_create(drv, filename, protocol_opts, errp);
768 out:
769     qemu_opts_del(protocol_opts);
770     qobject_unref(qdict);
771     return ret;
772 }
773 
774 int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
775 {
776     Error *local_err = NULL;
777     int ret;
778 
779     IO_CODE();
780     assert(bs != NULL);
781 
782     if (!bs->drv) {
783         error_setg(errp, "Block node '%s' is not opened", bs->filename);
784         return -ENOMEDIUM;
785     }
786 
787     if (!bs->drv->bdrv_co_delete_file) {
788         error_setg(errp, "Driver '%s' does not support image deletion",
789                    bs->drv->format_name);
790         return -ENOTSUP;
791     }
792 
793     ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
794     if (ret < 0) {
795         error_propagate(errp, local_err);
796     }
797 
798     return ret;
799 }
800 
801 void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
802 {
803     Error *local_err = NULL;
804     int ret;
805     IO_CODE();
806 
807     if (!bs) {
808         return;
809     }
810 
811     ret = bdrv_co_delete_file(bs, &local_err);
812     /*
813      * ENOTSUP will happen if the block driver doesn't support
814      * the 'bdrv_co_delete_file' interface. This is a predictable
815      * scenario and shouldn't be reported back to the user.
816      */
817     if (ret == -ENOTSUP) {
818         error_free(local_err);
819     } else if (ret < 0) {
820         error_report_err(local_err);
821     }
822 }
823 
824 /**
825  * Try to get @bs's logical and physical block size.
826  * On success, store them in @bsz struct and return 0.
827  * On failure return -errno.
828  * @bs must not be empty.
829  */
830 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
831 {
832     BlockDriver *drv = bs->drv;
833     BlockDriverState *filtered = bdrv_filter_bs(bs);
834     GLOBAL_STATE_CODE();
835 
836     if (drv && drv->bdrv_probe_blocksizes) {
837         return drv->bdrv_probe_blocksizes(bs, bsz);
838     } else if (filtered) {
839         return bdrv_probe_blocksizes(filtered, bsz);
840     }
841 
842     return -ENOTSUP;
843 }
844 
845 /**
846  * Try to get @bs's geometry (cyls, heads, sectors).
847  * On success, store them in @geo struct and return 0.
848  * On failure return -errno.
849  * @bs must not be empty.
850  */
851 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
852 {
853     BlockDriver *drv = bs->drv;
854     BlockDriverState *filtered = bdrv_filter_bs(bs);
855     GLOBAL_STATE_CODE();
856 
857     if (drv && drv->bdrv_probe_geometry) {
858         return drv->bdrv_probe_geometry(bs, geo);
859     } else if (filtered) {
860         return bdrv_probe_geometry(filtered, geo);
861     }
862 
863     return -ENOTSUP;
864 }
865 
866 /*
867  * Create a uniquely-named empty temporary file.
868  * Return the actual file name used upon success, otherwise NULL.
869  * This string should be freed with g_free() when not needed any longer.
870  *
871  * Note: creating a temporary file for the caller to (re)open is
872  * inherently racy. Use g_file_open_tmp() instead whenever practical.
873  */
874 char *create_tmp_file(Error **errp)
875 {
876     int fd;
877     const char *tmpdir;
878     g_autofree char *filename = NULL;
879 
880     tmpdir = g_get_tmp_dir();
881 #ifndef _WIN32
882     /*
883      * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
884      *
885      * This function is used to create temporary disk images (like -snapshot),
886      * so the files can become very large. /tmp is often a tmpfs where as
887      * /var/tmp is usually on a disk, so more appropriate for disk images.
888      */
889     if (!g_strcmp0(tmpdir, "/tmp")) {
890         tmpdir = "/var/tmp";
891     }
892 #endif
893 
894     filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
895     fd = g_mkstemp(filename);
896     if (fd < 0) {
897         error_setg_errno(errp, errno, "Could not open temporary file '%s'",
898                          filename);
899         return NULL;
900     }
901     close(fd);
902 
903     return g_steal_pointer(&filename);
904 }
905 
906 /*
907  * Detect host devices. By convention, /dev/cdrom[N] is always
908  * recognized as a host CDROM.
909  */
910 static BlockDriver *find_hdev_driver(const char *filename)
911 {
912     int score_max = 0, score;
913     BlockDriver *drv = NULL, *d;
914     GLOBAL_STATE_CODE();
915 
916     QLIST_FOREACH(d, &bdrv_drivers, list) {
917         if (d->bdrv_probe_device) {
918             score = d->bdrv_probe_device(filename);
919             if (score > score_max) {
920                 score_max = score;
921                 drv = d;
922             }
923         }
924     }
925 
926     return drv;
927 }
928 
929 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
930 {
931     BlockDriver *drv1;
932     GLOBAL_STATE_CODE();
933 
934     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
935         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
936             return drv1;
937         }
938     }
939 
940     return NULL;
941 }
942 
943 BlockDriver *bdrv_find_protocol(const char *filename,
944                                 bool allow_protocol_prefix,
945                                 Error **errp)
946 {
947     BlockDriver *drv1;
948     char protocol[128];
949     int len;
950     const char *p;
951     int i;
952 
953     GLOBAL_STATE_CODE();
954     /* TODO Drivers without bdrv_file_open must be specified explicitly */
955 
956     /*
957      * XXX(hch): we really should not let host device detection
958      * override an explicit protocol specification, but moving this
959      * later breaks access to device names with colons in them.
960      * Thanks to the brain-dead persistent naming schemes on udev-
961      * based Linux systems those actually are quite common.
962      */
963     drv1 = find_hdev_driver(filename);
964     if (drv1) {
965         return drv1;
966     }
967 
968     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
969         return &bdrv_file;
970     }
971 
972     p = strchr(filename, ':');
973     assert(p != NULL);
974     len = p - filename;
975     if (len > sizeof(protocol) - 1)
976         len = sizeof(protocol) - 1;
977     memcpy(protocol, filename, len);
978     protocol[len] = '\0';
979 
980     drv1 = bdrv_do_find_protocol(protocol);
981     if (drv1) {
982         return drv1;
983     }
984 
985     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
986         if (block_driver_modules[i].protocol_name &&
987             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
988             int rv = block_module_load(block_driver_modules[i].library_name, errp);
989             if (rv > 0) {
990                 drv1 = bdrv_do_find_protocol(protocol);
991             } else if (rv < 0) {
992                 return NULL;
993             }
994             break;
995         }
996     }
997 
998     if (!drv1) {
999         error_setg(errp, "Unknown protocol '%s'", protocol);
1000     }
1001     return drv1;
1002 }
1003 
1004 /*
1005  * Guess image format by probing its contents.
1006  * This is not a good idea when your image is raw (CVE-2008-2004), but
1007  * we do it anyway for backward compatibility.
1008  *
1009  * @buf         contains the image's first @buf_size bytes.
1010  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
1011  *              but can be smaller if the image file is smaller)
1012  * @filename    is its filename.
1013  *
1014  * For all block drivers, call the bdrv_probe() method to get its
1015  * probing score.
1016  * Return the first block driver with the highest probing score.
1017  */
1018 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
1019                             const char *filename)
1020 {
1021     int score_max = 0, score;
1022     BlockDriver *drv = NULL, *d;
1023     IO_CODE();
1024 
1025     QLIST_FOREACH(d, &bdrv_drivers, list) {
1026         if (d->bdrv_probe) {
1027             score = d->bdrv_probe(buf, buf_size, filename);
1028             if (score > score_max) {
1029                 score_max = score;
1030                 drv = d;
1031             }
1032         }
1033     }
1034 
1035     return drv;
1036 }
1037 
1038 static int find_image_format(BlockBackend *file, const char *filename,
1039                              BlockDriver **pdrv, Error **errp)
1040 {
1041     BlockDriver *drv;
1042     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1043     int ret = 0;
1044 
1045     GLOBAL_STATE_CODE();
1046 
1047     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
1048     if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1049         *pdrv = &bdrv_raw;
1050         return ret;
1051     }
1052 
1053     ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1054     if (ret < 0) {
1055         error_setg_errno(errp, -ret, "Could not read image for determining its "
1056                          "format");
1057         *pdrv = NULL;
1058         return ret;
1059     }
1060 
1061     drv = bdrv_probe_all(buf, sizeof(buf), filename);
1062     if (!drv) {
1063         error_setg(errp, "Could not determine image format: No compatible "
1064                    "driver found");
1065         *pdrv = NULL;
1066         return -ENOENT;
1067     }
1068 
1069     *pdrv = drv;
1070     return 0;
1071 }
1072 
1073 /**
1074  * Set the current 'total_sectors' value
1075  * Return 0 on success, -errno on error.
1076  */
1077 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
1078 {
1079     BlockDriver *drv = bs->drv;
1080     IO_CODE();
1081 
1082     if (!drv) {
1083         return -ENOMEDIUM;
1084     }
1085 
1086     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
1087     if (bdrv_is_sg(bs))
1088         return 0;
1089 
1090     /* query actual device if possible, otherwise just trust the hint */
1091     if (drv->bdrv_getlength) {
1092         int64_t length = drv->bdrv_getlength(bs);
1093         if (length < 0) {
1094             return length;
1095         }
1096         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
1097     }
1098 
1099     bs->total_sectors = hint;
1100 
1101     if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
1102         return -EFBIG;
1103     }
1104 
1105     return 0;
1106 }
1107 
1108 /**
1109  * Combines a QDict of new block driver @options with any missing options taken
1110  * from @old_options, so that leaving out an option defaults to its old value.
1111  */
1112 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1113                               QDict *old_options)
1114 {
1115     GLOBAL_STATE_CODE();
1116     if (bs->drv && bs->drv->bdrv_join_options) {
1117         bs->drv->bdrv_join_options(options, old_options);
1118     } else {
1119         qdict_join(options, old_options, false);
1120     }
1121 }
1122 
1123 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1124                                                             int open_flags,
1125                                                             Error **errp)
1126 {
1127     Error *local_err = NULL;
1128     char *value = qemu_opt_get_del(opts, "detect-zeroes");
1129     BlockdevDetectZeroesOptions detect_zeroes =
1130         qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1131                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1132     GLOBAL_STATE_CODE();
1133     g_free(value);
1134     if (local_err) {
1135         error_propagate(errp, local_err);
1136         return detect_zeroes;
1137     }
1138 
1139     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1140         !(open_flags & BDRV_O_UNMAP))
1141     {
1142         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1143                    "without setting discard operation to unmap");
1144     }
1145 
1146     return detect_zeroes;
1147 }
1148 
1149 /**
1150  * Set open flags for aio engine
1151  *
1152  * Return 0 on success, -1 if the engine specified is invalid
1153  */
1154 int bdrv_parse_aio(const char *mode, int *flags)
1155 {
1156     if (!strcmp(mode, "threads")) {
1157         /* do nothing, default */
1158     } else if (!strcmp(mode, "native")) {
1159         *flags |= BDRV_O_NATIVE_AIO;
1160 #ifdef CONFIG_LINUX_IO_URING
1161     } else if (!strcmp(mode, "io_uring")) {
1162         *flags |= BDRV_O_IO_URING;
1163 #endif
1164     } else {
1165         return -1;
1166     }
1167 
1168     return 0;
1169 }
1170 
1171 /**
1172  * Set open flags for a given discard mode
1173  *
1174  * Return 0 on success, -1 if the discard mode was invalid.
1175  */
1176 int bdrv_parse_discard_flags(const char *mode, int *flags)
1177 {
1178     *flags &= ~BDRV_O_UNMAP;
1179 
1180     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
1181         /* do nothing */
1182     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
1183         *flags |= BDRV_O_UNMAP;
1184     } else {
1185         return -1;
1186     }
1187 
1188     return 0;
1189 }
1190 
1191 /**
1192  * Set open flags for a given cache mode
1193  *
1194  * Return 0 on success, -1 if the cache mode was invalid.
1195  */
1196 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1197 {
1198     *flags &= ~BDRV_O_CACHE_MASK;
1199 
1200     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
1201         *writethrough = false;
1202         *flags |= BDRV_O_NOCACHE;
1203     } else if (!strcmp(mode, "directsync")) {
1204         *writethrough = true;
1205         *flags |= BDRV_O_NOCACHE;
1206     } else if (!strcmp(mode, "writeback")) {
1207         *writethrough = false;
1208     } else if (!strcmp(mode, "unsafe")) {
1209         *writethrough = false;
1210         *flags |= BDRV_O_NO_FLUSH;
1211     } else if (!strcmp(mode, "writethrough")) {
1212         *writethrough = true;
1213     } else {
1214         return -1;
1215     }
1216 
1217     return 0;
1218 }
1219 
1220 static char *bdrv_child_get_parent_desc(BdrvChild *c)
1221 {
1222     BlockDriverState *parent = c->opaque;
1223     return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1224 }
1225 
1226 static void bdrv_child_cb_drained_begin(BdrvChild *child)
1227 {
1228     BlockDriverState *bs = child->opaque;
1229     bdrv_do_drained_begin_quiesce(bs, NULL, false);
1230 }
1231 
1232 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
1233 {
1234     BlockDriverState *bs = child->opaque;
1235     return bdrv_drain_poll(bs, NULL, false);
1236 }
1237 
1238 static void bdrv_child_cb_drained_end(BdrvChild *child)
1239 {
1240     BlockDriverState *bs = child->opaque;
1241     bdrv_drained_end(bs);
1242 }
1243 
1244 static int bdrv_child_cb_inactivate(BdrvChild *child)
1245 {
1246     BlockDriverState *bs = child->opaque;
1247     GLOBAL_STATE_CODE();
1248     assert(bs->open_flags & BDRV_O_INACTIVE);
1249     return 0;
1250 }
1251 
1252 static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
1253                                          GHashTable *visited, Transaction *tran,
1254                                          Error **errp)
1255 {
1256     BlockDriverState *bs = child->opaque;
1257     return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
1258 }
1259 
1260 /*
1261  * Returns the options and flags that a temporary snapshot should get, based on
1262  * the originally requested flags (the originally requested image will have
1263  * flags like a backing file)
1264  */
1265 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
1266                                        int parent_flags, QDict *parent_options)
1267 {
1268     GLOBAL_STATE_CODE();
1269     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
1270 
1271     /* For temporary files, unconditional cache=unsafe is fine */
1272     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
1273     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
1274 
1275     /* Copy the read-only and discard options from the parent */
1276     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1277     qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1278 
1279     /* aio=native doesn't work for cache.direct=off, so disable it for the
1280      * temporary snapshot */
1281     *child_flags &= ~BDRV_O_NATIVE_AIO;
1282 }
1283 
1284 static void bdrv_backing_attach(BdrvChild *c)
1285 {
1286     BlockDriverState *parent = c->opaque;
1287     BlockDriverState *backing_hd = c->bs;
1288 
1289     GLOBAL_STATE_CODE();
1290     assert(!parent->backing_blocker);
1291     error_setg(&parent->backing_blocker,
1292                "node is used as backing hd of '%s'",
1293                bdrv_get_device_or_node_name(parent));
1294 
1295     bdrv_refresh_filename(backing_hd);
1296 
1297     parent->open_flags &= ~BDRV_O_NO_BACKING;
1298 
1299     bdrv_op_block_all(backing_hd, parent->backing_blocker);
1300     /* Otherwise we won't be able to commit or stream */
1301     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1302                     parent->backing_blocker);
1303     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1304                     parent->backing_blocker);
1305     /*
1306      * We do backup in 3 ways:
1307      * 1. drive backup
1308      *    The target bs is new opened, and the source is top BDS
1309      * 2. blockdev backup
1310      *    Both the source and the target are top BDSes.
1311      * 3. internal backup(used for block replication)
1312      *    Both the source and the target are backing file
1313      *
1314      * In case 1 and 2, neither the source nor the target is the backing file.
1315      * In case 3, we will block the top BDS, so there is only one block job
1316      * for the top BDS and its backing chain.
1317      */
1318     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1319                     parent->backing_blocker);
1320     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1321                     parent->backing_blocker);
1322 }
1323 
1324 static void bdrv_backing_detach(BdrvChild *c)
1325 {
1326     BlockDriverState *parent = c->opaque;
1327 
1328     GLOBAL_STATE_CODE();
1329     assert(parent->backing_blocker);
1330     bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1331     error_free(parent->backing_blocker);
1332     parent->backing_blocker = NULL;
1333 }
1334 
1335 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1336                                         const char *filename, Error **errp)
1337 {
1338     BlockDriverState *parent = c->opaque;
1339     bool read_only = bdrv_is_read_only(parent);
1340     int ret;
1341     GLOBAL_STATE_CODE();
1342 
1343     if (read_only) {
1344         ret = bdrv_reopen_set_read_only(parent, false, errp);
1345         if (ret < 0) {
1346             return ret;
1347         }
1348     }
1349 
1350     ret = bdrv_change_backing_file(parent, filename,
1351                                    base->drv ? base->drv->format_name : "",
1352                                    false);
1353     if (ret < 0) {
1354         error_setg_errno(errp, -ret, "Could not update backing file link");
1355     }
1356 
1357     if (read_only) {
1358         bdrv_reopen_set_read_only(parent, true, NULL);
1359     }
1360 
1361     return ret;
1362 }
1363 
1364 /*
1365  * Returns the options and flags that a generic child of a BDS should
1366  * get, based on the given options and flags for the parent BDS.
1367  */
1368 static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1369                                    int *child_flags, QDict *child_options,
1370                                    int parent_flags, QDict *parent_options)
1371 {
1372     int flags = parent_flags;
1373     GLOBAL_STATE_CODE();
1374 
1375     /*
1376      * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1377      * Generally, the question to answer is: Should this child be
1378      * format-probed by default?
1379      */
1380 
1381     /*
1382      * Pure and non-filtered data children of non-format nodes should
1383      * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1384      * set).  This only affects a very limited set of drivers (namely
1385      * quorum and blkverify when this comment was written).
1386      * Force-clear BDRV_O_PROTOCOL then.
1387      */
1388     if (!parent_is_format &&
1389         (role & BDRV_CHILD_DATA) &&
1390         !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1391     {
1392         flags &= ~BDRV_O_PROTOCOL;
1393     }
1394 
1395     /*
1396      * All children of format nodes (except for COW children) and all
1397      * metadata children in general should never be format-probed.
1398      * Force-set BDRV_O_PROTOCOL then.
1399      */
1400     if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1401         (role & BDRV_CHILD_METADATA))
1402     {
1403         flags |= BDRV_O_PROTOCOL;
1404     }
1405 
1406     /*
1407      * If the cache mode isn't explicitly set, inherit direct and no-flush from
1408      * the parent.
1409      */
1410     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1411     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1412     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1413 
1414     if (role & BDRV_CHILD_COW) {
1415         /* backing files are opened read-only by default */
1416         qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1417         qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1418     } else {
1419         /* Inherit the read-only option from the parent if it's not set */
1420         qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1421         qdict_copy_default(child_options, parent_options,
1422                            BDRV_OPT_AUTO_READ_ONLY);
1423     }
1424 
1425     /*
1426      * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1427      * can default to enable it on lower layers regardless of the
1428      * parent option.
1429      */
1430     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1431 
1432     /* Clear flags that only apply to the top layer */
1433     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1434 
1435     if (role & BDRV_CHILD_METADATA) {
1436         flags &= ~BDRV_O_NO_IO;
1437     }
1438     if (role & BDRV_CHILD_COW) {
1439         flags &= ~BDRV_O_TEMPORARY;
1440     }
1441 
1442     *child_flags = flags;
1443 }
1444 
1445 static void bdrv_child_cb_attach(BdrvChild *child)
1446 {
1447     BlockDriverState *bs = child->opaque;
1448 
1449     assert_bdrv_graph_writable(bs);
1450     QLIST_INSERT_HEAD(&bs->children, child, next);
1451     if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
1452         /*
1453          * Here we handle filters and block/raw-format.c when it behave like
1454          * filter. They generally have a single PRIMARY child, which is also the
1455          * FILTERED child, and that they may have multiple more children, which
1456          * are neither PRIMARY nor FILTERED. And never we have a COW child here.
1457          * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
1458          * into bs->backing on exceptional cases; and bs->backing will be
1459          * nothing else.
1460          */
1461         assert(!(child->role & BDRV_CHILD_COW));
1462         if (child->role & BDRV_CHILD_PRIMARY) {
1463             assert(child->role & BDRV_CHILD_FILTERED);
1464             assert(!bs->backing);
1465             assert(!bs->file);
1466 
1467             if (bs->drv->filtered_child_is_backing) {
1468                 bs->backing = child;
1469             } else {
1470                 bs->file = child;
1471             }
1472         } else {
1473             assert(!(child->role & BDRV_CHILD_FILTERED));
1474         }
1475     } else if (child->role & BDRV_CHILD_COW) {
1476         assert(bs->drv->supports_backing);
1477         assert(!(child->role & BDRV_CHILD_PRIMARY));
1478         assert(!bs->backing);
1479         bs->backing = child;
1480         bdrv_backing_attach(child);
1481     } else if (child->role & BDRV_CHILD_PRIMARY) {
1482         assert(!bs->file);
1483         bs->file = child;
1484     }
1485 }
1486 
1487 static void bdrv_child_cb_detach(BdrvChild *child)
1488 {
1489     BlockDriverState *bs = child->opaque;
1490 
1491     if (child->role & BDRV_CHILD_COW) {
1492         bdrv_backing_detach(child);
1493     }
1494 
1495     assert_bdrv_graph_writable(bs);
1496     QLIST_REMOVE(child, next);
1497     if (child == bs->backing) {
1498         assert(child != bs->file);
1499         bs->backing = NULL;
1500     } else if (child == bs->file) {
1501         bs->file = NULL;
1502     }
1503 }
1504 
1505 static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
1506                                          const char *filename, Error **errp)
1507 {
1508     if (c->role & BDRV_CHILD_COW) {
1509         return bdrv_backing_update_filename(c, base, filename, errp);
1510     }
1511     return 0;
1512 }
1513 
1514 AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
1515 {
1516     BlockDriverState *bs = c->opaque;
1517     IO_CODE();
1518 
1519     return bdrv_get_aio_context(bs);
1520 }
1521 
1522 const BdrvChildClass child_of_bds = {
1523     .parent_is_bds   = true,
1524     .get_parent_desc = bdrv_child_get_parent_desc,
1525     .inherit_options = bdrv_inherited_options,
1526     .drained_begin   = bdrv_child_cb_drained_begin,
1527     .drained_poll    = bdrv_child_cb_drained_poll,
1528     .drained_end     = bdrv_child_cb_drained_end,
1529     .attach          = bdrv_child_cb_attach,
1530     .detach          = bdrv_child_cb_detach,
1531     .inactivate      = bdrv_child_cb_inactivate,
1532     .change_aio_ctx  = bdrv_child_cb_change_aio_ctx,
1533     .update_filename = bdrv_child_cb_update_filename,
1534     .get_parent_aio_context = child_of_bds_get_parent_aio_context,
1535 };
1536 
1537 AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
1538 {
1539     IO_CODE();
1540     return c->klass->get_parent_aio_context(c);
1541 }
1542 
1543 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1544 {
1545     int open_flags = flags;
1546     GLOBAL_STATE_CODE();
1547 
1548     /*
1549      * Clear flags that are internal to the block layer before opening the
1550      * image.
1551      */
1552     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1553 
1554     return open_flags;
1555 }
1556 
1557 static void update_flags_from_options(int *flags, QemuOpts *opts)
1558 {
1559     GLOBAL_STATE_CODE();
1560 
1561     *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1562 
1563     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1564         *flags |= BDRV_O_NO_FLUSH;
1565     }
1566 
1567     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1568         *flags |= BDRV_O_NOCACHE;
1569     }
1570 
1571     if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1572         *flags |= BDRV_O_RDWR;
1573     }
1574 
1575     if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1576         *flags |= BDRV_O_AUTO_RDONLY;
1577     }
1578 }
1579 
1580 static void update_options_from_flags(QDict *options, int flags)
1581 {
1582     GLOBAL_STATE_CODE();
1583     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1584         qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1585     }
1586     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1587         qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1588                        flags & BDRV_O_NO_FLUSH);
1589     }
1590     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1591         qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1592     }
1593     if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1594         qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1595                        flags & BDRV_O_AUTO_RDONLY);
1596     }
1597 }
1598 
1599 static void bdrv_assign_node_name(BlockDriverState *bs,
1600                                   const char *node_name,
1601                                   Error **errp)
1602 {
1603     char *gen_node_name = NULL;
1604     GLOBAL_STATE_CODE();
1605 
1606     if (!node_name) {
1607         node_name = gen_node_name = id_generate(ID_BLOCK);
1608     } else if (!id_wellformed(node_name)) {
1609         /*
1610          * Check for empty string or invalid characters, but not if it is
1611          * generated (generated names use characters not available to the user)
1612          */
1613         error_setg(errp, "Invalid node-name: '%s'", node_name);
1614         return;
1615     }
1616 
1617     /* takes care of avoiding namespaces collisions */
1618     if (blk_by_name(node_name)) {
1619         error_setg(errp, "node-name=%s is conflicting with a device id",
1620                    node_name);
1621         goto out;
1622     }
1623 
1624     /* takes care of avoiding duplicates node names */
1625     if (bdrv_find_node(node_name)) {
1626         error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
1627         goto out;
1628     }
1629 
1630     /* Make sure that the node name isn't truncated */
1631     if (strlen(node_name) >= sizeof(bs->node_name)) {
1632         error_setg(errp, "Node name too long");
1633         goto out;
1634     }
1635 
1636     /* copy node name into the bs and insert it into the graph list */
1637     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1638     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1639 out:
1640     g_free(gen_node_name);
1641 }
1642 
1643 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1644                             const char *node_name, QDict *options,
1645                             int open_flags, Error **errp)
1646 {
1647     Error *local_err = NULL;
1648     int i, ret;
1649     GLOBAL_STATE_CODE();
1650 
1651     bdrv_assign_node_name(bs, node_name, &local_err);
1652     if (local_err) {
1653         error_propagate(errp, local_err);
1654         return -EINVAL;
1655     }
1656 
1657     bs->drv = drv;
1658     bs->opaque = g_malloc0(drv->instance_size);
1659 
1660     if (drv->bdrv_file_open) {
1661         assert(!drv->bdrv_needs_filename || bs->filename[0]);
1662         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1663     } else if (drv->bdrv_open) {
1664         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1665     } else {
1666         ret = 0;
1667     }
1668 
1669     if (ret < 0) {
1670         if (local_err) {
1671             error_propagate(errp, local_err);
1672         } else if (bs->filename[0]) {
1673             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1674         } else {
1675             error_setg_errno(errp, -ret, "Could not open image");
1676         }
1677         goto open_failed;
1678     }
1679 
1680     assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1681     assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1682 
1683     /*
1684      * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1685      * drivers that pass read/write requests through to a child the trouble of
1686      * declaring support explicitly.
1687      *
1688      * Drivers must not propagate this flag accidentally when they initiate I/O
1689      * to a bounce buffer. That case should be rare though.
1690      */
1691     bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1692     bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1693 
1694     ret = refresh_total_sectors(bs, bs->total_sectors);
1695     if (ret < 0) {
1696         error_setg_errno(errp, -ret, "Could not refresh total sector count");
1697         return ret;
1698     }
1699 
1700     bdrv_refresh_limits(bs, NULL, &local_err);
1701     if (local_err) {
1702         error_propagate(errp, local_err);
1703         return -EINVAL;
1704     }
1705 
1706     assert(bdrv_opt_mem_align(bs) != 0);
1707     assert(bdrv_min_mem_align(bs) != 0);
1708     assert(is_power_of_2(bs->bl.request_alignment));
1709 
1710     for (i = 0; i < bs->quiesce_counter; i++) {
1711         if (drv->bdrv_drain_begin) {
1712             drv->bdrv_drain_begin(bs);
1713         }
1714     }
1715 
1716     return 0;
1717 open_failed:
1718     bs->drv = NULL;
1719     if (bs->file != NULL) {
1720         bdrv_unref_child(bs, bs->file);
1721         assert(!bs->file);
1722     }
1723     g_free(bs->opaque);
1724     bs->opaque = NULL;
1725     return ret;
1726 }
1727 
1728 /*
1729  * Create and open a block node.
1730  *
1731  * @options is a QDict of options to pass to the block drivers, or NULL for an
1732  * empty set of options. The reference to the QDict belongs to the block layer
1733  * after the call (even on failure), so if the caller intends to reuse the
1734  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1735  */
1736 BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1737                                             const char *node_name,
1738                                             QDict *options, int flags,
1739                                             Error **errp)
1740 {
1741     BlockDriverState *bs;
1742     int ret;
1743 
1744     GLOBAL_STATE_CODE();
1745 
1746     bs = bdrv_new();
1747     bs->open_flags = flags;
1748     bs->options = options ?: qdict_new();
1749     bs->explicit_options = qdict_clone_shallow(bs->options);
1750     bs->opaque = NULL;
1751 
1752     update_options_from_flags(bs->options, flags);
1753 
1754     ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1755     if (ret < 0) {
1756         qobject_unref(bs->explicit_options);
1757         bs->explicit_options = NULL;
1758         qobject_unref(bs->options);
1759         bs->options = NULL;
1760         bdrv_unref(bs);
1761         return NULL;
1762     }
1763 
1764     return bs;
1765 }
1766 
1767 /* Create and open a block node. */
1768 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1769                                        int flags, Error **errp)
1770 {
1771     GLOBAL_STATE_CODE();
1772     return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1773 }
1774 
1775 QemuOptsList bdrv_runtime_opts = {
1776     .name = "bdrv_common",
1777     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1778     .desc = {
1779         {
1780             .name = "node-name",
1781             .type = QEMU_OPT_STRING,
1782             .help = "Node name of the block device node",
1783         },
1784         {
1785             .name = "driver",
1786             .type = QEMU_OPT_STRING,
1787             .help = "Block driver to use for the node",
1788         },
1789         {
1790             .name = BDRV_OPT_CACHE_DIRECT,
1791             .type = QEMU_OPT_BOOL,
1792             .help = "Bypass software writeback cache on the host",
1793         },
1794         {
1795             .name = BDRV_OPT_CACHE_NO_FLUSH,
1796             .type = QEMU_OPT_BOOL,
1797             .help = "Ignore flush requests",
1798         },
1799         {
1800             .name = BDRV_OPT_READ_ONLY,
1801             .type = QEMU_OPT_BOOL,
1802             .help = "Node is opened in read-only mode",
1803         },
1804         {
1805             .name = BDRV_OPT_AUTO_READ_ONLY,
1806             .type = QEMU_OPT_BOOL,
1807             .help = "Node can become read-only if opening read-write fails",
1808         },
1809         {
1810             .name = "detect-zeroes",
1811             .type = QEMU_OPT_STRING,
1812             .help = "try to optimize zero writes (off, on, unmap)",
1813         },
1814         {
1815             .name = BDRV_OPT_DISCARD,
1816             .type = QEMU_OPT_STRING,
1817             .help = "discard operation (ignore/off, unmap/on)",
1818         },
1819         {
1820             .name = BDRV_OPT_FORCE_SHARE,
1821             .type = QEMU_OPT_BOOL,
1822             .help = "always accept other writers (default: off)",
1823         },
1824         { /* end of list */ }
1825     },
1826 };
1827 
1828 QemuOptsList bdrv_create_opts_simple = {
1829     .name = "simple-create-opts",
1830     .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1831     .desc = {
1832         {
1833             .name = BLOCK_OPT_SIZE,
1834             .type = QEMU_OPT_SIZE,
1835             .help = "Virtual disk size"
1836         },
1837         {
1838             .name = BLOCK_OPT_PREALLOC,
1839             .type = QEMU_OPT_STRING,
1840             .help = "Preallocation mode (allowed values: off)"
1841         },
1842         { /* end of list */ }
1843     }
1844 };
1845 
1846 /*
1847  * Common part for opening disk images and files
1848  *
1849  * Removes all processed options from *options.
1850  */
1851 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1852                             QDict *options, Error **errp)
1853 {
1854     int ret, open_flags;
1855     const char *filename;
1856     const char *driver_name = NULL;
1857     const char *node_name = NULL;
1858     const char *discard;
1859     QemuOpts *opts;
1860     BlockDriver *drv;
1861     Error *local_err = NULL;
1862     bool ro;
1863 
1864     assert(bs->file == NULL);
1865     assert(options != NULL && bs->options != options);
1866     GLOBAL_STATE_CODE();
1867 
1868     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1869     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
1870         ret = -EINVAL;
1871         goto fail_opts;
1872     }
1873 
1874     update_flags_from_options(&bs->open_flags, opts);
1875 
1876     driver_name = qemu_opt_get(opts, "driver");
1877     drv = bdrv_find_format(driver_name);
1878     assert(drv != NULL);
1879 
1880     bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1881 
1882     if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1883         error_setg(errp,
1884                    BDRV_OPT_FORCE_SHARE
1885                    "=on can only be used with read-only images");
1886         ret = -EINVAL;
1887         goto fail_opts;
1888     }
1889 
1890     if (file != NULL) {
1891         bdrv_refresh_filename(blk_bs(file));
1892         filename = blk_bs(file)->filename;
1893     } else {
1894         /*
1895          * Caution: while qdict_get_try_str() is fine, getting
1896          * non-string types would require more care.  When @options
1897          * come from -blockdev or blockdev_add, its members are typed
1898          * according to the QAPI schema, but when they come from
1899          * -drive, they're all QString.
1900          */
1901         filename = qdict_get_try_str(options, "filename");
1902     }
1903 
1904     if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1905         error_setg(errp, "The '%s' block driver requires a file name",
1906                    drv->format_name);
1907         ret = -EINVAL;
1908         goto fail_opts;
1909     }
1910 
1911     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1912                            drv->format_name);
1913 
1914     ro = bdrv_is_read_only(bs);
1915 
1916     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1917         if (!ro && bdrv_is_whitelisted(drv, true)) {
1918             ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1919         } else {
1920             ret = -ENOTSUP;
1921         }
1922         if (ret < 0) {
1923             error_setg(errp,
1924                        !ro && bdrv_is_whitelisted(drv, true)
1925                        ? "Driver '%s' can only be used for read-only devices"
1926                        : "Driver '%s' is not whitelisted",
1927                        drv->format_name);
1928             goto fail_opts;
1929         }
1930     }
1931 
1932     /* bdrv_new() and bdrv_close() make it so */
1933     assert(qatomic_read(&bs->copy_on_read) == 0);
1934 
1935     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1936         if (!ro) {
1937             bdrv_enable_copy_on_read(bs);
1938         } else {
1939             error_setg(errp, "Can't use copy-on-read on read-only device");
1940             ret = -EINVAL;
1941             goto fail_opts;
1942         }
1943     }
1944 
1945     discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1946     if (discard != NULL) {
1947         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1948             error_setg(errp, "Invalid discard option");
1949             ret = -EINVAL;
1950             goto fail_opts;
1951         }
1952     }
1953 
1954     bs->detect_zeroes =
1955         bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1956     if (local_err) {
1957         error_propagate(errp, local_err);
1958         ret = -EINVAL;
1959         goto fail_opts;
1960     }
1961 
1962     if (filename != NULL) {
1963         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1964     } else {
1965         bs->filename[0] = '\0';
1966     }
1967     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1968 
1969     /* Open the image, either directly or using a protocol */
1970     open_flags = bdrv_open_flags(bs, bs->open_flags);
1971     node_name = qemu_opt_get(opts, "node-name");
1972 
1973     assert(!drv->bdrv_file_open || file == NULL);
1974     ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1975     if (ret < 0) {
1976         goto fail_opts;
1977     }
1978 
1979     qemu_opts_del(opts);
1980     return 0;
1981 
1982 fail_opts:
1983     qemu_opts_del(opts);
1984     return ret;
1985 }
1986 
1987 static QDict *parse_json_filename(const char *filename, Error **errp)
1988 {
1989     QObject *options_obj;
1990     QDict *options;
1991     int ret;
1992     GLOBAL_STATE_CODE();
1993 
1994     ret = strstart(filename, "json:", &filename);
1995     assert(ret);
1996 
1997     options_obj = qobject_from_json(filename, errp);
1998     if (!options_obj) {
1999         error_prepend(errp, "Could not parse the JSON options: ");
2000         return NULL;
2001     }
2002 
2003     options = qobject_to(QDict, options_obj);
2004     if (!options) {
2005         qobject_unref(options_obj);
2006         error_setg(errp, "Invalid JSON object given");
2007         return NULL;
2008     }
2009 
2010     qdict_flatten(options);
2011 
2012     return options;
2013 }
2014 
2015 static void parse_json_protocol(QDict *options, const char **pfilename,
2016                                 Error **errp)
2017 {
2018     QDict *json_options;
2019     Error *local_err = NULL;
2020     GLOBAL_STATE_CODE();
2021 
2022     /* Parse json: pseudo-protocol */
2023     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2024         return;
2025     }
2026 
2027     json_options = parse_json_filename(*pfilename, &local_err);
2028     if (local_err) {
2029         error_propagate(errp, local_err);
2030         return;
2031     }
2032 
2033     /* Options given in the filename have lower priority than options
2034      * specified directly */
2035     qdict_join(options, json_options, false);
2036     qobject_unref(json_options);
2037     *pfilename = NULL;
2038 }
2039 
2040 /*
2041  * Fills in default options for opening images and converts the legacy
2042  * filename/flags pair to option QDict entries.
2043  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
2044  * block driver has been specified explicitly.
2045  */
2046 static int bdrv_fill_options(QDict **options, const char *filename,
2047                              int *flags, Error **errp)
2048 {
2049     const char *drvname;
2050     bool protocol = *flags & BDRV_O_PROTOCOL;
2051     bool parse_filename = false;
2052     BlockDriver *drv = NULL;
2053     Error *local_err = NULL;
2054 
2055     GLOBAL_STATE_CODE();
2056 
2057     /*
2058      * Caution: while qdict_get_try_str() is fine, getting non-string
2059      * types would require more care.  When @options come from
2060      * -blockdev or blockdev_add, its members are typed according to
2061      * the QAPI schema, but when they come from -drive, they're all
2062      * QString.
2063      */
2064     drvname = qdict_get_try_str(*options, "driver");
2065     if (drvname) {
2066         drv = bdrv_find_format(drvname);
2067         if (!drv) {
2068             error_setg(errp, "Unknown driver '%s'", drvname);
2069             return -ENOENT;
2070         }
2071         /* If the user has explicitly specified the driver, this choice should
2072          * override the BDRV_O_PROTOCOL flag */
2073         protocol = drv->bdrv_file_open;
2074     }
2075 
2076     if (protocol) {
2077         *flags |= BDRV_O_PROTOCOL;
2078     } else {
2079         *flags &= ~BDRV_O_PROTOCOL;
2080     }
2081 
2082     /* Translate cache options from flags into options */
2083     update_options_from_flags(*options, *flags);
2084 
2085     /* Fetch the file name from the options QDict if necessary */
2086     if (protocol && filename) {
2087         if (!qdict_haskey(*options, "filename")) {
2088             qdict_put_str(*options, "filename", filename);
2089             parse_filename = true;
2090         } else {
2091             error_setg(errp, "Can't specify 'file' and 'filename' options at "
2092                              "the same time");
2093             return -EINVAL;
2094         }
2095     }
2096 
2097     /* Find the right block driver */
2098     /* See cautionary note on accessing @options above */
2099     filename = qdict_get_try_str(*options, "filename");
2100 
2101     if (!drvname && protocol) {
2102         if (filename) {
2103             drv = bdrv_find_protocol(filename, parse_filename, errp);
2104             if (!drv) {
2105                 return -EINVAL;
2106             }
2107 
2108             drvname = drv->format_name;
2109             qdict_put_str(*options, "driver", drvname);
2110         } else {
2111             error_setg(errp, "Must specify either driver or file");
2112             return -EINVAL;
2113         }
2114     }
2115 
2116     assert(drv || !protocol);
2117 
2118     /* Driver-specific filename parsing */
2119     if (drv && drv->bdrv_parse_filename && parse_filename) {
2120         drv->bdrv_parse_filename(filename, *options, &local_err);
2121         if (local_err) {
2122             error_propagate(errp, local_err);
2123             return -EINVAL;
2124         }
2125 
2126         if (!drv->bdrv_needs_filename) {
2127             qdict_del(*options, "filename");
2128         }
2129     }
2130 
2131     return 0;
2132 }
2133 
2134 typedef struct BlockReopenQueueEntry {
2135      bool prepared;
2136      bool perms_checked;
2137      BDRVReopenState state;
2138      QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2139 } BlockReopenQueueEntry;
2140 
2141 /*
2142  * Return the flags that @bs will have after the reopens in @q have
2143  * successfully completed. If @q is NULL (or @bs is not contained in @q),
2144  * return the current flags.
2145  */
2146 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2147 {
2148     BlockReopenQueueEntry *entry;
2149 
2150     if (q != NULL) {
2151         QTAILQ_FOREACH(entry, q, entry) {
2152             if (entry->state.bs == bs) {
2153                 return entry->state.flags;
2154             }
2155         }
2156     }
2157 
2158     return bs->open_flags;
2159 }
2160 
2161 /* Returns whether the image file can be written to after the reopen queue @q
2162  * has been successfully applied, or right now if @q is NULL. */
2163 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2164                                           BlockReopenQueue *q)
2165 {
2166     int flags = bdrv_reopen_get_flags(q, bs);
2167 
2168     return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2169 }
2170 
2171 /*
2172  * Return whether the BDS can be written to.  This is not necessarily
2173  * the same as !bdrv_is_read_only(bs), as inactivated images may not
2174  * be written to but do not count as read-only images.
2175  */
2176 bool bdrv_is_writable(BlockDriverState *bs)
2177 {
2178     IO_CODE();
2179     return bdrv_is_writable_after_reopen(bs, NULL);
2180 }
2181 
2182 static char *bdrv_child_user_desc(BdrvChild *c)
2183 {
2184     GLOBAL_STATE_CODE();
2185     return c->klass->get_parent_desc(c);
2186 }
2187 
2188 /*
2189  * Check that @a allows everything that @b needs. @a and @b must reference same
2190  * child node.
2191  */
2192 static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
2193 {
2194     const char *child_bs_name;
2195     g_autofree char *a_user = NULL;
2196     g_autofree char *b_user = NULL;
2197     g_autofree char *perms = NULL;
2198 
2199     assert(a->bs);
2200     assert(a->bs == b->bs);
2201     GLOBAL_STATE_CODE();
2202 
2203     if ((b->perm & a->shared_perm) == b->perm) {
2204         return true;
2205     }
2206 
2207     child_bs_name = bdrv_get_node_name(b->bs);
2208     a_user = bdrv_child_user_desc(a);
2209     b_user = bdrv_child_user_desc(b);
2210     perms = bdrv_perm_names(b->perm & ~a->shared_perm);
2211 
2212     error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
2213                "both required by %s (uses node '%s' as '%s' child) and "
2214                "unshared by %s (uses node '%s' as '%s' child).",
2215                child_bs_name, perms,
2216                b_user, child_bs_name, b->name,
2217                a_user, child_bs_name, a->name);
2218 
2219     return false;
2220 }
2221 
2222 static bool bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
2223 {
2224     BdrvChild *a, *b;
2225     GLOBAL_STATE_CODE();
2226 
2227     /*
2228      * During the loop we'll look at each pair twice. That's correct because
2229      * bdrv_a_allow_b() is asymmetric and we should check each pair in both
2230      * directions.
2231      */
2232     QLIST_FOREACH(a, &bs->parents, next_parent) {
2233         QLIST_FOREACH(b, &bs->parents, next_parent) {
2234             if (a == b) {
2235                 continue;
2236             }
2237 
2238             if (!bdrv_a_allow_b(a, b, errp)) {
2239                 return true;
2240             }
2241         }
2242     }
2243 
2244     return false;
2245 }
2246 
2247 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2248                             BdrvChild *c, BdrvChildRole role,
2249                             BlockReopenQueue *reopen_queue,
2250                             uint64_t parent_perm, uint64_t parent_shared,
2251                             uint64_t *nperm, uint64_t *nshared)
2252 {
2253     assert(bs->drv && bs->drv->bdrv_child_perm);
2254     GLOBAL_STATE_CODE();
2255     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2256                              parent_perm, parent_shared,
2257                              nperm, nshared);
2258     /* TODO Take force_share from reopen_queue */
2259     if (child_bs && child_bs->force_share) {
2260         *nshared = BLK_PERM_ALL;
2261     }
2262 }
2263 
2264 /*
2265  * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2266  * nodes that are already in the @list, of course) so that final list is
2267  * topologically sorted. Return the result (GSList @list object is updated, so
2268  * don't use old reference after function call).
2269  *
2270  * On function start @list must be already topologically sorted and for any node
2271  * in the @list the whole subtree of the node must be in the @list as well. The
2272  * simplest way to satisfy this criteria: use only result of
2273  * bdrv_topological_dfs() or NULL as @list parameter.
2274  */
2275 static GSList *bdrv_topological_dfs(GSList *list, GHashTable *found,
2276                                     BlockDriverState *bs)
2277 {
2278     BdrvChild *child;
2279     g_autoptr(GHashTable) local_found = NULL;
2280 
2281     GLOBAL_STATE_CODE();
2282 
2283     if (!found) {
2284         assert(!list);
2285         found = local_found = g_hash_table_new(NULL, NULL);
2286     }
2287 
2288     if (g_hash_table_contains(found, bs)) {
2289         return list;
2290     }
2291     g_hash_table_add(found, bs);
2292 
2293     QLIST_FOREACH(child, &bs->children, next) {
2294         list = bdrv_topological_dfs(list, found, child->bs);
2295     }
2296 
2297     return g_slist_prepend(list, bs);
2298 }
2299 
2300 typedef struct BdrvChildSetPermState {
2301     BdrvChild *child;
2302     uint64_t old_perm;
2303     uint64_t old_shared_perm;
2304 } BdrvChildSetPermState;
2305 
2306 static void bdrv_child_set_perm_abort(void *opaque)
2307 {
2308     BdrvChildSetPermState *s = opaque;
2309 
2310     GLOBAL_STATE_CODE();
2311 
2312     s->child->perm = s->old_perm;
2313     s->child->shared_perm = s->old_shared_perm;
2314 }
2315 
2316 static TransactionActionDrv bdrv_child_set_pem_drv = {
2317     .abort = bdrv_child_set_perm_abort,
2318     .clean = g_free,
2319 };
2320 
2321 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2322                                 uint64_t shared, Transaction *tran)
2323 {
2324     BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2325     GLOBAL_STATE_CODE();
2326 
2327     *s = (BdrvChildSetPermState) {
2328         .child = c,
2329         .old_perm = c->perm,
2330         .old_shared_perm = c->shared_perm,
2331     };
2332 
2333     c->perm = perm;
2334     c->shared_perm = shared;
2335 
2336     tran_add(tran, &bdrv_child_set_pem_drv, s);
2337 }
2338 
2339 static void bdrv_drv_set_perm_commit(void *opaque)
2340 {
2341     BlockDriverState *bs = opaque;
2342     uint64_t cumulative_perms, cumulative_shared_perms;
2343     GLOBAL_STATE_CODE();
2344 
2345     if (bs->drv->bdrv_set_perm) {
2346         bdrv_get_cumulative_perm(bs, &cumulative_perms,
2347                                  &cumulative_shared_perms);
2348         bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
2349     }
2350 }
2351 
2352 static void bdrv_drv_set_perm_abort(void *opaque)
2353 {
2354     BlockDriverState *bs = opaque;
2355     GLOBAL_STATE_CODE();
2356 
2357     if (bs->drv->bdrv_abort_perm_update) {
2358         bs->drv->bdrv_abort_perm_update(bs);
2359     }
2360 }
2361 
2362 TransactionActionDrv bdrv_drv_set_perm_drv = {
2363     .abort = bdrv_drv_set_perm_abort,
2364     .commit = bdrv_drv_set_perm_commit,
2365 };
2366 
2367 static int bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm,
2368                              uint64_t shared_perm, Transaction *tran,
2369                              Error **errp)
2370 {
2371     GLOBAL_STATE_CODE();
2372     if (!bs->drv) {
2373         return 0;
2374     }
2375 
2376     if (bs->drv->bdrv_check_perm) {
2377         int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
2378         if (ret < 0) {
2379             return ret;
2380         }
2381     }
2382 
2383     if (tran) {
2384         tran_add(tran, &bdrv_drv_set_perm_drv, bs);
2385     }
2386 
2387     return 0;
2388 }
2389 
2390 typedef struct BdrvReplaceChildState {
2391     BdrvChild *child;
2392     BlockDriverState *old_bs;
2393 } BdrvReplaceChildState;
2394 
2395 static void bdrv_replace_child_commit(void *opaque)
2396 {
2397     BdrvReplaceChildState *s = opaque;
2398     GLOBAL_STATE_CODE();
2399 
2400     bdrv_unref(s->old_bs);
2401 }
2402 
2403 static void bdrv_replace_child_abort(void *opaque)
2404 {
2405     BdrvReplaceChildState *s = opaque;
2406     BlockDriverState *new_bs = s->child->bs;
2407 
2408     GLOBAL_STATE_CODE();
2409     /* old_bs reference is transparently moved from @s to @s->child */
2410     bdrv_replace_child_noperm(s->child, s->old_bs);
2411     bdrv_unref(new_bs);
2412 }
2413 
2414 static TransactionActionDrv bdrv_replace_child_drv = {
2415     .commit = bdrv_replace_child_commit,
2416     .abort = bdrv_replace_child_abort,
2417     .clean = g_free,
2418 };
2419 
2420 /*
2421  * bdrv_replace_child_tran
2422  *
2423  * Note: real unref of old_bs is done only on commit.
2424  *
2425  * The function doesn't update permissions, caller is responsible for this.
2426  */
2427 static void bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
2428                                     Transaction *tran)
2429 {
2430     BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
2431     *s = (BdrvReplaceChildState) {
2432         .child = child,
2433         .old_bs = child->bs,
2434     };
2435     tran_add(tran, &bdrv_replace_child_drv, s);
2436 
2437     if (new_bs) {
2438         bdrv_ref(new_bs);
2439     }
2440     bdrv_replace_child_noperm(child, new_bs);
2441     /* old_bs reference is transparently moved from @child to @s */
2442 }
2443 
2444 /*
2445  * Refresh permissions in @bs subtree. The function is intended to be called
2446  * after some graph modification that was done without permission update.
2447  */
2448 static int bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2449                                   Transaction *tran, Error **errp)
2450 {
2451     BlockDriver *drv = bs->drv;
2452     BdrvChild *c;
2453     int ret;
2454     uint64_t cumulative_perms, cumulative_shared_perms;
2455     GLOBAL_STATE_CODE();
2456 
2457     bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
2458 
2459     /* Write permissions never work with read-only images */
2460     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2461         !bdrv_is_writable_after_reopen(bs, q))
2462     {
2463         if (!bdrv_is_writable_after_reopen(bs, NULL)) {
2464             error_setg(errp, "Block node is read-only");
2465         } else {
2466             error_setg(errp, "Read-only block node '%s' cannot support "
2467                        "read-write users", bdrv_get_node_name(bs));
2468         }
2469 
2470         return -EPERM;
2471     }
2472 
2473     /*
2474      * Unaligned requests will automatically be aligned to bl.request_alignment
2475      * and without RESIZE we can't extend requests to write to space beyond the
2476      * end of the image, so it's required that the image size is aligned.
2477      */
2478     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2479         !(cumulative_perms & BLK_PERM_RESIZE))
2480     {
2481         if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
2482             error_setg(errp, "Cannot get 'write' permission without 'resize': "
2483                              "Image size is not a multiple of request "
2484                              "alignment");
2485             return -EPERM;
2486         }
2487     }
2488 
2489     /* Check this node */
2490     if (!drv) {
2491         return 0;
2492     }
2493 
2494     ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
2495                             errp);
2496     if (ret < 0) {
2497         return ret;
2498     }
2499 
2500     /* Drivers that never have children can omit .bdrv_child_perm() */
2501     if (!drv->bdrv_child_perm) {
2502         assert(QLIST_EMPTY(&bs->children));
2503         return 0;
2504     }
2505 
2506     /* Check all children */
2507     QLIST_FOREACH(c, &bs->children, next) {
2508         uint64_t cur_perm, cur_shared;
2509 
2510         bdrv_child_perm(bs, c->bs, c, c->role, q,
2511                         cumulative_perms, cumulative_shared_perms,
2512                         &cur_perm, &cur_shared);
2513         bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2514     }
2515 
2516     return 0;
2517 }
2518 
2519 /*
2520  * @list is a product of bdrv_topological_dfs() (may be called several times) -
2521  * a topologically sorted subgraph.
2522  */
2523 static int bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q,
2524                                  Transaction *tran, Error **errp)
2525 {
2526     int ret;
2527     BlockDriverState *bs;
2528     GLOBAL_STATE_CODE();
2529 
2530     for ( ; list; list = list->next) {
2531         bs = list->data;
2532 
2533         if (bdrv_parent_perms_conflict(bs, errp)) {
2534             return -EINVAL;
2535         }
2536 
2537         ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2538         if (ret < 0) {
2539             return ret;
2540         }
2541     }
2542 
2543     return 0;
2544 }
2545 
2546 /*
2547  * @list is any list of nodes. List is completed by all subtrees and
2548  * topologically sorted. It's not a problem if some node occurs in the @list
2549  * several times.
2550  */
2551 static int bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q,
2552                                    Transaction *tran, Error **errp)
2553 {
2554     g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2555     g_autoptr(GSList) refresh_list = NULL;
2556 
2557     for ( ; list; list = list->next) {
2558         refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2559     }
2560 
2561     return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2562 }
2563 
2564 void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
2565                               uint64_t *shared_perm)
2566 {
2567     BdrvChild *c;
2568     uint64_t cumulative_perms = 0;
2569     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
2570 
2571     GLOBAL_STATE_CODE();
2572 
2573     QLIST_FOREACH(c, &bs->parents, next_parent) {
2574         cumulative_perms |= c->perm;
2575         cumulative_shared_perms &= c->shared_perm;
2576     }
2577 
2578     *perm = cumulative_perms;
2579     *shared_perm = cumulative_shared_perms;
2580 }
2581 
2582 char *bdrv_perm_names(uint64_t perm)
2583 {
2584     struct perm_name {
2585         uint64_t perm;
2586         const char *name;
2587     } permissions[] = {
2588         { BLK_PERM_CONSISTENT_READ, "consistent read" },
2589         { BLK_PERM_WRITE,           "write" },
2590         { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2591         { BLK_PERM_RESIZE,          "resize" },
2592         { 0, NULL }
2593     };
2594 
2595     GString *result = g_string_sized_new(30);
2596     struct perm_name *p;
2597 
2598     for (p = permissions; p->name; p++) {
2599         if (perm & p->perm) {
2600             if (result->len > 0) {
2601                 g_string_append(result, ", ");
2602             }
2603             g_string_append(result, p->name);
2604         }
2605     }
2606 
2607     return g_string_free(result, FALSE);
2608 }
2609 
2610 
2611 /* @tran is allowed to be NULL. In this case no rollback is possible */
2612 static int bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran,
2613                               Error **errp)
2614 {
2615     int ret;
2616     Transaction *local_tran = NULL;
2617     g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2618     GLOBAL_STATE_CODE();
2619 
2620     if (!tran) {
2621         tran = local_tran = tran_new();
2622     }
2623 
2624     ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2625 
2626     if (local_tran) {
2627         tran_finalize(local_tran, ret);
2628     }
2629 
2630     return ret;
2631 }
2632 
2633 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2634                             Error **errp)
2635 {
2636     Error *local_err = NULL;
2637     Transaction *tran = tran_new();
2638     int ret;
2639 
2640     GLOBAL_STATE_CODE();
2641 
2642     bdrv_child_set_perm(c, perm, shared, tran);
2643 
2644     ret = bdrv_refresh_perms(c->bs, tran, &local_err);
2645 
2646     tran_finalize(tran, ret);
2647 
2648     if (ret < 0) {
2649         if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2650             /* tighten permissions */
2651             error_propagate(errp, local_err);
2652         } else {
2653             /*
2654              * Our caller may intend to only loosen restrictions and
2655              * does not expect this function to fail.  Errors are not
2656              * fatal in such a case, so we can just hide them from our
2657              * caller.
2658              */
2659             error_free(local_err);
2660             ret = 0;
2661         }
2662     }
2663 
2664     return ret;
2665 }
2666 
2667 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2668 {
2669     uint64_t parent_perms, parent_shared;
2670     uint64_t perms, shared;
2671 
2672     GLOBAL_STATE_CODE();
2673 
2674     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2675     bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2676                     parent_perms, parent_shared, &perms, &shared);
2677 
2678     return bdrv_child_try_set_perm(c, perms, shared, errp);
2679 }
2680 
2681 /*
2682  * Default implementation for .bdrv_child_perm() for block filters:
2683  * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
2684  * filtered child.
2685  */
2686 static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2687                                       BdrvChildRole role,
2688                                       BlockReopenQueue *reopen_queue,
2689                                       uint64_t perm, uint64_t shared,
2690                                       uint64_t *nperm, uint64_t *nshared)
2691 {
2692     GLOBAL_STATE_CODE();
2693     *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2694     *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2695 }
2696 
2697 static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
2698                                        BdrvChildRole role,
2699                                        BlockReopenQueue *reopen_queue,
2700                                        uint64_t perm, uint64_t shared,
2701                                        uint64_t *nperm, uint64_t *nshared)
2702 {
2703     assert(role & BDRV_CHILD_COW);
2704     GLOBAL_STATE_CODE();
2705 
2706     /*
2707      * We want consistent read from backing files if the parent needs it.
2708      * No other operations are performed on backing files.
2709      */
2710     perm &= BLK_PERM_CONSISTENT_READ;
2711 
2712     /*
2713      * If the parent can deal with changing data, we're okay with a
2714      * writable and resizable backing file.
2715      * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
2716      */
2717     if (shared & BLK_PERM_WRITE) {
2718         shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2719     } else {
2720         shared = 0;
2721     }
2722 
2723     shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
2724 
2725     if (bs->open_flags & BDRV_O_INACTIVE) {
2726         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2727     }
2728 
2729     *nperm = perm;
2730     *nshared = shared;
2731 }
2732 
2733 static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2734                                            BdrvChildRole role,
2735                                            BlockReopenQueue *reopen_queue,
2736                                            uint64_t perm, uint64_t shared,
2737                                            uint64_t *nperm, uint64_t *nshared)
2738 {
2739     int flags;
2740 
2741     GLOBAL_STATE_CODE();
2742     assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
2743 
2744     flags = bdrv_reopen_get_flags(reopen_queue, bs);
2745 
2746     /*
2747      * Apart from the modifications below, the same permissions are
2748      * forwarded and left alone as for filters
2749      */
2750     bdrv_filter_default_perms(bs, c, role, reopen_queue,
2751                               perm, shared, &perm, &shared);
2752 
2753     if (role & BDRV_CHILD_METADATA) {
2754         /* Format drivers may touch metadata even if the guest doesn't write */
2755         if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2756             perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2757         }
2758 
2759         /*
2760          * bs->file always needs to be consistent because of the
2761          * metadata. We can never allow other users to resize or write
2762          * to it.
2763          */
2764         if (!(flags & BDRV_O_NO_IO)) {
2765             perm |= BLK_PERM_CONSISTENT_READ;
2766         }
2767         shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2768     }
2769 
2770     if (role & BDRV_CHILD_DATA) {
2771         /*
2772          * Technically, everything in this block is a subset of the
2773          * BDRV_CHILD_METADATA path taken above, and so this could
2774          * be an "else if" branch.  However, that is not obvious, and
2775          * this function is not performance critical, therefore we let
2776          * this be an independent "if".
2777          */
2778 
2779         /*
2780          * We cannot allow other users to resize the file because the
2781          * format driver might have some assumptions about the size
2782          * (e.g. because it is stored in metadata, or because the file
2783          * is split into fixed-size data files).
2784          */
2785         shared &= ~BLK_PERM_RESIZE;
2786 
2787         /*
2788          * WRITE_UNCHANGED often cannot be performed as such on the
2789          * data file.  For example, the qcow2 driver may still need to
2790          * write copied clusters on copy-on-read.
2791          */
2792         if (perm & BLK_PERM_WRITE_UNCHANGED) {
2793             perm |= BLK_PERM_WRITE;
2794         }
2795 
2796         /*
2797          * If the data file is written to, the format driver may
2798          * expect to be able to resize it by writing beyond the EOF.
2799          */
2800         if (perm & BLK_PERM_WRITE) {
2801             perm |= BLK_PERM_RESIZE;
2802         }
2803     }
2804 
2805     if (bs->open_flags & BDRV_O_INACTIVE) {
2806         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2807     }
2808 
2809     *nperm = perm;
2810     *nshared = shared;
2811 }
2812 
2813 void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2814                         BdrvChildRole role, BlockReopenQueue *reopen_queue,
2815                         uint64_t perm, uint64_t shared,
2816                         uint64_t *nperm, uint64_t *nshared)
2817 {
2818     GLOBAL_STATE_CODE();
2819     if (role & BDRV_CHILD_FILTERED) {
2820         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
2821                          BDRV_CHILD_COW)));
2822         bdrv_filter_default_perms(bs, c, role, reopen_queue,
2823                                   perm, shared, nperm, nshared);
2824     } else if (role & BDRV_CHILD_COW) {
2825         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2826         bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
2827                                    perm, shared, nperm, nshared);
2828     } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2829         bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
2830                                        perm, shared, nperm, nshared);
2831     } else {
2832         g_assert_not_reached();
2833     }
2834 }
2835 
2836 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2837 {
2838     static const uint64_t permissions[] = {
2839         [BLOCK_PERMISSION_CONSISTENT_READ]  = BLK_PERM_CONSISTENT_READ,
2840         [BLOCK_PERMISSION_WRITE]            = BLK_PERM_WRITE,
2841         [BLOCK_PERMISSION_WRITE_UNCHANGED]  = BLK_PERM_WRITE_UNCHANGED,
2842         [BLOCK_PERMISSION_RESIZE]           = BLK_PERM_RESIZE,
2843     };
2844 
2845     QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2846     QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2847 
2848     assert(qapi_perm < BLOCK_PERMISSION__MAX);
2849 
2850     return permissions[qapi_perm];
2851 }
2852 
2853 static void bdrv_replace_child_noperm(BdrvChild *child,
2854                                       BlockDriverState *new_bs)
2855 {
2856     BlockDriverState *old_bs = child->bs;
2857     int new_bs_quiesce_counter;
2858     int drain_saldo;
2859 
2860     assert(!child->frozen);
2861     assert(old_bs != new_bs);
2862     GLOBAL_STATE_CODE();
2863 
2864     if (old_bs && new_bs) {
2865         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2866     }
2867 
2868     new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2869     drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2870 
2871     /*
2872      * If the new child node is drained but the old one was not, flush
2873      * all outstanding requests to the old child node.
2874      */
2875     while (drain_saldo > 0 && child->klass->drained_begin) {
2876         bdrv_parent_drained_begin_single(child, true);
2877         drain_saldo--;
2878     }
2879 
2880     if (old_bs) {
2881         if (child->klass->detach) {
2882             child->klass->detach(child);
2883         }
2884         assert_bdrv_graph_writable(old_bs);
2885         QLIST_REMOVE(child, next_parent);
2886     }
2887 
2888     child->bs = new_bs;
2889 
2890     if (new_bs) {
2891         assert_bdrv_graph_writable(new_bs);
2892         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2893 
2894         /*
2895          * Polling in bdrv_parent_drained_begin_single() may have led to the new
2896          * node's quiesce_counter having been decreased.  Not a problem, we just
2897          * need to recognize this here and then invoke drained_end appropriately
2898          * more often.
2899          */
2900         assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2901         drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2902 
2903         if (child->klass->attach) {
2904             child->klass->attach(child);
2905         }
2906     }
2907 
2908     /*
2909      * If the old child node was drained but the new one is not, allow
2910      * requests to come in only after the new node has been attached.
2911      */
2912     while (drain_saldo < 0 && child->klass->drained_end) {
2913         bdrv_parent_drained_end_single(child);
2914         drain_saldo++;
2915     }
2916 }
2917 
2918 /**
2919  * Free the given @child.
2920  *
2921  * The child must be empty (i.e. `child->bs == NULL`) and it must be
2922  * unused (i.e. not in a children list).
2923  */
2924 static void bdrv_child_free(BdrvChild *child)
2925 {
2926     assert(!child->bs);
2927     GLOBAL_STATE_CODE();
2928     assert(!child->next.le_prev); /* not in children list */
2929 
2930     g_free(child->name);
2931     g_free(child);
2932 }
2933 
2934 typedef struct BdrvAttachChildCommonState {
2935     BdrvChild *child;
2936     AioContext *old_parent_ctx;
2937     AioContext *old_child_ctx;
2938 } BdrvAttachChildCommonState;
2939 
2940 static void bdrv_attach_child_common_abort(void *opaque)
2941 {
2942     BdrvAttachChildCommonState *s = opaque;
2943     BlockDriverState *bs = s->child->bs;
2944 
2945     GLOBAL_STATE_CODE();
2946     bdrv_replace_child_noperm(s->child, NULL);
2947 
2948     if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
2949         bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
2950     }
2951 
2952     if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
2953         Transaction *tran;
2954         GHashTable *visited;
2955         bool ret;
2956 
2957         tran = tran_new();
2958 
2959         /* No need to visit `child`, because it has been detached already */
2960         visited = g_hash_table_new(NULL, NULL);
2961         ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2962                                               visited, tran, &error_abort);
2963         g_hash_table_destroy(visited);
2964 
2965         /* transaction is supposed to always succeed */
2966         assert(ret == true);
2967         tran_commit(tran);
2968     }
2969 
2970     bdrv_unref(bs);
2971     bdrv_child_free(s->child);
2972 }
2973 
2974 static TransactionActionDrv bdrv_attach_child_common_drv = {
2975     .abort = bdrv_attach_child_common_abort,
2976     .clean = g_free,
2977 };
2978 
2979 /*
2980  * Common part of attaching bdrv child to bs or to blk or to job
2981  *
2982  * Function doesn't update permissions, caller is responsible for this.
2983  *
2984  * Returns new created child.
2985  */
2986 static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2987                                            const char *child_name,
2988                                            const BdrvChildClass *child_class,
2989                                            BdrvChildRole child_role,
2990                                            uint64_t perm, uint64_t shared_perm,
2991                                            void *opaque,
2992                                            Transaction *tran, Error **errp)
2993 {
2994     BdrvChild *new_child;
2995     AioContext *parent_ctx;
2996     AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2997 
2998     assert(child_class->get_parent_desc);
2999     GLOBAL_STATE_CODE();
3000 
3001     new_child = g_new(BdrvChild, 1);
3002     *new_child = (BdrvChild) {
3003         .bs             = NULL,
3004         .name           = g_strdup(child_name),
3005         .klass          = child_class,
3006         .role           = child_role,
3007         .perm           = perm,
3008         .shared_perm    = shared_perm,
3009         .opaque         = opaque,
3010     };
3011 
3012     /*
3013      * If the AioContexts don't match, first try to move the subtree of
3014      * child_bs into the AioContext of the new parent. If this doesn't work,
3015      * try moving the parent into the AioContext of child_bs instead.
3016      */
3017     parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3018     if (child_ctx != parent_ctx) {
3019         Error *local_err = NULL;
3020         int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3021                                               &local_err);
3022 
3023         if (ret < 0 && child_class->change_aio_ctx) {
3024             Transaction *tran = tran_new();
3025             GHashTable *visited = g_hash_table_new(NULL, NULL);
3026             bool ret_child;
3027 
3028             g_hash_table_add(visited, new_child);
3029             ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3030                                                     visited, tran, NULL);
3031             if (ret_child == true) {
3032                 error_free(local_err);
3033                 ret = 0;
3034             }
3035             tran_finalize(tran, ret_child == true ? 0 : -1);
3036             g_hash_table_destroy(visited);
3037         }
3038 
3039         if (ret < 0) {
3040             error_propagate(errp, local_err);
3041             bdrv_child_free(new_child);
3042             return NULL;
3043         }
3044     }
3045 
3046     bdrv_ref(child_bs);
3047     bdrv_replace_child_noperm(new_child, child_bs);
3048 
3049     BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3050     *s = (BdrvAttachChildCommonState) {
3051         .child = new_child,
3052         .old_parent_ctx = parent_ctx,
3053         .old_child_ctx = child_ctx,
3054     };
3055     tran_add(tran, &bdrv_attach_child_common_drv, s);
3056 
3057     return new_child;
3058 }
3059 
3060 /*
3061  * Function doesn't update permissions, caller is responsible for this.
3062  */
3063 static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3064                                            BlockDriverState *child_bs,
3065                                            const char *child_name,
3066                                            const BdrvChildClass *child_class,
3067                                            BdrvChildRole child_role,
3068                                            Transaction *tran,
3069                                            Error **errp)
3070 {
3071     uint64_t perm, shared_perm;
3072 
3073     assert(parent_bs->drv);
3074     GLOBAL_STATE_CODE();
3075 
3076     if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3077         error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3078                    child_bs->node_name, child_name, parent_bs->node_name);
3079         return NULL;
3080     }
3081 
3082     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3083     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3084                     perm, shared_perm, &perm, &shared_perm);
3085 
3086     return bdrv_attach_child_common(child_bs, child_name, child_class,
3087                                     child_role, perm, shared_perm, parent_bs,
3088                                     tran, errp);
3089 }
3090 
3091 /*
3092  * This function steals the reference to child_bs from the caller.
3093  * That reference is later dropped by bdrv_root_unref_child().
3094  *
3095  * On failure NULL is returned, errp is set and the reference to
3096  * child_bs is also dropped.
3097  *
3098  * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3099  * (unless @child_bs is already in @ctx).
3100  */
3101 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3102                                   const char *child_name,
3103                                   const BdrvChildClass *child_class,
3104                                   BdrvChildRole child_role,
3105                                   uint64_t perm, uint64_t shared_perm,
3106                                   void *opaque, Error **errp)
3107 {
3108     int ret;
3109     BdrvChild *child;
3110     Transaction *tran = tran_new();
3111 
3112     GLOBAL_STATE_CODE();
3113 
3114     child = bdrv_attach_child_common(child_bs, child_name, child_class,
3115                                    child_role, perm, shared_perm, opaque,
3116                                    tran, errp);
3117     if (!child) {
3118         ret = -EINVAL;
3119         goto out;
3120     }
3121 
3122     ret = bdrv_refresh_perms(child_bs, tran, errp);
3123 
3124 out:
3125     tran_finalize(tran, ret);
3126 
3127     bdrv_unref(child_bs);
3128 
3129     return ret < 0 ? NULL : child;
3130 }
3131 
3132 /*
3133  * This function transfers the reference to child_bs from the caller
3134  * to parent_bs. That reference is later dropped by parent_bs on
3135  * bdrv_close() or if someone calls bdrv_unref_child().
3136  *
3137  * On failure NULL is returned, errp is set and the reference to
3138  * child_bs is also dropped.
3139  *
3140  * If @parent_bs and @child_bs are in different AioContexts, the caller must
3141  * hold the AioContext lock for @child_bs, but not for @parent_bs.
3142  */
3143 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3144                              BlockDriverState *child_bs,
3145                              const char *child_name,
3146                              const BdrvChildClass *child_class,
3147                              BdrvChildRole child_role,
3148                              Error **errp)
3149 {
3150     int ret;
3151     BdrvChild *child;
3152     Transaction *tran = tran_new();
3153 
3154     GLOBAL_STATE_CODE();
3155 
3156     child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3157                                      child_class, child_role, tran, errp);
3158     if (!child) {
3159         ret = -EINVAL;
3160         goto out;
3161     }
3162 
3163     ret = bdrv_refresh_perms(parent_bs, tran, errp);
3164     if (ret < 0) {
3165         goto out;
3166     }
3167 
3168 out:
3169     tran_finalize(tran, ret);
3170 
3171     bdrv_unref(child_bs);
3172 
3173     return ret < 0 ? NULL : child;
3174 }
3175 
3176 /* Callers must ensure that child->frozen is false. */
3177 void bdrv_root_unref_child(BdrvChild *child)
3178 {
3179     BlockDriverState *child_bs = child->bs;
3180 
3181     GLOBAL_STATE_CODE();
3182     bdrv_replace_child_noperm(child, NULL);
3183     bdrv_child_free(child);
3184 
3185     if (child_bs) {
3186         /*
3187          * Update permissions for old node. We're just taking a parent away, so
3188          * we're loosening restrictions. Errors of permission update are not
3189          * fatal in this case, ignore them.
3190          */
3191         bdrv_refresh_perms(child_bs, NULL, NULL);
3192 
3193         /*
3194          * When the parent requiring a non-default AioContext is removed, the
3195          * node moves back to the main AioContext
3196          */
3197         bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
3198                                     NULL);
3199     }
3200 
3201     bdrv_unref(child_bs);
3202 }
3203 
3204 typedef struct BdrvSetInheritsFrom {
3205     BlockDriverState *bs;
3206     BlockDriverState *old_inherits_from;
3207 } BdrvSetInheritsFrom;
3208 
3209 static void bdrv_set_inherits_from_abort(void *opaque)
3210 {
3211     BdrvSetInheritsFrom *s = opaque;
3212 
3213     s->bs->inherits_from = s->old_inherits_from;
3214 }
3215 
3216 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3217     .abort = bdrv_set_inherits_from_abort,
3218     .clean = g_free,
3219 };
3220 
3221 /* @tran is allowed to be NULL. In this case no rollback is possible */
3222 static void bdrv_set_inherits_from(BlockDriverState *bs,
3223                                    BlockDriverState *new_inherits_from,
3224                                    Transaction *tran)
3225 {
3226     if (tran) {
3227         BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3228 
3229         *s = (BdrvSetInheritsFrom) {
3230             .bs = bs,
3231             .old_inherits_from = bs->inherits_from,
3232         };
3233 
3234         tran_add(tran, &bdrv_set_inherits_from_drv, s);
3235     }
3236 
3237     bs->inherits_from = new_inherits_from;
3238 }
3239 
3240 /**
3241  * Clear all inherits_from pointers from children and grandchildren of
3242  * @root that point to @root, where necessary.
3243  * @tran is allowed to be NULL. In this case no rollback is possible
3244  */
3245 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3246                                      Transaction *tran)
3247 {
3248     BdrvChild *c;
3249 
3250     if (child->bs->inherits_from == root) {
3251         /*
3252          * Remove inherits_from only when the last reference between root and
3253          * child->bs goes away.
3254          */
3255         QLIST_FOREACH(c, &root->children, next) {
3256             if (c != child && c->bs == child->bs) {
3257                 break;
3258             }
3259         }
3260         if (c == NULL) {
3261             bdrv_set_inherits_from(child->bs, NULL, tran);
3262         }
3263     }
3264 
3265     QLIST_FOREACH(c, &child->bs->children, next) {
3266         bdrv_unset_inherits_from(root, c, tran);
3267     }
3268 }
3269 
3270 /* Callers must ensure that child->frozen is false. */
3271 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3272 {
3273     GLOBAL_STATE_CODE();
3274     if (child == NULL) {
3275         return;
3276     }
3277 
3278     bdrv_unset_inherits_from(parent, child, NULL);
3279     bdrv_root_unref_child(child);
3280 }
3281 
3282 
3283 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3284 {
3285     BdrvChild *c;
3286     GLOBAL_STATE_CODE();
3287     QLIST_FOREACH(c, &bs->parents, next_parent) {
3288         if (c->klass->change_media) {
3289             c->klass->change_media(c, load);
3290         }
3291     }
3292 }
3293 
3294 /* Return true if you can reach parent going through child->inherits_from
3295  * recursively. If parent or child are NULL, return false */
3296 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3297                                          BlockDriverState *parent)
3298 {
3299     while (child && child != parent) {
3300         child = child->inherits_from;
3301     }
3302 
3303     return child != NULL;
3304 }
3305 
3306 /*
3307  * Return the BdrvChildRole for @bs's backing child.  bs->backing is
3308  * mostly used for COW backing children (role = COW), but also for
3309  * filtered children (role = FILTERED | PRIMARY).
3310  */
3311 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3312 {
3313     if (bs->drv && bs->drv->is_filter) {
3314         return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3315     } else {
3316         return BDRV_CHILD_COW;
3317     }
3318 }
3319 
3320 /*
3321  * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3322  * callers which don't need their own reference any more must call bdrv_unref().
3323  *
3324  * Function doesn't update permissions, caller is responsible for this.
3325  */
3326 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3327                                            BlockDriverState *child_bs,
3328                                            bool is_backing,
3329                                            Transaction *tran, Error **errp)
3330 {
3331     bool update_inherits_from =
3332         bdrv_inherits_from_recursive(child_bs, parent_bs);
3333     BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3334     BdrvChildRole role;
3335 
3336     GLOBAL_STATE_CODE();
3337 
3338     if (!parent_bs->drv) {
3339         /*
3340          * Node without drv is an object without a class :/. TODO: finally fix
3341          * qcow2 driver to never clear bs->drv and implement format corruption
3342          * handling in other way.
3343          */
3344         error_setg(errp, "Node corrupted");
3345         return -EINVAL;
3346     }
3347 
3348     if (child && child->frozen) {
3349         error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3350                    child->name, parent_bs->node_name, child->bs->node_name);
3351         return -EPERM;
3352     }
3353 
3354     if (is_backing && !parent_bs->drv->is_filter &&
3355         !parent_bs->drv->supports_backing)
3356     {
3357         error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3358                    "files", parent_bs->drv->format_name, parent_bs->node_name);
3359         return -EINVAL;
3360     }
3361 
3362     if (parent_bs->drv->is_filter) {
3363         role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3364     } else if (is_backing) {
3365         role = BDRV_CHILD_COW;
3366     } else {
3367         /*
3368          * We only can use same role as it is in existing child. We don't have
3369          * infrastructure to determine role of file child in generic way
3370          */
3371         if (!child) {
3372             error_setg(errp, "Cannot set file child to format node without "
3373                        "file child");
3374             return -EINVAL;
3375         }
3376         role = child->role;
3377     }
3378 
3379     if (child) {
3380         bdrv_unset_inherits_from(parent_bs, child, tran);
3381         bdrv_remove_child(child, tran);
3382     }
3383 
3384     if (!child_bs) {
3385         goto out;
3386     }
3387 
3388     child = bdrv_attach_child_noperm(parent_bs, child_bs,
3389                                      is_backing ? "backing" : "file",
3390                                      &child_of_bds, role,
3391                                      tran, errp);
3392     if (!child) {
3393         return -EINVAL;
3394     }
3395 
3396 
3397     /*
3398      * If inherits_from pointed recursively to bs then let's update it to
3399      * point directly to bs (else it will become NULL).
3400      */
3401     if (update_inherits_from) {
3402         bdrv_set_inherits_from(child_bs, parent_bs, tran);
3403     }
3404 
3405 out:
3406     bdrv_refresh_limits(parent_bs, tran, NULL);
3407 
3408     return 0;
3409 }
3410 
3411 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3412                                    BlockDriverState *backing_hd,
3413                                    Transaction *tran, Error **errp)
3414 {
3415     GLOBAL_STATE_CODE();
3416     return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3417 }
3418 
3419 int bdrv_set_backing_hd_drained(BlockDriverState *bs,
3420                                 BlockDriverState *backing_hd,
3421                                 Error **errp)
3422 {
3423     int ret;
3424     Transaction *tran = tran_new();
3425 
3426     GLOBAL_STATE_CODE();
3427     assert(bs->quiesce_counter > 0);
3428 
3429     ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3430     if (ret < 0) {
3431         goto out;
3432     }
3433 
3434     ret = bdrv_refresh_perms(bs, tran, errp);
3435 out:
3436     tran_finalize(tran, ret);
3437     return ret;
3438 }
3439 
3440 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3441                         Error **errp)
3442 {
3443     int ret;
3444     GLOBAL_STATE_CODE();
3445 
3446     bdrv_drained_begin(bs);
3447     ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
3448     bdrv_drained_end(bs);
3449 
3450     return ret;
3451 }
3452 
3453 /*
3454  * Opens the backing file for a BlockDriverState if not yet open
3455  *
3456  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3457  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3458  * itself, all options starting with "${bdref_key}." are considered part of the
3459  * BlockdevRef.
3460  *
3461  * TODO Can this be unified with bdrv_open_image()?
3462  */
3463 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3464                            const char *bdref_key, Error **errp)
3465 {
3466     char *backing_filename = NULL;
3467     char *bdref_key_dot;
3468     const char *reference = NULL;
3469     int ret = 0;
3470     bool implicit_backing = false;
3471     BlockDriverState *backing_hd;
3472     QDict *options;
3473     QDict *tmp_parent_options = NULL;
3474     Error *local_err = NULL;
3475 
3476     GLOBAL_STATE_CODE();
3477 
3478     if (bs->backing != NULL) {
3479         goto free_exit;
3480     }
3481 
3482     /* NULL means an empty set of options */
3483     if (parent_options == NULL) {
3484         tmp_parent_options = qdict_new();
3485         parent_options = tmp_parent_options;
3486     }
3487 
3488     bs->open_flags &= ~BDRV_O_NO_BACKING;
3489 
3490     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3491     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3492     g_free(bdref_key_dot);
3493 
3494     /*
3495      * Caution: while qdict_get_try_str() is fine, getting non-string
3496      * types would require more care.  When @parent_options come from
3497      * -blockdev or blockdev_add, its members are typed according to
3498      * the QAPI schema, but when they come from -drive, they're all
3499      * QString.
3500      */
3501     reference = qdict_get_try_str(parent_options, bdref_key);
3502     if (reference || qdict_haskey(options, "file.filename")) {
3503         /* keep backing_filename NULL */
3504     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3505         qobject_unref(options);
3506         goto free_exit;
3507     } else {
3508         if (qdict_size(options) == 0) {
3509             /* If the user specifies options that do not modify the
3510              * backing file's behavior, we might still consider it the
3511              * implicit backing file.  But it's easier this way, and
3512              * just specifying some of the backing BDS's options is
3513              * only possible with -drive anyway (otherwise the QAPI
3514              * schema forces the user to specify everything). */
3515             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3516         }
3517 
3518         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3519         if (local_err) {
3520             ret = -EINVAL;
3521             error_propagate(errp, local_err);
3522             qobject_unref(options);
3523             goto free_exit;
3524         }
3525     }
3526 
3527     if (!bs->drv || !bs->drv->supports_backing) {
3528         ret = -EINVAL;
3529         error_setg(errp, "Driver doesn't support backing files");
3530         qobject_unref(options);
3531         goto free_exit;
3532     }
3533 
3534     if (!reference &&
3535         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3536         qdict_put_str(options, "driver", bs->backing_format);
3537     }
3538 
3539     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3540                                    &child_of_bds, bdrv_backing_role(bs), errp);
3541     if (!backing_hd) {
3542         bs->open_flags |= BDRV_O_NO_BACKING;
3543         error_prepend(errp, "Could not open backing file: ");
3544         ret = -EINVAL;
3545         goto free_exit;
3546     }
3547 
3548     if (implicit_backing) {
3549         bdrv_refresh_filename(backing_hd);
3550         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3551                 backing_hd->filename);
3552     }
3553 
3554     /* Hook up the backing file link; drop our reference, bs owns the
3555      * backing_hd reference now */
3556     ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3557     bdrv_unref(backing_hd);
3558     if (ret < 0) {
3559         goto free_exit;
3560     }
3561 
3562     qdict_del(parent_options, bdref_key);
3563 
3564 free_exit:
3565     g_free(backing_filename);
3566     qobject_unref(tmp_parent_options);
3567     return ret;
3568 }
3569 
3570 static BlockDriverState *
3571 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3572                    BlockDriverState *parent, const BdrvChildClass *child_class,
3573                    BdrvChildRole child_role, bool allow_none, Error **errp)
3574 {
3575     BlockDriverState *bs = NULL;
3576     QDict *image_options;
3577     char *bdref_key_dot;
3578     const char *reference;
3579 
3580     assert(child_class != NULL);
3581 
3582     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3583     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3584     g_free(bdref_key_dot);
3585 
3586     /*
3587      * Caution: while qdict_get_try_str() is fine, getting non-string
3588      * types would require more care.  When @options come from
3589      * -blockdev or blockdev_add, its members are typed according to
3590      * the QAPI schema, but when they come from -drive, they're all
3591      * QString.
3592      */
3593     reference = qdict_get_try_str(options, bdref_key);
3594     if (!filename && !reference && !qdict_size(image_options)) {
3595         if (!allow_none) {
3596             error_setg(errp, "A block device must be specified for \"%s\"",
3597                        bdref_key);
3598         }
3599         qobject_unref(image_options);
3600         goto done;
3601     }
3602 
3603     bs = bdrv_open_inherit(filename, reference, image_options, 0,
3604                            parent, child_class, child_role, errp);
3605     if (!bs) {
3606         goto done;
3607     }
3608 
3609 done:
3610     qdict_del(options, bdref_key);
3611     return bs;
3612 }
3613 
3614 /*
3615  * Opens a disk image whose options are given as BlockdevRef in another block
3616  * device's options.
3617  *
3618  * If allow_none is true, no image will be opened if filename is false and no
3619  * BlockdevRef is given. NULL will be returned, but errp remains unset.
3620  *
3621  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3622  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3623  * itself, all options starting with "${bdref_key}." are considered part of the
3624  * BlockdevRef.
3625  *
3626  * The BlockdevRef will be removed from the options QDict.
3627  */
3628 BdrvChild *bdrv_open_child(const char *filename,
3629                            QDict *options, const char *bdref_key,
3630                            BlockDriverState *parent,
3631                            const BdrvChildClass *child_class,
3632                            BdrvChildRole child_role,
3633                            bool allow_none, Error **errp)
3634 {
3635     BlockDriverState *bs;
3636 
3637     GLOBAL_STATE_CODE();
3638 
3639     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3640                             child_role, allow_none, errp);
3641     if (bs == NULL) {
3642         return NULL;
3643     }
3644 
3645     return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3646                              errp);
3647 }
3648 
3649 /*
3650  * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3651  */
3652 int bdrv_open_file_child(const char *filename,
3653                          QDict *options, const char *bdref_key,
3654                          BlockDriverState *parent, Error **errp)
3655 {
3656     BdrvChildRole role;
3657 
3658     /* commit_top and mirror_top don't use this function */
3659     assert(!parent->drv->filtered_child_is_backing);
3660     role = parent->drv->is_filter ?
3661         (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3662 
3663     if (!bdrv_open_child(filename, options, bdref_key, parent,
3664                          &child_of_bds, role, false, errp))
3665     {
3666         return -EINVAL;
3667     }
3668 
3669     return 0;
3670 }
3671 
3672 /*
3673  * TODO Future callers may need to specify parent/child_class in order for
3674  * option inheritance to work. Existing callers use it for the root node.
3675  */
3676 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3677 {
3678     BlockDriverState *bs = NULL;
3679     QObject *obj = NULL;
3680     QDict *qdict = NULL;
3681     const char *reference = NULL;
3682     Visitor *v = NULL;
3683 
3684     GLOBAL_STATE_CODE();
3685 
3686     if (ref->type == QTYPE_QSTRING) {
3687         reference = ref->u.reference;
3688     } else {
3689         BlockdevOptions *options = &ref->u.definition;
3690         assert(ref->type == QTYPE_QDICT);
3691 
3692         v = qobject_output_visitor_new(&obj);
3693         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3694         visit_complete(v, &obj);
3695 
3696         qdict = qobject_to(QDict, obj);
3697         qdict_flatten(qdict);
3698 
3699         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3700          * compatibility with other callers) rather than what we want as the
3701          * real defaults. Apply the defaults here instead. */
3702         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3703         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3704         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3705         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3706 
3707     }
3708 
3709     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3710     obj = NULL;
3711     qobject_unref(obj);
3712     visit_free(v);
3713     return bs;
3714 }
3715 
3716 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3717                                                    int flags,
3718                                                    QDict *snapshot_options,
3719                                                    Error **errp)
3720 {
3721     g_autofree char *tmp_filename = NULL;
3722     int64_t total_size;
3723     QemuOpts *opts = NULL;
3724     BlockDriverState *bs_snapshot = NULL;
3725     int ret;
3726 
3727     GLOBAL_STATE_CODE();
3728 
3729     /* if snapshot, we create a temporary backing file and open it
3730        instead of opening 'filename' directly */
3731 
3732     /* Get the required size from the image */
3733     total_size = bdrv_getlength(bs);
3734     if (total_size < 0) {
3735         error_setg_errno(errp, -total_size, "Could not get image size");
3736         goto out;
3737     }
3738 
3739     /* Create the temporary image */
3740     tmp_filename = create_tmp_file(errp);
3741     if (!tmp_filename) {
3742         goto out;
3743     }
3744 
3745     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3746                             &error_abort);
3747     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3748     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3749     qemu_opts_del(opts);
3750     if (ret < 0) {
3751         error_prepend(errp, "Could not create temporary overlay '%s': ",
3752                       tmp_filename);
3753         goto out;
3754     }
3755 
3756     /* Prepare options QDict for the temporary file */
3757     qdict_put_str(snapshot_options, "file.driver", "file");
3758     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3759     qdict_put_str(snapshot_options, "driver", "qcow2");
3760 
3761     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3762     snapshot_options = NULL;
3763     if (!bs_snapshot) {
3764         goto out;
3765     }
3766 
3767     ret = bdrv_append(bs_snapshot, bs, errp);
3768     if (ret < 0) {
3769         bs_snapshot = NULL;
3770         goto out;
3771     }
3772 
3773 out:
3774     qobject_unref(snapshot_options);
3775     return bs_snapshot;
3776 }
3777 
3778 /*
3779  * Opens a disk image (raw, qcow2, vmdk, ...)
3780  *
3781  * options is a QDict of options to pass to the block drivers, or NULL for an
3782  * empty set of options. The reference to the QDict belongs to the block layer
3783  * after the call (even on failure), so if the caller intends to reuse the
3784  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3785  *
3786  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3787  * If it is not NULL, the referenced BDS will be reused.
3788  *
3789  * The reference parameter may be used to specify an existing block device which
3790  * should be opened. If specified, neither options nor a filename may be given,
3791  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3792  */
3793 static BlockDriverState *bdrv_open_inherit(const char *filename,
3794                                            const char *reference,
3795                                            QDict *options, int flags,
3796                                            BlockDriverState *parent,
3797                                            const BdrvChildClass *child_class,
3798                                            BdrvChildRole child_role,
3799                                            Error **errp)
3800 {
3801     int ret;
3802     BlockBackend *file = NULL;
3803     BlockDriverState *bs;
3804     BlockDriver *drv = NULL;
3805     BdrvChild *child;
3806     const char *drvname;
3807     const char *backing;
3808     Error *local_err = NULL;
3809     QDict *snapshot_options = NULL;
3810     int snapshot_flags = 0;
3811 
3812     assert(!child_class || !flags);
3813     assert(!child_class == !parent);
3814     GLOBAL_STATE_CODE();
3815 
3816     if (reference) {
3817         bool options_non_empty = options ? qdict_size(options) : false;
3818         qobject_unref(options);
3819 
3820         if (filename || options_non_empty) {
3821             error_setg(errp, "Cannot reference an existing block device with "
3822                        "additional options or a new filename");
3823             return NULL;
3824         }
3825 
3826         bs = bdrv_lookup_bs(reference, reference, errp);
3827         if (!bs) {
3828             return NULL;
3829         }
3830 
3831         bdrv_ref(bs);
3832         return bs;
3833     }
3834 
3835     bs = bdrv_new();
3836 
3837     /* NULL means an empty set of options */
3838     if (options == NULL) {
3839         options = qdict_new();
3840     }
3841 
3842     /* json: syntax counts as explicit options, as if in the QDict */
3843     parse_json_protocol(options, &filename, &local_err);
3844     if (local_err) {
3845         goto fail;
3846     }
3847 
3848     bs->explicit_options = qdict_clone_shallow(options);
3849 
3850     if (child_class) {
3851         bool parent_is_format;
3852 
3853         if (parent->drv) {
3854             parent_is_format = parent->drv->is_format;
3855         } else {
3856             /*
3857              * parent->drv is not set yet because this node is opened for
3858              * (potential) format probing.  That means that @parent is going
3859              * to be a format node.
3860              */
3861             parent_is_format = true;
3862         }
3863 
3864         bs->inherits_from = parent;
3865         child_class->inherit_options(child_role, parent_is_format,
3866                                      &flags, options,
3867                                      parent->open_flags, parent->options);
3868     }
3869 
3870     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3871     if (ret < 0) {
3872         goto fail;
3873     }
3874 
3875     /*
3876      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3877      * Caution: getting a boolean member of @options requires care.
3878      * When @options come from -blockdev or blockdev_add, members are
3879      * typed according to the QAPI schema, but when they come from
3880      * -drive, they're all QString.
3881      */
3882     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3883         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3884         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3885     } else {
3886         flags &= ~BDRV_O_RDWR;
3887     }
3888 
3889     if (flags & BDRV_O_SNAPSHOT) {
3890         snapshot_options = qdict_new();
3891         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3892                                    flags, options);
3893         /* Let bdrv_backing_options() override "read-only" */
3894         qdict_del(options, BDRV_OPT_READ_ONLY);
3895         bdrv_inherited_options(BDRV_CHILD_COW, true,
3896                                &flags, options, flags, options);
3897     }
3898 
3899     bs->open_flags = flags;
3900     bs->options = options;
3901     options = qdict_clone_shallow(options);
3902 
3903     /* Find the right image format driver */
3904     /* See cautionary note on accessing @options above */
3905     drvname = qdict_get_try_str(options, "driver");
3906     if (drvname) {
3907         drv = bdrv_find_format(drvname);
3908         if (!drv) {
3909             error_setg(errp, "Unknown driver: '%s'", drvname);
3910             goto fail;
3911         }
3912     }
3913 
3914     assert(drvname || !(flags & BDRV_O_PROTOCOL));
3915 
3916     /* See cautionary note on accessing @options above */
3917     backing = qdict_get_try_str(options, "backing");
3918     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3919         (backing && *backing == '\0'))
3920     {
3921         if (backing) {
3922             warn_report("Use of \"backing\": \"\" is deprecated; "
3923                         "use \"backing\": null instead");
3924         }
3925         flags |= BDRV_O_NO_BACKING;
3926         qdict_del(bs->explicit_options, "backing");
3927         qdict_del(bs->options, "backing");
3928         qdict_del(options, "backing");
3929     }
3930 
3931     /* Open image file without format layer. This BlockBackend is only used for
3932      * probing, the block drivers will do their own bdrv_open_child() for the
3933      * same BDS, which is why we put the node name back into options. */
3934     if ((flags & BDRV_O_PROTOCOL) == 0) {
3935         BlockDriverState *file_bs;
3936 
3937         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3938                                      &child_of_bds, BDRV_CHILD_IMAGE,
3939                                      true, &local_err);
3940         if (local_err) {
3941             goto fail;
3942         }
3943         if (file_bs != NULL) {
3944             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3945              * looking at the header to guess the image format. This works even
3946              * in cases where a guest would not see a consistent state. */
3947             file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3948             blk_insert_bs(file, file_bs, &local_err);
3949             bdrv_unref(file_bs);
3950             if (local_err) {
3951                 goto fail;
3952             }
3953 
3954             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3955         }
3956     }
3957 
3958     /* Image format probing */
3959     bs->probed = !drv;
3960     if (!drv && file) {
3961         ret = find_image_format(file, filename, &drv, &local_err);
3962         if (ret < 0) {
3963             goto fail;
3964         }
3965         /*
3966          * This option update would logically belong in bdrv_fill_options(),
3967          * but we first need to open bs->file for the probing to work, while
3968          * opening bs->file already requires the (mostly) final set of options
3969          * so that cache mode etc. can be inherited.
3970          *
3971          * Adding the driver later is somewhat ugly, but it's not an option
3972          * that would ever be inherited, so it's correct. We just need to make
3973          * sure to update both bs->options (which has the full effective
3974          * options for bs) and options (which has file.* already removed).
3975          */
3976         qdict_put_str(bs->options, "driver", drv->format_name);
3977         qdict_put_str(options, "driver", drv->format_name);
3978     } else if (!drv) {
3979         error_setg(errp, "Must specify either driver or file");
3980         goto fail;
3981     }
3982 
3983     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3984     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3985     /* file must be NULL if a protocol BDS is about to be created
3986      * (the inverse results in an error message from bdrv_open_common()) */
3987     assert(!(flags & BDRV_O_PROTOCOL) || !file);
3988 
3989     /* Open the image */
3990     ret = bdrv_open_common(bs, file, options, &local_err);
3991     if (ret < 0) {
3992         goto fail;
3993     }
3994 
3995     if (file) {
3996         blk_unref(file);
3997         file = NULL;
3998     }
3999 
4000     /* If there is a backing file, use it */
4001     if ((flags & BDRV_O_NO_BACKING) == 0) {
4002         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4003         if (ret < 0) {
4004             goto close_and_fail;
4005         }
4006     }
4007 
4008     /* Remove all children options and references
4009      * from bs->options and bs->explicit_options */
4010     QLIST_FOREACH(child, &bs->children, next) {
4011         char *child_key_dot;
4012         child_key_dot = g_strdup_printf("%s.", child->name);
4013         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
4014         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
4015         qdict_del(bs->explicit_options, child->name);
4016         qdict_del(bs->options, child->name);
4017         g_free(child_key_dot);
4018     }
4019 
4020     /* Check if any unknown options were used */
4021     if (qdict_size(options) != 0) {
4022         const QDictEntry *entry = qdict_first(options);
4023         if (flags & BDRV_O_PROTOCOL) {
4024             error_setg(errp, "Block protocol '%s' doesn't support the option "
4025                        "'%s'", drv->format_name, entry->key);
4026         } else {
4027             error_setg(errp,
4028                        "Block format '%s' does not support the option '%s'",
4029                        drv->format_name, entry->key);
4030         }
4031 
4032         goto close_and_fail;
4033     }
4034 
4035     bdrv_parent_cb_change_media(bs, true);
4036 
4037     qobject_unref(options);
4038     options = NULL;
4039 
4040     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4041      * temporary snapshot afterwards. */
4042     if (snapshot_flags) {
4043         BlockDriverState *snapshot_bs;
4044         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4045                                                 snapshot_options, &local_err);
4046         snapshot_options = NULL;
4047         if (local_err) {
4048             goto close_and_fail;
4049         }
4050         /* We are not going to return bs but the overlay on top of it
4051          * (snapshot_bs); thus, we have to drop the strong reference to bs
4052          * (which we obtained by calling bdrv_new()). bs will not be deleted,
4053          * though, because the overlay still has a reference to it. */
4054         bdrv_unref(bs);
4055         bs = snapshot_bs;
4056     }
4057 
4058     return bs;
4059 
4060 fail:
4061     blk_unref(file);
4062     qobject_unref(snapshot_options);
4063     qobject_unref(bs->explicit_options);
4064     qobject_unref(bs->options);
4065     qobject_unref(options);
4066     bs->options = NULL;
4067     bs->explicit_options = NULL;
4068     bdrv_unref(bs);
4069     error_propagate(errp, local_err);
4070     return NULL;
4071 
4072 close_and_fail:
4073     bdrv_unref(bs);
4074     qobject_unref(snapshot_options);
4075     qobject_unref(options);
4076     error_propagate(errp, local_err);
4077     return NULL;
4078 }
4079 
4080 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4081                             QDict *options, int flags, Error **errp)
4082 {
4083     GLOBAL_STATE_CODE();
4084 
4085     return bdrv_open_inherit(filename, reference, options, flags, NULL,
4086                              NULL, 0, errp);
4087 }
4088 
4089 /* Return true if the NULL-terminated @list contains @str */
4090 static bool is_str_in_list(const char *str, const char *const *list)
4091 {
4092     if (str && list) {
4093         int i;
4094         for (i = 0; list[i] != NULL; i++) {
4095             if (!strcmp(str, list[i])) {
4096                 return true;
4097             }
4098         }
4099     }
4100     return false;
4101 }
4102 
4103 /*
4104  * Check that every option set in @bs->options is also set in
4105  * @new_opts.
4106  *
4107  * Options listed in the common_options list and in
4108  * @bs->drv->mutable_opts are skipped.
4109  *
4110  * Return 0 on success, otherwise return -EINVAL and set @errp.
4111  */
4112 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4113                                       const QDict *new_opts, Error **errp)
4114 {
4115     const QDictEntry *e;
4116     /* These options are common to all block drivers and are handled
4117      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4118     const char *const common_options[] = {
4119         "node-name", "discard", "cache.direct", "cache.no-flush",
4120         "read-only", "auto-read-only", "detect-zeroes", NULL
4121     };
4122 
4123     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4124         if (!qdict_haskey(new_opts, e->key) &&
4125             !is_str_in_list(e->key, common_options) &&
4126             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4127             error_setg(errp, "Option '%s' cannot be reset "
4128                        "to its default value", e->key);
4129             return -EINVAL;
4130         }
4131     }
4132 
4133     return 0;
4134 }
4135 
4136 /*
4137  * Returns true if @child can be reached recursively from @bs
4138  */
4139 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4140                                    BlockDriverState *child)
4141 {
4142     BdrvChild *c;
4143 
4144     if (bs == child) {
4145         return true;
4146     }
4147 
4148     QLIST_FOREACH(c, &bs->children, next) {
4149         if (bdrv_recurse_has_child(c->bs, child)) {
4150             return true;
4151         }
4152     }
4153 
4154     return false;
4155 }
4156 
4157 /*
4158  * Adds a BlockDriverState to a simple queue for an atomic, transactional
4159  * reopen of multiple devices.
4160  *
4161  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4162  * already performed, or alternatively may be NULL a new BlockReopenQueue will
4163  * be created and initialized. This newly created BlockReopenQueue should be
4164  * passed back in for subsequent calls that are intended to be of the same
4165  * atomic 'set'.
4166  *
4167  * bs is the BlockDriverState to add to the reopen queue.
4168  *
4169  * options contains the changed options for the associated bs
4170  * (the BlockReopenQueue takes ownership)
4171  *
4172  * flags contains the open flags for the associated bs
4173  *
4174  * returns a pointer to bs_queue, which is either the newly allocated
4175  * bs_queue, or the existing bs_queue being used.
4176  *
4177  * bs is drained here and undrained by bdrv_reopen_queue_free().
4178  *
4179  * To be called with bs->aio_context locked.
4180  */
4181 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4182                                                  BlockDriverState *bs,
4183                                                  QDict *options,
4184                                                  const BdrvChildClass *klass,
4185                                                  BdrvChildRole role,
4186                                                  bool parent_is_format,
4187                                                  QDict *parent_options,
4188                                                  int parent_flags,
4189                                                  bool keep_old_opts)
4190 {
4191     assert(bs != NULL);
4192 
4193     BlockReopenQueueEntry *bs_entry;
4194     BdrvChild *child;
4195     QDict *old_options, *explicit_options, *options_copy;
4196     int flags;
4197     QemuOpts *opts;
4198 
4199     GLOBAL_STATE_CODE();
4200 
4201     bdrv_drained_begin(bs);
4202 
4203     if (bs_queue == NULL) {
4204         bs_queue = g_new0(BlockReopenQueue, 1);
4205         QTAILQ_INIT(bs_queue);
4206     }
4207 
4208     if (!options) {
4209         options = qdict_new();
4210     }
4211 
4212     /* Check if this BlockDriverState is already in the queue */
4213     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4214         if (bs == bs_entry->state.bs) {
4215             break;
4216         }
4217     }
4218 
4219     /*
4220      * Precedence of options:
4221      * 1. Explicitly passed in options (highest)
4222      * 2. Retained from explicitly set options of bs
4223      * 3. Inherited from parent node
4224      * 4. Retained from effective options of bs
4225      */
4226 
4227     /* Old explicitly set values (don't overwrite by inherited value) */
4228     if (bs_entry || keep_old_opts) {
4229         old_options = qdict_clone_shallow(bs_entry ?
4230                                           bs_entry->state.explicit_options :
4231                                           bs->explicit_options);
4232         bdrv_join_options(bs, options, old_options);
4233         qobject_unref(old_options);
4234     }
4235 
4236     explicit_options = qdict_clone_shallow(options);
4237 
4238     /* Inherit from parent node */
4239     if (parent_options) {
4240         flags = 0;
4241         klass->inherit_options(role, parent_is_format, &flags, options,
4242                                parent_flags, parent_options);
4243     } else {
4244         flags = bdrv_get_flags(bs);
4245     }
4246 
4247     if (keep_old_opts) {
4248         /* Old values are used for options that aren't set yet */
4249         old_options = qdict_clone_shallow(bs->options);
4250         bdrv_join_options(bs, options, old_options);
4251         qobject_unref(old_options);
4252     }
4253 
4254     /* We have the final set of options so let's update the flags */
4255     options_copy = qdict_clone_shallow(options);
4256     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4257     qemu_opts_absorb_qdict(opts, options_copy, NULL);
4258     update_flags_from_options(&flags, opts);
4259     qemu_opts_del(opts);
4260     qobject_unref(options_copy);
4261 
4262     /* bdrv_open_inherit() sets and clears some additional flags internally */
4263     flags &= ~BDRV_O_PROTOCOL;
4264     if (flags & BDRV_O_RDWR) {
4265         flags |= BDRV_O_ALLOW_RDWR;
4266     }
4267 
4268     if (!bs_entry) {
4269         bs_entry = g_new0(BlockReopenQueueEntry, 1);
4270         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4271     } else {
4272         qobject_unref(bs_entry->state.options);
4273         qobject_unref(bs_entry->state.explicit_options);
4274     }
4275 
4276     bs_entry->state.bs = bs;
4277     bs_entry->state.options = options;
4278     bs_entry->state.explicit_options = explicit_options;
4279     bs_entry->state.flags = flags;
4280 
4281     /*
4282      * If keep_old_opts is false then it means that unspecified
4283      * options must be reset to their original value. We don't allow
4284      * resetting 'backing' but we need to know if the option is
4285      * missing in order to decide if we have to return an error.
4286      */
4287     if (!keep_old_opts) {
4288         bs_entry->state.backing_missing =
4289             !qdict_haskey(options, "backing") &&
4290             !qdict_haskey(options, "backing.driver");
4291     }
4292 
4293     QLIST_FOREACH(child, &bs->children, next) {
4294         QDict *new_child_options = NULL;
4295         bool child_keep_old = keep_old_opts;
4296 
4297         /* reopen can only change the options of block devices that were
4298          * implicitly created and inherited options. For other (referenced)
4299          * block devices, a syntax like "backing.foo" results in an error. */
4300         if (child->bs->inherits_from != bs) {
4301             continue;
4302         }
4303 
4304         /* Check if the options contain a child reference */
4305         if (qdict_haskey(options, child->name)) {
4306             const char *childref = qdict_get_try_str(options, child->name);
4307             /*
4308              * The current child must not be reopened if the child
4309              * reference is null or points to a different node.
4310              */
4311             if (g_strcmp0(childref, child->bs->node_name)) {
4312                 continue;
4313             }
4314             /*
4315              * If the child reference points to the current child then
4316              * reopen it with its existing set of options (note that
4317              * it can still inherit new options from the parent).
4318              */
4319             child_keep_old = true;
4320         } else {
4321             /* Extract child options ("child-name.*") */
4322             char *child_key_dot = g_strdup_printf("%s.", child->name);
4323             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4324             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4325             g_free(child_key_dot);
4326         }
4327 
4328         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4329                                 child->klass, child->role, bs->drv->is_format,
4330                                 options, flags, child_keep_old);
4331     }
4332 
4333     return bs_queue;
4334 }
4335 
4336 /* To be called with bs->aio_context locked */
4337 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4338                                     BlockDriverState *bs,
4339                                     QDict *options, bool keep_old_opts)
4340 {
4341     GLOBAL_STATE_CODE();
4342 
4343     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4344                                    NULL, 0, keep_old_opts);
4345 }
4346 
4347 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4348 {
4349     GLOBAL_STATE_CODE();
4350     if (bs_queue) {
4351         BlockReopenQueueEntry *bs_entry, *next;
4352         QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4353             AioContext *ctx = bdrv_get_aio_context(bs_entry->state.bs);
4354 
4355             aio_context_acquire(ctx);
4356             bdrv_drained_end(bs_entry->state.bs);
4357             aio_context_release(ctx);
4358 
4359             qobject_unref(bs_entry->state.explicit_options);
4360             qobject_unref(bs_entry->state.options);
4361             g_free(bs_entry);
4362         }
4363         g_free(bs_queue);
4364     }
4365 }
4366 
4367 /*
4368  * Reopen multiple BlockDriverStates atomically & transactionally.
4369  *
4370  * The queue passed in (bs_queue) must have been built up previous
4371  * via bdrv_reopen_queue().
4372  *
4373  * Reopens all BDS specified in the queue, with the appropriate
4374  * flags.  All devices are prepared for reopen, and failure of any
4375  * device will cause all device changes to be abandoned, and intermediate
4376  * data cleaned up.
4377  *
4378  * If all devices prepare successfully, then the changes are committed
4379  * to all devices.
4380  *
4381  * All affected nodes must be drained between bdrv_reopen_queue() and
4382  * bdrv_reopen_multiple().
4383  *
4384  * To be called from the main thread, with all other AioContexts unlocked.
4385  */
4386 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4387 {
4388     int ret = -1;
4389     BlockReopenQueueEntry *bs_entry, *next;
4390     AioContext *ctx;
4391     Transaction *tran = tran_new();
4392     g_autoptr(GSList) refresh_list = NULL;
4393 
4394     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4395     assert(bs_queue != NULL);
4396     GLOBAL_STATE_CODE();
4397 
4398     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4399         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4400         aio_context_acquire(ctx);
4401         ret = bdrv_flush(bs_entry->state.bs);
4402         aio_context_release(ctx);
4403         if (ret < 0) {
4404             error_setg_errno(errp, -ret, "Error flushing drive");
4405             goto abort;
4406         }
4407     }
4408 
4409     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4410         assert(bs_entry->state.bs->quiesce_counter > 0);
4411         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4412         aio_context_acquire(ctx);
4413         ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4414         aio_context_release(ctx);
4415         if (ret < 0) {
4416             goto abort;
4417         }
4418         bs_entry->prepared = true;
4419     }
4420 
4421     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4422         BDRVReopenState *state = &bs_entry->state;
4423 
4424         refresh_list = g_slist_prepend(refresh_list, state->bs);
4425         if (state->old_backing_bs) {
4426             refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
4427         }
4428         if (state->old_file_bs) {
4429             refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4430         }
4431     }
4432 
4433     /*
4434      * Note that file-posix driver rely on permission update done during reopen
4435      * (even if no permission changed), because it wants "new" permissions for
4436      * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4437      * in raw_reopen_prepare() which is called with "old" permissions.
4438      */
4439     ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4440     if (ret < 0) {
4441         goto abort;
4442     }
4443 
4444     /*
4445      * If we reach this point, we have success and just need to apply the
4446      * changes.
4447      *
4448      * Reverse order is used to comfort qcow2 driver: on commit it need to write
4449      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4450      * children are usually goes after parents in reopen-queue, so go from last
4451      * to first element.
4452      */
4453     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4454         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4455         aio_context_acquire(ctx);
4456         bdrv_reopen_commit(&bs_entry->state);
4457         aio_context_release(ctx);
4458     }
4459 
4460     tran_commit(tran);
4461 
4462     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4463         BlockDriverState *bs = bs_entry->state.bs;
4464 
4465         if (bs->drv->bdrv_reopen_commit_post) {
4466             ctx = bdrv_get_aio_context(bs);
4467             aio_context_acquire(ctx);
4468             bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4469             aio_context_release(ctx);
4470         }
4471     }
4472 
4473     ret = 0;
4474     goto cleanup;
4475 
4476 abort:
4477     tran_abort(tran);
4478     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4479         if (bs_entry->prepared) {
4480             ctx = bdrv_get_aio_context(bs_entry->state.bs);
4481             aio_context_acquire(ctx);
4482             bdrv_reopen_abort(&bs_entry->state);
4483             aio_context_release(ctx);
4484         }
4485     }
4486 
4487 cleanup:
4488     bdrv_reopen_queue_free(bs_queue);
4489 
4490     return ret;
4491 }
4492 
4493 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4494                 Error **errp)
4495 {
4496     AioContext *ctx = bdrv_get_aio_context(bs);
4497     BlockReopenQueue *queue;
4498     int ret;
4499 
4500     GLOBAL_STATE_CODE();
4501 
4502     queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4503 
4504     if (ctx != qemu_get_aio_context()) {
4505         aio_context_release(ctx);
4506     }
4507     ret = bdrv_reopen_multiple(queue, errp);
4508 
4509     if (ctx != qemu_get_aio_context()) {
4510         aio_context_acquire(ctx);
4511     }
4512 
4513     return ret;
4514 }
4515 
4516 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4517                               Error **errp)
4518 {
4519     QDict *opts = qdict_new();
4520 
4521     GLOBAL_STATE_CODE();
4522 
4523     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4524 
4525     return bdrv_reopen(bs, opts, true, errp);
4526 }
4527 
4528 /*
4529  * Take a BDRVReopenState and check if the value of 'backing' in the
4530  * reopen_state->options QDict is valid or not.
4531  *
4532  * If 'backing' is missing from the QDict then return 0.
4533  *
4534  * If 'backing' contains the node name of the backing file of
4535  * reopen_state->bs then return 0.
4536  *
4537  * If 'backing' contains a different node name (or is null) then check
4538  * whether the current backing file can be replaced with the new one.
4539  * If that's the case then reopen_state->replace_backing_bs is set to
4540  * true and reopen_state->new_backing_bs contains a pointer to the new
4541  * backing BlockDriverState (or NULL).
4542  *
4543  * Return 0 on success, otherwise return < 0 and set @errp.
4544  */
4545 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4546                                              bool is_backing, Transaction *tran,
4547                                              Error **errp)
4548 {
4549     BlockDriverState *bs = reopen_state->bs;
4550     BlockDriverState *new_child_bs;
4551     BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4552                                                   child_bs(bs->file);
4553     const char *child_name = is_backing ? "backing" : "file";
4554     QObject *value;
4555     const char *str;
4556 
4557     GLOBAL_STATE_CODE();
4558 
4559     value = qdict_get(reopen_state->options, child_name);
4560     if (value == NULL) {
4561         return 0;
4562     }
4563 
4564     switch (qobject_type(value)) {
4565     case QTYPE_QNULL:
4566         assert(is_backing); /* The 'file' option does not allow a null value */
4567         new_child_bs = NULL;
4568         break;
4569     case QTYPE_QSTRING:
4570         str = qstring_get_str(qobject_to(QString, value));
4571         new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4572         if (new_child_bs == NULL) {
4573             return -EINVAL;
4574         } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4575             error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4576                        "cycle", str, child_name, bs->node_name);
4577             return -EINVAL;
4578         }
4579         break;
4580     default:
4581         /*
4582          * The options QDict has been flattened, so 'backing' and 'file'
4583          * do not allow any other data type here.
4584          */
4585         g_assert_not_reached();
4586     }
4587 
4588     if (old_child_bs == new_child_bs) {
4589         return 0;
4590     }
4591 
4592     if (old_child_bs) {
4593         if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4594             return 0;
4595         }
4596 
4597         if (old_child_bs->implicit) {
4598             error_setg(errp, "Cannot replace implicit %s child of %s",
4599                        child_name, bs->node_name);
4600             return -EPERM;
4601         }
4602     }
4603 
4604     if (bs->drv->is_filter && !old_child_bs) {
4605         /*
4606          * Filters always have a file or a backing child, so we are trying to
4607          * change wrong child
4608          */
4609         error_setg(errp, "'%s' is a %s filter node that does not support a "
4610                    "%s child", bs->node_name, bs->drv->format_name, child_name);
4611         return -EINVAL;
4612     }
4613 
4614     if (is_backing) {
4615         reopen_state->old_backing_bs = old_child_bs;
4616     } else {
4617         reopen_state->old_file_bs = old_child_bs;
4618     }
4619 
4620     return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4621                                            tran, errp);
4622 }
4623 
4624 /*
4625  * Prepares a BlockDriverState for reopen. All changes are staged in the
4626  * 'opaque' field of the BDRVReopenState, which is used and allocated by
4627  * the block driver layer .bdrv_reopen_prepare()
4628  *
4629  * bs is the BlockDriverState to reopen
4630  * flags are the new open flags
4631  * queue is the reopen queue
4632  *
4633  * Returns 0 on success, non-zero on error.  On error errp will be set
4634  * as well.
4635  *
4636  * On failure, bdrv_reopen_abort() will be called to clean up any data.
4637  * It is the responsibility of the caller to then call the abort() or
4638  * commit() for any other BDS that have been left in a prepare() state
4639  *
4640  */
4641 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4642                                BlockReopenQueue *queue,
4643                                Transaction *change_child_tran, Error **errp)
4644 {
4645     int ret = -1;
4646     int old_flags;
4647     Error *local_err = NULL;
4648     BlockDriver *drv;
4649     QemuOpts *opts;
4650     QDict *orig_reopen_opts;
4651     char *discard = NULL;
4652     bool read_only;
4653     bool drv_prepared = false;
4654 
4655     assert(reopen_state != NULL);
4656     assert(reopen_state->bs->drv != NULL);
4657     GLOBAL_STATE_CODE();
4658     drv = reopen_state->bs->drv;
4659 
4660     /* This function and each driver's bdrv_reopen_prepare() remove
4661      * entries from reopen_state->options as they are processed, so
4662      * we need to make a copy of the original QDict. */
4663     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4664 
4665     /* Process generic block layer options */
4666     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4667     if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4668         ret = -EINVAL;
4669         goto error;
4670     }
4671 
4672     /* This was already called in bdrv_reopen_queue_child() so the flags
4673      * are up-to-date. This time we simply want to remove the options from
4674      * QemuOpts in order to indicate that they have been processed. */
4675     old_flags = reopen_state->flags;
4676     update_flags_from_options(&reopen_state->flags, opts);
4677     assert(old_flags == reopen_state->flags);
4678 
4679     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4680     if (discard != NULL) {
4681         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4682             error_setg(errp, "Invalid discard option");
4683             ret = -EINVAL;
4684             goto error;
4685         }
4686     }
4687 
4688     reopen_state->detect_zeroes =
4689         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4690     if (local_err) {
4691         error_propagate(errp, local_err);
4692         ret = -EINVAL;
4693         goto error;
4694     }
4695 
4696     /* All other options (including node-name and driver) must be unchanged.
4697      * Put them back into the QDict, so that they are checked at the end
4698      * of this function. */
4699     qemu_opts_to_qdict(opts, reopen_state->options);
4700 
4701     /* If we are to stay read-only, do not allow permission change
4702      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4703      * not set, or if the BDS still has copy_on_read enabled */
4704     read_only = !(reopen_state->flags & BDRV_O_RDWR);
4705     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4706     if (local_err) {
4707         error_propagate(errp, local_err);
4708         goto error;
4709     }
4710 
4711     if (drv->bdrv_reopen_prepare) {
4712         /*
4713          * If a driver-specific option is missing, it means that we
4714          * should reset it to its default value.
4715          * But not all options allow that, so we need to check it first.
4716          */
4717         ret = bdrv_reset_options_allowed(reopen_state->bs,
4718                                          reopen_state->options, errp);
4719         if (ret) {
4720             goto error;
4721         }
4722 
4723         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4724         if (ret) {
4725             if (local_err != NULL) {
4726                 error_propagate(errp, local_err);
4727             } else {
4728                 bdrv_refresh_filename(reopen_state->bs);
4729                 error_setg(errp, "failed while preparing to reopen image '%s'",
4730                            reopen_state->bs->filename);
4731             }
4732             goto error;
4733         }
4734     } else {
4735         /* It is currently mandatory to have a bdrv_reopen_prepare()
4736          * handler for each supported drv. */
4737         error_setg(errp, "Block format '%s' used by node '%s' "
4738                    "does not support reopening files", drv->format_name,
4739                    bdrv_get_device_or_node_name(reopen_state->bs));
4740         ret = -1;
4741         goto error;
4742     }
4743 
4744     drv_prepared = true;
4745 
4746     /*
4747      * We must provide the 'backing' option if the BDS has a backing
4748      * file or if the image file has a backing file name as part of
4749      * its metadata. Otherwise the 'backing' option can be omitted.
4750      */
4751     if (drv->supports_backing && reopen_state->backing_missing &&
4752         (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4753         error_setg(errp, "backing is missing for '%s'",
4754                    reopen_state->bs->node_name);
4755         ret = -EINVAL;
4756         goto error;
4757     }
4758 
4759     /*
4760      * Allow changing the 'backing' option. The new value can be
4761      * either a reference to an existing node (using its node name)
4762      * or NULL to simply detach the current backing file.
4763      */
4764     ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4765                                             change_child_tran, errp);
4766     if (ret < 0) {
4767         goto error;
4768     }
4769     qdict_del(reopen_state->options, "backing");
4770 
4771     /* Allow changing the 'file' option. In this case NULL is not allowed */
4772     ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4773                                             change_child_tran, errp);
4774     if (ret < 0) {
4775         goto error;
4776     }
4777     qdict_del(reopen_state->options, "file");
4778 
4779     /* Options that are not handled are only okay if they are unchanged
4780      * compared to the old state. It is expected that some options are only
4781      * used for the initial open, but not reopen (e.g. filename) */
4782     if (qdict_size(reopen_state->options)) {
4783         const QDictEntry *entry = qdict_first(reopen_state->options);
4784 
4785         do {
4786             QObject *new = entry->value;
4787             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4788 
4789             /* Allow child references (child_name=node_name) as long as they
4790              * point to the current child (i.e. everything stays the same). */
4791             if (qobject_type(new) == QTYPE_QSTRING) {
4792                 BdrvChild *child;
4793                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4794                     if (!strcmp(child->name, entry->key)) {
4795                         break;
4796                     }
4797                 }
4798 
4799                 if (child) {
4800                     if (!strcmp(child->bs->node_name,
4801                                 qstring_get_str(qobject_to(QString, new)))) {
4802                         continue; /* Found child with this name, skip option */
4803                     }
4804                 }
4805             }
4806 
4807             /*
4808              * TODO: When using -drive to specify blockdev options, all values
4809              * will be strings; however, when using -blockdev, blockdev-add or
4810              * filenames using the json:{} pseudo-protocol, they will be
4811              * correctly typed.
4812              * In contrast, reopening options are (currently) always strings
4813              * (because you can only specify them through qemu-io; all other
4814              * callers do not specify any options).
4815              * Therefore, when using anything other than -drive to create a BDS,
4816              * this cannot detect non-string options as unchanged, because
4817              * qobject_is_equal() always returns false for objects of different
4818              * type.  In the future, this should be remedied by correctly typing
4819              * all options.  For now, this is not too big of an issue because
4820              * the user can simply omit options which cannot be changed anyway,
4821              * so they will stay unchanged.
4822              */
4823             if (!qobject_is_equal(new, old)) {
4824                 error_setg(errp, "Cannot change the option '%s'", entry->key);
4825                 ret = -EINVAL;
4826                 goto error;
4827             }
4828         } while ((entry = qdict_next(reopen_state->options, entry)));
4829     }
4830 
4831     ret = 0;
4832 
4833     /* Restore the original reopen_state->options QDict */
4834     qobject_unref(reopen_state->options);
4835     reopen_state->options = qobject_ref(orig_reopen_opts);
4836 
4837 error:
4838     if (ret < 0 && drv_prepared) {
4839         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4840          * call drv->bdrv_reopen_abort() before signaling an error
4841          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4842          * when the respective bdrv_reopen_prepare() has failed) */
4843         if (drv->bdrv_reopen_abort) {
4844             drv->bdrv_reopen_abort(reopen_state);
4845         }
4846     }
4847     qemu_opts_del(opts);
4848     qobject_unref(orig_reopen_opts);
4849     g_free(discard);
4850     return ret;
4851 }
4852 
4853 /*
4854  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4855  * makes them final by swapping the staging BlockDriverState contents into
4856  * the active BlockDriverState contents.
4857  */
4858 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4859 {
4860     BlockDriver *drv;
4861     BlockDriverState *bs;
4862     BdrvChild *child;
4863 
4864     assert(reopen_state != NULL);
4865     bs = reopen_state->bs;
4866     drv = bs->drv;
4867     assert(drv != NULL);
4868     GLOBAL_STATE_CODE();
4869 
4870     /* If there are any driver level actions to take */
4871     if (drv->bdrv_reopen_commit) {
4872         drv->bdrv_reopen_commit(reopen_state);
4873     }
4874 
4875     /* set BDS specific flags now */
4876     qobject_unref(bs->explicit_options);
4877     qobject_unref(bs->options);
4878     qobject_ref(reopen_state->explicit_options);
4879     qobject_ref(reopen_state->options);
4880 
4881     bs->explicit_options   = reopen_state->explicit_options;
4882     bs->options            = reopen_state->options;
4883     bs->open_flags         = reopen_state->flags;
4884     bs->detect_zeroes      = reopen_state->detect_zeroes;
4885 
4886     /* Remove child references from bs->options and bs->explicit_options.
4887      * Child options were already removed in bdrv_reopen_queue_child() */
4888     QLIST_FOREACH(child, &bs->children, next) {
4889         qdict_del(bs->explicit_options, child->name);
4890         qdict_del(bs->options, child->name);
4891     }
4892     /* backing is probably removed, so it's not handled by previous loop */
4893     qdict_del(bs->explicit_options, "backing");
4894     qdict_del(bs->options, "backing");
4895 
4896     bdrv_refresh_limits(bs, NULL, NULL);
4897 }
4898 
4899 /*
4900  * Abort the reopen, and delete and free the staged changes in
4901  * reopen_state
4902  */
4903 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4904 {
4905     BlockDriver *drv;
4906 
4907     assert(reopen_state != NULL);
4908     drv = reopen_state->bs->drv;
4909     assert(drv != NULL);
4910     GLOBAL_STATE_CODE();
4911 
4912     if (drv->bdrv_reopen_abort) {
4913         drv->bdrv_reopen_abort(reopen_state);
4914     }
4915 }
4916 
4917 
4918 static void bdrv_close(BlockDriverState *bs)
4919 {
4920     BdrvAioNotifier *ban, *ban_next;
4921     BdrvChild *child, *next;
4922 
4923     GLOBAL_STATE_CODE();
4924     assert(!bs->refcnt);
4925 
4926     bdrv_drained_begin(bs); /* complete I/O */
4927     bdrv_flush(bs);
4928     bdrv_drain(bs); /* in case flush left pending I/O */
4929 
4930     if (bs->drv) {
4931         if (bs->drv->bdrv_close) {
4932             /* Must unfreeze all children, so bdrv_unref_child() works */
4933             bs->drv->bdrv_close(bs);
4934         }
4935         bs->drv = NULL;
4936     }
4937 
4938     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4939         bdrv_unref_child(bs, child);
4940     }
4941 
4942     assert(!bs->backing);
4943     assert(!bs->file);
4944     g_free(bs->opaque);
4945     bs->opaque = NULL;
4946     qatomic_set(&bs->copy_on_read, 0);
4947     bs->backing_file[0] = '\0';
4948     bs->backing_format[0] = '\0';
4949     bs->total_sectors = 0;
4950     bs->encrypted = false;
4951     bs->sg = false;
4952     qobject_unref(bs->options);
4953     qobject_unref(bs->explicit_options);
4954     bs->options = NULL;
4955     bs->explicit_options = NULL;
4956     qobject_unref(bs->full_open_options);
4957     bs->full_open_options = NULL;
4958     g_free(bs->block_status_cache);
4959     bs->block_status_cache = NULL;
4960 
4961     bdrv_release_named_dirty_bitmaps(bs);
4962     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4963 
4964     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4965         g_free(ban);
4966     }
4967     QLIST_INIT(&bs->aio_notifiers);
4968     bdrv_drained_end(bs);
4969 
4970     /*
4971      * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4972      * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4973      * gets called.
4974      */
4975     if (bs->quiesce_counter) {
4976         bdrv_drain_all_end_quiesce(bs);
4977     }
4978 }
4979 
4980 void bdrv_close_all(void)
4981 {
4982     GLOBAL_STATE_CODE();
4983     assert(job_next(NULL) == NULL);
4984 
4985     /* Drop references from requests still in flight, such as canceled block
4986      * jobs whose AIO context has not been polled yet */
4987     bdrv_drain_all();
4988 
4989     blk_remove_all_bs();
4990     blockdev_close_all_bdrv_states();
4991 
4992     assert(QTAILQ_EMPTY(&all_bdrv_states));
4993 }
4994 
4995 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4996 {
4997     GQueue *queue;
4998     GHashTable *found;
4999     bool ret;
5000 
5001     if (c->klass->stay_at_node) {
5002         return false;
5003     }
5004 
5005     /* If the child @c belongs to the BDS @to, replacing the current
5006      * c->bs by @to would mean to create a loop.
5007      *
5008      * Such a case occurs when appending a BDS to a backing chain.
5009      * For instance, imagine the following chain:
5010      *
5011      *   guest device -> node A -> further backing chain...
5012      *
5013      * Now we create a new BDS B which we want to put on top of this
5014      * chain, so we first attach A as its backing node:
5015      *
5016      *                   node B
5017      *                     |
5018      *                     v
5019      *   guest device -> node A -> further backing chain...
5020      *
5021      * Finally we want to replace A by B.  When doing that, we want to
5022      * replace all pointers to A by pointers to B -- except for the
5023      * pointer from B because (1) that would create a loop, and (2)
5024      * that pointer should simply stay intact:
5025      *
5026      *   guest device -> node B
5027      *                     |
5028      *                     v
5029      *                   node A -> further backing chain...
5030      *
5031      * In general, when replacing a node A (c->bs) by a node B (@to),
5032      * if A is a child of B, that means we cannot replace A by B there
5033      * because that would create a loop.  Silently detaching A from B
5034      * is also not really an option.  So overall just leaving A in
5035      * place there is the most sensible choice.
5036      *
5037      * We would also create a loop in any cases where @c is only
5038      * indirectly referenced by @to. Prevent this by returning false
5039      * if @c is found (by breadth-first search) anywhere in the whole
5040      * subtree of @to.
5041      */
5042 
5043     ret = true;
5044     found = g_hash_table_new(NULL, NULL);
5045     g_hash_table_add(found, to);
5046     queue = g_queue_new();
5047     g_queue_push_tail(queue, to);
5048 
5049     while (!g_queue_is_empty(queue)) {
5050         BlockDriverState *v = g_queue_pop_head(queue);
5051         BdrvChild *c2;
5052 
5053         QLIST_FOREACH(c2, &v->children, next) {
5054             if (c2 == c) {
5055                 ret = false;
5056                 break;
5057             }
5058 
5059             if (g_hash_table_contains(found, c2->bs)) {
5060                 continue;
5061             }
5062 
5063             g_queue_push_tail(queue, c2->bs);
5064             g_hash_table_add(found, c2->bs);
5065         }
5066     }
5067 
5068     g_queue_free(queue);
5069     g_hash_table_destroy(found);
5070 
5071     return ret;
5072 }
5073 
5074 static void bdrv_remove_child_commit(void *opaque)
5075 {
5076     GLOBAL_STATE_CODE();
5077     bdrv_child_free(opaque);
5078 }
5079 
5080 static TransactionActionDrv bdrv_remove_child_drv = {
5081     .commit = bdrv_remove_child_commit,
5082 };
5083 
5084 /* Function doesn't update permissions, caller is responsible for this. */
5085 static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
5086 {
5087     if (!child) {
5088         return;
5089     }
5090 
5091     if (child->bs) {
5092         bdrv_replace_child_tran(child, NULL, tran);
5093     }
5094 
5095     tran_add(tran, &bdrv_remove_child_drv, child);
5096 }
5097 
5098 static int bdrv_replace_node_noperm(BlockDriverState *from,
5099                                     BlockDriverState *to,
5100                                     bool auto_skip, Transaction *tran,
5101                                     Error **errp)
5102 {
5103     BdrvChild *c, *next;
5104 
5105     GLOBAL_STATE_CODE();
5106 
5107     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5108         assert(c->bs == from);
5109         if (!should_update_child(c, to)) {
5110             if (auto_skip) {
5111                 continue;
5112             }
5113             error_setg(errp, "Should not change '%s' link to '%s'",
5114                        c->name, from->node_name);
5115             return -EINVAL;
5116         }
5117         if (c->frozen) {
5118             error_setg(errp, "Cannot change '%s' link to '%s'",
5119                        c->name, from->node_name);
5120             return -EPERM;
5121         }
5122         bdrv_replace_child_tran(c, to, tran);
5123     }
5124 
5125     return 0;
5126 }
5127 
5128 /*
5129  * With auto_skip=true bdrv_replace_node_common skips updating from parents
5130  * if it creates a parent-child relation loop or if parent is block-job.
5131  *
5132  * With auto_skip=false the error is returned if from has a parent which should
5133  * not be updated.
5134  *
5135  * With @detach_subchain=true @to must be in a backing chain of @from. In this
5136  * case backing link of the cow-parent of @to is removed.
5137  */
5138 static int bdrv_replace_node_common(BlockDriverState *from,
5139                                     BlockDriverState *to,
5140                                     bool auto_skip, bool detach_subchain,
5141                                     Error **errp)
5142 {
5143     Transaction *tran = tran_new();
5144     g_autoptr(GSList) refresh_list = NULL;
5145     BlockDriverState *to_cow_parent = NULL;
5146     int ret;
5147 
5148     GLOBAL_STATE_CODE();
5149 
5150     if (detach_subchain) {
5151         assert(bdrv_chain_contains(from, to));
5152         assert(from != to);
5153         for (to_cow_parent = from;
5154              bdrv_filter_or_cow_bs(to_cow_parent) != to;
5155              to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5156         {
5157             ;
5158         }
5159     }
5160 
5161     /* Make sure that @from doesn't go away until we have successfully attached
5162      * all of its parents to @to. */
5163     bdrv_ref(from);
5164 
5165     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5166     assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5167     bdrv_drained_begin(from);
5168 
5169     /*
5170      * Do the replacement without permission update.
5171      * Replacement may influence the permissions, we should calculate new
5172      * permissions based on new graph. If we fail, we'll roll-back the
5173      * replacement.
5174      */
5175     ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5176     if (ret < 0) {
5177         goto out;
5178     }
5179 
5180     if (detach_subchain) {
5181         bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
5182     }
5183 
5184     refresh_list = g_slist_prepend(refresh_list, to);
5185     refresh_list = g_slist_prepend(refresh_list, 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     BdrvChild *child;
5236     Transaction *tran = tran_new();
5237 
5238     GLOBAL_STATE_CODE();
5239 
5240     assert(!bs_new->backing);
5241 
5242     child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5243                                      &child_of_bds, bdrv_backing_role(bs_new),
5244                                      tran, errp);
5245     if (!child) {
5246         ret = -EINVAL;
5247         goto out;
5248     }
5249 
5250     ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5251     if (ret < 0) {
5252         goto out;
5253     }
5254 
5255     ret = bdrv_refresh_perms(bs_new, tran, errp);
5256 out:
5257     tran_finalize(tran, ret);
5258 
5259     bdrv_refresh_limits(bs_top, NULL, NULL);
5260 
5261     return ret;
5262 }
5263 
5264 /* Not for empty child */
5265 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5266                           Error **errp)
5267 {
5268     int ret;
5269     Transaction *tran = tran_new();
5270     g_autoptr(GSList) refresh_list = NULL;
5271     BlockDriverState *old_bs = child->bs;
5272 
5273     GLOBAL_STATE_CODE();
5274 
5275     bdrv_ref(old_bs);
5276     bdrv_drained_begin(old_bs);
5277     bdrv_drained_begin(new_bs);
5278 
5279     bdrv_replace_child_tran(child, new_bs, tran);
5280 
5281     refresh_list = g_slist_prepend(refresh_list, old_bs);
5282     refresh_list = g_slist_prepend(refresh_list, 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_drained_begin(base);
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_drained_end(base);
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, NULL, 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, 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     assert_bdrv_graph_writable(bs);
7191     bs->aio_context = NULL;
7192 }
7193 
7194 static void bdrv_attach_aio_context(BlockDriverState *bs,
7195                                     AioContext *new_context)
7196 {
7197     BdrvAioNotifier *ban, *ban_tmp;
7198     GLOBAL_STATE_CODE();
7199 
7200     if (bs->quiesce_counter) {
7201         aio_disable_external(new_context);
7202     }
7203 
7204     assert_bdrv_graph_writable(bs);
7205     bs->aio_context = new_context;
7206 
7207     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7208         bs->drv->bdrv_attach_aio_context(bs, new_context);
7209     }
7210 
7211     assert(!bs->walking_aio_notifiers);
7212     bs->walking_aio_notifiers = true;
7213     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7214         if (ban->deleted) {
7215             bdrv_do_remove_aio_context_notifier(ban);
7216         } else {
7217             ban->attached_aio_context(new_context, ban->opaque);
7218         }
7219     }
7220     bs->walking_aio_notifiers = false;
7221 }
7222 
7223 typedef struct BdrvStateSetAioContext {
7224     AioContext *new_ctx;
7225     BlockDriverState *bs;
7226 } BdrvStateSetAioContext;
7227 
7228 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7229                                            GHashTable *visited,
7230                                            Transaction *tran,
7231                                            Error **errp)
7232 {
7233     GLOBAL_STATE_CODE();
7234     if (g_hash_table_contains(visited, c)) {
7235         return true;
7236     }
7237     g_hash_table_add(visited, c);
7238 
7239     /*
7240      * A BdrvChildClass that doesn't handle AioContext changes cannot
7241      * tolerate any AioContext changes
7242      */
7243     if (!c->klass->change_aio_ctx) {
7244         char *user = bdrv_child_user_desc(c);
7245         error_setg(errp, "Changing iothreads is not supported by %s", user);
7246         g_free(user);
7247         return false;
7248     }
7249     if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7250         assert(!errp || *errp);
7251         return false;
7252     }
7253     return true;
7254 }
7255 
7256 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7257                                    GHashTable *visited, Transaction *tran,
7258                                    Error **errp)
7259 {
7260     GLOBAL_STATE_CODE();
7261     if (g_hash_table_contains(visited, c)) {
7262         return true;
7263     }
7264     g_hash_table_add(visited, c);
7265     return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7266 }
7267 
7268 static void bdrv_set_aio_context_clean(void *opaque)
7269 {
7270     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7271     BlockDriverState *bs = (BlockDriverState *) state->bs;
7272 
7273     /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7274     bdrv_drained_end(bs);
7275 
7276     g_free(state);
7277 }
7278 
7279 static void bdrv_set_aio_context_commit(void *opaque)
7280 {
7281     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7282     BlockDriverState *bs = (BlockDriverState *) state->bs;
7283     AioContext *new_context = state->new_ctx;
7284     AioContext *old_context = bdrv_get_aio_context(bs);
7285     assert_bdrv_graph_writable(bs);
7286 
7287     /*
7288      * Take the old AioContex when detaching it from bs.
7289      * At this point, new_context lock is already acquired, and we are now
7290      * also taking old_context. This is safe as long as bdrv_detach_aio_context
7291      * does not call AIO_POLL_WHILE().
7292      */
7293     if (old_context != qemu_get_aio_context()) {
7294         aio_context_acquire(old_context);
7295     }
7296     bdrv_detach_aio_context(bs);
7297     if (old_context != qemu_get_aio_context()) {
7298         aio_context_release(old_context);
7299     }
7300     bdrv_attach_aio_context(bs, new_context);
7301 }
7302 
7303 static TransactionActionDrv set_aio_context = {
7304     .commit = bdrv_set_aio_context_commit,
7305     .clean = bdrv_set_aio_context_clean,
7306 };
7307 
7308 /*
7309  * Changes the AioContext used for fd handlers, timers, and BHs by this
7310  * BlockDriverState and all its children and parents.
7311  *
7312  * Must be called from the main AioContext.
7313  *
7314  * The caller must own the AioContext lock for the old AioContext of bs, but it
7315  * must not own the AioContext lock for new_context (unless new_context is the
7316  * same as the current context of bs).
7317  *
7318  * @visited will accumulate all visited BdrvChild objects. The caller is
7319  * responsible for freeing the list afterwards.
7320  */
7321 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7322                                     GHashTable *visited, Transaction *tran,
7323                                     Error **errp)
7324 {
7325     BdrvChild *c;
7326     BdrvStateSetAioContext *state;
7327 
7328     GLOBAL_STATE_CODE();
7329 
7330     if (bdrv_get_aio_context(bs) == ctx) {
7331         return true;
7332     }
7333 
7334     QLIST_FOREACH(c, &bs->parents, next_parent) {
7335         if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7336             return false;
7337         }
7338     }
7339 
7340     QLIST_FOREACH(c, &bs->children, next) {
7341         if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7342             return false;
7343         }
7344     }
7345 
7346     state = g_new(BdrvStateSetAioContext, 1);
7347     *state = (BdrvStateSetAioContext) {
7348         .new_ctx = ctx,
7349         .bs = bs,
7350     };
7351 
7352     /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7353     bdrv_drained_begin(bs);
7354 
7355     tran_add(tran, &set_aio_context, state);
7356 
7357     return true;
7358 }
7359 
7360 /*
7361  * Change bs's and recursively all of its parents' and children's AioContext
7362  * to the given new context, returning an error if that isn't possible.
7363  *
7364  * If ignore_child is not NULL, that child (and its subgraph) will not
7365  * be touched.
7366  *
7367  * This function still requires the caller to take the bs current
7368  * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7369  * assumes the lock is always held if bs is in another AioContext.
7370  * For the same reason, it temporarily also holds the new AioContext, since
7371  * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7372  * Therefore the new AioContext lock must not be taken by the caller.
7373  */
7374 int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7375                                 BdrvChild *ignore_child, Error **errp)
7376 {
7377     Transaction *tran;
7378     GHashTable *visited;
7379     int ret;
7380     AioContext *old_context = bdrv_get_aio_context(bs);
7381     GLOBAL_STATE_CODE();
7382 
7383     /*
7384      * Recursion phase: go through all nodes of the graph.
7385      * Take care of checking that all nodes support changing AioContext
7386      * and drain them, builing a linear list of callbacks to run if everything
7387      * is successful (the transaction itself).
7388      */
7389     tran = tran_new();
7390     visited = g_hash_table_new(NULL, NULL);
7391     if (ignore_child) {
7392         g_hash_table_add(visited, ignore_child);
7393     }
7394     ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7395     g_hash_table_destroy(visited);
7396 
7397     /*
7398      * Linear phase: go through all callbacks collected in the transaction.
7399      * Run all callbacks collected in the recursion to switch all nodes
7400      * AioContext lock (transaction commit), or undo all changes done in the
7401      * recursion (transaction abort).
7402      */
7403 
7404     if (!ret) {
7405         /* Just run clean() callbacks. No AioContext changed. */
7406         tran_abort(tran);
7407         return -EPERM;
7408     }
7409 
7410     /*
7411      * Release old AioContext, it won't be needed anymore, as all
7412      * bdrv_drained_begin() have been called already.
7413      */
7414     if (qemu_get_aio_context() != old_context) {
7415         aio_context_release(old_context);
7416     }
7417 
7418     /*
7419      * Acquire new AioContext since bdrv_drained_end() is going to be called
7420      * after we switched all nodes in the new AioContext, and the function
7421      * assumes that the lock of the bs is always taken.
7422      */
7423     if (qemu_get_aio_context() != ctx) {
7424         aio_context_acquire(ctx);
7425     }
7426 
7427     tran_commit(tran);
7428 
7429     if (qemu_get_aio_context() != ctx) {
7430         aio_context_release(ctx);
7431     }
7432 
7433     /* Re-acquire the old AioContext, since the caller takes and releases it. */
7434     if (qemu_get_aio_context() != old_context) {
7435         aio_context_acquire(old_context);
7436     }
7437 
7438     return 0;
7439 }
7440 
7441 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7442         void (*attached_aio_context)(AioContext *new_context, void *opaque),
7443         void (*detach_aio_context)(void *opaque), void *opaque)
7444 {
7445     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7446     *ban = (BdrvAioNotifier){
7447         .attached_aio_context = attached_aio_context,
7448         .detach_aio_context   = detach_aio_context,
7449         .opaque               = opaque
7450     };
7451     GLOBAL_STATE_CODE();
7452 
7453     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7454 }
7455 
7456 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7457                                       void (*attached_aio_context)(AioContext *,
7458                                                                    void *),
7459                                       void (*detach_aio_context)(void *),
7460                                       void *opaque)
7461 {
7462     BdrvAioNotifier *ban, *ban_next;
7463     GLOBAL_STATE_CODE();
7464 
7465     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7466         if (ban->attached_aio_context == attached_aio_context &&
7467             ban->detach_aio_context   == detach_aio_context   &&
7468             ban->opaque               == opaque               &&
7469             ban->deleted              == false)
7470         {
7471             if (bs->walking_aio_notifiers) {
7472                 ban->deleted = true;
7473             } else {
7474                 bdrv_do_remove_aio_context_notifier(ban);
7475             }
7476             return;
7477         }
7478     }
7479 
7480     abort();
7481 }
7482 
7483 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7484                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7485                        bool force,
7486                        Error **errp)
7487 {
7488     GLOBAL_STATE_CODE();
7489     if (!bs->drv) {
7490         error_setg(errp, "Node is ejected");
7491         return -ENOMEDIUM;
7492     }
7493     if (!bs->drv->bdrv_amend_options) {
7494         error_setg(errp, "Block driver '%s' does not support option amendment",
7495                    bs->drv->format_name);
7496         return -ENOTSUP;
7497     }
7498     return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7499                                        cb_opaque, force, errp);
7500 }
7501 
7502 /*
7503  * This function checks whether the given @to_replace is allowed to be
7504  * replaced by a node that always shows the same data as @bs.  This is
7505  * used for example to verify whether the mirror job can replace
7506  * @to_replace by the target mirrored from @bs.
7507  * To be replaceable, @bs and @to_replace may either be guaranteed to
7508  * always show the same data (because they are only connected through
7509  * filters), or some driver may allow replacing one of its children
7510  * because it can guarantee that this child's data is not visible at
7511  * all (for example, for dissenting quorum children that have no other
7512  * parents).
7513  */
7514 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7515                               BlockDriverState *to_replace)
7516 {
7517     BlockDriverState *filtered;
7518 
7519     GLOBAL_STATE_CODE();
7520 
7521     if (!bs || !bs->drv) {
7522         return false;
7523     }
7524 
7525     if (bs == to_replace) {
7526         return true;
7527     }
7528 
7529     /* See what the driver can do */
7530     if (bs->drv->bdrv_recurse_can_replace) {
7531         return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7532     }
7533 
7534     /* For filters without an own implementation, we can recurse on our own */
7535     filtered = bdrv_filter_bs(bs);
7536     if (filtered) {
7537         return bdrv_recurse_can_replace(filtered, to_replace);
7538     }
7539 
7540     /* Safe default */
7541     return false;
7542 }
7543 
7544 /*
7545  * Check whether the given @node_name can be replaced by a node that
7546  * has the same data as @parent_bs.  If so, return @node_name's BDS;
7547  * NULL otherwise.
7548  *
7549  * @node_name must be a (recursive) *child of @parent_bs (or this
7550  * function will return NULL).
7551  *
7552  * The result (whether the node can be replaced or not) is only valid
7553  * for as long as no graph or permission changes occur.
7554  */
7555 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7556                                         const char *node_name, Error **errp)
7557 {
7558     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7559     AioContext *aio_context;
7560 
7561     GLOBAL_STATE_CODE();
7562 
7563     if (!to_replace_bs) {
7564         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7565         return NULL;
7566     }
7567 
7568     aio_context = bdrv_get_aio_context(to_replace_bs);
7569     aio_context_acquire(aio_context);
7570 
7571     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7572         to_replace_bs = NULL;
7573         goto out;
7574     }
7575 
7576     /* We don't want arbitrary node of the BDS chain to be replaced only the top
7577      * most non filter in order to prevent data corruption.
7578      * Another benefit is that this tests exclude backing files which are
7579      * blocked by the backing blockers.
7580      */
7581     if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7582         error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7583                    "because it cannot be guaranteed that doing so would not "
7584                    "lead to an abrupt change of visible data",
7585                    node_name, parent_bs->node_name);
7586         to_replace_bs = NULL;
7587         goto out;
7588     }
7589 
7590 out:
7591     aio_context_release(aio_context);
7592     return to_replace_bs;
7593 }
7594 
7595 /**
7596  * Iterates through the list of runtime option keys that are said to
7597  * be "strong" for a BDS.  An option is called "strong" if it changes
7598  * a BDS's data.  For example, the null block driver's "size" and
7599  * "read-zeroes" options are strong, but its "latency-ns" option is
7600  * not.
7601  *
7602  * If a key returned by this function ends with a dot, all options
7603  * starting with that prefix are strong.
7604  */
7605 static const char *const *strong_options(BlockDriverState *bs,
7606                                          const char *const *curopt)
7607 {
7608     static const char *const global_options[] = {
7609         "driver", "filename", NULL
7610     };
7611 
7612     if (!curopt) {
7613         return &global_options[0];
7614     }
7615 
7616     curopt++;
7617     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7618         curopt = bs->drv->strong_runtime_opts;
7619     }
7620 
7621     return (curopt && *curopt) ? curopt : NULL;
7622 }
7623 
7624 /**
7625  * Copies all strong runtime options from bs->options to the given
7626  * QDict.  The set of strong option keys is determined by invoking
7627  * strong_options().
7628  *
7629  * Returns true iff any strong option was present in bs->options (and
7630  * thus copied to the target QDict) with the exception of "filename"
7631  * and "driver".  The caller is expected to use this value to decide
7632  * whether the existence of strong options prevents the generation of
7633  * a plain filename.
7634  */
7635 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7636 {
7637     bool found_any = false;
7638     const char *const *option_name = NULL;
7639 
7640     if (!bs->drv) {
7641         return false;
7642     }
7643 
7644     while ((option_name = strong_options(bs, option_name))) {
7645         bool option_given = false;
7646 
7647         assert(strlen(*option_name) > 0);
7648         if ((*option_name)[strlen(*option_name) - 1] != '.') {
7649             QObject *entry = qdict_get(bs->options, *option_name);
7650             if (!entry) {
7651                 continue;
7652             }
7653 
7654             qdict_put_obj(d, *option_name, qobject_ref(entry));
7655             option_given = true;
7656         } else {
7657             const QDictEntry *entry;
7658             for (entry = qdict_first(bs->options); entry;
7659                  entry = qdict_next(bs->options, entry))
7660             {
7661                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7662                     qdict_put_obj(d, qdict_entry_key(entry),
7663                                   qobject_ref(qdict_entry_value(entry)));
7664                     option_given = true;
7665                 }
7666             }
7667         }
7668 
7669         /* While "driver" and "filename" need to be included in a JSON filename,
7670          * their existence does not prohibit generation of a plain filename. */
7671         if (!found_any && option_given &&
7672             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7673         {
7674             found_any = true;
7675         }
7676     }
7677 
7678     if (!qdict_haskey(d, "driver")) {
7679         /* Drivers created with bdrv_new_open_driver() may not have a
7680          * @driver option.  Add it here. */
7681         qdict_put_str(d, "driver", bs->drv->format_name);
7682     }
7683 
7684     return found_any;
7685 }
7686 
7687 /* Note: This function may return false positives; it may return true
7688  * even if opening the backing file specified by bs's image header
7689  * would result in exactly bs->backing. */
7690 static bool bdrv_backing_overridden(BlockDriverState *bs)
7691 {
7692     GLOBAL_STATE_CODE();
7693     if (bs->backing) {
7694         return strcmp(bs->auto_backing_file,
7695                       bs->backing->bs->filename);
7696     } else {
7697         /* No backing BDS, so if the image header reports any backing
7698          * file, it must have been suppressed */
7699         return bs->auto_backing_file[0] != '\0';
7700     }
7701 }
7702 
7703 /* Updates the following BDS fields:
7704  *  - exact_filename: A filename which may be used for opening a block device
7705  *                    which (mostly) equals the given BDS (even without any
7706  *                    other options; so reading and writing must return the same
7707  *                    results, but caching etc. may be different)
7708  *  - full_open_options: Options which, when given when opening a block device
7709  *                       (without a filename), result in a BDS (mostly)
7710  *                       equalling the given one
7711  *  - filename: If exact_filename is set, it is copied here. Otherwise,
7712  *              full_open_options is converted to a JSON object, prefixed with
7713  *              "json:" (for use through the JSON pseudo protocol) and put here.
7714  */
7715 void bdrv_refresh_filename(BlockDriverState *bs)
7716 {
7717     BlockDriver *drv = bs->drv;
7718     BdrvChild *child;
7719     BlockDriverState *primary_child_bs;
7720     QDict *opts;
7721     bool backing_overridden;
7722     bool generate_json_filename; /* Whether our default implementation should
7723                                     fill exact_filename (false) or not (true) */
7724 
7725     GLOBAL_STATE_CODE();
7726 
7727     if (!drv) {
7728         return;
7729     }
7730 
7731     /* This BDS's file name may depend on any of its children's file names, so
7732      * refresh those first */
7733     QLIST_FOREACH(child, &bs->children, next) {
7734         bdrv_refresh_filename(child->bs);
7735     }
7736 
7737     if (bs->implicit) {
7738         /* For implicit nodes, just copy everything from the single child */
7739         child = QLIST_FIRST(&bs->children);
7740         assert(QLIST_NEXT(child, next) == NULL);
7741 
7742         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7743                 child->bs->exact_filename);
7744         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7745 
7746         qobject_unref(bs->full_open_options);
7747         bs->full_open_options = qobject_ref(child->bs->full_open_options);
7748 
7749         return;
7750     }
7751 
7752     backing_overridden = bdrv_backing_overridden(bs);
7753 
7754     if (bs->open_flags & BDRV_O_NO_IO) {
7755         /* Without I/O, the backing file does not change anything.
7756          * Therefore, in such a case (primarily qemu-img), we can
7757          * pretend the backing file has not been overridden even if
7758          * it technically has been. */
7759         backing_overridden = false;
7760     }
7761 
7762     /* Gather the options QDict */
7763     opts = qdict_new();
7764     generate_json_filename = append_strong_runtime_options(opts, bs);
7765     generate_json_filename |= backing_overridden;
7766 
7767     if (drv->bdrv_gather_child_options) {
7768         /* Some block drivers may not want to present all of their children's
7769          * options, or name them differently from BdrvChild.name */
7770         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7771     } else {
7772         QLIST_FOREACH(child, &bs->children, next) {
7773             if (child == bs->backing && !backing_overridden) {
7774                 /* We can skip the backing BDS if it has not been overridden */
7775                 continue;
7776             }
7777 
7778             qdict_put(opts, child->name,
7779                       qobject_ref(child->bs->full_open_options));
7780         }
7781 
7782         if (backing_overridden && !bs->backing) {
7783             /* Force no backing file */
7784             qdict_put_null(opts, "backing");
7785         }
7786     }
7787 
7788     qobject_unref(bs->full_open_options);
7789     bs->full_open_options = opts;
7790 
7791     primary_child_bs = bdrv_primary_bs(bs);
7792 
7793     if (drv->bdrv_refresh_filename) {
7794         /* Obsolete information is of no use here, so drop the old file name
7795          * information before refreshing it */
7796         bs->exact_filename[0] = '\0';
7797 
7798         drv->bdrv_refresh_filename(bs);
7799     } else if (primary_child_bs) {
7800         /*
7801          * Try to reconstruct valid information from the underlying
7802          * file -- this only works for format nodes (filter nodes
7803          * cannot be probed and as such must be selected by the user
7804          * either through an options dict, or through a special
7805          * filename which the filter driver must construct in its
7806          * .bdrv_refresh_filename() implementation).
7807          */
7808 
7809         bs->exact_filename[0] = '\0';
7810 
7811         /*
7812          * We can use the underlying file's filename if:
7813          * - it has a filename,
7814          * - the current BDS is not a filter,
7815          * - the file is a protocol BDS, and
7816          * - opening that file (as this BDS's format) will automatically create
7817          *   the BDS tree we have right now, that is:
7818          *   - the user did not significantly change this BDS's behavior with
7819          *     some explicit (strong) options
7820          *   - no non-file child of this BDS has been overridden by the user
7821          *   Both of these conditions are represented by generate_json_filename.
7822          */
7823         if (primary_child_bs->exact_filename[0] &&
7824             primary_child_bs->drv->bdrv_file_open &&
7825             !drv->is_filter && !generate_json_filename)
7826         {
7827             strcpy(bs->exact_filename, primary_child_bs->exact_filename);
7828         }
7829     }
7830 
7831     if (bs->exact_filename[0]) {
7832         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
7833     } else {
7834         GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
7835         if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
7836                      json->str) >= sizeof(bs->filename)) {
7837             /* Give user a hint if we truncated things. */
7838             strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
7839         }
7840         g_string_free(json, true);
7841     }
7842 }
7843 
7844 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
7845 {
7846     BlockDriver *drv = bs->drv;
7847     BlockDriverState *child_bs;
7848 
7849     GLOBAL_STATE_CODE();
7850 
7851     if (!drv) {
7852         error_setg(errp, "Node '%s' is ejected", bs->node_name);
7853         return NULL;
7854     }
7855 
7856     if (drv->bdrv_dirname) {
7857         return drv->bdrv_dirname(bs, errp);
7858     }
7859 
7860     child_bs = bdrv_primary_bs(bs);
7861     if (child_bs) {
7862         return bdrv_dirname(child_bs, errp);
7863     }
7864 
7865     bdrv_refresh_filename(bs);
7866     if (bs->exact_filename[0] != '\0') {
7867         return path_combine(bs->exact_filename, "");
7868     }
7869 
7870     error_setg(errp, "Cannot generate a base directory for %s nodes",
7871                drv->format_name);
7872     return NULL;
7873 }
7874 
7875 /*
7876  * Hot add/remove a BDS's child. So the user can take a child offline when
7877  * it is broken and take a new child online
7878  */
7879 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
7880                     Error **errp)
7881 {
7882     GLOBAL_STATE_CODE();
7883     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
7884         error_setg(errp, "The node %s does not support adding a child",
7885                    bdrv_get_device_or_node_name(parent_bs));
7886         return;
7887     }
7888 
7889     if (!QLIST_EMPTY(&child_bs->parents)) {
7890         error_setg(errp, "The node %s already has a parent",
7891                    child_bs->node_name);
7892         return;
7893     }
7894 
7895     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
7896 }
7897 
7898 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
7899 {
7900     BdrvChild *tmp;
7901 
7902     GLOBAL_STATE_CODE();
7903     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
7904         error_setg(errp, "The node %s does not support removing a child",
7905                    bdrv_get_device_or_node_name(parent_bs));
7906         return;
7907     }
7908 
7909     QLIST_FOREACH(tmp, &parent_bs->children, next) {
7910         if (tmp == child) {
7911             break;
7912         }
7913     }
7914 
7915     if (!tmp) {
7916         error_setg(errp, "The node %s does not have a child named %s",
7917                    bdrv_get_device_or_node_name(parent_bs),
7918                    bdrv_get_device_or_node_name(child->bs));
7919         return;
7920     }
7921 
7922     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
7923 }
7924 
7925 int bdrv_make_empty(BdrvChild *c, Error **errp)
7926 {
7927     BlockDriver *drv = c->bs->drv;
7928     int ret;
7929 
7930     GLOBAL_STATE_CODE();
7931     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
7932 
7933     if (!drv->bdrv_make_empty) {
7934         error_setg(errp, "%s does not support emptying nodes",
7935                    drv->format_name);
7936         return -ENOTSUP;
7937     }
7938 
7939     ret = drv->bdrv_make_empty(c->bs);
7940     if (ret < 0) {
7941         error_setg_errno(errp, -ret, "Failed to empty %s",
7942                          c->bs->filename);
7943         return ret;
7944     }
7945 
7946     return 0;
7947 }
7948 
7949 /*
7950  * Return the child that @bs acts as an overlay for, and from which data may be
7951  * copied in COW or COR operations.  Usually this is the backing file.
7952  */
7953 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
7954 {
7955     IO_CODE();
7956 
7957     if (!bs || !bs->drv) {
7958         return NULL;
7959     }
7960 
7961     if (bs->drv->is_filter) {
7962         return NULL;
7963     }
7964 
7965     if (!bs->backing) {
7966         return NULL;
7967     }
7968 
7969     assert(bs->backing->role & BDRV_CHILD_COW);
7970     return bs->backing;
7971 }
7972 
7973 /*
7974  * If @bs acts as a filter for exactly one of its children, return
7975  * that child.
7976  */
7977 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
7978 {
7979     BdrvChild *c;
7980     IO_CODE();
7981 
7982     if (!bs || !bs->drv) {
7983         return NULL;
7984     }
7985 
7986     if (!bs->drv->is_filter) {
7987         return NULL;
7988     }
7989 
7990     /* Only one of @backing or @file may be used */
7991     assert(!(bs->backing && bs->file));
7992 
7993     c = bs->backing ?: bs->file;
7994     if (!c) {
7995         return NULL;
7996     }
7997 
7998     assert(c->role & BDRV_CHILD_FILTERED);
7999     return c;
8000 }
8001 
8002 /*
8003  * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8004  * whichever is non-NULL.
8005  *
8006  * Return NULL if both are NULL.
8007  */
8008 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8009 {
8010     BdrvChild *cow_child = bdrv_cow_child(bs);
8011     BdrvChild *filter_child = bdrv_filter_child(bs);
8012     IO_CODE();
8013 
8014     /* Filter nodes cannot have COW backing files */
8015     assert(!(cow_child && filter_child));
8016 
8017     return cow_child ?: filter_child;
8018 }
8019 
8020 /*
8021  * Return the primary child of this node: For filters, that is the
8022  * filtered child.  For other nodes, that is usually the child storing
8023  * metadata.
8024  * (A generally more helpful description is that this is (usually) the
8025  * child that has the same filename as @bs.)
8026  *
8027  * Drivers do not necessarily have a primary child; for example quorum
8028  * does not.
8029  */
8030 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8031 {
8032     BdrvChild *c, *found = NULL;
8033     IO_CODE();
8034 
8035     QLIST_FOREACH(c, &bs->children, next) {
8036         if (c->role & BDRV_CHILD_PRIMARY) {
8037             assert(!found);
8038             found = c;
8039         }
8040     }
8041 
8042     return found;
8043 }
8044 
8045 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8046                                               bool stop_on_explicit_filter)
8047 {
8048     BdrvChild *c;
8049 
8050     if (!bs) {
8051         return NULL;
8052     }
8053 
8054     while (!(stop_on_explicit_filter && !bs->implicit)) {
8055         c = bdrv_filter_child(bs);
8056         if (!c) {
8057             /*
8058              * A filter that is embedded in a working block graph must
8059              * have a child.  Assert this here so this function does
8060              * not return a filter node that is not expected by the
8061              * caller.
8062              */
8063             assert(!bs->drv || !bs->drv->is_filter);
8064             break;
8065         }
8066         bs = c->bs;
8067     }
8068     /*
8069      * Note that this treats nodes with bs->drv == NULL as not being
8070      * filters (bs->drv == NULL should be replaced by something else
8071      * anyway).
8072      * The advantage of this behavior is that this function will thus
8073      * always return a non-NULL value (given a non-NULL @bs).
8074      */
8075 
8076     return bs;
8077 }
8078 
8079 /*
8080  * Return the first BDS that has not been added implicitly or that
8081  * does not have a filtered child down the chain starting from @bs
8082  * (including @bs itself).
8083  */
8084 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8085 {
8086     GLOBAL_STATE_CODE();
8087     return bdrv_do_skip_filters(bs, true);
8088 }
8089 
8090 /*
8091  * Return the first BDS that does not have a filtered child down the
8092  * chain starting from @bs (including @bs itself).
8093  */
8094 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8095 {
8096     IO_CODE();
8097     return bdrv_do_skip_filters(bs, false);
8098 }
8099 
8100 /*
8101  * For a backing chain, return the first non-filter backing image of
8102  * the first non-filter image.
8103  */
8104 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8105 {
8106     IO_CODE();
8107     return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8108 }
8109 
8110 /**
8111  * Check whether [offset, offset + bytes) overlaps with the cached
8112  * block-status data region.
8113  *
8114  * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8115  * which is what bdrv_bsc_is_data()'s interface needs.
8116  * Otherwise, *pnum is not touched.
8117  */
8118 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8119                                            int64_t offset, int64_t bytes,
8120                                            int64_t *pnum)
8121 {
8122     BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8123     bool overlaps;
8124 
8125     overlaps =
8126         qatomic_read(&bsc->valid) &&
8127         ranges_overlap(offset, bytes, bsc->data_start,
8128                        bsc->data_end - bsc->data_start);
8129 
8130     if (overlaps && pnum) {
8131         *pnum = bsc->data_end - offset;
8132     }
8133 
8134     return overlaps;
8135 }
8136 
8137 /**
8138  * See block_int.h for this function's documentation.
8139  */
8140 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8141 {
8142     IO_CODE();
8143     RCU_READ_LOCK_GUARD();
8144     return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8145 }
8146 
8147 /**
8148  * See block_int.h for this function's documentation.
8149  */
8150 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8151                                int64_t offset, int64_t bytes)
8152 {
8153     IO_CODE();
8154     RCU_READ_LOCK_GUARD();
8155 
8156     if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8157         qatomic_set(&bs->block_status_cache->valid, false);
8158     }
8159 }
8160 
8161 /**
8162  * See block_int.h for this function's documentation.
8163  */
8164 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8165 {
8166     BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8167     BdrvBlockStatusCache *old_bsc;
8168     IO_CODE();
8169 
8170     *new_bsc = (BdrvBlockStatusCache) {
8171         .valid = true,
8172         .data_start = offset,
8173         .data_end = offset + bytes,
8174     };
8175 
8176     QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8177 
8178     old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8179     qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8180     if (old_bsc) {
8181         g_free_rcu(old_bsc, rcu);
8182     }
8183 }
8184