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