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