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