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