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