xref: /openbmc/qemu/block.c (revision f8be48adf08641f43dfb34b6abf50f9bc21fc250)
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         Transaction *tran;
2928         GHashTable *visited;
2929         bool ret;
2930 
2931         tran = tran_new();
2932 
2933         /* No need to visit `child`, because it has been detached already */
2934         visited = g_hash_table_new(NULL, NULL);
2935         ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
2936                                               visited, tran, &error_abort);
2937         g_hash_table_destroy(visited);
2938 
2939         /* transaction is supposed to always succeed */
2940         assert(ret == true);
2941         tran_commit(tran);
2942     }
2943 
2944     bdrv_unref(bs);
2945     bdrv_child_free(s->child);
2946 }
2947 
2948 static TransactionActionDrv bdrv_attach_child_common_drv = {
2949     .abort = bdrv_attach_child_common_abort,
2950     .clean = g_free,
2951 };
2952 
2953 /*
2954  * Common part of attaching bdrv child to bs or to blk or to job
2955  *
2956  * Function doesn't update permissions, caller is responsible for this.
2957  *
2958  * Returns new created child.
2959  */
2960 static BdrvChild *bdrv_attach_child_common(BlockDriverState *child_bs,
2961                                            const char *child_name,
2962                                            const BdrvChildClass *child_class,
2963                                            BdrvChildRole child_role,
2964                                            uint64_t perm, uint64_t shared_perm,
2965                                            void *opaque,
2966                                            Transaction *tran, Error **errp)
2967 {
2968     BdrvChild *new_child;
2969     AioContext *parent_ctx;
2970     AioContext *child_ctx = bdrv_get_aio_context(child_bs);
2971 
2972     assert(child_class->get_parent_desc);
2973     GLOBAL_STATE_CODE();
2974 
2975     new_child = g_new(BdrvChild, 1);
2976     *new_child = (BdrvChild) {
2977         .bs             = NULL,
2978         .name           = g_strdup(child_name),
2979         .klass          = child_class,
2980         .role           = child_role,
2981         .perm           = perm,
2982         .shared_perm    = shared_perm,
2983         .opaque         = opaque,
2984     };
2985 
2986     /*
2987      * If the AioContexts don't match, first try to move the subtree of
2988      * child_bs into the AioContext of the new parent. If this doesn't work,
2989      * try moving the parent into the AioContext of child_bs instead.
2990      */
2991     parent_ctx = bdrv_child_get_parent_aio_context(new_child);
2992     if (child_ctx != parent_ctx) {
2993         Error *local_err = NULL;
2994         int ret = bdrv_try_set_aio_context(child_bs, parent_ctx, &local_err);
2995 
2996         if (ret < 0 && child_class->change_aio_ctx) {
2997             Transaction *tran = tran_new();
2998             GHashTable *visited = g_hash_table_new(NULL, NULL);
2999             bool ret_child;
3000 
3001             g_hash_table_add(visited, new_child);
3002             ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3003                                                     visited, tran, NULL);
3004             if (ret_child == true) {
3005                 error_free(local_err);
3006                 ret = 0;
3007             }
3008             tran_finalize(tran, ret_child == true ? 0 : -1);
3009             g_hash_table_destroy(visited);
3010         }
3011 
3012         if (ret < 0) {
3013             error_propagate(errp, local_err);
3014             bdrv_child_free(new_child);
3015             return NULL;
3016         }
3017     }
3018 
3019     bdrv_ref(child_bs);
3020     bdrv_replace_child_noperm(new_child, child_bs);
3021 
3022     BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3023     *s = (BdrvAttachChildCommonState) {
3024         .child = new_child,
3025         .old_parent_ctx = parent_ctx,
3026         .old_child_ctx = child_ctx,
3027     };
3028     tran_add(tran, &bdrv_attach_child_common_drv, s);
3029 
3030     return new_child;
3031 }
3032 
3033 /*
3034  * Function doesn't update permissions, caller is responsible for this.
3035  */
3036 static BdrvChild *bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3037                                            BlockDriverState *child_bs,
3038                                            const char *child_name,
3039                                            const BdrvChildClass *child_class,
3040                                            BdrvChildRole child_role,
3041                                            Transaction *tran,
3042                                            Error **errp)
3043 {
3044     uint64_t perm, shared_perm;
3045 
3046     assert(parent_bs->drv);
3047     GLOBAL_STATE_CODE();
3048 
3049     if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3050         error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3051                    child_bs->node_name, child_name, parent_bs->node_name);
3052         return NULL;
3053     }
3054 
3055     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3056     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3057                     perm, shared_perm, &perm, &shared_perm);
3058 
3059     return bdrv_attach_child_common(child_bs, child_name, child_class,
3060                                     child_role, perm, shared_perm, parent_bs,
3061                                     tran, errp);
3062 }
3063 
3064 static void bdrv_detach_child(BdrvChild *child)
3065 {
3066     BlockDriverState *old_bs = child->bs;
3067 
3068     GLOBAL_STATE_CODE();
3069     bdrv_replace_child_noperm(child, NULL);
3070     bdrv_child_free(child);
3071 
3072     if (old_bs) {
3073         /*
3074          * Update permissions for old node. We're just taking a parent away, so
3075          * we're loosening restrictions. Errors of permission update are not
3076          * fatal in this case, ignore them.
3077          */
3078         bdrv_refresh_perms(old_bs, NULL);
3079 
3080         /*
3081          * When the parent requiring a non-default AioContext is removed, the
3082          * node moves back to the main AioContext
3083          */
3084         bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
3085     }
3086 }
3087 
3088 /*
3089  * This function steals the reference to child_bs from the caller.
3090  * That reference is later dropped by bdrv_root_unref_child().
3091  *
3092  * On failure NULL is returned, errp is set and the reference to
3093  * child_bs is also dropped.
3094  *
3095  * The caller must hold the AioContext lock @child_bs, but not that of @ctx
3096  * (unless @child_bs is already in @ctx).
3097  */
3098 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3099                                   const char *child_name,
3100                                   const BdrvChildClass *child_class,
3101                                   BdrvChildRole child_role,
3102                                   uint64_t perm, uint64_t shared_perm,
3103                                   void *opaque, Error **errp)
3104 {
3105     int ret;
3106     BdrvChild *child;
3107     Transaction *tran = tran_new();
3108 
3109     GLOBAL_STATE_CODE();
3110 
3111     child = bdrv_attach_child_common(child_bs, child_name, child_class,
3112                                    child_role, perm, shared_perm, opaque,
3113                                    tran, errp);
3114     if (!child) {
3115         ret = -EINVAL;
3116         goto out;
3117     }
3118 
3119     ret = bdrv_refresh_perms(child_bs, errp);
3120 
3121 out:
3122     tran_finalize(tran, ret);
3123 
3124     bdrv_unref(child_bs);
3125 
3126     return ret < 0 ? NULL : child;
3127 }
3128 
3129 /*
3130  * This function transfers the reference to child_bs from the caller
3131  * to parent_bs. That reference is later dropped by parent_bs on
3132  * bdrv_close() or if someone calls bdrv_unref_child().
3133  *
3134  * On failure NULL is returned, errp is set and the reference to
3135  * child_bs is also dropped.
3136  *
3137  * If @parent_bs and @child_bs are in different AioContexts, the caller must
3138  * hold the AioContext lock for @child_bs, but not for @parent_bs.
3139  */
3140 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3141                              BlockDriverState *child_bs,
3142                              const char *child_name,
3143                              const BdrvChildClass *child_class,
3144                              BdrvChildRole child_role,
3145                              Error **errp)
3146 {
3147     int ret;
3148     BdrvChild *child;
3149     Transaction *tran = tran_new();
3150 
3151     GLOBAL_STATE_CODE();
3152 
3153     child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
3154                                      child_class, child_role, tran, errp);
3155     if (!child) {
3156         ret = -EINVAL;
3157         goto out;
3158     }
3159 
3160     ret = bdrv_refresh_perms(parent_bs, errp);
3161     if (ret < 0) {
3162         goto out;
3163     }
3164 
3165 out:
3166     tran_finalize(tran, ret);
3167 
3168     bdrv_unref(child_bs);
3169 
3170     return ret < 0 ? NULL : child;
3171 }
3172 
3173 /* Callers must ensure that child->frozen is false. */
3174 void bdrv_root_unref_child(BdrvChild *child)
3175 {
3176     BlockDriverState *child_bs;
3177 
3178     GLOBAL_STATE_CODE();
3179 
3180     child_bs = child->bs;
3181     bdrv_detach_child(child);
3182     bdrv_unref(child_bs);
3183 }
3184 
3185 typedef struct BdrvSetInheritsFrom {
3186     BlockDriverState *bs;
3187     BlockDriverState *old_inherits_from;
3188 } BdrvSetInheritsFrom;
3189 
3190 static void bdrv_set_inherits_from_abort(void *opaque)
3191 {
3192     BdrvSetInheritsFrom *s = opaque;
3193 
3194     s->bs->inherits_from = s->old_inherits_from;
3195 }
3196 
3197 static TransactionActionDrv bdrv_set_inherits_from_drv = {
3198     .abort = bdrv_set_inherits_from_abort,
3199     .clean = g_free,
3200 };
3201 
3202 /* @tran is allowed to be NULL. In this case no rollback is possible */
3203 static void bdrv_set_inherits_from(BlockDriverState *bs,
3204                                    BlockDriverState *new_inherits_from,
3205                                    Transaction *tran)
3206 {
3207     if (tran) {
3208         BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3209 
3210         *s = (BdrvSetInheritsFrom) {
3211             .bs = bs,
3212             .old_inherits_from = bs->inherits_from,
3213         };
3214 
3215         tran_add(tran, &bdrv_set_inherits_from_drv, s);
3216     }
3217 
3218     bs->inherits_from = new_inherits_from;
3219 }
3220 
3221 /**
3222  * Clear all inherits_from pointers from children and grandchildren of
3223  * @root that point to @root, where necessary.
3224  * @tran is allowed to be NULL. In this case no rollback is possible
3225  */
3226 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3227                                      Transaction *tran)
3228 {
3229     BdrvChild *c;
3230 
3231     if (child->bs->inherits_from == root) {
3232         /*
3233          * Remove inherits_from only when the last reference between root and
3234          * child->bs goes away.
3235          */
3236         QLIST_FOREACH(c, &root->children, next) {
3237             if (c != child && c->bs == child->bs) {
3238                 break;
3239             }
3240         }
3241         if (c == NULL) {
3242             bdrv_set_inherits_from(child->bs, NULL, tran);
3243         }
3244     }
3245 
3246     QLIST_FOREACH(c, &child->bs->children, next) {
3247         bdrv_unset_inherits_from(root, c, tran);
3248     }
3249 }
3250 
3251 /* Callers must ensure that child->frozen is false. */
3252 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
3253 {
3254     GLOBAL_STATE_CODE();
3255     if (child == NULL) {
3256         return;
3257     }
3258 
3259     bdrv_unset_inherits_from(parent, child, NULL);
3260     bdrv_root_unref_child(child);
3261 }
3262 
3263 
3264 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
3265 {
3266     BdrvChild *c;
3267     GLOBAL_STATE_CODE();
3268     QLIST_FOREACH(c, &bs->parents, next_parent) {
3269         if (c->klass->change_media) {
3270             c->klass->change_media(c, load);
3271         }
3272     }
3273 }
3274 
3275 /* Return true if you can reach parent going through child->inherits_from
3276  * recursively. If parent or child are NULL, return false */
3277 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
3278                                          BlockDriverState *parent)
3279 {
3280     while (child && child != parent) {
3281         child = child->inherits_from;
3282     }
3283 
3284     return child != NULL;
3285 }
3286 
3287 /*
3288  * Return the BdrvChildRole for @bs's backing child.  bs->backing is
3289  * mostly used for COW backing children (role = COW), but also for
3290  * filtered children (role = FILTERED | PRIMARY).
3291  */
3292 static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
3293 {
3294     if (bs->drv && bs->drv->is_filter) {
3295         return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3296     } else {
3297         return BDRV_CHILD_COW;
3298     }
3299 }
3300 
3301 /*
3302  * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3303  * callers which don't need their own reference any more must call bdrv_unref().
3304  *
3305  * Function doesn't update permissions, caller is responsible for this.
3306  */
3307 static int bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3308                                            BlockDriverState *child_bs,
3309                                            bool is_backing,
3310                                            Transaction *tran, Error **errp)
3311 {
3312     bool update_inherits_from =
3313         bdrv_inherits_from_recursive(child_bs, parent_bs);
3314     BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3315     BdrvChildRole role;
3316 
3317     GLOBAL_STATE_CODE();
3318 
3319     if (!parent_bs->drv) {
3320         /*
3321          * Node without drv is an object without a class :/. TODO: finally fix
3322          * qcow2 driver to never clear bs->drv and implement format corruption
3323          * handling in other way.
3324          */
3325         error_setg(errp, "Node corrupted");
3326         return -EINVAL;
3327     }
3328 
3329     if (child && child->frozen) {
3330         error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3331                    child->name, parent_bs->node_name, child->bs->node_name);
3332         return -EPERM;
3333     }
3334 
3335     if (is_backing && !parent_bs->drv->is_filter &&
3336         !parent_bs->drv->supports_backing)
3337     {
3338         error_setg(errp, "Driver '%s' of node '%s' does not support backing "
3339                    "files", parent_bs->drv->format_name, parent_bs->node_name);
3340         return -EINVAL;
3341     }
3342 
3343     if (parent_bs->drv->is_filter) {
3344         role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3345     } else if (is_backing) {
3346         role = BDRV_CHILD_COW;
3347     } else {
3348         /*
3349          * We only can use same role as it is in existing child. We don't have
3350          * infrastructure to determine role of file child in generic way
3351          */
3352         if (!child) {
3353             error_setg(errp, "Cannot set file child to format node without "
3354                        "file child");
3355             return -EINVAL;
3356         }
3357         role = child->role;
3358     }
3359 
3360     if (child) {
3361         bdrv_unset_inherits_from(parent_bs, child, tran);
3362         bdrv_remove_child(child, tran);
3363     }
3364 
3365     if (!child_bs) {
3366         goto out;
3367     }
3368 
3369     child = bdrv_attach_child_noperm(parent_bs, child_bs,
3370                                      is_backing ? "backing" : "file",
3371                                      &child_of_bds, role,
3372                                      tran, errp);
3373     if (!child) {
3374         return -EINVAL;
3375     }
3376 
3377 
3378     /*
3379      * If inherits_from pointed recursively to bs then let's update it to
3380      * point directly to bs (else it will become NULL).
3381      */
3382     if (update_inherits_from) {
3383         bdrv_set_inherits_from(child_bs, parent_bs, tran);
3384     }
3385 
3386 out:
3387     bdrv_refresh_limits(parent_bs, tran, NULL);
3388 
3389     return 0;
3390 }
3391 
3392 static int bdrv_set_backing_noperm(BlockDriverState *bs,
3393                                    BlockDriverState *backing_hd,
3394                                    Transaction *tran, Error **errp)
3395 {
3396     GLOBAL_STATE_CODE();
3397     return bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3398 }
3399 
3400 int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
3401                         Error **errp)
3402 {
3403     int ret;
3404     Transaction *tran = tran_new();
3405 
3406     GLOBAL_STATE_CODE();
3407     bdrv_drained_begin(bs);
3408 
3409     ret = bdrv_set_backing_noperm(bs, backing_hd, tran, errp);
3410     if (ret < 0) {
3411         goto out;
3412     }
3413 
3414     ret = bdrv_refresh_perms(bs, errp);
3415 out:
3416     tran_finalize(tran, ret);
3417 
3418     bdrv_drained_end(bs);
3419 
3420     return ret;
3421 }
3422 
3423 /*
3424  * Opens the backing file for a BlockDriverState if not yet open
3425  *
3426  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3427  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3428  * itself, all options starting with "${bdref_key}." are considered part of the
3429  * BlockdevRef.
3430  *
3431  * TODO Can this be unified with bdrv_open_image()?
3432  */
3433 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3434                            const char *bdref_key, Error **errp)
3435 {
3436     char *backing_filename = NULL;
3437     char *bdref_key_dot;
3438     const char *reference = NULL;
3439     int ret = 0;
3440     bool implicit_backing = false;
3441     BlockDriverState *backing_hd;
3442     QDict *options;
3443     QDict *tmp_parent_options = NULL;
3444     Error *local_err = NULL;
3445 
3446     GLOBAL_STATE_CODE();
3447 
3448     if (bs->backing != NULL) {
3449         goto free_exit;
3450     }
3451 
3452     /* NULL means an empty set of options */
3453     if (parent_options == NULL) {
3454         tmp_parent_options = qdict_new();
3455         parent_options = tmp_parent_options;
3456     }
3457 
3458     bs->open_flags &= ~BDRV_O_NO_BACKING;
3459 
3460     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3461     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3462     g_free(bdref_key_dot);
3463 
3464     /*
3465      * Caution: while qdict_get_try_str() is fine, getting non-string
3466      * types would require more care.  When @parent_options come from
3467      * -blockdev or blockdev_add, its members are typed according to
3468      * the QAPI schema, but when they come from -drive, they're all
3469      * QString.
3470      */
3471     reference = qdict_get_try_str(parent_options, bdref_key);
3472     if (reference || qdict_haskey(options, "file.filename")) {
3473         /* keep backing_filename NULL */
3474     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3475         qobject_unref(options);
3476         goto free_exit;
3477     } else {
3478         if (qdict_size(options) == 0) {
3479             /* If the user specifies options that do not modify the
3480              * backing file's behavior, we might still consider it the
3481              * implicit backing file.  But it's easier this way, and
3482              * just specifying some of the backing BDS's options is
3483              * only possible with -drive anyway (otherwise the QAPI
3484              * schema forces the user to specify everything). */
3485             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3486         }
3487 
3488         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
3489         if (local_err) {
3490             ret = -EINVAL;
3491             error_propagate(errp, local_err);
3492             qobject_unref(options);
3493             goto free_exit;
3494         }
3495     }
3496 
3497     if (!bs->drv || !bs->drv->supports_backing) {
3498         ret = -EINVAL;
3499         error_setg(errp, "Driver doesn't support backing files");
3500         qobject_unref(options);
3501         goto free_exit;
3502     }
3503 
3504     if (!reference &&
3505         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
3506         qdict_put_str(options, "driver", bs->backing_format);
3507     }
3508 
3509     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
3510                                    &child_of_bds, bdrv_backing_role(bs), errp);
3511     if (!backing_hd) {
3512         bs->open_flags |= BDRV_O_NO_BACKING;
3513         error_prepend(errp, "Could not open backing file: ");
3514         ret = -EINVAL;
3515         goto free_exit;
3516     }
3517 
3518     if (implicit_backing) {
3519         bdrv_refresh_filename(backing_hd);
3520         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3521                 backing_hd->filename);
3522     }
3523 
3524     /* Hook up the backing file link; drop our reference, bs owns the
3525      * backing_hd reference now */
3526     ret = bdrv_set_backing_hd(bs, backing_hd, errp);
3527     bdrv_unref(backing_hd);
3528     if (ret < 0) {
3529         goto free_exit;
3530     }
3531 
3532     qdict_del(parent_options, bdref_key);
3533 
3534 free_exit:
3535     g_free(backing_filename);
3536     qobject_unref(tmp_parent_options);
3537     return ret;
3538 }
3539 
3540 static BlockDriverState *
3541 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3542                    BlockDriverState *parent, const BdrvChildClass *child_class,
3543                    BdrvChildRole child_role, bool allow_none, Error **errp)
3544 {
3545     BlockDriverState *bs = NULL;
3546     QDict *image_options;
3547     char *bdref_key_dot;
3548     const char *reference;
3549 
3550     assert(child_class != NULL);
3551 
3552     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3553     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3554     g_free(bdref_key_dot);
3555 
3556     /*
3557      * Caution: while qdict_get_try_str() is fine, getting non-string
3558      * types would require more care.  When @options come from
3559      * -blockdev or blockdev_add, its members are typed according to
3560      * the QAPI schema, but when they come from -drive, they're all
3561      * QString.
3562      */
3563     reference = qdict_get_try_str(options, bdref_key);
3564     if (!filename && !reference && !qdict_size(image_options)) {
3565         if (!allow_none) {
3566             error_setg(errp, "A block device must be specified for \"%s\"",
3567                        bdref_key);
3568         }
3569         qobject_unref(image_options);
3570         goto done;
3571     }
3572 
3573     bs = bdrv_open_inherit(filename, reference, image_options, 0,
3574                            parent, child_class, child_role, errp);
3575     if (!bs) {
3576         goto done;
3577     }
3578 
3579 done:
3580     qdict_del(options, bdref_key);
3581     return bs;
3582 }
3583 
3584 /*
3585  * Opens a disk image whose options are given as BlockdevRef in another block
3586  * device's options.
3587  *
3588  * If allow_none is true, no image will be opened if filename is false and no
3589  * BlockdevRef is given. NULL will be returned, but errp remains unset.
3590  *
3591  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
3592  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3593  * itself, all options starting with "${bdref_key}." are considered part of the
3594  * BlockdevRef.
3595  *
3596  * The BlockdevRef will be removed from the options QDict.
3597  */
3598 BdrvChild *bdrv_open_child(const char *filename,
3599                            QDict *options, const char *bdref_key,
3600                            BlockDriverState *parent,
3601                            const BdrvChildClass *child_class,
3602                            BdrvChildRole child_role,
3603                            bool allow_none, Error **errp)
3604 {
3605     BlockDriverState *bs;
3606 
3607     GLOBAL_STATE_CODE();
3608 
3609     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
3610                             child_role, allow_none, errp);
3611     if (bs == NULL) {
3612         return NULL;
3613     }
3614 
3615     return bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
3616                              errp);
3617 }
3618 
3619 /*
3620  * Wrapper on bdrv_open_child() for most popular case: open primary child of bs.
3621  */
3622 int bdrv_open_file_child(const char *filename,
3623                          QDict *options, const char *bdref_key,
3624                          BlockDriverState *parent, Error **errp)
3625 {
3626     BdrvChildRole role;
3627 
3628     /* commit_top and mirror_top don't use this function */
3629     assert(!parent->drv->filtered_child_is_backing);
3630     role = parent->drv->is_filter ?
3631         (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
3632 
3633     if (!bdrv_open_child(filename, options, bdref_key, parent,
3634                          &child_of_bds, role, false, errp))
3635     {
3636         return -EINVAL;
3637     }
3638 
3639     return 0;
3640 }
3641 
3642 /*
3643  * TODO Future callers may need to specify parent/child_class in order for
3644  * option inheritance to work. Existing callers use it for the root node.
3645  */
3646 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3647 {
3648     BlockDriverState *bs = NULL;
3649     QObject *obj = NULL;
3650     QDict *qdict = NULL;
3651     const char *reference = NULL;
3652     Visitor *v = NULL;
3653 
3654     GLOBAL_STATE_CODE();
3655 
3656     if (ref->type == QTYPE_QSTRING) {
3657         reference = ref->u.reference;
3658     } else {
3659         BlockdevOptions *options = &ref->u.definition;
3660         assert(ref->type == QTYPE_QDICT);
3661 
3662         v = qobject_output_visitor_new(&obj);
3663         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3664         visit_complete(v, &obj);
3665 
3666         qdict = qobject_to(QDict, obj);
3667         qdict_flatten(qdict);
3668 
3669         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3670          * compatibility with other callers) rather than what we want as the
3671          * real defaults. Apply the defaults here instead. */
3672         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3673         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3674         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3675         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3676 
3677     }
3678 
3679     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, errp);
3680     obj = NULL;
3681     qobject_unref(obj);
3682     visit_free(v);
3683     return bs;
3684 }
3685 
3686 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
3687                                                    int flags,
3688                                                    QDict *snapshot_options,
3689                                                    Error **errp)
3690 {
3691     g_autofree char *tmp_filename = NULL;
3692     int64_t total_size;
3693     QemuOpts *opts = NULL;
3694     BlockDriverState *bs_snapshot = NULL;
3695     int ret;
3696 
3697     GLOBAL_STATE_CODE();
3698 
3699     /* if snapshot, we create a temporary backing file and open it
3700        instead of opening 'filename' directly */
3701 
3702     /* Get the required size from the image */
3703     total_size = bdrv_getlength(bs);
3704     if (total_size < 0) {
3705         error_setg_errno(errp, -total_size, "Could not get image size");
3706         goto out;
3707     }
3708 
3709     /* Create the temporary image */
3710     tmp_filename = create_tmp_file(errp);
3711     if (!tmp_filename) {
3712         goto out;
3713     }
3714 
3715     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3716                             &error_abort);
3717     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3718     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
3719     qemu_opts_del(opts);
3720     if (ret < 0) {
3721         error_prepend(errp, "Could not create temporary overlay '%s': ",
3722                       tmp_filename);
3723         goto out;
3724     }
3725 
3726     /* Prepare options QDict for the temporary file */
3727     qdict_put_str(snapshot_options, "file.driver", "file");
3728     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
3729     qdict_put_str(snapshot_options, "driver", "qcow2");
3730 
3731     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
3732     snapshot_options = NULL;
3733     if (!bs_snapshot) {
3734         goto out;
3735     }
3736 
3737     ret = bdrv_append(bs_snapshot, bs, errp);
3738     if (ret < 0) {
3739         bs_snapshot = NULL;
3740         goto out;
3741     }
3742 
3743 out:
3744     qobject_unref(snapshot_options);
3745     return bs_snapshot;
3746 }
3747 
3748 /*
3749  * Opens a disk image (raw, qcow2, vmdk, ...)
3750  *
3751  * options is a QDict of options to pass to the block drivers, or NULL for an
3752  * empty set of options. The reference to the QDict belongs to the block layer
3753  * after the call (even on failure), so if the caller intends to reuse the
3754  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3755  *
3756  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3757  * If it is not NULL, the referenced BDS will be reused.
3758  *
3759  * The reference parameter may be used to specify an existing block device which
3760  * should be opened. If specified, neither options nor a filename may be given,
3761  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3762  */
3763 static BlockDriverState *bdrv_open_inherit(const char *filename,
3764                                            const char *reference,
3765                                            QDict *options, int flags,
3766                                            BlockDriverState *parent,
3767                                            const BdrvChildClass *child_class,
3768                                            BdrvChildRole child_role,
3769                                            Error **errp)
3770 {
3771     int ret;
3772     BlockBackend *file = NULL;
3773     BlockDriverState *bs;
3774     BlockDriver *drv = NULL;
3775     BdrvChild *child;
3776     const char *drvname;
3777     const char *backing;
3778     Error *local_err = NULL;
3779     QDict *snapshot_options = NULL;
3780     int snapshot_flags = 0;
3781 
3782     assert(!child_class || !flags);
3783     assert(!child_class == !parent);
3784     GLOBAL_STATE_CODE();
3785 
3786     if (reference) {
3787         bool options_non_empty = options ? qdict_size(options) : false;
3788         qobject_unref(options);
3789 
3790         if (filename || options_non_empty) {
3791             error_setg(errp, "Cannot reference an existing block device with "
3792                        "additional options or a new filename");
3793             return NULL;
3794         }
3795 
3796         bs = bdrv_lookup_bs(reference, reference, errp);
3797         if (!bs) {
3798             return NULL;
3799         }
3800 
3801         bdrv_ref(bs);
3802         return bs;
3803     }
3804 
3805     bs = bdrv_new();
3806 
3807     /* NULL means an empty set of options */
3808     if (options == NULL) {
3809         options = qdict_new();
3810     }
3811 
3812     /* json: syntax counts as explicit options, as if in the QDict */
3813     parse_json_protocol(options, &filename, &local_err);
3814     if (local_err) {
3815         goto fail;
3816     }
3817 
3818     bs->explicit_options = qdict_clone_shallow(options);
3819 
3820     if (child_class) {
3821         bool parent_is_format;
3822 
3823         if (parent->drv) {
3824             parent_is_format = parent->drv->is_format;
3825         } else {
3826             /*
3827              * parent->drv is not set yet because this node is opened for
3828              * (potential) format probing.  That means that @parent is going
3829              * to be a format node.
3830              */
3831             parent_is_format = true;
3832         }
3833 
3834         bs->inherits_from = parent;
3835         child_class->inherit_options(child_role, parent_is_format,
3836                                      &flags, options,
3837                                      parent->open_flags, parent->options);
3838     }
3839 
3840     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3841     if (ret < 0) {
3842         goto fail;
3843     }
3844 
3845     /*
3846      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3847      * Caution: getting a boolean member of @options requires care.
3848      * When @options come from -blockdev or blockdev_add, members are
3849      * typed according to the QAPI schema, but when they come from
3850      * -drive, they're all QString.
3851      */
3852     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3853         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3854         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3855     } else {
3856         flags &= ~BDRV_O_RDWR;
3857     }
3858 
3859     if (flags & BDRV_O_SNAPSHOT) {
3860         snapshot_options = qdict_new();
3861         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3862                                    flags, options);
3863         /* Let bdrv_backing_options() override "read-only" */
3864         qdict_del(options, BDRV_OPT_READ_ONLY);
3865         bdrv_inherited_options(BDRV_CHILD_COW, true,
3866                                &flags, options, flags, options);
3867     }
3868 
3869     bs->open_flags = flags;
3870     bs->options = options;
3871     options = qdict_clone_shallow(options);
3872 
3873     /* Find the right image format driver */
3874     /* See cautionary note on accessing @options above */
3875     drvname = qdict_get_try_str(options, "driver");
3876     if (drvname) {
3877         drv = bdrv_find_format(drvname);
3878         if (!drv) {
3879             error_setg(errp, "Unknown driver: '%s'", drvname);
3880             goto fail;
3881         }
3882     }
3883 
3884     assert(drvname || !(flags & BDRV_O_PROTOCOL));
3885 
3886     /* See cautionary note on accessing @options above */
3887     backing = qdict_get_try_str(options, "backing");
3888     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3889         (backing && *backing == '\0'))
3890     {
3891         if (backing) {
3892             warn_report("Use of \"backing\": \"\" is deprecated; "
3893                         "use \"backing\": null instead");
3894         }
3895         flags |= BDRV_O_NO_BACKING;
3896         qdict_del(bs->explicit_options, "backing");
3897         qdict_del(bs->options, "backing");
3898         qdict_del(options, "backing");
3899     }
3900 
3901     /* Open image file without format layer. This BlockBackend is only used for
3902      * probing, the block drivers will do their own bdrv_open_child() for the
3903      * same BDS, which is why we put the node name back into options. */
3904     if ((flags & BDRV_O_PROTOCOL) == 0) {
3905         BlockDriverState *file_bs;
3906 
3907         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3908                                      &child_of_bds, BDRV_CHILD_IMAGE,
3909                                      true, &local_err);
3910         if (local_err) {
3911             goto fail;
3912         }
3913         if (file_bs != NULL) {
3914             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3915              * looking at the header to guess the image format. This works even
3916              * in cases where a guest would not see a consistent state. */
3917             file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3918             blk_insert_bs(file, file_bs, &local_err);
3919             bdrv_unref(file_bs);
3920             if (local_err) {
3921                 goto fail;
3922             }
3923 
3924             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3925         }
3926     }
3927 
3928     /* Image format probing */
3929     bs->probed = !drv;
3930     if (!drv && file) {
3931         ret = find_image_format(file, filename, &drv, &local_err);
3932         if (ret < 0) {
3933             goto fail;
3934         }
3935         /*
3936          * This option update would logically belong in bdrv_fill_options(),
3937          * but we first need to open bs->file for the probing to work, while
3938          * opening bs->file already requires the (mostly) final set of options
3939          * so that cache mode etc. can be inherited.
3940          *
3941          * Adding the driver later is somewhat ugly, but it's not an option
3942          * that would ever be inherited, so it's correct. We just need to make
3943          * sure to update both bs->options (which has the full effective
3944          * options for bs) and options (which has file.* already removed).
3945          */
3946         qdict_put_str(bs->options, "driver", drv->format_name);
3947         qdict_put_str(options, "driver", drv->format_name);
3948     } else if (!drv) {
3949         error_setg(errp, "Must specify either driver or file");
3950         goto fail;
3951     }
3952 
3953     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3954     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3955     /* file must be NULL if a protocol BDS is about to be created
3956      * (the inverse results in an error message from bdrv_open_common()) */
3957     assert(!(flags & BDRV_O_PROTOCOL) || !file);
3958 
3959     /* Open the image */
3960     ret = bdrv_open_common(bs, file, options, &local_err);
3961     if (ret < 0) {
3962         goto fail;
3963     }
3964 
3965     if (file) {
3966         blk_unref(file);
3967         file = NULL;
3968     }
3969 
3970     /* If there is a backing file, use it */
3971     if ((flags & BDRV_O_NO_BACKING) == 0) {
3972         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3973         if (ret < 0) {
3974             goto close_and_fail;
3975         }
3976     }
3977 
3978     /* Remove all children options and references
3979      * from bs->options and bs->explicit_options */
3980     QLIST_FOREACH(child, &bs->children, next) {
3981         char *child_key_dot;
3982         child_key_dot = g_strdup_printf("%s.", child->name);
3983         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3984         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3985         qdict_del(bs->explicit_options, child->name);
3986         qdict_del(bs->options, child->name);
3987         g_free(child_key_dot);
3988     }
3989 
3990     /* Check if any unknown options were used */
3991     if (qdict_size(options) != 0) {
3992         const QDictEntry *entry = qdict_first(options);
3993         if (flags & BDRV_O_PROTOCOL) {
3994             error_setg(errp, "Block protocol '%s' doesn't support the option "
3995                        "'%s'", drv->format_name, entry->key);
3996         } else {
3997             error_setg(errp,
3998                        "Block format '%s' does not support the option '%s'",
3999                        drv->format_name, entry->key);
4000         }
4001 
4002         goto close_and_fail;
4003     }
4004 
4005     bdrv_parent_cb_change_media(bs, true);
4006 
4007     qobject_unref(options);
4008     options = NULL;
4009 
4010     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4011      * temporary snapshot afterwards. */
4012     if (snapshot_flags) {
4013         BlockDriverState *snapshot_bs;
4014         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
4015                                                 snapshot_options, &local_err);
4016         snapshot_options = NULL;
4017         if (local_err) {
4018             goto close_and_fail;
4019         }
4020         /* We are not going to return bs but the overlay on top of it
4021          * (snapshot_bs); thus, we have to drop the strong reference to bs
4022          * (which we obtained by calling bdrv_new()). bs will not be deleted,
4023          * though, because the overlay still has a reference to it. */
4024         bdrv_unref(bs);
4025         bs = snapshot_bs;
4026     }
4027 
4028     return bs;
4029 
4030 fail:
4031     blk_unref(file);
4032     qobject_unref(snapshot_options);
4033     qobject_unref(bs->explicit_options);
4034     qobject_unref(bs->options);
4035     qobject_unref(options);
4036     bs->options = NULL;
4037     bs->explicit_options = NULL;
4038     bdrv_unref(bs);
4039     error_propagate(errp, local_err);
4040     return NULL;
4041 
4042 close_and_fail:
4043     bdrv_unref(bs);
4044     qobject_unref(snapshot_options);
4045     qobject_unref(options);
4046     error_propagate(errp, local_err);
4047     return NULL;
4048 }
4049 
4050 BlockDriverState *bdrv_open(const char *filename, const char *reference,
4051                             QDict *options, int flags, Error **errp)
4052 {
4053     GLOBAL_STATE_CODE();
4054 
4055     return bdrv_open_inherit(filename, reference, options, flags, NULL,
4056                              NULL, 0, errp);
4057 }
4058 
4059 /* Return true if the NULL-terminated @list contains @str */
4060 static bool is_str_in_list(const char *str, const char *const *list)
4061 {
4062     if (str && list) {
4063         int i;
4064         for (i = 0; list[i] != NULL; i++) {
4065             if (!strcmp(str, list[i])) {
4066                 return true;
4067             }
4068         }
4069     }
4070     return false;
4071 }
4072 
4073 /*
4074  * Check that every option set in @bs->options is also set in
4075  * @new_opts.
4076  *
4077  * Options listed in the common_options list and in
4078  * @bs->drv->mutable_opts are skipped.
4079  *
4080  * Return 0 on success, otherwise return -EINVAL and set @errp.
4081  */
4082 static int bdrv_reset_options_allowed(BlockDriverState *bs,
4083                                       const QDict *new_opts, Error **errp)
4084 {
4085     const QDictEntry *e;
4086     /* These options are common to all block drivers and are handled
4087      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4088     const char *const common_options[] = {
4089         "node-name", "discard", "cache.direct", "cache.no-flush",
4090         "read-only", "auto-read-only", "detect-zeroes", NULL
4091     };
4092 
4093     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4094         if (!qdict_haskey(new_opts, e->key) &&
4095             !is_str_in_list(e->key, common_options) &&
4096             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4097             error_setg(errp, "Option '%s' cannot be reset "
4098                        "to its default value", e->key);
4099             return -EINVAL;
4100         }
4101     }
4102 
4103     return 0;
4104 }
4105 
4106 /*
4107  * Returns true if @child can be reached recursively from @bs
4108  */
4109 static bool bdrv_recurse_has_child(BlockDriverState *bs,
4110                                    BlockDriverState *child)
4111 {
4112     BdrvChild *c;
4113 
4114     if (bs == child) {
4115         return true;
4116     }
4117 
4118     QLIST_FOREACH(c, &bs->children, next) {
4119         if (bdrv_recurse_has_child(c->bs, child)) {
4120             return true;
4121         }
4122     }
4123 
4124     return false;
4125 }
4126 
4127 /*
4128  * Adds a BlockDriverState to a simple queue for an atomic, transactional
4129  * reopen of multiple devices.
4130  *
4131  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4132  * already performed, or alternatively may be NULL a new BlockReopenQueue will
4133  * be created and initialized. This newly created BlockReopenQueue should be
4134  * passed back in for subsequent calls that are intended to be of the same
4135  * atomic 'set'.
4136  *
4137  * bs is the BlockDriverState to add to the reopen queue.
4138  *
4139  * options contains the changed options for the associated bs
4140  * (the BlockReopenQueue takes ownership)
4141  *
4142  * flags contains the open flags for the associated bs
4143  *
4144  * returns a pointer to bs_queue, which is either the newly allocated
4145  * bs_queue, or the existing bs_queue being used.
4146  *
4147  * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
4148  */
4149 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
4150                                                  BlockDriverState *bs,
4151                                                  QDict *options,
4152                                                  const BdrvChildClass *klass,
4153                                                  BdrvChildRole role,
4154                                                  bool parent_is_format,
4155                                                  QDict *parent_options,
4156                                                  int parent_flags,
4157                                                  bool keep_old_opts)
4158 {
4159     assert(bs != NULL);
4160 
4161     BlockReopenQueueEntry *bs_entry;
4162     BdrvChild *child;
4163     QDict *old_options, *explicit_options, *options_copy;
4164     int flags;
4165     QemuOpts *opts;
4166 
4167     /* Make sure that the caller remembered to use a drained section. This is
4168      * important to avoid graph changes between the recursive queuing here and
4169      * bdrv_reopen_multiple(). */
4170     assert(bs->quiesce_counter > 0);
4171     GLOBAL_STATE_CODE();
4172 
4173     if (bs_queue == NULL) {
4174         bs_queue = g_new0(BlockReopenQueue, 1);
4175         QTAILQ_INIT(bs_queue);
4176     }
4177 
4178     if (!options) {
4179         options = qdict_new();
4180     }
4181 
4182     /* Check if this BlockDriverState is already in the queue */
4183     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4184         if (bs == bs_entry->state.bs) {
4185             break;
4186         }
4187     }
4188 
4189     /*
4190      * Precedence of options:
4191      * 1. Explicitly passed in options (highest)
4192      * 2. Retained from explicitly set options of bs
4193      * 3. Inherited from parent node
4194      * 4. Retained from effective options of bs
4195      */
4196 
4197     /* Old explicitly set values (don't overwrite by inherited value) */
4198     if (bs_entry || keep_old_opts) {
4199         old_options = qdict_clone_shallow(bs_entry ?
4200                                           bs_entry->state.explicit_options :
4201                                           bs->explicit_options);
4202         bdrv_join_options(bs, options, old_options);
4203         qobject_unref(old_options);
4204     }
4205 
4206     explicit_options = qdict_clone_shallow(options);
4207 
4208     /* Inherit from parent node */
4209     if (parent_options) {
4210         flags = 0;
4211         klass->inherit_options(role, parent_is_format, &flags, options,
4212                                parent_flags, parent_options);
4213     } else {
4214         flags = bdrv_get_flags(bs);
4215     }
4216 
4217     if (keep_old_opts) {
4218         /* Old values are used for options that aren't set yet */
4219         old_options = qdict_clone_shallow(bs->options);
4220         bdrv_join_options(bs, options, old_options);
4221         qobject_unref(old_options);
4222     }
4223 
4224     /* We have the final set of options so let's update the flags */
4225     options_copy = qdict_clone_shallow(options);
4226     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4227     qemu_opts_absorb_qdict(opts, options_copy, NULL);
4228     update_flags_from_options(&flags, opts);
4229     qemu_opts_del(opts);
4230     qobject_unref(options_copy);
4231 
4232     /* bdrv_open_inherit() sets and clears some additional flags internally */
4233     flags &= ~BDRV_O_PROTOCOL;
4234     if (flags & BDRV_O_RDWR) {
4235         flags |= BDRV_O_ALLOW_RDWR;
4236     }
4237 
4238     if (!bs_entry) {
4239         bs_entry = g_new0(BlockReopenQueueEntry, 1);
4240         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
4241     } else {
4242         qobject_unref(bs_entry->state.options);
4243         qobject_unref(bs_entry->state.explicit_options);
4244     }
4245 
4246     bs_entry->state.bs = bs;
4247     bs_entry->state.options = options;
4248     bs_entry->state.explicit_options = explicit_options;
4249     bs_entry->state.flags = flags;
4250 
4251     /*
4252      * If keep_old_opts is false then it means that unspecified
4253      * options must be reset to their original value. We don't allow
4254      * resetting 'backing' but we need to know if the option is
4255      * missing in order to decide if we have to return an error.
4256      */
4257     if (!keep_old_opts) {
4258         bs_entry->state.backing_missing =
4259             !qdict_haskey(options, "backing") &&
4260             !qdict_haskey(options, "backing.driver");
4261     }
4262 
4263     QLIST_FOREACH(child, &bs->children, next) {
4264         QDict *new_child_options = NULL;
4265         bool child_keep_old = keep_old_opts;
4266 
4267         /* reopen can only change the options of block devices that were
4268          * implicitly created and inherited options. For other (referenced)
4269          * block devices, a syntax like "backing.foo" results in an error. */
4270         if (child->bs->inherits_from != bs) {
4271             continue;
4272         }
4273 
4274         /* Check if the options contain a child reference */
4275         if (qdict_haskey(options, child->name)) {
4276             const char *childref = qdict_get_try_str(options, child->name);
4277             /*
4278              * The current child must not be reopened if the child
4279              * reference is null or points to a different node.
4280              */
4281             if (g_strcmp0(childref, child->bs->node_name)) {
4282                 continue;
4283             }
4284             /*
4285              * If the child reference points to the current child then
4286              * reopen it with its existing set of options (note that
4287              * it can still inherit new options from the parent).
4288              */
4289             child_keep_old = true;
4290         } else {
4291             /* Extract child options ("child-name.*") */
4292             char *child_key_dot = g_strdup_printf("%s.", child->name);
4293             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
4294             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
4295             g_free(child_key_dot);
4296         }
4297 
4298         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
4299                                 child->klass, child->role, bs->drv->is_format,
4300                                 options, flags, child_keep_old);
4301     }
4302 
4303     return bs_queue;
4304 }
4305 
4306 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
4307                                     BlockDriverState *bs,
4308                                     QDict *options, bool keep_old_opts)
4309 {
4310     GLOBAL_STATE_CODE();
4311 
4312     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
4313                                    NULL, 0, keep_old_opts);
4314 }
4315 
4316 void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4317 {
4318     GLOBAL_STATE_CODE();
4319     if (bs_queue) {
4320         BlockReopenQueueEntry *bs_entry, *next;
4321         QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4322             qobject_unref(bs_entry->state.explicit_options);
4323             qobject_unref(bs_entry->state.options);
4324             g_free(bs_entry);
4325         }
4326         g_free(bs_queue);
4327     }
4328 }
4329 
4330 /*
4331  * Reopen multiple BlockDriverStates atomically & transactionally.
4332  *
4333  * The queue passed in (bs_queue) must have been built up previous
4334  * via bdrv_reopen_queue().
4335  *
4336  * Reopens all BDS specified in the queue, with the appropriate
4337  * flags.  All devices are prepared for reopen, and failure of any
4338  * device will cause all device changes to be abandoned, and intermediate
4339  * data cleaned up.
4340  *
4341  * If all devices prepare successfully, then the changes are committed
4342  * to all devices.
4343  *
4344  * All affected nodes must be drained between bdrv_reopen_queue() and
4345  * bdrv_reopen_multiple().
4346  *
4347  * To be called from the main thread, with all other AioContexts unlocked.
4348  */
4349 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4350 {
4351     int ret = -1;
4352     BlockReopenQueueEntry *bs_entry, *next;
4353     AioContext *ctx;
4354     Transaction *tran = tran_new();
4355     g_autoptr(GHashTable) found = NULL;
4356     g_autoptr(GSList) refresh_list = NULL;
4357 
4358     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4359     assert(bs_queue != NULL);
4360     GLOBAL_STATE_CODE();
4361 
4362     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4363         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4364         aio_context_acquire(ctx);
4365         ret = bdrv_flush(bs_entry->state.bs);
4366         aio_context_release(ctx);
4367         if (ret < 0) {
4368             error_setg_errno(errp, -ret, "Error flushing drive");
4369             goto abort;
4370         }
4371     }
4372 
4373     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4374         assert(bs_entry->state.bs->quiesce_counter > 0);
4375         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4376         aio_context_acquire(ctx);
4377         ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
4378         aio_context_release(ctx);
4379         if (ret < 0) {
4380             goto abort;
4381         }
4382         bs_entry->prepared = true;
4383     }
4384 
4385     found = g_hash_table_new(NULL, NULL);
4386     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4387         BDRVReopenState *state = &bs_entry->state;
4388 
4389         refresh_list = bdrv_topological_dfs(refresh_list, found, state->bs);
4390         if (state->old_backing_bs) {
4391             refresh_list = bdrv_topological_dfs(refresh_list, found,
4392                                                 state->old_backing_bs);
4393         }
4394         if (state->old_file_bs) {
4395             refresh_list = bdrv_topological_dfs(refresh_list, found,
4396                                                 state->old_file_bs);
4397         }
4398     }
4399 
4400     /*
4401      * Note that file-posix driver rely on permission update done during reopen
4402      * (even if no permission changed), because it wants "new" permissions for
4403      * reconfiguring the fd and that's why it does it in raw_check_perm(), not
4404      * in raw_reopen_prepare() which is called with "old" permissions.
4405      */
4406     ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
4407     if (ret < 0) {
4408         goto abort;
4409     }
4410 
4411     /*
4412      * If we reach this point, we have success and just need to apply the
4413      * changes.
4414      *
4415      * Reverse order is used to comfort qcow2 driver: on commit it need to write
4416      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4417      * children are usually goes after parents in reopen-queue, so go from last
4418      * to first element.
4419      */
4420     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4421         ctx = bdrv_get_aio_context(bs_entry->state.bs);
4422         aio_context_acquire(ctx);
4423         bdrv_reopen_commit(&bs_entry->state);
4424         aio_context_release(ctx);
4425     }
4426 
4427     tran_commit(tran);
4428 
4429     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4430         BlockDriverState *bs = bs_entry->state.bs;
4431 
4432         if (bs->drv->bdrv_reopen_commit_post) {
4433             ctx = bdrv_get_aio_context(bs);
4434             aio_context_acquire(ctx);
4435             bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
4436             aio_context_release(ctx);
4437         }
4438     }
4439 
4440     ret = 0;
4441     goto cleanup;
4442 
4443 abort:
4444     tran_abort(tran);
4445     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4446         if (bs_entry->prepared) {
4447             ctx = bdrv_get_aio_context(bs_entry->state.bs);
4448             aio_context_acquire(ctx);
4449             bdrv_reopen_abort(&bs_entry->state);
4450             aio_context_release(ctx);
4451         }
4452     }
4453 
4454 cleanup:
4455     bdrv_reopen_queue_free(bs_queue);
4456 
4457     return ret;
4458 }
4459 
4460 int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
4461                 Error **errp)
4462 {
4463     AioContext *ctx = bdrv_get_aio_context(bs);
4464     BlockReopenQueue *queue;
4465     int ret;
4466 
4467     GLOBAL_STATE_CODE();
4468 
4469     bdrv_subtree_drained_begin(bs);
4470     if (ctx != qemu_get_aio_context()) {
4471         aio_context_release(ctx);
4472     }
4473 
4474     queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
4475     ret = bdrv_reopen_multiple(queue, errp);
4476 
4477     if (ctx != qemu_get_aio_context()) {
4478         aio_context_acquire(ctx);
4479     }
4480     bdrv_subtree_drained_end(bs);
4481 
4482     return ret;
4483 }
4484 
4485 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
4486                               Error **errp)
4487 {
4488     QDict *opts = qdict_new();
4489 
4490     GLOBAL_STATE_CODE();
4491 
4492     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
4493 
4494     return bdrv_reopen(bs, opts, true, errp);
4495 }
4496 
4497 /*
4498  * Take a BDRVReopenState and check if the value of 'backing' in the
4499  * reopen_state->options QDict is valid or not.
4500  *
4501  * If 'backing' is missing from the QDict then return 0.
4502  *
4503  * If 'backing' contains the node name of the backing file of
4504  * reopen_state->bs then return 0.
4505  *
4506  * If 'backing' contains a different node name (or is null) then check
4507  * whether the current backing file can be replaced with the new one.
4508  * If that's the case then reopen_state->replace_backing_bs is set to
4509  * true and reopen_state->new_backing_bs contains a pointer to the new
4510  * backing BlockDriverState (or NULL).
4511  *
4512  * Return 0 on success, otherwise return < 0 and set @errp.
4513  */
4514 static int bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4515                                              bool is_backing, Transaction *tran,
4516                                              Error **errp)
4517 {
4518     BlockDriverState *bs = reopen_state->bs;
4519     BlockDriverState *new_child_bs;
4520     BlockDriverState *old_child_bs = is_backing ? child_bs(bs->backing) :
4521                                                   child_bs(bs->file);
4522     const char *child_name = is_backing ? "backing" : "file";
4523     QObject *value;
4524     const char *str;
4525 
4526     GLOBAL_STATE_CODE();
4527 
4528     value = qdict_get(reopen_state->options, child_name);
4529     if (value == NULL) {
4530         return 0;
4531     }
4532 
4533     switch (qobject_type(value)) {
4534     case QTYPE_QNULL:
4535         assert(is_backing); /* The 'file' option does not allow a null value */
4536         new_child_bs = NULL;
4537         break;
4538     case QTYPE_QSTRING:
4539         str = qstring_get_str(qobject_to(QString, value));
4540         new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4541         if (new_child_bs == NULL) {
4542             return -EINVAL;
4543         } else if (bdrv_recurse_has_child(new_child_bs, bs)) {
4544             error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4545                        "cycle", str, child_name, bs->node_name);
4546             return -EINVAL;
4547         }
4548         break;
4549     default:
4550         /*
4551          * The options QDict has been flattened, so 'backing' and 'file'
4552          * do not allow any other data type here.
4553          */
4554         g_assert_not_reached();
4555     }
4556 
4557     if (old_child_bs == new_child_bs) {
4558         return 0;
4559     }
4560 
4561     if (old_child_bs) {
4562         if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4563             return 0;
4564         }
4565 
4566         if (old_child_bs->implicit) {
4567             error_setg(errp, "Cannot replace implicit %s child of %s",
4568                        child_name, bs->node_name);
4569             return -EPERM;
4570         }
4571     }
4572 
4573     if (bs->drv->is_filter && !old_child_bs) {
4574         /*
4575          * Filters always have a file or a backing child, so we are trying to
4576          * change wrong child
4577          */
4578         error_setg(errp, "'%s' is a %s filter node that does not support a "
4579                    "%s child", bs->node_name, bs->drv->format_name, child_name);
4580         return -EINVAL;
4581     }
4582 
4583     if (is_backing) {
4584         reopen_state->old_backing_bs = old_child_bs;
4585     } else {
4586         reopen_state->old_file_bs = old_child_bs;
4587     }
4588 
4589     return bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4590                                            tran, errp);
4591 }
4592 
4593 /*
4594  * Prepares a BlockDriverState for reopen. All changes are staged in the
4595  * 'opaque' field of the BDRVReopenState, which is used and allocated by
4596  * the block driver layer .bdrv_reopen_prepare()
4597  *
4598  * bs is the BlockDriverState to reopen
4599  * flags are the new open flags
4600  * queue is the reopen queue
4601  *
4602  * Returns 0 on success, non-zero on error.  On error errp will be set
4603  * as well.
4604  *
4605  * On failure, bdrv_reopen_abort() will be called to clean up any data.
4606  * It is the responsibility of the caller to then call the abort() or
4607  * commit() for any other BDS that have been left in a prepare() state
4608  *
4609  */
4610 static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
4611                                BlockReopenQueue *queue,
4612                                Transaction *change_child_tran, Error **errp)
4613 {
4614     int ret = -1;
4615     int old_flags;
4616     Error *local_err = NULL;
4617     BlockDriver *drv;
4618     QemuOpts *opts;
4619     QDict *orig_reopen_opts;
4620     char *discard = NULL;
4621     bool read_only;
4622     bool drv_prepared = false;
4623 
4624     assert(reopen_state != NULL);
4625     assert(reopen_state->bs->drv != NULL);
4626     GLOBAL_STATE_CODE();
4627     drv = reopen_state->bs->drv;
4628 
4629     /* This function and each driver's bdrv_reopen_prepare() remove
4630      * entries from reopen_state->options as they are processed, so
4631      * we need to make a copy of the original QDict. */
4632     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
4633 
4634     /* Process generic block layer options */
4635     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4636     if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4637         ret = -EINVAL;
4638         goto error;
4639     }
4640 
4641     /* This was already called in bdrv_reopen_queue_child() so the flags
4642      * are up-to-date. This time we simply want to remove the options from
4643      * QemuOpts in order to indicate that they have been processed. */
4644     old_flags = reopen_state->flags;
4645     update_flags_from_options(&reopen_state->flags, opts);
4646     assert(old_flags == reopen_state->flags);
4647 
4648     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4649     if (discard != NULL) {
4650         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4651             error_setg(errp, "Invalid discard option");
4652             ret = -EINVAL;
4653             goto error;
4654         }
4655     }
4656 
4657     reopen_state->detect_zeroes =
4658         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4659     if (local_err) {
4660         error_propagate(errp, local_err);
4661         ret = -EINVAL;
4662         goto error;
4663     }
4664 
4665     /* All other options (including node-name and driver) must be unchanged.
4666      * Put them back into the QDict, so that they are checked at the end
4667      * of this function. */
4668     qemu_opts_to_qdict(opts, reopen_state->options);
4669 
4670     /* If we are to stay read-only, do not allow permission change
4671      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
4672      * not set, or if the BDS still has copy_on_read enabled */
4673     read_only = !(reopen_state->flags & BDRV_O_RDWR);
4674     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
4675     if (local_err) {
4676         error_propagate(errp, local_err);
4677         goto error;
4678     }
4679 
4680     if (drv->bdrv_reopen_prepare) {
4681         /*
4682          * If a driver-specific option is missing, it means that we
4683          * should reset it to its default value.
4684          * But not all options allow that, so we need to check it first.
4685          */
4686         ret = bdrv_reset_options_allowed(reopen_state->bs,
4687                                          reopen_state->options, errp);
4688         if (ret) {
4689             goto error;
4690         }
4691 
4692         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4693         if (ret) {
4694             if (local_err != NULL) {
4695                 error_propagate(errp, local_err);
4696             } else {
4697                 bdrv_refresh_filename(reopen_state->bs);
4698                 error_setg(errp, "failed while preparing to reopen image '%s'",
4699                            reopen_state->bs->filename);
4700             }
4701             goto error;
4702         }
4703     } else {
4704         /* It is currently mandatory to have a bdrv_reopen_prepare()
4705          * handler for each supported drv. */
4706         error_setg(errp, "Block format '%s' used by node '%s' "
4707                    "does not support reopening files", drv->format_name,
4708                    bdrv_get_device_or_node_name(reopen_state->bs));
4709         ret = -1;
4710         goto error;
4711     }
4712 
4713     drv_prepared = true;
4714 
4715     /*
4716      * We must provide the 'backing' option if the BDS has a backing
4717      * file or if the image file has a backing file name as part of
4718      * its metadata. Otherwise the 'backing' option can be omitted.
4719      */
4720     if (drv->supports_backing && reopen_state->backing_missing &&
4721         (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
4722         error_setg(errp, "backing is missing for '%s'",
4723                    reopen_state->bs->node_name);
4724         ret = -EINVAL;
4725         goto error;
4726     }
4727 
4728     /*
4729      * Allow changing the 'backing' option. The new value can be
4730      * either a reference to an existing node (using its node name)
4731      * or NULL to simply detach the current backing file.
4732      */
4733     ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4734                                             change_child_tran, errp);
4735     if (ret < 0) {
4736         goto error;
4737     }
4738     qdict_del(reopen_state->options, "backing");
4739 
4740     /* Allow changing the 'file' option. In this case NULL is not allowed */
4741     ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4742                                             change_child_tran, errp);
4743     if (ret < 0) {
4744         goto error;
4745     }
4746     qdict_del(reopen_state->options, "file");
4747 
4748     /* Options that are not handled are only okay if they are unchanged
4749      * compared to the old state. It is expected that some options are only
4750      * used for the initial open, but not reopen (e.g. filename) */
4751     if (qdict_size(reopen_state->options)) {
4752         const QDictEntry *entry = qdict_first(reopen_state->options);
4753 
4754         do {
4755             QObject *new = entry->value;
4756             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
4757 
4758             /* Allow child references (child_name=node_name) as long as they
4759              * point to the current child (i.e. everything stays the same). */
4760             if (qobject_type(new) == QTYPE_QSTRING) {
4761                 BdrvChild *child;
4762                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4763                     if (!strcmp(child->name, entry->key)) {
4764                         break;
4765                     }
4766                 }
4767 
4768                 if (child) {
4769                     if (!strcmp(child->bs->node_name,
4770                                 qstring_get_str(qobject_to(QString, new)))) {
4771                         continue; /* Found child with this name, skip option */
4772                     }
4773                 }
4774             }
4775 
4776             /*
4777              * TODO: When using -drive to specify blockdev options, all values
4778              * will be strings; however, when using -blockdev, blockdev-add or
4779              * filenames using the json:{} pseudo-protocol, they will be
4780              * correctly typed.
4781              * In contrast, reopening options are (currently) always strings
4782              * (because you can only specify them through qemu-io; all other
4783              * callers do not specify any options).
4784              * Therefore, when using anything other than -drive to create a BDS,
4785              * this cannot detect non-string options as unchanged, because
4786              * qobject_is_equal() always returns false for objects of different
4787              * type.  In the future, this should be remedied by correctly typing
4788              * all options.  For now, this is not too big of an issue because
4789              * the user can simply omit options which cannot be changed anyway,
4790              * so they will stay unchanged.
4791              */
4792             if (!qobject_is_equal(new, old)) {
4793                 error_setg(errp, "Cannot change the option '%s'", entry->key);
4794                 ret = -EINVAL;
4795                 goto error;
4796             }
4797         } while ((entry = qdict_next(reopen_state->options, entry)));
4798     }
4799 
4800     ret = 0;
4801 
4802     /* Restore the original reopen_state->options QDict */
4803     qobject_unref(reopen_state->options);
4804     reopen_state->options = qobject_ref(orig_reopen_opts);
4805 
4806 error:
4807     if (ret < 0 && drv_prepared) {
4808         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
4809          * call drv->bdrv_reopen_abort() before signaling an error
4810          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
4811          * when the respective bdrv_reopen_prepare() has failed) */
4812         if (drv->bdrv_reopen_abort) {
4813             drv->bdrv_reopen_abort(reopen_state);
4814         }
4815     }
4816     qemu_opts_del(opts);
4817     qobject_unref(orig_reopen_opts);
4818     g_free(discard);
4819     return ret;
4820 }
4821 
4822 /*
4823  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
4824  * makes them final by swapping the staging BlockDriverState contents into
4825  * the active BlockDriverState contents.
4826  */
4827 static void bdrv_reopen_commit(BDRVReopenState *reopen_state)
4828 {
4829     BlockDriver *drv;
4830     BlockDriverState *bs;
4831     BdrvChild *child;
4832 
4833     assert(reopen_state != NULL);
4834     bs = reopen_state->bs;
4835     drv = bs->drv;
4836     assert(drv != NULL);
4837     GLOBAL_STATE_CODE();
4838 
4839     /* If there are any driver level actions to take */
4840     if (drv->bdrv_reopen_commit) {
4841         drv->bdrv_reopen_commit(reopen_state);
4842     }
4843 
4844     /* set BDS specific flags now */
4845     qobject_unref(bs->explicit_options);
4846     qobject_unref(bs->options);
4847     qobject_ref(reopen_state->explicit_options);
4848     qobject_ref(reopen_state->options);
4849 
4850     bs->explicit_options   = reopen_state->explicit_options;
4851     bs->options            = reopen_state->options;
4852     bs->open_flags         = reopen_state->flags;
4853     bs->detect_zeroes      = reopen_state->detect_zeroes;
4854 
4855     /* Remove child references from bs->options and bs->explicit_options.
4856      * Child options were already removed in bdrv_reopen_queue_child() */
4857     QLIST_FOREACH(child, &bs->children, next) {
4858         qdict_del(bs->explicit_options, child->name);
4859         qdict_del(bs->options, child->name);
4860     }
4861     /* backing is probably removed, so it's not handled by previous loop */
4862     qdict_del(bs->explicit_options, "backing");
4863     qdict_del(bs->options, "backing");
4864 
4865     bdrv_refresh_limits(bs, NULL, NULL);
4866 }
4867 
4868 /*
4869  * Abort the reopen, and delete and free the staged changes in
4870  * reopen_state
4871  */
4872 static void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4873 {
4874     BlockDriver *drv;
4875 
4876     assert(reopen_state != NULL);
4877     drv = reopen_state->bs->drv;
4878     assert(drv != NULL);
4879     GLOBAL_STATE_CODE();
4880 
4881     if (drv->bdrv_reopen_abort) {
4882         drv->bdrv_reopen_abort(reopen_state);
4883     }
4884 }
4885 
4886 
4887 static void bdrv_close(BlockDriverState *bs)
4888 {
4889     BdrvAioNotifier *ban, *ban_next;
4890     BdrvChild *child, *next;
4891 
4892     GLOBAL_STATE_CODE();
4893     assert(!bs->refcnt);
4894 
4895     bdrv_drained_begin(bs); /* complete I/O */
4896     bdrv_flush(bs);
4897     bdrv_drain(bs); /* in case flush left pending I/O */
4898 
4899     if (bs->drv) {
4900         if (bs->drv->bdrv_close) {
4901             /* Must unfreeze all children, so bdrv_unref_child() works */
4902             bs->drv->bdrv_close(bs);
4903         }
4904         bs->drv = NULL;
4905     }
4906 
4907     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4908         bdrv_unref_child(bs, child);
4909     }
4910 
4911     assert(!bs->backing);
4912     assert(!bs->file);
4913     g_free(bs->opaque);
4914     bs->opaque = NULL;
4915     qatomic_set(&bs->copy_on_read, 0);
4916     bs->backing_file[0] = '\0';
4917     bs->backing_format[0] = '\0';
4918     bs->total_sectors = 0;
4919     bs->encrypted = false;
4920     bs->sg = false;
4921     qobject_unref(bs->options);
4922     qobject_unref(bs->explicit_options);
4923     bs->options = NULL;
4924     bs->explicit_options = NULL;
4925     qobject_unref(bs->full_open_options);
4926     bs->full_open_options = NULL;
4927     g_free(bs->block_status_cache);
4928     bs->block_status_cache = NULL;
4929 
4930     bdrv_release_named_dirty_bitmaps(bs);
4931     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4932 
4933     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4934         g_free(ban);
4935     }
4936     QLIST_INIT(&bs->aio_notifiers);
4937     bdrv_drained_end(bs);
4938 
4939     /*
4940      * If we're still inside some bdrv_drain_all_begin()/end() sections, end
4941      * them now since this BDS won't exist anymore when bdrv_drain_all_end()
4942      * gets called.
4943      */
4944     if (bs->quiesce_counter) {
4945         bdrv_drain_all_end_quiesce(bs);
4946     }
4947 }
4948 
4949 void bdrv_close_all(void)
4950 {
4951     GLOBAL_STATE_CODE();
4952     assert(job_next(NULL) == NULL);
4953 
4954     /* Drop references from requests still in flight, such as canceled block
4955      * jobs whose AIO context has not been polled yet */
4956     bdrv_drain_all();
4957 
4958     blk_remove_all_bs();
4959     blockdev_close_all_bdrv_states();
4960 
4961     assert(QTAILQ_EMPTY(&all_bdrv_states));
4962 }
4963 
4964 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4965 {
4966     GQueue *queue;
4967     GHashTable *found;
4968     bool ret;
4969 
4970     if (c->klass->stay_at_node) {
4971         return false;
4972     }
4973 
4974     /* If the child @c belongs to the BDS @to, replacing the current
4975      * c->bs by @to would mean to create a loop.
4976      *
4977      * Such a case occurs when appending a BDS to a backing chain.
4978      * For instance, imagine the following chain:
4979      *
4980      *   guest device -> node A -> further backing chain...
4981      *
4982      * Now we create a new BDS B which we want to put on top of this
4983      * chain, so we first attach A as its backing node:
4984      *
4985      *                   node B
4986      *                     |
4987      *                     v
4988      *   guest device -> node A -> further backing chain...
4989      *
4990      * Finally we want to replace A by B.  When doing that, we want to
4991      * replace all pointers to A by pointers to B -- except for the
4992      * pointer from B because (1) that would create a loop, and (2)
4993      * that pointer should simply stay intact:
4994      *
4995      *   guest device -> node B
4996      *                     |
4997      *                     v
4998      *                   node A -> further backing chain...
4999      *
5000      * In general, when replacing a node A (c->bs) by a node B (@to),
5001      * if A is a child of B, that means we cannot replace A by B there
5002      * because that would create a loop.  Silently detaching A from B
5003      * is also not really an option.  So overall just leaving A in
5004      * place there is the most sensible choice.
5005      *
5006      * We would also create a loop in any cases where @c is only
5007      * indirectly referenced by @to. Prevent this by returning false
5008      * if @c is found (by breadth-first search) anywhere in the whole
5009      * subtree of @to.
5010      */
5011 
5012     ret = true;
5013     found = g_hash_table_new(NULL, NULL);
5014     g_hash_table_add(found, to);
5015     queue = g_queue_new();
5016     g_queue_push_tail(queue, to);
5017 
5018     while (!g_queue_is_empty(queue)) {
5019         BlockDriverState *v = g_queue_pop_head(queue);
5020         BdrvChild *c2;
5021 
5022         QLIST_FOREACH(c2, &v->children, next) {
5023             if (c2 == c) {
5024                 ret = false;
5025                 break;
5026             }
5027 
5028             if (g_hash_table_contains(found, c2->bs)) {
5029                 continue;
5030             }
5031 
5032             g_queue_push_tail(queue, c2->bs);
5033             g_hash_table_add(found, c2->bs);
5034         }
5035     }
5036 
5037     g_queue_free(queue);
5038     g_hash_table_destroy(found);
5039 
5040     return ret;
5041 }
5042 
5043 static void bdrv_remove_child_commit(void *opaque)
5044 {
5045     GLOBAL_STATE_CODE();
5046     bdrv_child_free(opaque);
5047 }
5048 
5049 static TransactionActionDrv bdrv_remove_child_drv = {
5050     .commit = bdrv_remove_child_commit,
5051 };
5052 
5053 /* Function doesn't update permissions, caller is responsible for this. */
5054 static void bdrv_remove_child(BdrvChild *child, Transaction *tran)
5055 {
5056     if (!child) {
5057         return;
5058     }
5059 
5060     if (child->bs) {
5061         bdrv_replace_child_tran(child, NULL, tran);
5062     }
5063 
5064     tran_add(tran, &bdrv_remove_child_drv, child);
5065 }
5066 
5067 /*
5068  * A function to remove backing-chain child of @bs if exists: cow child for
5069  * format nodes (always .backing) and filter child for filters (may be .file or
5070  * .backing)
5071  */
5072 static void bdrv_remove_filter_or_cow_child(BlockDriverState *bs,
5073                                             Transaction *tran)
5074 {
5075     bdrv_remove_child(bdrv_filter_or_cow_child(bs), tran);
5076 }
5077 
5078 static int bdrv_replace_node_noperm(BlockDriverState *from,
5079                                     BlockDriverState *to,
5080                                     bool auto_skip, Transaction *tran,
5081                                     Error **errp)
5082 {
5083     BdrvChild *c, *next;
5084 
5085     GLOBAL_STATE_CODE();
5086 
5087     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5088         assert(c->bs == from);
5089         if (!should_update_child(c, to)) {
5090             if (auto_skip) {
5091                 continue;
5092             }
5093             error_setg(errp, "Should not change '%s' link to '%s'",
5094                        c->name, from->node_name);
5095             return -EINVAL;
5096         }
5097         if (c->frozen) {
5098             error_setg(errp, "Cannot change '%s' link to '%s'",
5099                        c->name, from->node_name);
5100             return -EPERM;
5101         }
5102         bdrv_replace_child_tran(c, to, tran);
5103     }
5104 
5105     return 0;
5106 }
5107 
5108 /*
5109  * With auto_skip=true bdrv_replace_node_common skips updating from parents
5110  * if it creates a parent-child relation loop or if parent is block-job.
5111  *
5112  * With auto_skip=false the error is returned if from has a parent which should
5113  * not be updated.
5114  *
5115  * With @detach_subchain=true @to must be in a backing chain of @from. In this
5116  * case backing link of the cow-parent of @to is removed.
5117  */
5118 static int bdrv_replace_node_common(BlockDriverState *from,
5119                                     BlockDriverState *to,
5120                                     bool auto_skip, bool detach_subchain,
5121                                     Error **errp)
5122 {
5123     Transaction *tran = tran_new();
5124     g_autoptr(GHashTable) found = NULL;
5125     g_autoptr(GSList) refresh_list = NULL;
5126     BlockDriverState *to_cow_parent = NULL;
5127     int ret;
5128 
5129     GLOBAL_STATE_CODE();
5130 
5131     if (detach_subchain) {
5132         assert(bdrv_chain_contains(from, to));
5133         assert(from != to);
5134         for (to_cow_parent = from;
5135              bdrv_filter_or_cow_bs(to_cow_parent) != to;
5136              to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5137         {
5138             ;
5139         }
5140     }
5141 
5142     /* Make sure that @from doesn't go away until we have successfully attached
5143      * all of its parents to @to. */
5144     bdrv_ref(from);
5145 
5146     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
5147     assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5148     bdrv_drained_begin(from);
5149 
5150     /*
5151      * Do the replacement without permission update.
5152      * Replacement may influence the permissions, we should calculate new
5153      * permissions based on new graph. If we fail, we'll roll-back the
5154      * replacement.
5155      */
5156     ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5157     if (ret < 0) {
5158         goto out;
5159     }
5160 
5161     if (detach_subchain) {
5162         bdrv_remove_filter_or_cow_child(to_cow_parent, tran);
5163     }
5164 
5165     found = g_hash_table_new(NULL, NULL);
5166 
5167     refresh_list = bdrv_topological_dfs(refresh_list, found, to);
5168     refresh_list = bdrv_topological_dfs(refresh_list, found, from);
5169 
5170     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5171     if (ret < 0) {
5172         goto out;
5173     }
5174 
5175     ret = 0;
5176 
5177 out:
5178     tran_finalize(tran, ret);
5179 
5180     bdrv_drained_end(from);
5181     bdrv_unref(from);
5182 
5183     return ret;
5184 }
5185 
5186 int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
5187                       Error **errp)
5188 {
5189     GLOBAL_STATE_CODE();
5190 
5191     return bdrv_replace_node_common(from, to, true, false, errp);
5192 }
5193 
5194 int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
5195 {
5196     GLOBAL_STATE_CODE();
5197 
5198     return bdrv_replace_node_common(bs, bdrv_filter_or_cow_bs(bs), true, true,
5199                                     errp);
5200 }
5201 
5202 /*
5203  * Add new bs contents at the top of an image chain while the chain is
5204  * live, while keeping required fields on the top layer.
5205  *
5206  * This will modify the BlockDriverState fields, and swap contents
5207  * between bs_new and bs_top. Both bs_new and bs_top are modified.
5208  *
5209  * bs_new must not be attached to a BlockBackend and must not have backing
5210  * child.
5211  *
5212  * This function does not create any image files.
5213  */
5214 int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5215                 Error **errp)
5216 {
5217     int ret;
5218     BdrvChild *child;
5219     Transaction *tran = tran_new();
5220 
5221     GLOBAL_STATE_CODE();
5222 
5223     assert(!bs_new->backing);
5224 
5225     child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
5226                                      &child_of_bds, bdrv_backing_role(bs_new),
5227                                      tran, errp);
5228     if (!child) {
5229         ret = -EINVAL;
5230         goto out;
5231     }
5232 
5233     ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5234     if (ret < 0) {
5235         goto out;
5236     }
5237 
5238     ret = bdrv_refresh_perms(bs_new, errp);
5239 out:
5240     tran_finalize(tran, ret);
5241 
5242     bdrv_refresh_limits(bs_top, NULL, NULL);
5243 
5244     return ret;
5245 }
5246 
5247 /* Not for empty child */
5248 int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5249                           Error **errp)
5250 {
5251     int ret;
5252     Transaction *tran = tran_new();
5253     g_autoptr(GHashTable) found = NULL;
5254     g_autoptr(GSList) refresh_list = NULL;
5255     BlockDriverState *old_bs = child->bs;
5256 
5257     GLOBAL_STATE_CODE();
5258 
5259     bdrv_ref(old_bs);
5260     bdrv_drained_begin(old_bs);
5261     bdrv_drained_begin(new_bs);
5262 
5263     bdrv_replace_child_tran(child, new_bs, tran);
5264 
5265     found = g_hash_table_new(NULL, NULL);
5266     refresh_list = bdrv_topological_dfs(refresh_list, found, old_bs);
5267     refresh_list = bdrv_topological_dfs(refresh_list, found, new_bs);
5268 
5269     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5270 
5271     tran_finalize(tran, ret);
5272 
5273     bdrv_drained_end(old_bs);
5274     bdrv_drained_end(new_bs);
5275     bdrv_unref(old_bs);
5276 
5277     return ret;
5278 }
5279 
5280 static void bdrv_delete(BlockDriverState *bs)
5281 {
5282     assert(bdrv_op_blocker_is_empty(bs));
5283     assert(!bs->refcnt);
5284     GLOBAL_STATE_CODE();
5285 
5286     /* remove from list, if necessary */
5287     if (bs->node_name[0] != '\0') {
5288         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
5289     }
5290     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
5291 
5292     bdrv_close(bs);
5293 
5294     g_free(bs);
5295 }
5296 
5297 
5298 /*
5299  * Replace @bs by newly created block node.
5300  *
5301  * @options is a QDict of options to pass to the block drivers, or NULL for an
5302  * empty set of options. The reference to the QDict belongs to the block layer
5303  * after the call (even on failure), so if the caller intends to reuse the
5304  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
5305  */
5306 BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
5307                                    int flags, Error **errp)
5308 {
5309     ERRP_GUARD();
5310     int ret;
5311     BlockDriverState *new_node_bs = NULL;
5312     const char *drvname, *node_name;
5313     BlockDriver *drv;
5314 
5315     drvname = qdict_get_try_str(options, "driver");
5316     if (!drvname) {
5317         error_setg(errp, "driver is not specified");
5318         goto fail;
5319     }
5320 
5321     drv = bdrv_find_format(drvname);
5322     if (!drv) {
5323         error_setg(errp, "Unknown driver: '%s'", drvname);
5324         goto fail;
5325     }
5326 
5327     node_name = qdict_get_try_str(options, "node-name");
5328 
5329     GLOBAL_STATE_CODE();
5330 
5331     new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5332                                             errp);
5333     options = NULL; /* bdrv_new_open_driver() eats options */
5334     if (!new_node_bs) {
5335         error_prepend(errp, "Could not create node: ");
5336         goto fail;
5337     }
5338 
5339     bdrv_drained_begin(bs);
5340     ret = bdrv_replace_node(bs, new_node_bs, errp);
5341     bdrv_drained_end(bs);
5342 
5343     if (ret < 0) {
5344         error_prepend(errp, "Could not replace node: ");
5345         goto fail;
5346     }
5347 
5348     return new_node_bs;
5349 
5350 fail:
5351     qobject_unref(options);
5352     bdrv_unref(new_node_bs);
5353     return NULL;
5354 }
5355 
5356 /*
5357  * Run consistency checks on an image
5358  *
5359  * Returns 0 if the check could be completed (it doesn't mean that the image is
5360  * free of errors) or -errno when an internal error occurred. The results of the
5361  * check are stored in res.
5362  */
5363 int coroutine_fn bdrv_co_check(BlockDriverState *bs,
5364                                BdrvCheckResult *res, BdrvCheckMode fix)
5365 {
5366     IO_CODE();
5367     if (bs->drv == NULL) {
5368         return -ENOMEDIUM;
5369     }
5370     if (bs->drv->bdrv_co_check == NULL) {
5371         return -ENOTSUP;
5372     }
5373 
5374     memset(res, 0, sizeof(*res));
5375     return bs->drv->bdrv_co_check(bs, res, fix);
5376 }
5377 
5378 /*
5379  * Return values:
5380  * 0        - success
5381  * -EINVAL  - backing format specified, but no file
5382  * -ENOSPC  - can't update the backing file because no space is left in the
5383  *            image file header
5384  * -ENOTSUP - format driver doesn't support changing the backing file
5385  */
5386 int bdrv_change_backing_file(BlockDriverState *bs, const char *backing_file,
5387                              const char *backing_fmt, bool require)
5388 {
5389     BlockDriver *drv = bs->drv;
5390     int ret;
5391 
5392     GLOBAL_STATE_CODE();
5393 
5394     if (!drv) {
5395         return -ENOMEDIUM;
5396     }
5397 
5398     /* Backing file format doesn't make sense without a backing file */
5399     if (backing_fmt && !backing_file) {
5400         return -EINVAL;
5401     }
5402 
5403     if (require && backing_file && !backing_fmt) {
5404         return -EINVAL;
5405     }
5406 
5407     if (drv->bdrv_change_backing_file != NULL) {
5408         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
5409     } else {
5410         ret = -ENOTSUP;
5411     }
5412 
5413     if (ret == 0) {
5414         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5415         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5416         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5417                 backing_file ?: "");
5418     }
5419     return ret;
5420 }
5421 
5422 /*
5423  * Finds the first non-filter node above bs in the chain between
5424  * active and bs.  The returned node is either an immediate parent of
5425  * bs, or there are only filter nodes between the two.
5426  *
5427  * Returns NULL if bs is not found in active's image chain,
5428  * or if active == bs.
5429  *
5430  * Returns the bottommost base image if bs == NULL.
5431  */
5432 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
5433                                     BlockDriverState *bs)
5434 {
5435 
5436     GLOBAL_STATE_CODE();
5437 
5438     bs = bdrv_skip_filters(bs);
5439     active = bdrv_skip_filters(active);
5440 
5441     while (active) {
5442         BlockDriverState *next = bdrv_backing_chain_next(active);
5443         if (bs == next) {
5444             return active;
5445         }
5446         active = next;
5447     }
5448 
5449     return NULL;
5450 }
5451 
5452 /* Given a BDS, searches for the base layer. */
5453 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
5454 {
5455     GLOBAL_STATE_CODE();
5456 
5457     return bdrv_find_overlay(bs, NULL);
5458 }
5459 
5460 /*
5461  * Return true if at least one of the COW (backing) and filter links
5462  * between @bs and @base is frozen. @errp is set if that's the case.
5463  * @base must be reachable from @bs, or NULL.
5464  */
5465 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
5466                                   Error **errp)
5467 {
5468     BlockDriverState *i;
5469     BdrvChild *child;
5470 
5471     GLOBAL_STATE_CODE();
5472 
5473     for (i = bs; i != base; i = child_bs(child)) {
5474         child = bdrv_filter_or_cow_child(i);
5475 
5476         if (child && child->frozen) {
5477             error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
5478                        child->name, i->node_name, child->bs->node_name);
5479             return true;
5480         }
5481     }
5482 
5483     return false;
5484 }
5485 
5486 /*
5487  * Freeze all COW (backing) and filter links between @bs and @base.
5488  * If any of the links is already frozen the operation is aborted and
5489  * none of the links are modified.
5490  * @base must be reachable from @bs, or NULL.
5491  * Returns 0 on success. On failure returns < 0 and sets @errp.
5492  */
5493 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
5494                               Error **errp)
5495 {
5496     BlockDriverState *i;
5497     BdrvChild *child;
5498 
5499     GLOBAL_STATE_CODE();
5500 
5501     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
5502         return -EPERM;
5503     }
5504 
5505     for (i = bs; i != base; i = child_bs(child)) {
5506         child = bdrv_filter_or_cow_child(i);
5507         if (child && child->bs->never_freeze) {
5508             error_setg(errp, "Cannot freeze '%s' link to '%s'",
5509                        child->name, child->bs->node_name);
5510             return -EPERM;
5511         }
5512     }
5513 
5514     for (i = bs; i != base; i = child_bs(child)) {
5515         child = bdrv_filter_or_cow_child(i);
5516         if (child) {
5517             child->frozen = true;
5518         }
5519     }
5520 
5521     return 0;
5522 }
5523 
5524 /*
5525  * Unfreeze all COW (backing) and filter links between @bs and @base.
5526  * The caller must ensure that all links are frozen before using this
5527  * function.
5528  * @base must be reachable from @bs, or NULL.
5529  */
5530 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
5531 {
5532     BlockDriverState *i;
5533     BdrvChild *child;
5534 
5535     GLOBAL_STATE_CODE();
5536 
5537     for (i = bs; i != base; i = child_bs(child)) {
5538         child = bdrv_filter_or_cow_child(i);
5539         if (child) {
5540             assert(child->frozen);
5541             child->frozen = false;
5542         }
5543     }
5544 }
5545 
5546 /*
5547  * Drops images above 'base' up to and including 'top', and sets the image
5548  * above 'top' to have base as its backing file.
5549  *
5550  * Requires that the overlay to 'top' is opened r/w, so that the backing file
5551  * information in 'bs' can be properly updated.
5552  *
5553  * E.g., this will convert the following chain:
5554  * bottom <- base <- intermediate <- top <- active
5555  *
5556  * to
5557  *
5558  * bottom <- base <- active
5559  *
5560  * It is allowed for bottom==base, in which case it converts:
5561  *
5562  * base <- intermediate <- top <- active
5563  *
5564  * to
5565  *
5566  * base <- active
5567  *
5568  * If backing_file_str is non-NULL, it will be used when modifying top's
5569  * overlay image metadata.
5570  *
5571  * Error conditions:
5572  *  if active == top, that is considered an error
5573  *
5574  */
5575 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
5576                            const char *backing_file_str)
5577 {
5578     BlockDriverState *explicit_top = top;
5579     bool update_inherits_from;
5580     BdrvChild *c;
5581     Error *local_err = NULL;
5582     int ret = -EIO;
5583     g_autoptr(GSList) updated_children = NULL;
5584     GSList *p;
5585 
5586     GLOBAL_STATE_CODE();
5587 
5588     bdrv_ref(top);
5589     bdrv_subtree_drained_begin(top);
5590 
5591     if (!top->drv || !base->drv) {
5592         goto exit;
5593     }
5594 
5595     /* Make sure that base is in the backing chain of top */
5596     if (!bdrv_chain_contains(top, base)) {
5597         goto exit;
5598     }
5599 
5600     /* If 'base' recursively inherits from 'top' then we should set
5601      * base->inherits_from to top->inherits_from after 'top' and all
5602      * other intermediate nodes have been dropped.
5603      * If 'top' is an implicit node (e.g. "commit_top") we should skip
5604      * it because no one inherits from it. We use explicit_top for that. */
5605     explicit_top = bdrv_skip_implicit_filters(explicit_top);
5606     update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
5607 
5608     /* success - we can delete the intermediate states, and link top->base */
5609     if (!backing_file_str) {
5610         bdrv_refresh_filename(base);
5611         backing_file_str = base->filename;
5612     }
5613 
5614     QLIST_FOREACH(c, &top->parents, next_parent) {
5615         updated_children = g_slist_prepend(updated_children, c);
5616     }
5617 
5618     /*
5619      * It seems correct to pass detach_subchain=true here, but it triggers
5620      * one more yet not fixed bug, when due to nested aio_poll loop we switch to
5621      * another drained section, which modify the graph (for example, removing
5622      * the child, which we keep in updated_children list). So, it's a TODO.
5623      *
5624      * Note, bug triggered if pass detach_subchain=true here and run
5625      * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
5626      * That's a FIXME.
5627      */
5628     bdrv_replace_node_common(top, base, false, false, &local_err);
5629     if (local_err) {
5630         error_report_err(local_err);
5631         goto exit;
5632     }
5633 
5634     for (p = updated_children; p; p = p->next) {
5635         c = p->data;
5636 
5637         if (c->klass->update_filename) {
5638             ret = c->klass->update_filename(c, base, backing_file_str,
5639                                             &local_err);
5640             if (ret < 0) {
5641                 /*
5642                  * TODO: Actually, we want to rollback all previous iterations
5643                  * of this loop, and (which is almost impossible) previous
5644                  * bdrv_replace_node()...
5645                  *
5646                  * Note, that c->klass->update_filename may lead to permission
5647                  * update, so it's a bad idea to call it inside permission
5648                  * update transaction of bdrv_replace_node.
5649                  */
5650                 error_report_err(local_err);
5651                 goto exit;
5652             }
5653         }
5654     }
5655 
5656     if (update_inherits_from) {
5657         base->inherits_from = explicit_top->inherits_from;
5658     }
5659 
5660     ret = 0;
5661 exit:
5662     bdrv_subtree_drained_end(top);
5663     bdrv_unref(top);
5664     return ret;
5665 }
5666 
5667 /**
5668  * Implementation of BlockDriver.bdrv_get_allocated_file_size() that
5669  * sums the size of all data-bearing children.  (This excludes backing
5670  * children.)
5671  */
5672 static int64_t bdrv_sum_allocated_file_size(BlockDriverState *bs)
5673 {
5674     BdrvChild *child;
5675     int64_t child_size, sum = 0;
5676 
5677     QLIST_FOREACH(child, &bs->children, next) {
5678         if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5679                            BDRV_CHILD_FILTERED))
5680         {
5681             child_size = bdrv_get_allocated_file_size(child->bs);
5682             if (child_size < 0) {
5683                 return child_size;
5684             }
5685             sum += child_size;
5686         }
5687     }
5688 
5689     return sum;
5690 }
5691 
5692 /**
5693  * Length of a allocated file in bytes. Sparse files are counted by actual
5694  * allocated space. Return < 0 if error or unknown.
5695  */
5696 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
5697 {
5698     BlockDriver *drv = bs->drv;
5699     IO_CODE();
5700 
5701     if (!drv) {
5702         return -ENOMEDIUM;
5703     }
5704     if (drv->bdrv_get_allocated_file_size) {
5705         return drv->bdrv_get_allocated_file_size(bs);
5706     }
5707 
5708     if (drv->bdrv_file_open) {
5709         /*
5710          * Protocol drivers default to -ENOTSUP (most of their data is
5711          * not stored in any of their children (if they even have any),
5712          * so there is no generic way to figure it out).
5713          */
5714         return -ENOTSUP;
5715     } else if (drv->is_filter) {
5716         /* Filter drivers default to the size of their filtered child */
5717         return bdrv_get_allocated_file_size(bdrv_filter_bs(bs));
5718     } else {
5719         /* Other drivers default to summing their children's sizes */
5720         return bdrv_sum_allocated_file_size(bs);
5721     }
5722 }
5723 
5724 /*
5725  * bdrv_measure:
5726  * @drv: Format driver
5727  * @opts: Creation options for new image
5728  * @in_bs: Existing image containing data for new image (may be NULL)
5729  * @errp: Error object
5730  * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
5731  *          or NULL on error
5732  *
5733  * Calculate file size required to create a new image.
5734  *
5735  * If @in_bs is given then space for allocated clusters and zero clusters
5736  * from that image are included in the calculation.  If @opts contains a
5737  * backing file that is shared by @in_bs then backing clusters may be omitted
5738  * from the calculation.
5739  *
5740  * If @in_bs is NULL then the calculation includes no allocated clusters
5741  * unless a preallocation option is given in @opts.
5742  *
5743  * Note that @in_bs may use a different BlockDriver from @drv.
5744  *
5745  * If an error occurs the @errp pointer is set.
5746  */
5747 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
5748                                BlockDriverState *in_bs, Error **errp)
5749 {
5750     IO_CODE();
5751     if (!drv->bdrv_measure) {
5752         error_setg(errp, "Block driver '%s' does not support size measurement",
5753                    drv->format_name);
5754         return NULL;
5755     }
5756 
5757     return drv->bdrv_measure(opts, in_bs, errp);
5758 }
5759 
5760 /**
5761  * Return number of sectors on success, -errno on error.
5762  */
5763 int64_t bdrv_nb_sectors(BlockDriverState *bs)
5764 {
5765     BlockDriver *drv = bs->drv;
5766     IO_CODE();
5767 
5768     if (!drv)
5769         return -ENOMEDIUM;
5770 
5771     if (drv->has_variable_length) {
5772         int ret = refresh_total_sectors(bs, bs->total_sectors);
5773         if (ret < 0) {
5774             return ret;
5775         }
5776     }
5777     return bs->total_sectors;
5778 }
5779 
5780 /**
5781  * Return length in bytes on success, -errno on error.
5782  * The length is always a multiple of BDRV_SECTOR_SIZE.
5783  */
5784 int64_t bdrv_getlength(BlockDriverState *bs)
5785 {
5786     int64_t ret = bdrv_nb_sectors(bs);
5787     IO_CODE();
5788 
5789     if (ret < 0) {
5790         return ret;
5791     }
5792     if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
5793         return -EFBIG;
5794     }
5795     return ret * BDRV_SECTOR_SIZE;
5796 }
5797 
5798 /* return 0 as number of sectors if no device present or error */
5799 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
5800 {
5801     int64_t nb_sectors = bdrv_nb_sectors(bs);
5802     IO_CODE();
5803 
5804     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
5805 }
5806 
5807 bool bdrv_is_sg(BlockDriverState *bs)
5808 {
5809     IO_CODE();
5810     return bs->sg;
5811 }
5812 
5813 /**
5814  * Return whether the given node supports compressed writes.
5815  */
5816 bool bdrv_supports_compressed_writes(BlockDriverState *bs)
5817 {
5818     BlockDriverState *filtered;
5819     IO_CODE();
5820 
5821     if (!bs->drv || !block_driver_can_compress(bs->drv)) {
5822         return false;
5823     }
5824 
5825     filtered = bdrv_filter_bs(bs);
5826     if (filtered) {
5827         /*
5828          * Filters can only forward compressed writes, so we have to
5829          * check the child.
5830          */
5831         return bdrv_supports_compressed_writes(filtered);
5832     }
5833 
5834     return true;
5835 }
5836 
5837 const char *bdrv_get_format_name(BlockDriverState *bs)
5838 {
5839     IO_CODE();
5840     return bs->drv ? bs->drv->format_name : NULL;
5841 }
5842 
5843 static int qsort_strcmp(const void *a, const void *b)
5844 {
5845     return strcmp(*(char *const *)a, *(char *const *)b);
5846 }
5847 
5848 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
5849                          void *opaque, bool read_only)
5850 {
5851     BlockDriver *drv;
5852     int count = 0;
5853     int i;
5854     const char **formats = NULL;
5855 
5856     GLOBAL_STATE_CODE();
5857 
5858     QLIST_FOREACH(drv, &bdrv_drivers, list) {
5859         if (drv->format_name) {
5860             bool found = false;
5861             int i = count;
5862 
5863             if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
5864                 continue;
5865             }
5866 
5867             while (formats && i && !found) {
5868                 found = !strcmp(formats[--i], drv->format_name);
5869             }
5870 
5871             if (!found) {
5872                 formats = g_renew(const char *, formats, count + 1);
5873                 formats[count++] = drv->format_name;
5874             }
5875         }
5876     }
5877 
5878     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
5879         const char *format_name = block_driver_modules[i].format_name;
5880 
5881         if (format_name) {
5882             bool found = false;
5883             int j = count;
5884 
5885             if (use_bdrv_whitelist &&
5886                 !bdrv_format_is_whitelisted(format_name, read_only)) {
5887                 continue;
5888             }
5889 
5890             while (formats && j && !found) {
5891                 found = !strcmp(formats[--j], format_name);
5892             }
5893 
5894             if (!found) {
5895                 formats = g_renew(const char *, formats, count + 1);
5896                 formats[count++] = format_name;
5897             }
5898         }
5899     }
5900 
5901     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
5902 
5903     for (i = 0; i < count; i++) {
5904         it(opaque, formats[i]);
5905     }
5906 
5907     g_free(formats);
5908 }
5909 
5910 /* This function is to find a node in the bs graph */
5911 BlockDriverState *bdrv_find_node(const char *node_name)
5912 {
5913     BlockDriverState *bs;
5914 
5915     assert(node_name);
5916     GLOBAL_STATE_CODE();
5917 
5918     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5919         if (!strcmp(node_name, bs->node_name)) {
5920             return bs;
5921         }
5922     }
5923     return NULL;
5924 }
5925 
5926 /* Put this QMP function here so it can access the static graph_bdrv_states. */
5927 BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
5928                                            Error **errp)
5929 {
5930     BlockDeviceInfoList *list;
5931     BlockDriverState *bs;
5932 
5933     GLOBAL_STATE_CODE();
5934 
5935     list = NULL;
5936     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
5937         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
5938         if (!info) {
5939             qapi_free_BlockDeviceInfoList(list);
5940             return NULL;
5941         }
5942         QAPI_LIST_PREPEND(list, info);
5943     }
5944 
5945     return list;
5946 }
5947 
5948 typedef struct XDbgBlockGraphConstructor {
5949     XDbgBlockGraph *graph;
5950     GHashTable *graph_nodes;
5951 } XDbgBlockGraphConstructor;
5952 
5953 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
5954 {
5955     XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
5956 
5957     gr->graph = g_new0(XDbgBlockGraph, 1);
5958     gr->graph_nodes = g_hash_table_new(NULL, NULL);
5959 
5960     return gr;
5961 }
5962 
5963 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
5964 {
5965     XDbgBlockGraph *graph = gr->graph;
5966 
5967     g_hash_table_destroy(gr->graph_nodes);
5968     g_free(gr);
5969 
5970     return graph;
5971 }
5972 
5973 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
5974 {
5975     uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
5976 
5977     if (ret != 0) {
5978         return ret;
5979     }
5980 
5981     /*
5982      * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
5983      * answer of g_hash_table_lookup.
5984      */
5985     ret = g_hash_table_size(gr->graph_nodes) + 1;
5986     g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
5987 
5988     return ret;
5989 }
5990 
5991 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
5992                                 XDbgBlockGraphNodeType type, const char *name)
5993 {
5994     XDbgBlockGraphNode *n;
5995 
5996     n = g_new0(XDbgBlockGraphNode, 1);
5997 
5998     n->id = xdbg_graph_node_num(gr, node);
5999     n->type = type;
6000     n->name = g_strdup(name);
6001 
6002     QAPI_LIST_PREPEND(gr->graph->nodes, n);
6003 }
6004 
6005 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
6006                                 const BdrvChild *child)
6007 {
6008     BlockPermission qapi_perm;
6009     XDbgBlockGraphEdge *edge;
6010     GLOBAL_STATE_CODE();
6011 
6012     edge = g_new0(XDbgBlockGraphEdge, 1);
6013 
6014     edge->parent = xdbg_graph_node_num(gr, parent);
6015     edge->child = xdbg_graph_node_num(gr, child->bs);
6016     edge->name = g_strdup(child->name);
6017 
6018     for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6019         uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6020 
6021         if (flag & child->perm) {
6022             QAPI_LIST_PREPEND(edge->perm, qapi_perm);
6023         }
6024         if (flag & child->shared_perm) {
6025             QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
6026         }
6027     }
6028 
6029     QAPI_LIST_PREPEND(gr->graph->edges, edge);
6030 }
6031 
6032 
6033 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
6034 {
6035     BlockBackend *blk;
6036     BlockJob *job;
6037     BlockDriverState *bs;
6038     BdrvChild *child;
6039     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
6040 
6041     GLOBAL_STATE_CODE();
6042 
6043     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
6044         char *allocated_name = NULL;
6045         const char *name = blk_name(blk);
6046 
6047         if (!*name) {
6048             name = allocated_name = blk_get_attached_dev_id(blk);
6049         }
6050         xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
6051                            name);
6052         g_free(allocated_name);
6053         if (blk_root(blk)) {
6054             xdbg_graph_add_edge(gr, blk, blk_root(blk));
6055         }
6056     }
6057 
6058     WITH_JOB_LOCK_GUARD() {
6059         for (job = block_job_next_locked(NULL); job;
6060              job = block_job_next_locked(job)) {
6061             GSList *el;
6062 
6063             xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
6064                                 job->job.id);
6065             for (el = job->nodes; el; el = el->next) {
6066                 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
6067             }
6068         }
6069     }
6070 
6071     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6072         xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
6073                            bs->node_name);
6074         QLIST_FOREACH(child, &bs->children, next) {
6075             xdbg_graph_add_edge(gr, bs, child);
6076         }
6077     }
6078 
6079     return xdbg_graph_finalize(gr);
6080 }
6081 
6082 BlockDriverState *bdrv_lookup_bs(const char *device,
6083                                  const char *node_name,
6084                                  Error **errp)
6085 {
6086     BlockBackend *blk;
6087     BlockDriverState *bs;
6088 
6089     GLOBAL_STATE_CODE();
6090 
6091     if (device) {
6092         blk = blk_by_name(device);
6093 
6094         if (blk) {
6095             bs = blk_bs(blk);
6096             if (!bs) {
6097                 error_setg(errp, "Device '%s' has no medium", device);
6098             }
6099 
6100             return bs;
6101         }
6102     }
6103 
6104     if (node_name) {
6105         bs = bdrv_find_node(node_name);
6106 
6107         if (bs) {
6108             return bs;
6109         }
6110     }
6111 
6112     error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6113                      device ? device : "",
6114                      node_name ? node_name : "");
6115     return NULL;
6116 }
6117 
6118 /* If 'base' is in the same chain as 'top', return true. Otherwise,
6119  * return false.  If either argument is NULL, return false. */
6120 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
6121 {
6122 
6123     GLOBAL_STATE_CODE();
6124 
6125     while (top && top != base) {
6126         top = bdrv_filter_or_cow_bs(top);
6127     }
6128 
6129     return top != NULL;
6130 }
6131 
6132 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
6133 {
6134     GLOBAL_STATE_CODE();
6135     if (!bs) {
6136         return QTAILQ_FIRST(&graph_bdrv_states);
6137     }
6138     return QTAILQ_NEXT(bs, node_list);
6139 }
6140 
6141 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
6142 {
6143     GLOBAL_STATE_CODE();
6144     if (!bs) {
6145         return QTAILQ_FIRST(&all_bdrv_states);
6146     }
6147     return QTAILQ_NEXT(bs, bs_list);
6148 }
6149 
6150 const char *bdrv_get_node_name(const BlockDriverState *bs)
6151 {
6152     IO_CODE();
6153     return bs->node_name;
6154 }
6155 
6156 const char *bdrv_get_parent_name(const BlockDriverState *bs)
6157 {
6158     BdrvChild *c;
6159     const char *name;
6160     IO_CODE();
6161 
6162     /* If multiple parents have a name, just pick the first one. */
6163     QLIST_FOREACH(c, &bs->parents, next_parent) {
6164         if (c->klass->get_name) {
6165             name = c->klass->get_name(c);
6166             if (name && *name) {
6167                 return name;
6168             }
6169         }
6170     }
6171 
6172     return NULL;
6173 }
6174 
6175 /* TODO check what callers really want: bs->node_name or blk_name() */
6176 const char *bdrv_get_device_name(const BlockDriverState *bs)
6177 {
6178     IO_CODE();
6179     return bdrv_get_parent_name(bs) ?: "";
6180 }
6181 
6182 /* This can be used to identify nodes that might not have a device
6183  * name associated. Since node and device names live in the same
6184  * namespace, the result is unambiguous. The exception is if both are
6185  * absent, then this returns an empty (non-null) string. */
6186 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
6187 {
6188     IO_CODE();
6189     return bdrv_get_parent_name(bs) ?: bs->node_name;
6190 }
6191 
6192 int bdrv_get_flags(BlockDriverState *bs)
6193 {
6194     IO_CODE();
6195     return bs->open_flags;
6196 }
6197 
6198 int bdrv_has_zero_init_1(BlockDriverState *bs)
6199 {
6200     GLOBAL_STATE_CODE();
6201     return 1;
6202 }
6203 
6204 int bdrv_has_zero_init(BlockDriverState *bs)
6205 {
6206     BlockDriverState *filtered;
6207     GLOBAL_STATE_CODE();
6208 
6209     if (!bs->drv) {
6210         return 0;
6211     }
6212 
6213     /* If BS is a copy on write image, it is initialized to
6214        the contents of the base image, which may not be zeroes.  */
6215     if (bdrv_cow_child(bs)) {
6216         return 0;
6217     }
6218     if (bs->drv->bdrv_has_zero_init) {
6219         return bs->drv->bdrv_has_zero_init(bs);
6220     }
6221 
6222     filtered = bdrv_filter_bs(bs);
6223     if (filtered) {
6224         return bdrv_has_zero_init(filtered);
6225     }
6226 
6227     /* safe default */
6228     return 0;
6229 }
6230 
6231 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
6232 {
6233     IO_CODE();
6234     if (!(bs->open_flags & BDRV_O_UNMAP)) {
6235         return false;
6236     }
6237 
6238     return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
6239 }
6240 
6241 void bdrv_get_backing_filename(BlockDriverState *bs,
6242                                char *filename, int filename_size)
6243 {
6244     IO_CODE();
6245     pstrcpy(filename, filename_size, bs->backing_file);
6246 }
6247 
6248 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6249 {
6250     int ret;
6251     BlockDriver *drv = bs->drv;
6252     IO_CODE();
6253     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
6254     if (!drv) {
6255         return -ENOMEDIUM;
6256     }
6257     if (!drv->bdrv_get_info) {
6258         BlockDriverState *filtered = bdrv_filter_bs(bs);
6259         if (filtered) {
6260             return bdrv_get_info(filtered, bdi);
6261         }
6262         return -ENOTSUP;
6263     }
6264     memset(bdi, 0, sizeof(*bdi));
6265     ret = drv->bdrv_get_info(bs, bdi);
6266     if (ret < 0) {
6267         return ret;
6268     }
6269 
6270     if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
6271         return -EINVAL;
6272     }
6273 
6274     return 0;
6275 }
6276 
6277 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
6278                                           Error **errp)
6279 {
6280     BlockDriver *drv = bs->drv;
6281     IO_CODE();
6282     if (drv && drv->bdrv_get_specific_info) {
6283         return drv->bdrv_get_specific_info(bs, errp);
6284     }
6285     return NULL;
6286 }
6287 
6288 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6289 {
6290     BlockDriver *drv = bs->drv;
6291     IO_CODE();
6292     if (!drv || !drv->bdrv_get_specific_stats) {
6293         return NULL;
6294     }
6295     return drv->bdrv_get_specific_stats(bs);
6296 }
6297 
6298 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
6299 {
6300     IO_CODE();
6301     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
6302         return;
6303     }
6304 
6305     bs->drv->bdrv_debug_event(bs, event);
6306 }
6307 
6308 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
6309 {
6310     GLOBAL_STATE_CODE();
6311     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6312         bs = bdrv_primary_bs(bs);
6313     }
6314 
6315     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6316         assert(bs->drv->bdrv_debug_remove_breakpoint);
6317         return bs;
6318     }
6319 
6320     return NULL;
6321 }
6322 
6323 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6324                           const char *tag)
6325 {
6326     GLOBAL_STATE_CODE();
6327     bs = bdrv_find_debug_node(bs);
6328     if (bs) {
6329         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
6330     }
6331 
6332     return -ENOTSUP;
6333 }
6334 
6335 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
6336 {
6337     GLOBAL_STATE_CODE();
6338     bs = bdrv_find_debug_node(bs);
6339     if (bs) {
6340         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
6341     }
6342 
6343     return -ENOTSUP;
6344 }
6345 
6346 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
6347 {
6348     GLOBAL_STATE_CODE();
6349     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6350         bs = bdrv_primary_bs(bs);
6351     }
6352 
6353     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
6354         return bs->drv->bdrv_debug_resume(bs, tag);
6355     }
6356 
6357     return -ENOTSUP;
6358 }
6359 
6360 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
6361 {
6362     GLOBAL_STATE_CODE();
6363     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6364         bs = bdrv_primary_bs(bs);
6365     }
6366 
6367     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
6368         return bs->drv->bdrv_debug_is_suspended(bs, tag);
6369     }
6370 
6371     return false;
6372 }
6373 
6374 /* backing_file can either be relative, or absolute, or a protocol.  If it is
6375  * relative, it must be relative to the chain.  So, passing in bs->filename
6376  * from a BDS as backing_file should not be done, as that may be relative to
6377  * the CWD rather than the chain. */
6378 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6379         const char *backing_file)
6380 {
6381     char *filename_full = NULL;
6382     char *backing_file_full = NULL;
6383     char *filename_tmp = NULL;
6384     int is_protocol = 0;
6385     bool filenames_refreshed = false;
6386     BlockDriverState *curr_bs = NULL;
6387     BlockDriverState *retval = NULL;
6388     BlockDriverState *bs_below;
6389 
6390     GLOBAL_STATE_CODE();
6391 
6392     if (!bs || !bs->drv || !backing_file) {
6393         return NULL;
6394     }
6395 
6396     filename_full     = g_malloc(PATH_MAX);
6397     backing_file_full = g_malloc(PATH_MAX);
6398 
6399     is_protocol = path_has_protocol(backing_file);
6400 
6401     /*
6402      * Being largely a legacy function, skip any filters here
6403      * (because filters do not have normal filenames, so they cannot
6404      * match anyway; and allowing json:{} filenames is a bit out of
6405      * scope).
6406      */
6407     for (curr_bs = bdrv_skip_filters(bs);
6408          bdrv_cow_child(curr_bs) != NULL;
6409          curr_bs = bs_below)
6410     {
6411         bs_below = bdrv_backing_chain_next(curr_bs);
6412 
6413         if (bdrv_backing_overridden(curr_bs)) {
6414             /*
6415              * If the backing file was overridden, we can only compare
6416              * directly against the backing node's filename.
6417              */
6418 
6419             if (!filenames_refreshed) {
6420                 /*
6421                  * This will automatically refresh all of the
6422                  * filenames in the rest of the backing chain, so we
6423                  * only need to do this once.
6424                  */
6425                 bdrv_refresh_filename(bs_below);
6426                 filenames_refreshed = true;
6427             }
6428 
6429             if (strcmp(backing_file, bs_below->filename) == 0) {
6430                 retval = bs_below;
6431                 break;
6432             }
6433         } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
6434             /*
6435              * If either of the filename paths is actually a protocol, then
6436              * compare unmodified paths; otherwise make paths relative.
6437              */
6438             char *backing_file_full_ret;
6439 
6440             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6441                 retval = bs_below;
6442                 break;
6443             }
6444             /* Also check against the full backing filename for the image */
6445             backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
6446                                                                    NULL);
6447             if (backing_file_full_ret) {
6448                 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
6449                 g_free(backing_file_full_ret);
6450                 if (equal) {
6451                     retval = bs_below;
6452                     break;
6453                 }
6454             }
6455         } else {
6456             /* If not an absolute filename path, make it relative to the current
6457              * image's filename path */
6458             filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
6459                                                        NULL);
6460             /* We are going to compare canonicalized absolute pathnames */
6461             if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
6462                 g_free(filename_tmp);
6463                 continue;
6464             }
6465             g_free(filename_tmp);
6466 
6467             /* We need to make sure the backing filename we are comparing against
6468              * is relative to the current image filename (or absolute) */
6469             filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
6470             if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
6471                 g_free(filename_tmp);
6472                 continue;
6473             }
6474             g_free(filename_tmp);
6475 
6476             if (strcmp(backing_file_full, filename_full) == 0) {
6477                 retval = bs_below;
6478                 break;
6479             }
6480         }
6481     }
6482 
6483     g_free(filename_full);
6484     g_free(backing_file_full);
6485     return retval;
6486 }
6487 
6488 void bdrv_init(void)
6489 {
6490 #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6491     use_bdrv_whitelist = 1;
6492 #endif
6493     module_call_init(MODULE_INIT_BLOCK);
6494 }
6495 
6496 void bdrv_init_with_whitelist(void)
6497 {
6498     use_bdrv_whitelist = 1;
6499     bdrv_init();
6500 }
6501 
6502 int bdrv_activate(BlockDriverState *bs, Error **errp)
6503 {
6504     BdrvChild *child, *parent;
6505     Error *local_err = NULL;
6506     int ret;
6507     BdrvDirtyBitmap *bm;
6508 
6509     GLOBAL_STATE_CODE();
6510 
6511     if (!bs->drv)  {
6512         return -ENOMEDIUM;
6513     }
6514 
6515     QLIST_FOREACH(child, &bs->children, next) {
6516         bdrv_activate(child->bs, &local_err);
6517         if (local_err) {
6518             error_propagate(errp, local_err);
6519             return -EINVAL;
6520         }
6521     }
6522 
6523     /*
6524      * Update permissions, they may differ for inactive nodes.
6525      *
6526      * Note that the required permissions of inactive images are always a
6527      * subset of the permissions required after activating the image. This
6528      * allows us to just get the permissions upfront without restricting
6529      * bdrv_co_invalidate_cache().
6530      *
6531      * It also means that in error cases, we don't have to try and revert to
6532      * the old permissions (which is an operation that could fail, too). We can
6533      * just keep the extended permissions for the next time that an activation
6534      * of the image is tried.
6535      */
6536     if (bs->open_flags & BDRV_O_INACTIVE) {
6537         bs->open_flags &= ~BDRV_O_INACTIVE;
6538         ret = bdrv_refresh_perms(bs, errp);
6539         if (ret < 0) {
6540             bs->open_flags |= BDRV_O_INACTIVE;
6541             return ret;
6542         }
6543 
6544         ret = bdrv_invalidate_cache(bs, errp);
6545         if (ret < 0) {
6546             bs->open_flags |= BDRV_O_INACTIVE;
6547             return ret;
6548         }
6549 
6550         FOR_EACH_DIRTY_BITMAP(bs, bm) {
6551             bdrv_dirty_bitmap_skip_store(bm, false);
6552         }
6553 
6554         ret = refresh_total_sectors(bs, bs->total_sectors);
6555         if (ret < 0) {
6556             bs->open_flags |= BDRV_O_INACTIVE;
6557             error_setg_errno(errp, -ret, "Could not refresh total sector count");
6558             return ret;
6559         }
6560     }
6561 
6562     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6563         if (parent->klass->activate) {
6564             parent->klass->activate(parent, &local_err);
6565             if (local_err) {
6566                 bs->open_flags |= BDRV_O_INACTIVE;
6567                 error_propagate(errp, local_err);
6568                 return -EINVAL;
6569             }
6570         }
6571     }
6572 
6573     return 0;
6574 }
6575 
6576 int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
6577 {
6578     Error *local_err = NULL;
6579     IO_CODE();
6580 
6581     assert(!(bs->open_flags & BDRV_O_INACTIVE));
6582 
6583     if (bs->drv->bdrv_co_invalidate_cache) {
6584         bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
6585         if (local_err) {
6586             error_propagate(errp, local_err);
6587             return -EINVAL;
6588         }
6589     }
6590 
6591     return 0;
6592 }
6593 
6594 void bdrv_activate_all(Error **errp)
6595 {
6596     BlockDriverState *bs;
6597     BdrvNextIterator it;
6598 
6599     GLOBAL_STATE_CODE();
6600 
6601     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6602         AioContext *aio_context = bdrv_get_aio_context(bs);
6603         int ret;
6604 
6605         aio_context_acquire(aio_context);
6606         ret = bdrv_activate(bs, errp);
6607         aio_context_release(aio_context);
6608         if (ret < 0) {
6609             bdrv_next_cleanup(&it);
6610             return;
6611         }
6612     }
6613 }
6614 
6615 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
6616 {
6617     BdrvChild *parent;
6618     GLOBAL_STATE_CODE();
6619 
6620     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6621         if (parent->klass->parent_is_bds) {
6622             BlockDriverState *parent_bs = parent->opaque;
6623             if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
6624                 return true;
6625             }
6626         }
6627     }
6628 
6629     return false;
6630 }
6631 
6632 static int bdrv_inactivate_recurse(BlockDriverState *bs)
6633 {
6634     BdrvChild *child, *parent;
6635     int ret;
6636     uint64_t cumulative_perms, cumulative_shared_perms;
6637 
6638     GLOBAL_STATE_CODE();
6639 
6640     if (!bs->drv) {
6641         return -ENOMEDIUM;
6642     }
6643 
6644     /* Make sure that we don't inactivate a child before its parent.
6645      * It will be covered by recursion from the yet active parent. */
6646     if (bdrv_has_bds_parent(bs, true)) {
6647         return 0;
6648     }
6649 
6650     assert(!(bs->open_flags & BDRV_O_INACTIVE));
6651 
6652     /* Inactivate this node */
6653     if (bs->drv->bdrv_inactivate) {
6654         ret = bs->drv->bdrv_inactivate(bs);
6655         if (ret < 0) {
6656             return ret;
6657         }
6658     }
6659 
6660     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6661         if (parent->klass->inactivate) {
6662             ret = parent->klass->inactivate(parent);
6663             if (ret < 0) {
6664                 return ret;
6665             }
6666         }
6667     }
6668 
6669     bdrv_get_cumulative_perm(bs, &cumulative_perms,
6670                              &cumulative_shared_perms);
6671     if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6672         /* Our inactive parents still need write access. Inactivation failed. */
6673         return -EPERM;
6674     }
6675 
6676     bs->open_flags |= BDRV_O_INACTIVE;
6677 
6678     /*
6679      * Update permissions, they may differ for inactive nodes.
6680      * We only tried to loosen restrictions, so errors are not fatal, ignore
6681      * them.
6682      */
6683     bdrv_refresh_perms(bs, NULL);
6684 
6685     /* Recursively inactivate children */
6686     QLIST_FOREACH(child, &bs->children, next) {
6687         ret = bdrv_inactivate_recurse(child->bs);
6688         if (ret < 0) {
6689             return ret;
6690         }
6691     }
6692 
6693     return 0;
6694 }
6695 
6696 int bdrv_inactivate_all(void)
6697 {
6698     BlockDriverState *bs = NULL;
6699     BdrvNextIterator it;
6700     int ret = 0;
6701     GSList *aio_ctxs = NULL, *ctx;
6702 
6703     GLOBAL_STATE_CODE();
6704 
6705     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6706         AioContext *aio_context = bdrv_get_aio_context(bs);
6707 
6708         if (!g_slist_find(aio_ctxs, aio_context)) {
6709             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
6710             aio_context_acquire(aio_context);
6711         }
6712     }
6713 
6714     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6715         /* Nodes with BDS parents are covered by recursion from the last
6716          * parent that gets inactivated. Don't inactivate them a second
6717          * time if that has already happened. */
6718         if (bdrv_has_bds_parent(bs, false)) {
6719             continue;
6720         }
6721         ret = bdrv_inactivate_recurse(bs);
6722         if (ret < 0) {
6723             bdrv_next_cleanup(&it);
6724             goto out;
6725         }
6726     }
6727 
6728 out:
6729     for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
6730         AioContext *aio_context = ctx->data;
6731         aio_context_release(aio_context);
6732     }
6733     g_slist_free(aio_ctxs);
6734 
6735     return ret;
6736 }
6737 
6738 /**************************************************************/
6739 /* removable device support */
6740 
6741 /**
6742  * Return TRUE if the media is present
6743  */
6744 bool bdrv_is_inserted(BlockDriverState *bs)
6745 {
6746     BlockDriver *drv = bs->drv;
6747     BdrvChild *child;
6748     IO_CODE();
6749 
6750     if (!drv) {
6751         return false;
6752     }
6753     if (drv->bdrv_is_inserted) {
6754         return drv->bdrv_is_inserted(bs);
6755     }
6756     QLIST_FOREACH(child, &bs->children, next) {
6757         if (!bdrv_is_inserted(child->bs)) {
6758             return false;
6759         }
6760     }
6761     return true;
6762 }
6763 
6764 /**
6765  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
6766  */
6767 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
6768 {
6769     BlockDriver *drv = bs->drv;
6770     IO_CODE();
6771 
6772     if (drv && drv->bdrv_eject) {
6773         drv->bdrv_eject(bs, eject_flag);
6774     }
6775 }
6776 
6777 /**
6778  * Lock or unlock the media (if it is locked, the user won't be able
6779  * to eject it manually).
6780  */
6781 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
6782 {
6783     BlockDriver *drv = bs->drv;
6784     IO_CODE();
6785     trace_bdrv_lock_medium(bs, locked);
6786 
6787     if (drv && drv->bdrv_lock_medium) {
6788         drv->bdrv_lock_medium(bs, locked);
6789     }
6790 }
6791 
6792 /* Get a reference to bs */
6793 void bdrv_ref(BlockDriverState *bs)
6794 {
6795     GLOBAL_STATE_CODE();
6796     bs->refcnt++;
6797 }
6798 
6799 /* Release a previously grabbed reference to bs.
6800  * If after releasing, reference count is zero, the BlockDriverState is
6801  * deleted. */
6802 void bdrv_unref(BlockDriverState *bs)
6803 {
6804     GLOBAL_STATE_CODE();
6805     if (!bs) {
6806         return;
6807     }
6808     assert(bs->refcnt > 0);
6809     if (--bs->refcnt == 0) {
6810         bdrv_delete(bs);
6811     }
6812 }
6813 
6814 struct BdrvOpBlocker {
6815     Error *reason;
6816     QLIST_ENTRY(BdrvOpBlocker) list;
6817 };
6818 
6819 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
6820 {
6821     BdrvOpBlocker *blocker;
6822     GLOBAL_STATE_CODE();
6823     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6824     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
6825         blocker = QLIST_FIRST(&bs->op_blockers[op]);
6826         error_propagate_prepend(errp, error_copy(blocker->reason),
6827                                 "Node '%s' is busy: ",
6828                                 bdrv_get_device_or_node_name(bs));
6829         return true;
6830     }
6831     return false;
6832 }
6833 
6834 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
6835 {
6836     BdrvOpBlocker *blocker;
6837     GLOBAL_STATE_CODE();
6838     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6839 
6840     blocker = g_new0(BdrvOpBlocker, 1);
6841     blocker->reason = reason;
6842     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
6843 }
6844 
6845 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
6846 {
6847     BdrvOpBlocker *blocker, *next;
6848     GLOBAL_STATE_CODE();
6849     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
6850     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
6851         if (blocker->reason == reason) {
6852             QLIST_REMOVE(blocker, list);
6853             g_free(blocker);
6854         }
6855     }
6856 }
6857 
6858 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
6859 {
6860     int i;
6861     GLOBAL_STATE_CODE();
6862     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6863         bdrv_op_block(bs, i, reason);
6864     }
6865 }
6866 
6867 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
6868 {
6869     int i;
6870     GLOBAL_STATE_CODE();
6871     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6872         bdrv_op_unblock(bs, i, reason);
6873     }
6874 }
6875 
6876 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
6877 {
6878     int i;
6879     GLOBAL_STATE_CODE();
6880     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
6881         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
6882             return false;
6883         }
6884     }
6885     return true;
6886 }
6887 
6888 void bdrv_img_create(const char *filename, const char *fmt,
6889                      const char *base_filename, const char *base_fmt,
6890                      char *options, uint64_t img_size, int flags, bool quiet,
6891                      Error **errp)
6892 {
6893     QemuOptsList *create_opts = NULL;
6894     QemuOpts *opts = NULL;
6895     const char *backing_fmt, *backing_file;
6896     int64_t size;
6897     BlockDriver *drv, *proto_drv;
6898     Error *local_err = NULL;
6899     int ret = 0;
6900 
6901     GLOBAL_STATE_CODE();
6902 
6903     /* Find driver and parse its options */
6904     drv = bdrv_find_format(fmt);
6905     if (!drv) {
6906         error_setg(errp, "Unknown file format '%s'", fmt);
6907         return;
6908     }
6909 
6910     proto_drv = bdrv_find_protocol(filename, true, errp);
6911     if (!proto_drv) {
6912         return;
6913     }
6914 
6915     if (!drv->create_opts) {
6916         error_setg(errp, "Format driver '%s' does not support image creation",
6917                    drv->format_name);
6918         return;
6919     }
6920 
6921     if (!proto_drv->create_opts) {
6922         error_setg(errp, "Protocol driver '%s' does not support image creation",
6923                    proto_drv->format_name);
6924         return;
6925     }
6926 
6927     /* Create parameter list */
6928     create_opts = qemu_opts_append(create_opts, drv->create_opts);
6929     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
6930 
6931     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
6932 
6933     /* Parse -o options */
6934     if (options) {
6935         if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
6936             goto out;
6937         }
6938     }
6939 
6940     if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
6941         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
6942     } else if (img_size != UINT64_C(-1)) {
6943         error_setg(errp, "The image size must be specified only once");
6944         goto out;
6945     }
6946 
6947     if (base_filename) {
6948         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
6949                           NULL)) {
6950             error_setg(errp, "Backing file not supported for file format '%s'",
6951                        fmt);
6952             goto out;
6953         }
6954     }
6955 
6956     if (base_fmt) {
6957         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
6958             error_setg(errp, "Backing file format not supported for file "
6959                              "format '%s'", fmt);
6960             goto out;
6961         }
6962     }
6963 
6964     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
6965     if (backing_file) {
6966         if (!strcmp(filename, backing_file)) {
6967             error_setg(errp, "Error: Trying to create an image with the "
6968                              "same filename as the backing file");
6969             goto out;
6970         }
6971         if (backing_file[0] == '\0') {
6972             error_setg(errp, "Expected backing file name, got empty string");
6973             goto out;
6974         }
6975     }
6976 
6977     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
6978 
6979     /* The size for the image must always be specified, unless we have a backing
6980      * file and we have not been forbidden from opening it. */
6981     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
6982     if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
6983         BlockDriverState *bs;
6984         char *full_backing;
6985         int back_flags;
6986         QDict *backing_options = NULL;
6987 
6988         full_backing =
6989             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
6990                                                          &local_err);
6991         if (local_err) {
6992             goto out;
6993         }
6994         assert(full_backing);
6995 
6996         /*
6997          * No need to do I/O here, which allows us to open encrypted
6998          * backing images without needing the secret
6999          */
7000         back_flags = flags;
7001         back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7002         back_flags |= BDRV_O_NO_IO;
7003 
7004         backing_options = qdict_new();
7005         if (backing_fmt) {
7006             qdict_put_str(backing_options, "driver", backing_fmt);
7007         }
7008         qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7009 
7010         bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
7011                        &local_err);
7012         g_free(full_backing);
7013         if (!bs) {
7014             error_append_hint(&local_err, "Could not open backing image.\n");
7015             goto out;
7016         } else {
7017             if (!backing_fmt) {
7018                 error_setg(&local_err,
7019                            "Backing file specified without backing format");
7020                 error_append_hint(&local_err, "Detected format of %s.",
7021                                   bs->drv->format_name);
7022                 goto out;
7023             }
7024             if (size == -1) {
7025                 /* Opened BS, have no size */
7026                 size = bdrv_getlength(bs);
7027                 if (size < 0) {
7028                     error_setg_errno(errp, -size, "Could not get size of '%s'",
7029                                      backing_file);
7030                     bdrv_unref(bs);
7031                     goto out;
7032                 }
7033                 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
7034             }
7035             bdrv_unref(bs);
7036         }
7037         /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7038     } else if (backing_file && !backing_fmt) {
7039         error_setg(&local_err,
7040                    "Backing file specified without backing format");
7041         goto out;
7042     }
7043 
7044     if (size == -1) {
7045         error_setg(errp, "Image creation needs a size parameter");
7046         goto out;
7047     }
7048 
7049     if (!quiet) {
7050         printf("Formatting '%s', fmt=%s ", filename, fmt);
7051         qemu_opts_print(opts, " ");
7052         puts("");
7053         fflush(stdout);
7054     }
7055 
7056     ret = bdrv_create(drv, filename, opts, &local_err);
7057 
7058     if (ret == -EFBIG) {
7059         /* This is generally a better message than whatever the driver would
7060          * deliver (especially because of the cluster_size_hint), since that
7061          * is most probably not much different from "image too large". */
7062         const char *cluster_size_hint = "";
7063         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7064             cluster_size_hint = " (try using a larger cluster size)";
7065         }
7066         error_setg(errp, "The image size is too large for file format '%s'"
7067                    "%s", fmt, cluster_size_hint);
7068         error_free(local_err);
7069         local_err = NULL;
7070     }
7071 
7072 out:
7073     qemu_opts_del(opts);
7074     qemu_opts_free(create_opts);
7075     error_propagate(errp, local_err);
7076 }
7077 
7078 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
7079 {
7080     IO_CODE();
7081     return bs ? bs->aio_context : qemu_get_aio_context();
7082 }
7083 
7084 AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7085 {
7086     Coroutine *self = qemu_coroutine_self();
7087     AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7088     AioContext *new_ctx;
7089     IO_CODE();
7090 
7091     /*
7092      * Increase bs->in_flight to ensure that this operation is completed before
7093      * moving the node to a different AioContext. Read new_ctx only afterwards.
7094      */
7095     bdrv_inc_in_flight(bs);
7096 
7097     new_ctx = bdrv_get_aio_context(bs);
7098     aio_co_reschedule_self(new_ctx);
7099     return old_ctx;
7100 }
7101 
7102 void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7103 {
7104     IO_CODE();
7105     aio_co_reschedule_self(old_ctx);
7106     bdrv_dec_in_flight(bs);
7107 }
7108 
7109 void coroutine_fn bdrv_co_lock(BlockDriverState *bs)
7110 {
7111     AioContext *ctx = bdrv_get_aio_context(bs);
7112 
7113     /* In the main thread, bs->aio_context won't change concurrently */
7114     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7115 
7116     /*
7117      * We're in coroutine context, so we already hold the lock of the main
7118      * loop AioContext. Don't lock it twice to avoid deadlocks.
7119      */
7120     assert(qemu_in_coroutine());
7121     if (ctx != qemu_get_aio_context()) {
7122         aio_context_acquire(ctx);
7123     }
7124 }
7125 
7126 void coroutine_fn bdrv_co_unlock(BlockDriverState *bs)
7127 {
7128     AioContext *ctx = bdrv_get_aio_context(bs);
7129 
7130     assert(qemu_in_coroutine());
7131     if (ctx != qemu_get_aio_context()) {
7132         aio_context_release(ctx);
7133     }
7134 }
7135 
7136 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
7137 {
7138     IO_CODE();
7139     aio_co_enter(bdrv_get_aio_context(bs), co);
7140 }
7141 
7142 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7143 {
7144     GLOBAL_STATE_CODE();
7145     QLIST_REMOVE(ban, list);
7146     g_free(ban);
7147 }
7148 
7149 static void bdrv_detach_aio_context(BlockDriverState *bs)
7150 {
7151     BdrvAioNotifier *baf, *baf_tmp;
7152 
7153     assert(!bs->walking_aio_notifiers);
7154     GLOBAL_STATE_CODE();
7155     bs->walking_aio_notifiers = true;
7156     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7157         if (baf->deleted) {
7158             bdrv_do_remove_aio_context_notifier(baf);
7159         } else {
7160             baf->detach_aio_context(baf->opaque);
7161         }
7162     }
7163     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
7164      * remove remaining aio notifiers if we aren't called again.
7165      */
7166     bs->walking_aio_notifiers = false;
7167 
7168     if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7169         bs->drv->bdrv_detach_aio_context(bs);
7170     }
7171 
7172     if (bs->quiesce_counter) {
7173         aio_enable_external(bs->aio_context);
7174     }
7175     assert_bdrv_graph_writable(bs);
7176     bs->aio_context = NULL;
7177 }
7178 
7179 static void bdrv_attach_aio_context(BlockDriverState *bs,
7180                                     AioContext *new_context)
7181 {
7182     BdrvAioNotifier *ban, *ban_tmp;
7183     GLOBAL_STATE_CODE();
7184 
7185     if (bs->quiesce_counter) {
7186         aio_disable_external(new_context);
7187     }
7188 
7189     assert_bdrv_graph_writable(bs);
7190     bs->aio_context = new_context;
7191 
7192     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7193         bs->drv->bdrv_attach_aio_context(bs, new_context);
7194     }
7195 
7196     assert(!bs->walking_aio_notifiers);
7197     bs->walking_aio_notifiers = true;
7198     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7199         if (ban->deleted) {
7200             bdrv_do_remove_aio_context_notifier(ban);
7201         } else {
7202             ban->attached_aio_context(new_context, ban->opaque);
7203         }
7204     }
7205     bs->walking_aio_notifiers = false;
7206 }
7207 
7208 /*
7209  * Changes the AioContext used for fd handlers, timers, and BHs by this
7210  * BlockDriverState and all its children and parents.
7211  *
7212  * Must be called from the main AioContext.
7213  *
7214  * The caller must own the AioContext lock for the old AioContext of bs, but it
7215  * must not own the AioContext lock for new_context (unless new_context is the
7216  * same as the current context of bs).
7217  *
7218  * @ignore will accumulate all visited BdrvChild objects. The caller is
7219  * responsible for freeing the list afterwards.
7220  */
7221 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
7222                                  AioContext *new_context, GSList **ignore)
7223 {
7224     AioContext *old_context = bdrv_get_aio_context(bs);
7225     GSList *children_to_process = NULL;
7226     GSList *parents_to_process = NULL;
7227     GSList *entry;
7228     BdrvChild *child, *parent;
7229 
7230     g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
7231     GLOBAL_STATE_CODE();
7232 
7233     if (old_context == new_context) {
7234         return;
7235     }
7236 
7237     bdrv_drained_begin(bs);
7238 
7239     QLIST_FOREACH(child, &bs->children, next) {
7240         if (g_slist_find(*ignore, child)) {
7241             continue;
7242         }
7243         *ignore = g_slist_prepend(*ignore, child);
7244         children_to_process = g_slist_prepend(children_to_process, child);
7245     }
7246 
7247     QLIST_FOREACH(parent, &bs->parents, next_parent) {
7248         if (g_slist_find(*ignore, parent)) {
7249             continue;
7250         }
7251         *ignore = g_slist_prepend(*ignore, parent);
7252         parents_to_process = g_slist_prepend(parents_to_process, parent);
7253     }
7254 
7255     for (entry = children_to_process;
7256          entry != NULL;
7257          entry = g_slist_next(entry)) {
7258         child = entry->data;
7259         bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
7260     }
7261     g_slist_free(children_to_process);
7262 
7263     for (entry = parents_to_process;
7264          entry != NULL;
7265          entry = g_slist_next(entry)) {
7266         parent = entry->data;
7267         assert(parent->klass->set_aio_ctx);
7268         parent->klass->set_aio_ctx(parent, new_context, ignore);
7269     }
7270     g_slist_free(parents_to_process);
7271 
7272     bdrv_detach_aio_context(bs);
7273 
7274     /* Acquire the new context, if necessary */
7275     if (qemu_get_aio_context() != new_context) {
7276         aio_context_acquire(new_context);
7277     }
7278 
7279     bdrv_attach_aio_context(bs, new_context);
7280 
7281     /*
7282      * If this function was recursively called from
7283      * bdrv_set_aio_context_ignore(), there may be nodes in the
7284      * subtree that have not yet been moved to the new AioContext.
7285      * Release the old one so bdrv_drained_end() can poll them.
7286      */
7287     if (qemu_get_aio_context() != old_context) {
7288         aio_context_release(old_context);
7289     }
7290 
7291     bdrv_drained_end(bs);
7292 
7293     if (qemu_get_aio_context() != old_context) {
7294         aio_context_acquire(old_context);
7295     }
7296     if (qemu_get_aio_context() != new_context) {
7297         aio_context_release(new_context);
7298     }
7299 }
7300 
7301 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7302                                             GSList **ignore, Error **errp)
7303 {
7304     GLOBAL_STATE_CODE();
7305     if (g_slist_find(*ignore, c)) {
7306         return true;
7307     }
7308     *ignore = g_slist_prepend(*ignore, c);
7309 
7310     /*
7311      * A BdrvChildClass that doesn't handle AioContext changes cannot
7312      * tolerate any AioContext changes
7313      */
7314     if (!c->klass->can_set_aio_ctx) {
7315         char *user = bdrv_child_user_desc(c);
7316         error_setg(errp, "Changing iothreads is not supported by %s", user);
7317         g_free(user);
7318         return false;
7319     }
7320     if (!c->klass->can_set_aio_ctx(c, ctx, ignore, errp)) {
7321         assert(!errp || *errp);
7322         return false;
7323     }
7324     return true;
7325 }
7326 
7327 typedef struct BdrvStateSetAioContext {
7328     AioContext *new_ctx;
7329     BlockDriverState *bs;
7330 } BdrvStateSetAioContext;
7331 
7332 static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7333                                            GHashTable *visited,
7334                                            Transaction *tran,
7335                                            Error **errp)
7336 {
7337     GLOBAL_STATE_CODE();
7338     if (g_hash_table_contains(visited, c)) {
7339         return true;
7340     }
7341     g_hash_table_add(visited, c);
7342 
7343     /*
7344      * A BdrvChildClass that doesn't handle AioContext changes cannot
7345      * tolerate any AioContext changes
7346      */
7347     if (!c->klass->change_aio_ctx) {
7348         char *user = bdrv_child_user_desc(c);
7349         error_setg(errp, "Changing iothreads is not supported by %s", user);
7350         g_free(user);
7351         return false;
7352     }
7353     if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
7354         assert(!errp || *errp);
7355         return false;
7356     }
7357     return true;
7358 }
7359 
7360 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
7361                                     GSList **ignore, Error **errp)
7362 {
7363     GLOBAL_STATE_CODE();
7364     if (g_slist_find(*ignore, c)) {
7365         return true;
7366     }
7367     *ignore = g_slist_prepend(*ignore, c);
7368     return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
7369 }
7370 
7371 bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7372                                    GHashTable *visited, Transaction *tran,
7373                                    Error **errp)
7374 {
7375     GLOBAL_STATE_CODE();
7376     if (g_hash_table_contains(visited, c)) {
7377         return true;
7378     }
7379     g_hash_table_add(visited, c);
7380     return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
7381 }
7382 
7383 /* @ignore will accumulate all visited BdrvChild object. The caller is
7384  * responsible for freeing the list afterwards. */
7385 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7386                               GSList **ignore, Error **errp)
7387 {
7388     BdrvChild *c;
7389 
7390     if (bdrv_get_aio_context(bs) == ctx) {
7391         return true;
7392     }
7393 
7394     GLOBAL_STATE_CODE();
7395 
7396     QLIST_FOREACH(c, &bs->parents, next_parent) {
7397         if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
7398             return false;
7399         }
7400     }
7401     QLIST_FOREACH(c, &bs->children, next) {
7402         if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
7403             return false;
7404         }
7405     }
7406 
7407     return true;
7408 }
7409 
7410 static void bdrv_set_aio_context_clean(void *opaque)
7411 {
7412     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7413     BlockDriverState *bs = (BlockDriverState *) state->bs;
7414 
7415     /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
7416     bdrv_drained_end(bs);
7417 
7418     g_free(state);
7419 }
7420 
7421 static void bdrv_set_aio_context_commit(void *opaque)
7422 {
7423     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
7424     BlockDriverState *bs = (BlockDriverState *) state->bs;
7425     AioContext *new_context = state->new_ctx;
7426     AioContext *old_context = bdrv_get_aio_context(bs);
7427     assert_bdrv_graph_writable(bs);
7428 
7429     /*
7430      * Take the old AioContex when detaching it from bs.
7431      * At this point, new_context lock is already acquired, and we are now
7432      * also taking old_context. This is safe as long as bdrv_detach_aio_context
7433      * does not call AIO_POLL_WHILE().
7434      */
7435     if (old_context != qemu_get_aio_context()) {
7436         aio_context_acquire(old_context);
7437     }
7438     bdrv_detach_aio_context(bs);
7439     if (old_context != qemu_get_aio_context()) {
7440         aio_context_release(old_context);
7441     }
7442     bdrv_attach_aio_context(bs, new_context);
7443 }
7444 
7445 static TransactionActionDrv set_aio_context = {
7446     .commit = bdrv_set_aio_context_commit,
7447     .clean = bdrv_set_aio_context_clean,
7448 };
7449 
7450 /*
7451  * Changes the AioContext used for fd handlers, timers, and BHs by this
7452  * BlockDriverState and all its children and parents.
7453  *
7454  * Must be called from the main AioContext.
7455  *
7456  * The caller must own the AioContext lock for the old AioContext of bs, but it
7457  * must not own the AioContext lock for new_context (unless new_context is the
7458  * same as the current context of bs).
7459  *
7460  * @visited will accumulate all visited BdrvChild objects. The caller is
7461  * responsible for freeing the list afterwards.
7462  */
7463 static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7464                                     GHashTable *visited, Transaction *tran,
7465                                     Error **errp)
7466 {
7467     BdrvChild *c;
7468     BdrvStateSetAioContext *state;
7469 
7470     GLOBAL_STATE_CODE();
7471 
7472     if (bdrv_get_aio_context(bs) == ctx) {
7473         return true;
7474     }
7475 
7476     QLIST_FOREACH(c, &bs->parents, next_parent) {
7477         if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
7478             return false;
7479         }
7480     }
7481 
7482     QLIST_FOREACH(c, &bs->children, next) {
7483         if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
7484             return false;
7485         }
7486     }
7487 
7488     state = g_new(BdrvStateSetAioContext, 1);
7489     *state = (BdrvStateSetAioContext) {
7490         .new_ctx = ctx,
7491         .bs = bs,
7492     };
7493 
7494     /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
7495     bdrv_drained_begin(bs);
7496 
7497     tran_add(tran, &set_aio_context, state);
7498 
7499     return true;
7500 }
7501 
7502 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7503                                    BdrvChild *ignore_child, Error **errp)
7504 {
7505     GSList *ignore;
7506     bool ret;
7507 
7508     GLOBAL_STATE_CODE();
7509 
7510     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7511     ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
7512     g_slist_free(ignore);
7513 
7514     if (!ret) {
7515         return -EPERM;
7516     }
7517 
7518     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
7519     bdrv_set_aio_context_ignore(bs, ctx, &ignore);
7520     g_slist_free(ignore);
7521 
7522     return 0;
7523 }
7524 
7525 /*
7526  * Change bs's and recursively all of its parents' and children's AioContext
7527  * to the given new context, returning an error if that isn't possible.
7528  *
7529  * If ignore_child is not NULL, that child (and its subgraph) will not
7530  * be touched.
7531  *
7532  * This function still requires the caller to take the bs current
7533  * AioContext lock, otherwise draining will fail since AIO_WAIT_WHILE
7534  * assumes the lock is always held if bs is in another AioContext.
7535  * For the same reason, it temporarily also holds the new AioContext, since
7536  * bdrv_drained_end calls BDRV_POLL_WHILE that assumes the lock is taken too.
7537  * Therefore the new AioContext lock must not be taken by the caller.
7538  */
7539 int bdrv_child_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7540                                       BdrvChild *ignore_child, Error **errp)
7541 {
7542     Transaction *tran;
7543     GHashTable *visited;
7544     int ret;
7545     AioContext *old_context = bdrv_get_aio_context(bs);
7546     GLOBAL_STATE_CODE();
7547 
7548     /*
7549      * Recursion phase: go through all nodes of the graph.
7550      * Take care of checking that all nodes support changing AioContext
7551      * and drain them, builing a linear list of callbacks to run if everything
7552      * is successful (the transaction itself).
7553      */
7554     tran = tran_new();
7555     visited = g_hash_table_new(NULL, NULL);
7556     if (ignore_child) {
7557         g_hash_table_add(visited, ignore_child);
7558     }
7559     ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7560     g_hash_table_destroy(visited);
7561 
7562     /*
7563      * Linear phase: go through all callbacks collected in the transaction.
7564      * Run all callbacks collected in the recursion to switch all nodes
7565      * AioContext lock (transaction commit), or undo all changes done in the
7566      * recursion (transaction abort).
7567      */
7568 
7569     if (!ret) {
7570         /* Just run clean() callbacks. No AioContext changed. */
7571         tran_abort(tran);
7572         return -EPERM;
7573     }
7574 
7575     /*
7576      * Release old AioContext, it won't be needed anymore, as all
7577      * bdrv_drained_begin() have been called already.
7578      */
7579     if (qemu_get_aio_context() != old_context) {
7580         aio_context_release(old_context);
7581     }
7582 
7583     /*
7584      * Acquire new AioContext since bdrv_drained_end() is going to be called
7585      * after we switched all nodes in the new AioContext, and the function
7586      * assumes that the lock of the bs is always taken.
7587      */
7588     if (qemu_get_aio_context() != ctx) {
7589         aio_context_acquire(ctx);
7590     }
7591 
7592     tran_commit(tran);
7593 
7594     if (qemu_get_aio_context() != ctx) {
7595         aio_context_release(ctx);
7596     }
7597 
7598     /* Re-acquire the old AioContext, since the caller takes and releases it. */
7599     if (qemu_get_aio_context() != old_context) {
7600         aio_context_acquire(old_context);
7601     }
7602 
7603     return 0;
7604 }
7605 
7606 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
7607                              Error **errp)
7608 {
7609     GLOBAL_STATE_CODE();
7610     return bdrv_child_try_change_aio_context(bs, ctx, NULL, errp);
7611 }
7612 
7613 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
7614         void (*attached_aio_context)(AioContext *new_context, void *opaque),
7615         void (*detach_aio_context)(void *opaque), void *opaque)
7616 {
7617     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
7618     *ban = (BdrvAioNotifier){
7619         .attached_aio_context = attached_aio_context,
7620         .detach_aio_context   = detach_aio_context,
7621         .opaque               = opaque
7622     };
7623     GLOBAL_STATE_CODE();
7624 
7625     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
7626 }
7627 
7628 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
7629                                       void (*attached_aio_context)(AioContext *,
7630                                                                    void *),
7631                                       void (*detach_aio_context)(void *),
7632                                       void *opaque)
7633 {
7634     BdrvAioNotifier *ban, *ban_next;
7635     GLOBAL_STATE_CODE();
7636 
7637     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
7638         if (ban->attached_aio_context == attached_aio_context &&
7639             ban->detach_aio_context   == detach_aio_context   &&
7640             ban->opaque               == opaque               &&
7641             ban->deleted              == false)
7642         {
7643             if (bs->walking_aio_notifiers) {
7644                 ban->deleted = true;
7645             } else {
7646                 bdrv_do_remove_aio_context_notifier(ban);
7647             }
7648             return;
7649         }
7650     }
7651 
7652     abort();
7653 }
7654 
7655 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7656                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7657                        bool force,
7658                        Error **errp)
7659 {
7660     GLOBAL_STATE_CODE();
7661     if (!bs->drv) {
7662         error_setg(errp, "Node is ejected");
7663         return -ENOMEDIUM;
7664     }
7665     if (!bs->drv->bdrv_amend_options) {
7666         error_setg(errp, "Block driver '%s' does not support option amendment",
7667                    bs->drv->format_name);
7668         return -ENOTSUP;
7669     }
7670     return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7671                                        cb_opaque, force, errp);
7672 }
7673 
7674 /*
7675  * This function checks whether the given @to_replace is allowed to be
7676  * replaced by a node that always shows the same data as @bs.  This is
7677  * used for example to verify whether the mirror job can replace
7678  * @to_replace by the target mirrored from @bs.
7679  * To be replaceable, @bs and @to_replace may either be guaranteed to
7680  * always show the same data (because they are only connected through
7681  * filters), or some driver may allow replacing one of its children
7682  * because it can guarantee that this child's data is not visible at
7683  * all (for example, for dissenting quorum children that have no other
7684  * parents).
7685  */
7686 bool bdrv_recurse_can_replace(BlockDriverState *bs,
7687                               BlockDriverState *to_replace)
7688 {
7689     BlockDriverState *filtered;
7690 
7691     GLOBAL_STATE_CODE();
7692 
7693     if (!bs || !bs->drv) {
7694         return false;
7695     }
7696 
7697     if (bs == to_replace) {
7698         return true;
7699     }
7700 
7701     /* See what the driver can do */
7702     if (bs->drv->bdrv_recurse_can_replace) {
7703         return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
7704     }
7705 
7706     /* For filters without an own implementation, we can recurse on our own */
7707     filtered = bdrv_filter_bs(bs);
7708     if (filtered) {
7709         return bdrv_recurse_can_replace(filtered, to_replace);
7710     }
7711 
7712     /* Safe default */
7713     return false;
7714 }
7715 
7716 /*
7717  * Check whether the given @node_name can be replaced by a node that
7718  * has the same data as @parent_bs.  If so, return @node_name's BDS;
7719  * NULL otherwise.
7720  *
7721  * @node_name must be a (recursive) *child of @parent_bs (or this
7722  * function will return NULL).
7723  *
7724  * The result (whether the node can be replaced or not) is only valid
7725  * for as long as no graph or permission changes occur.
7726  */
7727 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7728                                         const char *node_name, Error **errp)
7729 {
7730     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
7731     AioContext *aio_context;
7732 
7733     GLOBAL_STATE_CODE();
7734 
7735     if (!to_replace_bs) {
7736         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
7737         return NULL;
7738     }
7739 
7740     aio_context = bdrv_get_aio_context(to_replace_bs);
7741     aio_context_acquire(aio_context);
7742 
7743     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7744         to_replace_bs = NULL;
7745         goto out;
7746     }
7747 
7748     /* We don't want arbitrary node of the BDS chain to be replaced only the top
7749      * most non filter in order to prevent data corruption.
7750      * Another benefit is that this tests exclude backing files which are
7751      * blocked by the backing blockers.
7752      */
7753     if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7754         error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7755                    "because it cannot be guaranteed that doing so would not "
7756                    "lead to an abrupt change of visible data",
7757                    node_name, parent_bs->node_name);
7758         to_replace_bs = NULL;
7759         goto out;
7760     }
7761 
7762 out:
7763     aio_context_release(aio_context);
7764     return to_replace_bs;
7765 }
7766 
7767 /**
7768  * Iterates through the list of runtime option keys that are said to
7769  * be "strong" for a BDS.  An option is called "strong" if it changes
7770  * a BDS's data.  For example, the null block driver's "size" and
7771  * "read-zeroes" options are strong, but its "latency-ns" option is
7772  * not.
7773  *
7774  * If a key returned by this function ends with a dot, all options
7775  * starting with that prefix are strong.
7776  */
7777 static const char *const *strong_options(BlockDriverState *bs,
7778                                          const char *const *curopt)
7779 {
7780     static const char *const global_options[] = {
7781         "driver", "filename", NULL
7782     };
7783 
7784     if (!curopt) {
7785         return &global_options[0];
7786     }
7787 
7788     curopt++;
7789     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
7790         curopt = bs->drv->strong_runtime_opts;
7791     }
7792 
7793     return (curopt && *curopt) ? curopt : NULL;
7794 }
7795 
7796 /**
7797  * Copies all strong runtime options from bs->options to the given
7798  * QDict.  The set of strong option keys is determined by invoking
7799  * strong_options().
7800  *
7801  * Returns true iff any strong option was present in bs->options (and
7802  * thus copied to the target QDict) with the exception of "filename"
7803  * and "driver".  The caller is expected to use this value to decide
7804  * whether the existence of strong options prevents the generation of
7805  * a plain filename.
7806  */
7807 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
7808 {
7809     bool found_any = false;
7810     const char *const *option_name = NULL;
7811 
7812     if (!bs->drv) {
7813         return false;
7814     }
7815 
7816     while ((option_name = strong_options(bs, option_name))) {
7817         bool option_given = false;
7818 
7819         assert(strlen(*option_name) > 0);
7820         if ((*option_name)[strlen(*option_name) - 1] != '.') {
7821             QObject *entry = qdict_get(bs->options, *option_name);
7822             if (!entry) {
7823                 continue;
7824             }
7825 
7826             qdict_put_obj(d, *option_name, qobject_ref(entry));
7827             option_given = true;
7828         } else {
7829             const QDictEntry *entry;
7830             for (entry = qdict_first(bs->options); entry;
7831                  entry = qdict_next(bs->options, entry))
7832             {
7833                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
7834                     qdict_put_obj(d, qdict_entry_key(entry),
7835                                   qobject_ref(qdict_entry_value(entry)));
7836                     option_given = true;
7837                 }
7838             }
7839         }
7840 
7841         /* While "driver" and "filename" need to be included in a JSON filename,
7842          * their existence does not prohibit generation of a plain filename. */
7843         if (!found_any && option_given &&
7844             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
7845         {
7846             found_any = true;
7847         }
7848     }
7849 
7850     if (!qdict_haskey(d, "driver")) {
7851         /* Drivers created with bdrv_new_open_driver() may not have a
7852          * @driver option.  Add it here. */
7853         qdict_put_str(d, "driver", bs->drv->format_name);
7854     }
7855 
7856     return found_any;
7857 }
7858 
7859 /* Note: This function may return false positives; it may return true
7860  * even if opening the backing file specified by bs's image header
7861  * would result in exactly bs->backing. */
7862 static bool bdrv_backing_overridden(BlockDriverState *bs)
7863 {
7864     GLOBAL_STATE_CODE();
7865     if (bs->backing) {
7866         return strcmp(bs->auto_backing_file,
7867                       bs->backing->bs->filename);
7868     } else {
7869         /* No backing BDS, so if the image header reports any backing
7870          * file, it must have been suppressed */
7871         return bs->auto_backing_file[0] != '\0';
7872     }
7873 }
7874 
7875 /* Updates the following BDS fields:
7876  *  - exact_filename: A filename which may be used for opening a block device
7877  *                    which (mostly) equals the given BDS (even without any
7878  *                    other options; so reading and writing must return the same
7879  *                    results, but caching etc. may be different)
7880  *  - full_open_options: Options which, when given when opening a block device
7881  *                       (without a filename), result in a BDS (mostly)
7882  *                       equalling the given one
7883  *  - filename: If exact_filename is set, it is copied here. Otherwise,
7884  *              full_open_options is converted to a JSON object, prefixed with
7885  *              "json:" (for use through the JSON pseudo protocol) and put here.
7886  */
7887 void bdrv_refresh_filename(BlockDriverState *bs)
7888 {
7889     BlockDriver *drv = bs->drv;
7890     BdrvChild *child;
7891     BlockDriverState *primary_child_bs;
7892     QDict *opts;
7893     bool backing_overridden;
7894     bool generate_json_filename; /* Whether our default implementation should
7895                                     fill exact_filename (false) or not (true) */
7896 
7897     GLOBAL_STATE_CODE();
7898 
7899     if (!drv) {
7900         return;
7901     }
7902 
7903     /* This BDS's file name may depend on any of its children's file names, so
7904      * refresh those first */
7905     QLIST_FOREACH(child, &bs->children, next) {
7906         bdrv_refresh_filename(child->bs);
7907     }
7908 
7909     if (bs->implicit) {
7910         /* For implicit nodes, just copy everything from the single child */
7911         child = QLIST_FIRST(&bs->children);
7912         assert(QLIST_NEXT(child, next) == NULL);
7913 
7914         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7915                 child->bs->exact_filename);
7916         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7917 
7918         qobject_unref(bs->full_open_options);
7919         bs->full_open_options = qobject_ref(child->bs->full_open_options);
7920 
7921         return;
7922     }
7923 
7924     backing_overridden = bdrv_backing_overridden(bs);
7925 
7926     if (bs->open_flags & BDRV_O_NO_IO) {
7927         /* Without I/O, the backing file does not change anything.
7928          * Therefore, in such a case (primarily qemu-img), we can
7929          * pretend the backing file has not been overridden even if
7930          * it technically has been. */
7931         backing_overridden = false;
7932     }
7933 
7934     /* Gather the options QDict */
7935     opts = qdict_new();
7936     generate_json_filename = append_strong_runtime_options(opts, bs);
7937     generate_json_filename |= backing_overridden;
7938 
7939     if (drv->bdrv_gather_child_options) {
7940         /* Some block drivers may not want to present all of their children's
7941          * options, or name them differently from BdrvChild.name */
7942         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
7943     } else {
7944         QLIST_FOREACH(child, &bs->children, next) {
7945             if (child == bs->backing && !backing_overridden) {
7946                 /* We can skip the backing BDS if it has not been overridden */
7947                 continue;
7948             }
7949 
7950             qdict_put(opts, child->name,
7951                       qobject_ref(child->bs->full_open_options));
7952         }
7953 
7954         if (backing_overridden && !bs->backing) {
7955             /* Force no backing file */
7956             qdict_put_null(opts, "backing");
7957         }
7958     }
7959 
7960     qobject_unref(bs->full_open_options);
7961     bs->full_open_options = opts;
7962 
7963     primary_child_bs = bdrv_primary_bs(bs);
7964 
7965     if (drv->bdrv_refresh_filename) {
7966         /* Obsolete information is of no use here, so drop the old file name
7967          * information before refreshing it */
7968         bs->exact_filename[0] = '\0';
7969 
7970         drv->bdrv_refresh_filename(bs);
7971     } else if (primary_child_bs) {
7972         /*
7973          * Try to reconstruct valid information from the underlying
7974          * file -- this only works for format nodes (filter nodes
7975          * cannot be probed and as such must be selected by the user
7976          * either through an options dict, or through a special
7977          * filename which the filter driver must construct in its
7978          * .bdrv_refresh_filename() implementation).
7979          */
7980 
7981         bs->exact_filename[0] = '\0';
7982 
7983         /*
7984          * We can use the underlying file's filename if:
7985          * - it has a filename,
7986          * - the current BDS is not a filter,
7987          * - the file is a protocol BDS, and
7988          * - opening that file (as this BDS's format) will automatically create
7989          *   the BDS tree we have right now, that is:
7990          *   - the user did not significantly change this BDS's behavior with
7991          *     some explicit (strong) options
7992          *   - no non-file child of this BDS has been overridden by the user
7993          *   Both of these conditions are represented by generate_json_filename.
7994          */
7995         if (primary_child_bs->exact_filename[0] &&
7996             primary_child_bs->drv->bdrv_file_open &&
7997             !drv->is_filter && !generate_json_filename)
7998         {
7999             strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8000         }
8001     }
8002 
8003     if (bs->exact_filename[0]) {
8004         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
8005     } else {
8006         GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
8007         if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8008                      json->str) >= sizeof(bs->filename)) {
8009             /* Give user a hint if we truncated things. */
8010             strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
8011         }
8012         g_string_free(json, true);
8013     }
8014 }
8015 
8016 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
8017 {
8018     BlockDriver *drv = bs->drv;
8019     BlockDriverState *child_bs;
8020 
8021     GLOBAL_STATE_CODE();
8022 
8023     if (!drv) {
8024         error_setg(errp, "Node '%s' is ejected", bs->node_name);
8025         return NULL;
8026     }
8027 
8028     if (drv->bdrv_dirname) {
8029         return drv->bdrv_dirname(bs, errp);
8030     }
8031 
8032     child_bs = bdrv_primary_bs(bs);
8033     if (child_bs) {
8034         return bdrv_dirname(child_bs, errp);
8035     }
8036 
8037     bdrv_refresh_filename(bs);
8038     if (bs->exact_filename[0] != '\0') {
8039         return path_combine(bs->exact_filename, "");
8040     }
8041 
8042     error_setg(errp, "Cannot generate a base directory for %s nodes",
8043                drv->format_name);
8044     return NULL;
8045 }
8046 
8047 /*
8048  * Hot add/remove a BDS's child. So the user can take a child offline when
8049  * it is broken and take a new child online
8050  */
8051 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8052                     Error **errp)
8053 {
8054     GLOBAL_STATE_CODE();
8055     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8056         error_setg(errp, "The node %s does not support adding a child",
8057                    bdrv_get_device_or_node_name(parent_bs));
8058         return;
8059     }
8060 
8061     if (!QLIST_EMPTY(&child_bs->parents)) {
8062         error_setg(errp, "The node %s already has a parent",
8063                    child_bs->node_name);
8064         return;
8065     }
8066 
8067     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8068 }
8069 
8070 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8071 {
8072     BdrvChild *tmp;
8073 
8074     GLOBAL_STATE_CODE();
8075     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8076         error_setg(errp, "The node %s does not support removing a child",
8077                    bdrv_get_device_or_node_name(parent_bs));
8078         return;
8079     }
8080 
8081     QLIST_FOREACH(tmp, &parent_bs->children, next) {
8082         if (tmp == child) {
8083             break;
8084         }
8085     }
8086 
8087     if (!tmp) {
8088         error_setg(errp, "The node %s does not have a child named %s",
8089                    bdrv_get_device_or_node_name(parent_bs),
8090                    bdrv_get_device_or_node_name(child->bs));
8091         return;
8092     }
8093 
8094     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8095 }
8096 
8097 int bdrv_make_empty(BdrvChild *c, Error **errp)
8098 {
8099     BlockDriver *drv = c->bs->drv;
8100     int ret;
8101 
8102     GLOBAL_STATE_CODE();
8103     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
8104 
8105     if (!drv->bdrv_make_empty) {
8106         error_setg(errp, "%s does not support emptying nodes",
8107                    drv->format_name);
8108         return -ENOTSUP;
8109     }
8110 
8111     ret = drv->bdrv_make_empty(c->bs);
8112     if (ret < 0) {
8113         error_setg_errno(errp, -ret, "Failed to empty %s",
8114                          c->bs->filename);
8115         return ret;
8116     }
8117 
8118     return 0;
8119 }
8120 
8121 /*
8122  * Return the child that @bs acts as an overlay for, and from which data may be
8123  * copied in COW or COR operations.  Usually this is the backing file.
8124  */
8125 BdrvChild *bdrv_cow_child(BlockDriverState *bs)
8126 {
8127     IO_CODE();
8128 
8129     if (!bs || !bs->drv) {
8130         return NULL;
8131     }
8132 
8133     if (bs->drv->is_filter) {
8134         return NULL;
8135     }
8136 
8137     if (!bs->backing) {
8138         return NULL;
8139     }
8140 
8141     assert(bs->backing->role & BDRV_CHILD_COW);
8142     return bs->backing;
8143 }
8144 
8145 /*
8146  * If @bs acts as a filter for exactly one of its children, return
8147  * that child.
8148  */
8149 BdrvChild *bdrv_filter_child(BlockDriverState *bs)
8150 {
8151     BdrvChild *c;
8152     IO_CODE();
8153 
8154     if (!bs || !bs->drv) {
8155         return NULL;
8156     }
8157 
8158     if (!bs->drv->is_filter) {
8159         return NULL;
8160     }
8161 
8162     /* Only one of @backing or @file may be used */
8163     assert(!(bs->backing && bs->file));
8164 
8165     c = bs->backing ?: bs->file;
8166     if (!c) {
8167         return NULL;
8168     }
8169 
8170     assert(c->role & BDRV_CHILD_FILTERED);
8171     return c;
8172 }
8173 
8174 /*
8175  * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
8176  * whichever is non-NULL.
8177  *
8178  * Return NULL if both are NULL.
8179  */
8180 BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
8181 {
8182     BdrvChild *cow_child = bdrv_cow_child(bs);
8183     BdrvChild *filter_child = bdrv_filter_child(bs);
8184     IO_CODE();
8185 
8186     /* Filter nodes cannot have COW backing files */
8187     assert(!(cow_child && filter_child));
8188 
8189     return cow_child ?: filter_child;
8190 }
8191 
8192 /*
8193  * Return the primary child of this node: For filters, that is the
8194  * filtered child.  For other nodes, that is usually the child storing
8195  * metadata.
8196  * (A generally more helpful description is that this is (usually) the
8197  * child that has the same filename as @bs.)
8198  *
8199  * Drivers do not necessarily have a primary child; for example quorum
8200  * does not.
8201  */
8202 BdrvChild *bdrv_primary_child(BlockDriverState *bs)
8203 {
8204     BdrvChild *c, *found = NULL;
8205     IO_CODE();
8206 
8207     QLIST_FOREACH(c, &bs->children, next) {
8208         if (c->role & BDRV_CHILD_PRIMARY) {
8209             assert(!found);
8210             found = c;
8211         }
8212     }
8213 
8214     return found;
8215 }
8216 
8217 static BlockDriverState *bdrv_do_skip_filters(BlockDriverState *bs,
8218                                               bool stop_on_explicit_filter)
8219 {
8220     BdrvChild *c;
8221 
8222     if (!bs) {
8223         return NULL;
8224     }
8225 
8226     while (!(stop_on_explicit_filter && !bs->implicit)) {
8227         c = bdrv_filter_child(bs);
8228         if (!c) {
8229             /*
8230              * A filter that is embedded in a working block graph must
8231              * have a child.  Assert this here so this function does
8232              * not return a filter node that is not expected by the
8233              * caller.
8234              */
8235             assert(!bs->drv || !bs->drv->is_filter);
8236             break;
8237         }
8238         bs = c->bs;
8239     }
8240     /*
8241      * Note that this treats nodes with bs->drv == NULL as not being
8242      * filters (bs->drv == NULL should be replaced by something else
8243      * anyway).
8244      * The advantage of this behavior is that this function will thus
8245      * always return a non-NULL value (given a non-NULL @bs).
8246      */
8247 
8248     return bs;
8249 }
8250 
8251 /*
8252  * Return the first BDS that has not been added implicitly or that
8253  * does not have a filtered child down the chain starting from @bs
8254  * (including @bs itself).
8255  */
8256 BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8257 {
8258     GLOBAL_STATE_CODE();
8259     return bdrv_do_skip_filters(bs, true);
8260 }
8261 
8262 /*
8263  * Return the first BDS that does not have a filtered child down the
8264  * chain starting from @bs (including @bs itself).
8265  */
8266 BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8267 {
8268     IO_CODE();
8269     return bdrv_do_skip_filters(bs, false);
8270 }
8271 
8272 /*
8273  * For a backing chain, return the first non-filter backing image of
8274  * the first non-filter image.
8275  */
8276 BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8277 {
8278     IO_CODE();
8279     return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8280 }
8281 
8282 /**
8283  * Check whether [offset, offset + bytes) overlaps with the cached
8284  * block-status data region.
8285  *
8286  * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
8287  * which is what bdrv_bsc_is_data()'s interface needs.
8288  * Otherwise, *pnum is not touched.
8289  */
8290 static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
8291                                            int64_t offset, int64_t bytes,
8292                                            int64_t *pnum)
8293 {
8294     BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
8295     bool overlaps;
8296 
8297     overlaps =
8298         qatomic_read(&bsc->valid) &&
8299         ranges_overlap(offset, bytes, bsc->data_start,
8300                        bsc->data_end - bsc->data_start);
8301 
8302     if (overlaps && pnum) {
8303         *pnum = bsc->data_end - offset;
8304     }
8305 
8306     return overlaps;
8307 }
8308 
8309 /**
8310  * See block_int.h for this function's documentation.
8311  */
8312 bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
8313 {
8314     IO_CODE();
8315     RCU_READ_LOCK_GUARD();
8316     return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
8317 }
8318 
8319 /**
8320  * See block_int.h for this function's documentation.
8321  */
8322 void bdrv_bsc_invalidate_range(BlockDriverState *bs,
8323                                int64_t offset, int64_t bytes)
8324 {
8325     IO_CODE();
8326     RCU_READ_LOCK_GUARD();
8327 
8328     if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
8329         qatomic_set(&bs->block_status_cache->valid, false);
8330     }
8331 }
8332 
8333 /**
8334  * See block_int.h for this function's documentation.
8335  */
8336 void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
8337 {
8338     BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
8339     BdrvBlockStatusCache *old_bsc;
8340     IO_CODE();
8341 
8342     *new_bsc = (BdrvBlockStatusCache) {
8343         .valid = true,
8344         .data_start = offset,
8345         .data_end = offset + bytes,
8346     };
8347 
8348     QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
8349 
8350     old_bsc = qatomic_rcu_read(&bs->block_status_cache);
8351     qatomic_rcu_set(&bs->block_status_cache, new_bsc);
8352     if (old_bsc) {
8353         g_free_rcu(old_bsc, rcu);
8354     }
8355 }
8356