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