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