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