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