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