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