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