xref: /openbmc/qemu/block.c (revision d9018fbbd68bf3a8338828ee3038341518c74212)
1 /*
2  * QEMU System Emulator block driver
3  *
4  * Copyright (c) 2003 Fabrice Bellard
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 
25 #include "qemu/osdep.h"
26 #include "block/trace.h"
27 #include "block/block_int.h"
28 #include "block/blockjob.h"
29 #include "block/nbd.h"
30 #include "block/qdict.h"
31 #include "qemu/error-report.h"
32 #include "module_block.h"
33 #include "qemu/main-loop.h"
34 #include "qemu/module.h"
35 #include "qapi/error.h"
36 #include "qapi/qmp/qdict.h"
37 #include "qapi/qmp/qjson.h"
38 #include "qapi/qmp/qnull.h"
39 #include "qapi/qmp/qstring.h"
40 #include "qapi/qobject-output-visitor.h"
41 #include "qapi/qapi-visit-block-core.h"
42 #include "sysemu/block-backend.h"
43 #include "sysemu/sysemu.h"
44 #include "qemu/notify.h"
45 #include "qemu/option.h"
46 #include "qemu/coroutine.h"
47 #include "block/qapi.h"
48 #include "qemu/timer.h"
49 #include "qemu/cutils.h"
50 #include "qemu/id.h"
51 
52 #ifdef CONFIG_BSD
53 #include <sys/ioctl.h>
54 #include <sys/queue.h>
55 #ifndef __DragonFly__
56 #include <sys/disk.h>
57 #endif
58 #endif
59 
60 #ifdef _WIN32
61 #include <windows.h>
62 #endif
63 
64 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
65 
66 static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
67     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
68 
69 static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
70     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
71 
72 static QLIST_HEAD(, BlockDriver) bdrv_drivers =
73     QLIST_HEAD_INITIALIZER(bdrv_drivers);
74 
75 static BlockDriverState *bdrv_open_inherit(const char *filename,
76                                            const char *reference,
77                                            QDict *options, int flags,
78                                            BlockDriverState *parent,
79                                            const BdrvChildRole *child_role,
80                                            Error **errp);
81 
82 /* If non-zero, use only whitelisted block drivers */
83 static int use_bdrv_whitelist;
84 
85 #ifdef _WIN32
86 static int is_windows_drive_prefix(const char *filename)
87 {
88     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
89              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
90             filename[1] == ':');
91 }
92 
93 int is_windows_drive(const char *filename)
94 {
95     if (is_windows_drive_prefix(filename) &&
96         filename[2] == '\0')
97         return 1;
98     if (strstart(filename, "\\\\.\\", NULL) ||
99         strstart(filename, "//./", NULL))
100         return 1;
101     return 0;
102 }
103 #endif
104 
105 size_t bdrv_opt_mem_align(BlockDriverState *bs)
106 {
107     if (!bs || !bs->drv) {
108         /* page size or 4k (hdd sector size) should be on the safe side */
109         return MAX(4096, qemu_real_host_page_size);
110     }
111 
112     return bs->bl.opt_mem_alignment;
113 }
114 
115 size_t bdrv_min_mem_align(BlockDriverState *bs)
116 {
117     if (!bs || !bs->drv) {
118         /* page size or 4k (hdd sector size) should be on the safe side */
119         return MAX(4096, qemu_real_host_page_size);
120     }
121 
122     return bs->bl.min_mem_alignment;
123 }
124 
125 /* check if the path starts with "<protocol>:" */
126 int path_has_protocol(const char *path)
127 {
128     const char *p;
129 
130 #ifdef _WIN32
131     if (is_windows_drive(path) ||
132         is_windows_drive_prefix(path)) {
133         return 0;
134     }
135     p = path + strcspn(path, ":/\\");
136 #else
137     p = path + strcspn(path, ":/");
138 #endif
139 
140     return *p == ':';
141 }
142 
143 int path_is_absolute(const char *path)
144 {
145 #ifdef _WIN32
146     /* specific case for names like: "\\.\d:" */
147     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
148         return 1;
149     }
150     return (*path == '/' || *path == '\\');
151 #else
152     return (*path == '/');
153 #endif
154 }
155 
156 /* if filename is absolute, just return its duplicate. Otherwise, build a
157    path to it by considering it is relative to base_path. URL are
158    supported. */
159 char *path_combine(const char *base_path, const char *filename)
160 {
161     const char *protocol_stripped = NULL;
162     const char *p, *p1;
163     char *result;
164     int len;
165 
166     if (path_is_absolute(filename)) {
167         return g_strdup(filename);
168     }
169 
170     if (path_has_protocol(base_path)) {
171         protocol_stripped = strchr(base_path, ':');
172         if (protocol_stripped) {
173             protocol_stripped++;
174         }
175     }
176     p = protocol_stripped ?: base_path;
177 
178     p1 = strrchr(base_path, '/');
179 #ifdef _WIN32
180     {
181         const char *p2;
182         p2 = strrchr(base_path, '\\');
183         if (!p1 || p2 > p1) {
184             p1 = p2;
185         }
186     }
187 #endif
188     if (p1) {
189         p1++;
190     } else {
191         p1 = base_path;
192     }
193     if (p1 > p) {
194         p = p1;
195     }
196     len = p - base_path;
197 
198     result = g_malloc(len + strlen(filename) + 1);
199     memcpy(result, base_path, len);
200     strcpy(result + len, filename);
201 
202     return result;
203 }
204 
205 /*
206  * Helper function for bdrv_parse_filename() implementations to remove optional
207  * protocol prefixes (especially "file:") from a filename and for putting the
208  * stripped filename into the options QDict if there is such a prefix.
209  */
210 void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
211                                       QDict *options)
212 {
213     if (strstart(filename, prefix, &filename)) {
214         /* Stripping the explicit protocol prefix may result in a protocol
215          * prefix being (wrongly) detected (if the filename contains a colon) */
216         if (path_has_protocol(filename)) {
217             QString *fat_filename;
218 
219             /* This means there is some colon before the first slash; therefore,
220              * this cannot be an absolute path */
221             assert(!path_is_absolute(filename));
222 
223             /* And we can thus fix the protocol detection issue by prefixing it
224              * by "./" */
225             fat_filename = qstring_from_str("./");
226             qstring_append(fat_filename, filename);
227 
228             assert(!path_has_protocol(qstring_get_str(fat_filename)));
229 
230             qdict_put(options, "filename", fat_filename);
231         } else {
232             /* If no protocol prefix was detected, we can use the shortened
233              * filename as-is */
234             qdict_put_str(options, "filename", filename);
235         }
236     }
237 }
238 
239 
240 /* Returns whether the image file is opened as read-only. Note that this can
241  * return false and writing to the image file is still not possible because the
242  * image is inactivated. */
243 bool bdrv_is_read_only(BlockDriverState *bs)
244 {
245     return bs->read_only;
246 }
247 
248 int bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
249                            bool ignore_allow_rdw, Error **errp)
250 {
251     /* Do not set read_only if copy_on_read is enabled */
252     if (bs->copy_on_read && read_only) {
253         error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
254                    bdrv_get_device_or_node_name(bs));
255         return -EINVAL;
256     }
257 
258     /* Do not clear read_only if it is prohibited */
259     if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
260         !ignore_allow_rdw)
261     {
262         error_setg(errp, "Node '%s' is read only",
263                    bdrv_get_device_or_node_name(bs));
264         return -EPERM;
265     }
266 
267     return 0;
268 }
269 
270 /*
271  * Called by a driver that can only provide a read-only image.
272  *
273  * Returns 0 if the node is already read-only or it could switch the node to
274  * read-only because BDRV_O_AUTO_RDONLY is set.
275  *
276  * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
277  * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
278  * is not NULL, it is used as the error message for the Error object.
279  */
280 int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
281                               Error **errp)
282 {
283     int ret = 0;
284 
285     if (!(bs->open_flags & BDRV_O_RDWR)) {
286         return 0;
287     }
288     if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
289         goto fail;
290     }
291 
292     ret = bdrv_can_set_read_only(bs, true, false, NULL);
293     if (ret < 0) {
294         goto fail;
295     }
296 
297     bs->read_only = true;
298     bs->open_flags &= ~BDRV_O_RDWR;
299 
300     return 0;
301 
302 fail:
303     error_setg(errp, "%s", errmsg ?: "Image is read-only");
304     return -EACCES;
305 }
306 
307 /*
308  * If @backing is empty, this function returns NULL without setting
309  * @errp.  In all other cases, NULL will only be returned with @errp
310  * set.
311  *
312  * Therefore, a return value of NULL without @errp set means that
313  * there is no backing file; if @errp is set, there is one but its
314  * absolute filename cannot be generated.
315  */
316 char *bdrv_get_full_backing_filename_from_filename(const char *backed,
317                                                    const char *backing,
318                                                    Error **errp)
319 {
320     if (backing[0] == '\0') {
321         return NULL;
322     } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
323         return g_strdup(backing);
324     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
325         error_setg(errp, "Cannot use relative backing file names for '%s'",
326                    backed);
327         return NULL;
328     } else {
329         return path_combine(backed, backing);
330     }
331 }
332 
333 /*
334  * If @filename is empty or NULL, this function returns NULL without
335  * setting @errp.  In all other cases, NULL will only be returned with
336  * @errp set.
337  */
338 static char *bdrv_make_absolute_filename(BlockDriverState *relative_to,
339                                          const char *filename, Error **errp)
340 {
341     char *dir, *full_name;
342 
343     if (!filename || filename[0] == '\0') {
344         return NULL;
345     } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
346         return g_strdup(filename);
347     }
348 
349     dir = bdrv_dirname(relative_to, errp);
350     if (!dir) {
351         return NULL;
352     }
353 
354     full_name = g_strconcat(dir, filename, NULL);
355     g_free(dir);
356     return full_name;
357 }
358 
359 char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
360 {
361     return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
362 }
363 
364 void bdrv_register(BlockDriver *bdrv)
365 {
366     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
367 }
368 
369 BlockDriverState *bdrv_new(void)
370 {
371     BlockDriverState *bs;
372     int i;
373 
374     bs = g_new0(BlockDriverState, 1);
375     QLIST_INIT(&bs->dirty_bitmaps);
376     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
377         QLIST_INIT(&bs->op_blockers[i]);
378     }
379     notifier_with_return_list_init(&bs->before_write_notifiers);
380     qemu_co_mutex_init(&bs->reqs_lock);
381     qemu_mutex_init(&bs->dirty_bitmap_mutex);
382     bs->refcnt = 1;
383     bs->aio_context = qemu_get_aio_context();
384 
385     qemu_co_queue_init(&bs->flush_queue);
386 
387     for (i = 0; i < bdrv_drain_all_count; i++) {
388         bdrv_drained_begin(bs);
389     }
390 
391     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
392 
393     return bs;
394 }
395 
396 static BlockDriver *bdrv_do_find_format(const char *format_name)
397 {
398     BlockDriver *drv1;
399 
400     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
401         if (!strcmp(drv1->format_name, format_name)) {
402             return drv1;
403         }
404     }
405 
406     return NULL;
407 }
408 
409 BlockDriver *bdrv_find_format(const char *format_name)
410 {
411     BlockDriver *drv1;
412     int i;
413 
414     drv1 = bdrv_do_find_format(format_name);
415     if (drv1) {
416         return drv1;
417     }
418 
419     /* The driver isn't registered, maybe we need to load a module */
420     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
421         if (!strcmp(block_driver_modules[i].format_name, format_name)) {
422             block_module_load_one(block_driver_modules[i].library_name);
423             break;
424         }
425     }
426 
427     return bdrv_do_find_format(format_name);
428 }
429 
430 static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
431 {
432     static const char *whitelist_rw[] = {
433         CONFIG_BDRV_RW_WHITELIST
434     };
435     static const char *whitelist_ro[] = {
436         CONFIG_BDRV_RO_WHITELIST
437     };
438     const char **p;
439 
440     if (!whitelist_rw[0] && !whitelist_ro[0]) {
441         return 1;               /* no whitelist, anything goes */
442     }
443 
444     for (p = whitelist_rw; *p; p++) {
445         if (!strcmp(format_name, *p)) {
446             return 1;
447         }
448     }
449     if (read_only) {
450         for (p = whitelist_ro; *p; p++) {
451             if (!strcmp(format_name, *p)) {
452                 return 1;
453             }
454         }
455     }
456     return 0;
457 }
458 
459 int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
460 {
461     return bdrv_format_is_whitelisted(drv->format_name, read_only);
462 }
463 
464 bool bdrv_uses_whitelist(void)
465 {
466     return use_bdrv_whitelist;
467 }
468 
469 typedef struct CreateCo {
470     BlockDriver *drv;
471     char *filename;
472     QemuOpts *opts;
473     int ret;
474     Error *err;
475 } CreateCo;
476 
477 static void coroutine_fn bdrv_create_co_entry(void *opaque)
478 {
479     Error *local_err = NULL;
480     int ret;
481 
482     CreateCo *cco = opaque;
483     assert(cco->drv);
484 
485     ret = cco->drv->bdrv_co_create_opts(cco->filename, cco->opts, &local_err);
486     error_propagate(&cco->err, local_err);
487     cco->ret = ret;
488 }
489 
490 int bdrv_create(BlockDriver *drv, const char* filename,
491                 QemuOpts *opts, Error **errp)
492 {
493     int ret;
494 
495     Coroutine *co;
496     CreateCo cco = {
497         .drv = drv,
498         .filename = g_strdup(filename),
499         .opts = opts,
500         .ret = NOT_DONE,
501         .err = NULL,
502     };
503 
504     if (!drv->bdrv_co_create_opts) {
505         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
506         ret = -ENOTSUP;
507         goto out;
508     }
509 
510     if (qemu_in_coroutine()) {
511         /* Fast-path if already in coroutine context */
512         bdrv_create_co_entry(&cco);
513     } else {
514         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
515         qemu_coroutine_enter(co);
516         while (cco.ret == NOT_DONE) {
517             aio_poll(qemu_get_aio_context(), true);
518         }
519     }
520 
521     ret = cco.ret;
522     if (ret < 0) {
523         if (cco.err) {
524             error_propagate(errp, cco.err);
525         } else {
526             error_setg_errno(errp, -ret, "Could not create image");
527         }
528     }
529 
530 out:
531     g_free(cco.filename);
532     return ret;
533 }
534 
535 int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
536 {
537     BlockDriver *drv;
538     Error *local_err = NULL;
539     int ret;
540 
541     drv = bdrv_find_protocol(filename, true, errp);
542     if (drv == NULL) {
543         return -ENOENT;
544     }
545 
546     ret = bdrv_create(drv, filename, opts, &local_err);
547     error_propagate(errp, local_err);
548     return ret;
549 }
550 
551 /**
552  * Try to get @bs's logical and physical block size.
553  * On success, store them in @bsz struct and return 0.
554  * On failure return -errno.
555  * @bs must not be empty.
556  */
557 int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
558 {
559     BlockDriver *drv = bs->drv;
560 
561     if (drv && drv->bdrv_probe_blocksizes) {
562         return drv->bdrv_probe_blocksizes(bs, bsz);
563     } else if (drv && drv->is_filter && bs->file) {
564         return bdrv_probe_blocksizes(bs->file->bs, bsz);
565     }
566 
567     return -ENOTSUP;
568 }
569 
570 /**
571  * Try to get @bs's geometry (cyls, heads, sectors).
572  * On success, store them in @geo struct and return 0.
573  * On failure return -errno.
574  * @bs must not be empty.
575  */
576 int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
577 {
578     BlockDriver *drv = bs->drv;
579 
580     if (drv && drv->bdrv_probe_geometry) {
581         return drv->bdrv_probe_geometry(bs, geo);
582     } else if (drv && drv->is_filter && bs->file) {
583         return bdrv_probe_geometry(bs->file->bs, geo);
584     }
585 
586     return -ENOTSUP;
587 }
588 
589 /*
590  * Create a uniquely-named empty temporary file.
591  * Return 0 upon success, otherwise a negative errno value.
592  */
593 int get_tmp_filename(char *filename, int size)
594 {
595 #ifdef _WIN32
596     char temp_dir[MAX_PATH];
597     /* GetTempFileName requires that its output buffer (4th param)
598        have length MAX_PATH or greater.  */
599     assert(size >= MAX_PATH);
600     return (GetTempPath(MAX_PATH, temp_dir)
601             && GetTempFileName(temp_dir, "qem", 0, filename)
602             ? 0 : -GetLastError());
603 #else
604     int fd;
605     const char *tmpdir;
606     tmpdir = getenv("TMPDIR");
607     if (!tmpdir) {
608         tmpdir = "/var/tmp";
609     }
610     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
611         return -EOVERFLOW;
612     }
613     fd = mkstemp(filename);
614     if (fd < 0) {
615         return -errno;
616     }
617     if (close(fd) != 0) {
618         unlink(filename);
619         return -errno;
620     }
621     return 0;
622 #endif
623 }
624 
625 /*
626  * Detect host devices. By convention, /dev/cdrom[N] is always
627  * recognized as a host CDROM.
628  */
629 static BlockDriver *find_hdev_driver(const char *filename)
630 {
631     int score_max = 0, score;
632     BlockDriver *drv = NULL, *d;
633 
634     QLIST_FOREACH(d, &bdrv_drivers, list) {
635         if (d->bdrv_probe_device) {
636             score = d->bdrv_probe_device(filename);
637             if (score > score_max) {
638                 score_max = score;
639                 drv = d;
640             }
641         }
642     }
643 
644     return drv;
645 }
646 
647 static BlockDriver *bdrv_do_find_protocol(const char *protocol)
648 {
649     BlockDriver *drv1;
650 
651     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
652         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
653             return drv1;
654         }
655     }
656 
657     return NULL;
658 }
659 
660 BlockDriver *bdrv_find_protocol(const char *filename,
661                                 bool allow_protocol_prefix,
662                                 Error **errp)
663 {
664     BlockDriver *drv1;
665     char protocol[128];
666     int len;
667     const char *p;
668     int i;
669 
670     /* TODO Drivers without bdrv_file_open must be specified explicitly */
671 
672     /*
673      * XXX(hch): we really should not let host device detection
674      * override an explicit protocol specification, but moving this
675      * later breaks access to device names with colons in them.
676      * Thanks to the brain-dead persistent naming schemes on udev-
677      * based Linux systems those actually are quite common.
678      */
679     drv1 = find_hdev_driver(filename);
680     if (drv1) {
681         return drv1;
682     }
683 
684     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
685         return &bdrv_file;
686     }
687 
688     p = strchr(filename, ':');
689     assert(p != NULL);
690     len = p - filename;
691     if (len > sizeof(protocol) - 1)
692         len = sizeof(protocol) - 1;
693     memcpy(protocol, filename, len);
694     protocol[len] = '\0';
695 
696     drv1 = bdrv_do_find_protocol(protocol);
697     if (drv1) {
698         return drv1;
699     }
700 
701     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
702         if (block_driver_modules[i].protocol_name &&
703             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
704             block_module_load_one(block_driver_modules[i].library_name);
705             break;
706         }
707     }
708 
709     drv1 = bdrv_do_find_protocol(protocol);
710     if (!drv1) {
711         error_setg(errp, "Unknown protocol '%s'", protocol);
712     }
713     return drv1;
714 }
715 
716 /*
717  * Guess image format by probing its contents.
718  * This is not a good idea when your image is raw (CVE-2008-2004), but
719  * we do it anyway for backward compatibility.
720  *
721  * @buf         contains the image's first @buf_size bytes.
722  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
723  *              but can be smaller if the image file is smaller)
724  * @filename    is its filename.
725  *
726  * For all block drivers, call the bdrv_probe() method to get its
727  * probing score.
728  * Return the first block driver with the highest probing score.
729  */
730 BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
731                             const char *filename)
732 {
733     int score_max = 0, score;
734     BlockDriver *drv = NULL, *d;
735 
736     QLIST_FOREACH(d, &bdrv_drivers, list) {
737         if (d->bdrv_probe) {
738             score = d->bdrv_probe(buf, buf_size, filename);
739             if (score > score_max) {
740                 score_max = score;
741                 drv = d;
742             }
743         }
744     }
745 
746     return drv;
747 }
748 
749 static int find_image_format(BlockBackend *file, const char *filename,
750                              BlockDriver **pdrv, Error **errp)
751 {
752     BlockDriver *drv;
753     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
754     int ret = 0;
755 
756     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
757     if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
758         *pdrv = &bdrv_raw;
759         return ret;
760     }
761 
762     ret = blk_pread(file, 0, buf, sizeof(buf));
763     if (ret < 0) {
764         error_setg_errno(errp, -ret, "Could not read image for determining its "
765                          "format");
766         *pdrv = NULL;
767         return ret;
768     }
769 
770     drv = bdrv_probe_all(buf, ret, filename);
771     if (!drv) {
772         error_setg(errp, "Could not determine image format: No compatible "
773                    "driver found");
774         ret = -ENOENT;
775     }
776     *pdrv = drv;
777     return ret;
778 }
779 
780 /**
781  * Set the current 'total_sectors' value
782  * Return 0 on success, -errno on error.
783  */
784 int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
785 {
786     BlockDriver *drv = bs->drv;
787 
788     if (!drv) {
789         return -ENOMEDIUM;
790     }
791 
792     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
793     if (bdrv_is_sg(bs))
794         return 0;
795 
796     /* query actual device if possible, otherwise just trust the hint */
797     if (drv->bdrv_getlength) {
798         int64_t length = drv->bdrv_getlength(bs);
799         if (length < 0) {
800             return length;
801         }
802         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
803     }
804 
805     bs->total_sectors = hint;
806     return 0;
807 }
808 
809 /**
810  * Combines a QDict of new block driver @options with any missing options taken
811  * from @old_options, so that leaving out an option defaults to its old value.
812  */
813 static void bdrv_join_options(BlockDriverState *bs, QDict *options,
814                               QDict *old_options)
815 {
816     if (bs->drv && bs->drv->bdrv_join_options) {
817         bs->drv->bdrv_join_options(options, old_options);
818     } else {
819         qdict_join(options, old_options, false);
820     }
821 }
822 
823 static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
824                                                             int open_flags,
825                                                             Error **errp)
826 {
827     Error *local_err = NULL;
828     char *value = qemu_opt_get_del(opts, "detect-zeroes");
829     BlockdevDetectZeroesOptions detect_zeroes =
830         qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
831                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
832     g_free(value);
833     if (local_err) {
834         error_propagate(errp, local_err);
835         return detect_zeroes;
836     }
837 
838     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
839         !(open_flags & BDRV_O_UNMAP))
840     {
841         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
842                    "without setting discard operation to unmap");
843     }
844 
845     return detect_zeroes;
846 }
847 
848 /**
849  * Set open flags for aio engine
850  *
851  * Return 0 on success, -1 if the engine specified is invalid
852  */
853 int bdrv_parse_aio(const char *mode, int *flags)
854 {
855     if (!strcmp(mode, "threads")) {
856         /* do nothing, default */
857     } else if (!strcmp(mode, "native")) {
858         *flags |= BDRV_O_NATIVE_AIO;
859 #ifdef CONFIG_LINUX_IO_URING
860     } else if (!strcmp(mode, "io_uring")) {
861         *flags |= BDRV_O_IO_URING;
862 #endif
863     } else {
864         return -1;
865     }
866 
867     return 0;
868 }
869 
870 /**
871  * Set open flags for a given discard mode
872  *
873  * Return 0 on success, -1 if the discard mode was invalid.
874  */
875 int bdrv_parse_discard_flags(const char *mode, int *flags)
876 {
877     *flags &= ~BDRV_O_UNMAP;
878 
879     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
880         /* do nothing */
881     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
882         *flags |= BDRV_O_UNMAP;
883     } else {
884         return -1;
885     }
886 
887     return 0;
888 }
889 
890 /**
891  * Set open flags for a given cache mode
892  *
893  * Return 0 on success, -1 if the cache mode was invalid.
894  */
895 int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
896 {
897     *flags &= ~BDRV_O_CACHE_MASK;
898 
899     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
900         *writethrough = false;
901         *flags |= BDRV_O_NOCACHE;
902     } else if (!strcmp(mode, "directsync")) {
903         *writethrough = true;
904         *flags |= BDRV_O_NOCACHE;
905     } else if (!strcmp(mode, "writeback")) {
906         *writethrough = false;
907     } else if (!strcmp(mode, "unsafe")) {
908         *writethrough = false;
909         *flags |= BDRV_O_NO_FLUSH;
910     } else if (!strcmp(mode, "writethrough")) {
911         *writethrough = true;
912     } else {
913         return -1;
914     }
915 
916     return 0;
917 }
918 
919 static char *bdrv_child_get_parent_desc(BdrvChild *c)
920 {
921     BlockDriverState *parent = c->opaque;
922     return g_strdup(bdrv_get_device_or_node_name(parent));
923 }
924 
925 static void bdrv_child_cb_drained_begin(BdrvChild *child)
926 {
927     BlockDriverState *bs = child->opaque;
928     bdrv_do_drained_begin_quiesce(bs, NULL, false);
929 }
930 
931 static bool bdrv_child_cb_drained_poll(BdrvChild *child)
932 {
933     BlockDriverState *bs = child->opaque;
934     return bdrv_drain_poll(bs, false, NULL, false);
935 }
936 
937 static void bdrv_child_cb_drained_end(BdrvChild *child,
938                                       int *drained_end_counter)
939 {
940     BlockDriverState *bs = child->opaque;
941     bdrv_drained_end_no_poll(bs, drained_end_counter);
942 }
943 
944 static void bdrv_child_cb_attach(BdrvChild *child)
945 {
946     BlockDriverState *bs = child->opaque;
947     bdrv_apply_subtree_drain(child, bs);
948 }
949 
950 static void bdrv_child_cb_detach(BdrvChild *child)
951 {
952     BlockDriverState *bs = child->opaque;
953     bdrv_unapply_subtree_drain(child, bs);
954 }
955 
956 static int bdrv_child_cb_inactivate(BdrvChild *child)
957 {
958     BlockDriverState *bs = child->opaque;
959     assert(bs->open_flags & BDRV_O_INACTIVE);
960     return 0;
961 }
962 
963 static bool bdrv_child_cb_can_set_aio_ctx(BdrvChild *child, AioContext *ctx,
964                                           GSList **ignore, Error **errp)
965 {
966     BlockDriverState *bs = child->opaque;
967     return bdrv_can_set_aio_context(bs, ctx, ignore, errp);
968 }
969 
970 static void bdrv_child_cb_set_aio_ctx(BdrvChild *child, AioContext *ctx,
971                                       GSList **ignore)
972 {
973     BlockDriverState *bs = child->opaque;
974     return bdrv_set_aio_context_ignore(bs, ctx, ignore);
975 }
976 
977 /*
978  * Returns the options and flags that a temporary snapshot should get, based on
979  * the originally requested flags (the originally requested image will have
980  * flags like a backing file)
981  */
982 static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
983                                        int parent_flags, QDict *parent_options)
984 {
985     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
986 
987     /* For temporary files, unconditional cache=unsafe is fine */
988     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
989     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
990 
991     /* Copy the read-only and discard options from the parent */
992     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
993     qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
994 
995     /* aio=native doesn't work for cache.direct=off, so disable it for the
996      * temporary snapshot */
997     *child_flags &= ~BDRV_O_NATIVE_AIO;
998 }
999 
1000 /*
1001  * Returns the options and flags that bs->file should get if a protocol driver
1002  * is expected, based on the given options and flags for the parent BDS
1003  */
1004 static void bdrv_inherited_options(int *child_flags, QDict *child_options,
1005                                    int parent_flags, QDict *parent_options)
1006 {
1007     int flags = parent_flags;
1008 
1009     /* Enable protocol handling, disable format probing for bs->file */
1010     flags |= BDRV_O_PROTOCOL;
1011 
1012     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
1013      * the parent. */
1014     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1015     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1016     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1017 
1018     /* Inherit the read-only option from the parent if it's not set */
1019     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1020     qdict_copy_default(child_options, parent_options, BDRV_OPT_AUTO_READ_ONLY);
1021 
1022     /* Our block drivers take care to send flushes and respect unmap policy,
1023      * so we can default to enable both on lower layers regardless of the
1024      * corresponding parent options. */
1025     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1026 
1027     /* Clear flags that only apply to the top layer */
1028     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
1029                BDRV_O_NO_IO);
1030 
1031     *child_flags = flags;
1032 }
1033 
1034 const BdrvChildRole child_file = {
1035     .parent_is_bds   = true,
1036     .get_parent_desc = bdrv_child_get_parent_desc,
1037     .inherit_options = bdrv_inherited_options,
1038     .drained_begin   = bdrv_child_cb_drained_begin,
1039     .drained_poll    = bdrv_child_cb_drained_poll,
1040     .drained_end     = bdrv_child_cb_drained_end,
1041     .attach          = bdrv_child_cb_attach,
1042     .detach          = bdrv_child_cb_detach,
1043     .inactivate      = bdrv_child_cb_inactivate,
1044     .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1045     .set_aio_ctx     = bdrv_child_cb_set_aio_ctx,
1046 };
1047 
1048 /*
1049  * Returns the options and flags that bs->file should get if the use of formats
1050  * (and not only protocols) is permitted for it, based on the given options and
1051  * flags for the parent BDS
1052  */
1053 static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
1054                                        int parent_flags, QDict *parent_options)
1055 {
1056     child_file.inherit_options(child_flags, child_options,
1057                                parent_flags, parent_options);
1058 
1059     *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
1060 }
1061 
1062 const BdrvChildRole child_format = {
1063     .parent_is_bds   = true,
1064     .get_parent_desc = bdrv_child_get_parent_desc,
1065     .inherit_options = bdrv_inherited_fmt_options,
1066     .drained_begin   = bdrv_child_cb_drained_begin,
1067     .drained_poll    = bdrv_child_cb_drained_poll,
1068     .drained_end     = bdrv_child_cb_drained_end,
1069     .attach          = bdrv_child_cb_attach,
1070     .detach          = bdrv_child_cb_detach,
1071     .inactivate      = bdrv_child_cb_inactivate,
1072     .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1073     .set_aio_ctx     = bdrv_child_cb_set_aio_ctx,
1074 };
1075 
1076 static void bdrv_backing_attach(BdrvChild *c)
1077 {
1078     BlockDriverState *parent = c->opaque;
1079     BlockDriverState *backing_hd = c->bs;
1080 
1081     assert(!parent->backing_blocker);
1082     error_setg(&parent->backing_blocker,
1083                "node is used as backing hd of '%s'",
1084                bdrv_get_device_or_node_name(parent));
1085 
1086     bdrv_refresh_filename(backing_hd);
1087 
1088     parent->open_flags &= ~BDRV_O_NO_BACKING;
1089     pstrcpy(parent->backing_file, sizeof(parent->backing_file),
1090             backing_hd->filename);
1091     pstrcpy(parent->backing_format, sizeof(parent->backing_format),
1092             backing_hd->drv ? backing_hd->drv->format_name : "");
1093 
1094     bdrv_op_block_all(backing_hd, parent->backing_blocker);
1095     /* Otherwise we won't be able to commit or stream */
1096     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1097                     parent->backing_blocker);
1098     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1099                     parent->backing_blocker);
1100     /*
1101      * We do backup in 3 ways:
1102      * 1. drive backup
1103      *    The target bs is new opened, and the source is top BDS
1104      * 2. blockdev backup
1105      *    Both the source and the target are top BDSes.
1106      * 3. internal backup(used for block replication)
1107      *    Both the source and the target are backing file
1108      *
1109      * In case 1 and 2, neither the source nor the target is the backing file.
1110      * In case 3, we will block the top BDS, so there is only one block job
1111      * for the top BDS and its backing chain.
1112      */
1113     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1114                     parent->backing_blocker);
1115     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1116                     parent->backing_blocker);
1117 
1118     bdrv_child_cb_attach(c);
1119 }
1120 
1121 static void bdrv_backing_detach(BdrvChild *c)
1122 {
1123     BlockDriverState *parent = c->opaque;
1124 
1125     assert(parent->backing_blocker);
1126     bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1127     error_free(parent->backing_blocker);
1128     parent->backing_blocker = NULL;
1129 
1130     bdrv_child_cb_detach(c);
1131 }
1132 
1133 /*
1134  * Returns the options and flags that bs->backing should get, based on the
1135  * given options and flags for the parent BDS
1136  */
1137 static void bdrv_backing_options(int *child_flags, QDict *child_options,
1138                                  int parent_flags, QDict *parent_options)
1139 {
1140     int flags = parent_flags;
1141 
1142     /* The cache mode is inherited unmodified for backing files; except WCE,
1143      * which is only applied on the top level (BlockBackend) */
1144     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1145     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1146     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1147 
1148     /* backing files always opened read-only */
1149     qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1150     qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1151     flags &= ~BDRV_O_COPY_ON_READ;
1152 
1153     /* snapshot=on is handled on the top layer */
1154     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
1155 
1156     *child_flags = flags;
1157 }
1158 
1159 static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
1160                                         const char *filename, Error **errp)
1161 {
1162     BlockDriverState *parent = c->opaque;
1163     bool read_only = bdrv_is_read_only(parent);
1164     int ret;
1165 
1166     if (read_only) {
1167         ret = bdrv_reopen_set_read_only(parent, false, errp);
1168         if (ret < 0) {
1169             return ret;
1170         }
1171     }
1172 
1173     ret = bdrv_change_backing_file(parent, filename,
1174                                    base->drv ? base->drv->format_name : "");
1175     if (ret < 0) {
1176         error_setg_errno(errp, -ret, "Could not update backing file link");
1177     }
1178 
1179     if (read_only) {
1180         bdrv_reopen_set_read_only(parent, true, NULL);
1181     }
1182 
1183     return ret;
1184 }
1185 
1186 const BdrvChildRole child_backing = {
1187     .parent_is_bds   = true,
1188     .get_parent_desc = bdrv_child_get_parent_desc,
1189     .attach          = bdrv_backing_attach,
1190     .detach          = bdrv_backing_detach,
1191     .inherit_options = bdrv_backing_options,
1192     .drained_begin   = bdrv_child_cb_drained_begin,
1193     .drained_poll    = bdrv_child_cb_drained_poll,
1194     .drained_end     = bdrv_child_cb_drained_end,
1195     .inactivate      = bdrv_child_cb_inactivate,
1196     .update_filename = bdrv_backing_update_filename,
1197     .can_set_aio_ctx = bdrv_child_cb_can_set_aio_ctx,
1198     .set_aio_ctx     = bdrv_child_cb_set_aio_ctx,
1199 };
1200 
1201 static int bdrv_open_flags(BlockDriverState *bs, int flags)
1202 {
1203     int open_flags = flags;
1204 
1205     /*
1206      * Clear flags that are internal to the block layer before opening the
1207      * image.
1208      */
1209     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
1210 
1211     return open_flags;
1212 }
1213 
1214 static void update_flags_from_options(int *flags, QemuOpts *opts)
1215 {
1216     *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
1217 
1218     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
1219         *flags |= BDRV_O_NO_FLUSH;
1220     }
1221 
1222     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
1223         *flags |= BDRV_O_NOCACHE;
1224     }
1225 
1226     if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1227         *flags |= BDRV_O_RDWR;
1228     }
1229 
1230     if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1231         *flags |= BDRV_O_AUTO_RDONLY;
1232     }
1233 }
1234 
1235 static void update_options_from_flags(QDict *options, int flags)
1236 {
1237     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
1238         qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
1239     }
1240     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
1241         qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
1242                        flags & BDRV_O_NO_FLUSH);
1243     }
1244     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
1245         qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1246     }
1247     if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1248         qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1249                        flags & BDRV_O_AUTO_RDONLY);
1250     }
1251 }
1252 
1253 static void bdrv_assign_node_name(BlockDriverState *bs,
1254                                   const char *node_name,
1255                                   Error **errp)
1256 {
1257     char *gen_node_name = NULL;
1258 
1259     if (!node_name) {
1260         node_name = gen_node_name = id_generate(ID_BLOCK);
1261     } else if (!id_wellformed(node_name)) {
1262         /*
1263          * Check for empty string or invalid characters, but not if it is
1264          * generated (generated names use characters not available to the user)
1265          */
1266         error_setg(errp, "Invalid node name");
1267         return;
1268     }
1269 
1270     /* takes care of avoiding namespaces collisions */
1271     if (blk_by_name(node_name)) {
1272         error_setg(errp, "node-name=%s is conflicting with a device id",
1273                    node_name);
1274         goto out;
1275     }
1276 
1277     /* takes care of avoiding duplicates node names */
1278     if (bdrv_find_node(node_name)) {
1279         error_setg(errp, "Duplicate node name");
1280         goto out;
1281     }
1282 
1283     /* Make sure that the node name isn't truncated */
1284     if (strlen(node_name) >= sizeof(bs->node_name)) {
1285         error_setg(errp, "Node name too long");
1286         goto out;
1287     }
1288 
1289     /* copy node name into the bs and insert it into the graph list */
1290     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
1291     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
1292 out:
1293     g_free(gen_node_name);
1294 }
1295 
1296 static int bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv,
1297                             const char *node_name, QDict *options,
1298                             int open_flags, Error **errp)
1299 {
1300     Error *local_err = NULL;
1301     int i, ret;
1302 
1303     bdrv_assign_node_name(bs, node_name, &local_err);
1304     if (local_err) {
1305         error_propagate(errp, local_err);
1306         return -EINVAL;
1307     }
1308 
1309     bs->drv = drv;
1310     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1311     bs->opaque = g_malloc0(drv->instance_size);
1312 
1313     if (drv->bdrv_file_open) {
1314         assert(!drv->bdrv_needs_filename || bs->filename[0]);
1315         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1316     } else if (drv->bdrv_open) {
1317         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1318     } else {
1319         ret = 0;
1320     }
1321 
1322     if (ret < 0) {
1323         if (local_err) {
1324             error_propagate(errp, local_err);
1325         } else if (bs->filename[0]) {
1326             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
1327         } else {
1328             error_setg_errno(errp, -ret, "Could not open image");
1329         }
1330         goto open_failed;
1331     }
1332 
1333     ret = refresh_total_sectors(bs, bs->total_sectors);
1334     if (ret < 0) {
1335         error_setg_errno(errp, -ret, "Could not refresh total sector count");
1336         return ret;
1337     }
1338 
1339     bdrv_refresh_limits(bs, &local_err);
1340     if (local_err) {
1341         error_propagate(errp, local_err);
1342         return -EINVAL;
1343     }
1344 
1345     assert(bdrv_opt_mem_align(bs) != 0);
1346     assert(bdrv_min_mem_align(bs) != 0);
1347     assert(is_power_of_2(bs->bl.request_alignment));
1348 
1349     for (i = 0; i < bs->quiesce_counter; i++) {
1350         if (drv->bdrv_co_drain_begin) {
1351             drv->bdrv_co_drain_begin(bs);
1352         }
1353     }
1354 
1355     return 0;
1356 open_failed:
1357     bs->drv = NULL;
1358     if (bs->file != NULL) {
1359         bdrv_unref_child(bs, bs->file);
1360         bs->file = NULL;
1361     }
1362     g_free(bs->opaque);
1363     bs->opaque = NULL;
1364     return ret;
1365 }
1366 
1367 BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1368                                        int flags, Error **errp)
1369 {
1370     BlockDriverState *bs;
1371     int ret;
1372 
1373     bs = bdrv_new();
1374     bs->open_flags = flags;
1375     bs->explicit_options = qdict_new();
1376     bs->options = qdict_new();
1377     bs->opaque = NULL;
1378 
1379     update_options_from_flags(bs->options, flags);
1380 
1381     ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1382     if (ret < 0) {
1383         qobject_unref(bs->explicit_options);
1384         bs->explicit_options = NULL;
1385         qobject_unref(bs->options);
1386         bs->options = NULL;
1387         bdrv_unref(bs);
1388         return NULL;
1389     }
1390 
1391     return bs;
1392 }
1393 
1394 QemuOptsList bdrv_runtime_opts = {
1395     .name = "bdrv_common",
1396     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
1397     .desc = {
1398         {
1399             .name = "node-name",
1400             .type = QEMU_OPT_STRING,
1401             .help = "Node name of the block device node",
1402         },
1403         {
1404             .name = "driver",
1405             .type = QEMU_OPT_STRING,
1406             .help = "Block driver to use for the node",
1407         },
1408         {
1409             .name = BDRV_OPT_CACHE_DIRECT,
1410             .type = QEMU_OPT_BOOL,
1411             .help = "Bypass software writeback cache on the host",
1412         },
1413         {
1414             .name = BDRV_OPT_CACHE_NO_FLUSH,
1415             .type = QEMU_OPT_BOOL,
1416             .help = "Ignore flush requests",
1417         },
1418         {
1419             .name = BDRV_OPT_READ_ONLY,
1420             .type = QEMU_OPT_BOOL,
1421             .help = "Node is opened in read-only mode",
1422         },
1423         {
1424             .name = BDRV_OPT_AUTO_READ_ONLY,
1425             .type = QEMU_OPT_BOOL,
1426             .help = "Node can become read-only if opening read-write fails",
1427         },
1428         {
1429             .name = "detect-zeroes",
1430             .type = QEMU_OPT_STRING,
1431             .help = "try to optimize zero writes (off, on, unmap)",
1432         },
1433         {
1434             .name = BDRV_OPT_DISCARD,
1435             .type = QEMU_OPT_STRING,
1436             .help = "discard operation (ignore/off, unmap/on)",
1437         },
1438         {
1439             .name = BDRV_OPT_FORCE_SHARE,
1440             .type = QEMU_OPT_BOOL,
1441             .help = "always accept other writers (default: off)",
1442         },
1443         { /* end of list */ }
1444     },
1445 };
1446 
1447 /*
1448  * Common part for opening disk images and files
1449  *
1450  * Removes all processed options from *options.
1451  */
1452 static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
1453                             QDict *options, Error **errp)
1454 {
1455     int ret, open_flags;
1456     const char *filename;
1457     const char *driver_name = NULL;
1458     const char *node_name = NULL;
1459     const char *discard;
1460     QemuOpts *opts;
1461     BlockDriver *drv;
1462     Error *local_err = NULL;
1463 
1464     assert(bs->file == NULL);
1465     assert(options != NULL && bs->options != options);
1466 
1467     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1468     qemu_opts_absorb_qdict(opts, options, &local_err);
1469     if (local_err) {
1470         error_propagate(errp, local_err);
1471         ret = -EINVAL;
1472         goto fail_opts;
1473     }
1474 
1475     update_flags_from_options(&bs->open_flags, opts);
1476 
1477     driver_name = qemu_opt_get(opts, "driver");
1478     drv = bdrv_find_format(driver_name);
1479     assert(drv != NULL);
1480 
1481     bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
1482 
1483     if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
1484         error_setg(errp,
1485                    BDRV_OPT_FORCE_SHARE
1486                    "=on can only be used with read-only images");
1487         ret = -EINVAL;
1488         goto fail_opts;
1489     }
1490 
1491     if (file != NULL) {
1492         bdrv_refresh_filename(blk_bs(file));
1493         filename = blk_bs(file)->filename;
1494     } else {
1495         /*
1496          * Caution: while qdict_get_try_str() is fine, getting
1497          * non-string types would require more care.  When @options
1498          * come from -blockdev or blockdev_add, its members are typed
1499          * according to the QAPI schema, but when they come from
1500          * -drive, they're all QString.
1501          */
1502         filename = qdict_get_try_str(options, "filename");
1503     }
1504 
1505     if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1506         error_setg(errp, "The '%s' block driver requires a file name",
1507                    drv->format_name);
1508         ret = -EINVAL;
1509         goto fail_opts;
1510     }
1511 
1512     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
1513                            drv->format_name);
1514 
1515     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1516 
1517     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
1518         if (!bs->read_only && bdrv_is_whitelisted(drv, true)) {
1519             ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1520         } else {
1521             ret = -ENOTSUP;
1522         }
1523         if (ret < 0) {
1524             error_setg(errp,
1525                        !bs->read_only && bdrv_is_whitelisted(drv, true)
1526                        ? "Driver '%s' can only be used for read-only devices"
1527                        : "Driver '%s' is not whitelisted",
1528                        drv->format_name);
1529             goto fail_opts;
1530         }
1531     }
1532 
1533     /* bdrv_new() and bdrv_close() make it so */
1534     assert(atomic_read(&bs->copy_on_read) == 0);
1535 
1536     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1537         if (!bs->read_only) {
1538             bdrv_enable_copy_on_read(bs);
1539         } else {
1540             error_setg(errp, "Can't use copy-on-read on read-only device");
1541             ret = -EINVAL;
1542             goto fail_opts;
1543         }
1544     }
1545 
1546     discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1547     if (discard != NULL) {
1548         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1549             error_setg(errp, "Invalid discard option");
1550             ret = -EINVAL;
1551             goto fail_opts;
1552         }
1553     }
1554 
1555     bs->detect_zeroes =
1556         bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1557     if (local_err) {
1558         error_propagate(errp, local_err);
1559         ret = -EINVAL;
1560         goto fail_opts;
1561     }
1562 
1563     if (filename != NULL) {
1564         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1565     } else {
1566         bs->filename[0] = '\0';
1567     }
1568     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
1569 
1570     /* Open the image, either directly or using a protocol */
1571     open_flags = bdrv_open_flags(bs, bs->open_flags);
1572     node_name = qemu_opt_get(opts, "node-name");
1573 
1574     assert(!drv->bdrv_file_open || file == NULL);
1575     ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
1576     if (ret < 0) {
1577         goto fail_opts;
1578     }
1579 
1580     qemu_opts_del(opts);
1581     return 0;
1582 
1583 fail_opts:
1584     qemu_opts_del(opts);
1585     return ret;
1586 }
1587 
1588 static QDict *parse_json_filename(const char *filename, Error **errp)
1589 {
1590     QObject *options_obj;
1591     QDict *options;
1592     int ret;
1593 
1594     ret = strstart(filename, "json:", &filename);
1595     assert(ret);
1596 
1597     options_obj = qobject_from_json(filename, errp);
1598     if (!options_obj) {
1599         error_prepend(errp, "Could not parse the JSON options: ");
1600         return NULL;
1601     }
1602 
1603     options = qobject_to(QDict, options_obj);
1604     if (!options) {
1605         qobject_unref(options_obj);
1606         error_setg(errp, "Invalid JSON object given");
1607         return NULL;
1608     }
1609 
1610     qdict_flatten(options);
1611 
1612     return options;
1613 }
1614 
1615 static void parse_json_protocol(QDict *options, const char **pfilename,
1616                                 Error **errp)
1617 {
1618     QDict *json_options;
1619     Error *local_err = NULL;
1620 
1621     /* Parse json: pseudo-protocol */
1622     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1623         return;
1624     }
1625 
1626     json_options = parse_json_filename(*pfilename, &local_err);
1627     if (local_err) {
1628         error_propagate(errp, local_err);
1629         return;
1630     }
1631 
1632     /* Options given in the filename have lower priority than options
1633      * specified directly */
1634     qdict_join(options, json_options, false);
1635     qobject_unref(json_options);
1636     *pfilename = NULL;
1637 }
1638 
1639 /*
1640  * Fills in default options for opening images and converts the legacy
1641  * filename/flags pair to option QDict entries.
1642  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
1643  * block driver has been specified explicitly.
1644  */
1645 static int bdrv_fill_options(QDict **options, const char *filename,
1646                              int *flags, Error **errp)
1647 {
1648     const char *drvname;
1649     bool protocol = *flags & BDRV_O_PROTOCOL;
1650     bool parse_filename = false;
1651     BlockDriver *drv = NULL;
1652     Error *local_err = NULL;
1653 
1654     /*
1655      * Caution: while qdict_get_try_str() is fine, getting non-string
1656      * types would require more care.  When @options come from
1657      * -blockdev or blockdev_add, its members are typed according to
1658      * the QAPI schema, but when they come from -drive, they're all
1659      * QString.
1660      */
1661     drvname = qdict_get_try_str(*options, "driver");
1662     if (drvname) {
1663         drv = bdrv_find_format(drvname);
1664         if (!drv) {
1665             error_setg(errp, "Unknown driver '%s'", drvname);
1666             return -ENOENT;
1667         }
1668         /* If the user has explicitly specified the driver, this choice should
1669          * override the BDRV_O_PROTOCOL flag */
1670         protocol = drv->bdrv_file_open;
1671     }
1672 
1673     if (protocol) {
1674         *flags |= BDRV_O_PROTOCOL;
1675     } else {
1676         *flags &= ~BDRV_O_PROTOCOL;
1677     }
1678 
1679     /* Translate cache options from flags into options */
1680     update_options_from_flags(*options, *flags);
1681 
1682     /* Fetch the file name from the options QDict if necessary */
1683     if (protocol && filename) {
1684         if (!qdict_haskey(*options, "filename")) {
1685             qdict_put_str(*options, "filename", filename);
1686             parse_filename = true;
1687         } else {
1688             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1689                              "the same time");
1690             return -EINVAL;
1691         }
1692     }
1693 
1694     /* Find the right block driver */
1695     /* See cautionary note on accessing @options above */
1696     filename = qdict_get_try_str(*options, "filename");
1697 
1698     if (!drvname && protocol) {
1699         if (filename) {
1700             drv = bdrv_find_protocol(filename, parse_filename, errp);
1701             if (!drv) {
1702                 return -EINVAL;
1703             }
1704 
1705             drvname = drv->format_name;
1706             qdict_put_str(*options, "driver", drvname);
1707         } else {
1708             error_setg(errp, "Must specify either driver or file");
1709             return -EINVAL;
1710         }
1711     }
1712 
1713     assert(drv || !protocol);
1714 
1715     /* Driver-specific filename parsing */
1716     if (drv && drv->bdrv_parse_filename && parse_filename) {
1717         drv->bdrv_parse_filename(filename, *options, &local_err);
1718         if (local_err) {
1719             error_propagate(errp, local_err);
1720             return -EINVAL;
1721         }
1722 
1723         if (!drv->bdrv_needs_filename) {
1724             qdict_del(*options, "filename");
1725         }
1726     }
1727 
1728     return 0;
1729 }
1730 
1731 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
1732                                  uint64_t perm, uint64_t shared,
1733                                  GSList *ignore_children,
1734                                  bool *tighten_restrictions, Error **errp);
1735 static void bdrv_child_abort_perm_update(BdrvChild *c);
1736 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared);
1737 static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1738                                      uint64_t *shared_perm);
1739 
1740 typedef struct BlockReopenQueueEntry {
1741      bool prepared;
1742      bool perms_checked;
1743      BDRVReopenState state;
1744      QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
1745 } BlockReopenQueueEntry;
1746 
1747 /*
1748  * Return the flags that @bs will have after the reopens in @q have
1749  * successfully completed. If @q is NULL (or @bs is not contained in @q),
1750  * return the current flags.
1751  */
1752 static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
1753 {
1754     BlockReopenQueueEntry *entry;
1755 
1756     if (q != NULL) {
1757         QTAILQ_FOREACH(entry, q, entry) {
1758             if (entry->state.bs == bs) {
1759                 return entry->state.flags;
1760             }
1761         }
1762     }
1763 
1764     return bs->open_flags;
1765 }
1766 
1767 /* Returns whether the image file can be written to after the reopen queue @q
1768  * has been successfully applied, or right now if @q is NULL. */
1769 static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
1770                                           BlockReopenQueue *q)
1771 {
1772     int flags = bdrv_reopen_get_flags(q, bs);
1773 
1774     return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
1775 }
1776 
1777 /*
1778  * Return whether the BDS can be written to.  This is not necessarily
1779  * the same as !bdrv_is_read_only(bs), as inactivated images may not
1780  * be written to but do not count as read-only images.
1781  */
1782 bool bdrv_is_writable(BlockDriverState *bs)
1783 {
1784     return bdrv_is_writable_after_reopen(bs, NULL);
1785 }
1786 
1787 static void bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
1788                             BdrvChild *c, const BdrvChildRole *role,
1789                             BlockReopenQueue *reopen_queue,
1790                             uint64_t parent_perm, uint64_t parent_shared,
1791                             uint64_t *nperm, uint64_t *nshared)
1792 {
1793     assert(bs->drv && bs->drv->bdrv_child_perm);
1794     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
1795                              parent_perm, parent_shared,
1796                              nperm, nshared);
1797     /* TODO Take force_share from reopen_queue */
1798     if (child_bs && child_bs->force_share) {
1799         *nshared = BLK_PERM_ALL;
1800     }
1801 }
1802 
1803 /*
1804  * Check whether permissions on this node can be changed in a way that
1805  * @cumulative_perms and @cumulative_shared_perms are the new cumulative
1806  * permissions of all its parents. This involves checking whether all necessary
1807  * permission changes to child nodes can be performed.
1808  *
1809  * Will set *tighten_restrictions to true if and only if new permissions have to
1810  * be taken or currently shared permissions are to be unshared.  Otherwise,
1811  * errors are not fatal as long as the caller accepts that the restrictions
1812  * remain tighter than they need to be.  The caller still has to abort the
1813  * transaction.
1814  * @tighten_restrictions cannot be used together with @q: When reopening, we may
1815  * encounter fatal errors even though no restrictions are to be tightened.  For
1816  * example, changing a node from RW to RO will fail if the WRITE permission is
1817  * to be kept.
1818  *
1819  * A call to this function must always be followed by a call to bdrv_set_perm()
1820  * or bdrv_abort_perm_update().
1821  */
1822 static int bdrv_check_perm(BlockDriverState *bs, BlockReopenQueue *q,
1823                            uint64_t cumulative_perms,
1824                            uint64_t cumulative_shared_perms,
1825                            GSList *ignore_children,
1826                            bool *tighten_restrictions, Error **errp)
1827 {
1828     BlockDriver *drv = bs->drv;
1829     BdrvChild *c;
1830     int ret;
1831 
1832     assert(!q || !tighten_restrictions);
1833 
1834     if (tighten_restrictions) {
1835         uint64_t current_perms, current_shared;
1836         uint64_t added_perms, removed_shared_perms;
1837 
1838         bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
1839 
1840         added_perms = cumulative_perms & ~current_perms;
1841         removed_shared_perms = current_shared & ~cumulative_shared_perms;
1842 
1843         *tighten_restrictions = added_perms || removed_shared_perms;
1844     }
1845 
1846     /* Write permissions never work with read-only images */
1847     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
1848         !bdrv_is_writable_after_reopen(bs, q))
1849     {
1850         if (!bdrv_is_writable_after_reopen(bs, NULL)) {
1851             error_setg(errp, "Block node is read-only");
1852         } else {
1853             uint64_t current_perms, current_shared;
1854             bdrv_get_cumulative_perm(bs, &current_perms, &current_shared);
1855             if (current_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
1856                 error_setg(errp, "Cannot make block node read-only, there is "
1857                            "a writer on it");
1858             } else {
1859                 error_setg(errp, "Cannot make block node read-only and create "
1860                            "a writer on it");
1861             }
1862         }
1863 
1864         return -EPERM;
1865     }
1866 
1867     /* Check this node */
1868     if (!drv) {
1869         return 0;
1870     }
1871 
1872     if (drv->bdrv_check_perm) {
1873         return drv->bdrv_check_perm(bs, cumulative_perms,
1874                                     cumulative_shared_perms, errp);
1875     }
1876 
1877     /* Drivers that never have children can omit .bdrv_child_perm() */
1878     if (!drv->bdrv_child_perm) {
1879         assert(QLIST_EMPTY(&bs->children));
1880         return 0;
1881     }
1882 
1883     /* Check all children */
1884     QLIST_FOREACH(c, &bs->children, next) {
1885         uint64_t cur_perm, cur_shared;
1886         bool child_tighten_restr;
1887 
1888         bdrv_child_perm(bs, c->bs, c, c->role, q,
1889                         cumulative_perms, cumulative_shared_perms,
1890                         &cur_perm, &cur_shared);
1891         ret = bdrv_child_check_perm(c, q, cur_perm, cur_shared, ignore_children,
1892                                     tighten_restrictions ? &child_tighten_restr
1893                                                          : NULL,
1894                                     errp);
1895         if (tighten_restrictions) {
1896             *tighten_restrictions |= child_tighten_restr;
1897         }
1898         if (ret < 0) {
1899             return ret;
1900         }
1901     }
1902 
1903     return 0;
1904 }
1905 
1906 /*
1907  * Notifies drivers that after a previous bdrv_check_perm() call, the
1908  * permission update is not performed and any preparations made for it (e.g.
1909  * taken file locks) need to be undone.
1910  *
1911  * This function recursively notifies all child nodes.
1912  */
1913 static void bdrv_abort_perm_update(BlockDriverState *bs)
1914 {
1915     BlockDriver *drv = bs->drv;
1916     BdrvChild *c;
1917 
1918     if (!drv) {
1919         return;
1920     }
1921 
1922     if (drv->bdrv_abort_perm_update) {
1923         drv->bdrv_abort_perm_update(bs);
1924     }
1925 
1926     QLIST_FOREACH(c, &bs->children, next) {
1927         bdrv_child_abort_perm_update(c);
1928     }
1929 }
1930 
1931 static void bdrv_set_perm(BlockDriverState *bs, uint64_t cumulative_perms,
1932                           uint64_t cumulative_shared_perms)
1933 {
1934     BlockDriver *drv = bs->drv;
1935     BdrvChild *c;
1936 
1937     if (!drv) {
1938         return;
1939     }
1940 
1941     /* Update this node */
1942     if (drv->bdrv_set_perm) {
1943         drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
1944     }
1945 
1946     /* Drivers that never have children can omit .bdrv_child_perm() */
1947     if (!drv->bdrv_child_perm) {
1948         assert(QLIST_EMPTY(&bs->children));
1949         return;
1950     }
1951 
1952     /* Update all children */
1953     QLIST_FOREACH(c, &bs->children, next) {
1954         uint64_t cur_perm, cur_shared;
1955         bdrv_child_perm(bs, c->bs, c, c->role, NULL,
1956                         cumulative_perms, cumulative_shared_perms,
1957                         &cur_perm, &cur_shared);
1958         bdrv_child_set_perm(c, cur_perm, cur_shared);
1959     }
1960 }
1961 
1962 static void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
1963                                      uint64_t *shared_perm)
1964 {
1965     BdrvChild *c;
1966     uint64_t cumulative_perms = 0;
1967     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
1968 
1969     QLIST_FOREACH(c, &bs->parents, next_parent) {
1970         cumulative_perms |= c->perm;
1971         cumulative_shared_perms &= c->shared_perm;
1972     }
1973 
1974     *perm = cumulative_perms;
1975     *shared_perm = cumulative_shared_perms;
1976 }
1977 
1978 static char *bdrv_child_user_desc(BdrvChild *c)
1979 {
1980     if (c->role->get_parent_desc) {
1981         return c->role->get_parent_desc(c);
1982     }
1983 
1984     return g_strdup("another user");
1985 }
1986 
1987 char *bdrv_perm_names(uint64_t perm)
1988 {
1989     struct perm_name {
1990         uint64_t perm;
1991         const char *name;
1992     } permissions[] = {
1993         { BLK_PERM_CONSISTENT_READ, "consistent read" },
1994         { BLK_PERM_WRITE,           "write" },
1995         { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
1996         { BLK_PERM_RESIZE,          "resize" },
1997         { BLK_PERM_GRAPH_MOD,       "change children" },
1998         { 0, NULL }
1999     };
2000 
2001     char *result = g_strdup("");
2002     struct perm_name *p;
2003 
2004     for (p = permissions; p->name; p++) {
2005         if (perm & p->perm) {
2006             char *old = result;
2007             result = g_strdup_printf("%s%s%s", old, *old ? ", " : "", p->name);
2008             g_free(old);
2009         }
2010     }
2011 
2012     return result;
2013 }
2014 
2015 /*
2016  * Checks whether a new reference to @bs can be added if the new user requires
2017  * @new_used_perm/@new_shared_perm as its permissions. If @ignore_children is
2018  * set, the BdrvChild objects in this list are ignored in the calculations;
2019  * this allows checking permission updates for an existing reference.
2020  *
2021  * See bdrv_check_perm() for the semantics of @tighten_restrictions.
2022  *
2023  * Needs to be followed by a call to either bdrv_set_perm() or
2024  * bdrv_abort_perm_update(). */
2025 static int bdrv_check_update_perm(BlockDriverState *bs, BlockReopenQueue *q,
2026                                   uint64_t new_used_perm,
2027                                   uint64_t new_shared_perm,
2028                                   GSList *ignore_children,
2029                                   bool *tighten_restrictions,
2030                                   Error **errp)
2031 {
2032     BdrvChild *c;
2033     uint64_t cumulative_perms = new_used_perm;
2034     uint64_t cumulative_shared_perms = new_shared_perm;
2035 
2036     assert(!q || !tighten_restrictions);
2037 
2038     /* There is no reason why anyone couldn't tolerate write_unchanged */
2039     assert(new_shared_perm & BLK_PERM_WRITE_UNCHANGED);
2040 
2041     QLIST_FOREACH(c, &bs->parents, next_parent) {
2042         if (g_slist_find(ignore_children, c)) {
2043             continue;
2044         }
2045 
2046         if ((new_used_perm & c->shared_perm) != new_used_perm) {
2047             char *user = bdrv_child_user_desc(c);
2048             char *perm_names = bdrv_perm_names(new_used_perm & ~c->shared_perm);
2049 
2050             if (tighten_restrictions) {
2051                 *tighten_restrictions = true;
2052             }
2053 
2054             error_setg(errp, "Conflicts with use by %s as '%s', which does not "
2055                              "allow '%s' on %s",
2056                        user, c->name, perm_names, bdrv_get_node_name(c->bs));
2057             g_free(user);
2058             g_free(perm_names);
2059             return -EPERM;
2060         }
2061 
2062         if ((c->perm & new_shared_perm) != c->perm) {
2063             char *user = bdrv_child_user_desc(c);
2064             char *perm_names = bdrv_perm_names(c->perm & ~new_shared_perm);
2065 
2066             if (tighten_restrictions) {
2067                 *tighten_restrictions = true;
2068             }
2069 
2070             error_setg(errp, "Conflicts with use by %s as '%s', which uses "
2071                              "'%s' on %s",
2072                        user, c->name, perm_names, bdrv_get_node_name(c->bs));
2073             g_free(user);
2074             g_free(perm_names);
2075             return -EPERM;
2076         }
2077 
2078         cumulative_perms |= c->perm;
2079         cumulative_shared_perms &= c->shared_perm;
2080     }
2081 
2082     return bdrv_check_perm(bs, q, cumulative_perms, cumulative_shared_perms,
2083                            ignore_children, tighten_restrictions, errp);
2084 }
2085 
2086 /* Needs to be followed by a call to either bdrv_child_set_perm() or
2087  * bdrv_child_abort_perm_update(). */
2088 static int bdrv_child_check_perm(BdrvChild *c, BlockReopenQueue *q,
2089                                  uint64_t perm, uint64_t shared,
2090                                  GSList *ignore_children,
2091                                  bool *tighten_restrictions, Error **errp)
2092 {
2093     int ret;
2094 
2095     ignore_children = g_slist_prepend(g_slist_copy(ignore_children), c);
2096     ret = bdrv_check_update_perm(c->bs, q, perm, shared, ignore_children,
2097                                  tighten_restrictions, errp);
2098     g_slist_free(ignore_children);
2099 
2100     if (ret < 0) {
2101         return ret;
2102     }
2103 
2104     if (!c->has_backup_perm) {
2105         c->has_backup_perm = true;
2106         c->backup_perm = c->perm;
2107         c->backup_shared_perm = c->shared_perm;
2108     }
2109     /*
2110      * Note: it's OK if c->has_backup_perm was already set, as we can find the
2111      * same child twice during check_perm procedure
2112      */
2113 
2114     c->perm = perm;
2115     c->shared_perm = shared;
2116 
2117     return 0;
2118 }
2119 
2120 static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared)
2121 {
2122     uint64_t cumulative_perms, cumulative_shared_perms;
2123 
2124     c->has_backup_perm = false;
2125 
2126     c->perm = perm;
2127     c->shared_perm = shared;
2128 
2129     bdrv_get_cumulative_perm(c->bs, &cumulative_perms,
2130                              &cumulative_shared_perms);
2131     bdrv_set_perm(c->bs, cumulative_perms, cumulative_shared_perms);
2132 }
2133 
2134 static void bdrv_child_abort_perm_update(BdrvChild *c)
2135 {
2136     if (c->has_backup_perm) {
2137         c->perm = c->backup_perm;
2138         c->shared_perm = c->backup_shared_perm;
2139         c->has_backup_perm = false;
2140     }
2141 
2142     bdrv_abort_perm_update(c->bs);
2143 }
2144 
2145 int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
2146                             Error **errp)
2147 {
2148     Error *local_err = NULL;
2149     int ret;
2150     bool tighten_restrictions;
2151 
2152     ret = bdrv_child_check_perm(c, NULL, perm, shared, NULL,
2153                                 &tighten_restrictions, &local_err);
2154     if (ret < 0) {
2155         bdrv_child_abort_perm_update(c);
2156         if (tighten_restrictions) {
2157             error_propagate(errp, local_err);
2158         } else {
2159             /*
2160              * Our caller may intend to only loosen restrictions and
2161              * does not expect this function to fail.  Errors are not
2162              * fatal in such a case, so we can just hide them from our
2163              * caller.
2164              */
2165             error_free(local_err);
2166             ret = 0;
2167         }
2168         return ret;
2169     }
2170 
2171     bdrv_child_set_perm(c, perm, shared);
2172 
2173     return 0;
2174 }
2175 
2176 int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2177 {
2178     uint64_t parent_perms, parent_shared;
2179     uint64_t perms, shared;
2180 
2181     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2182     bdrv_child_perm(bs, c->bs, c, c->role, NULL, parent_perms, parent_shared,
2183                     &perms, &shared);
2184 
2185     return bdrv_child_try_set_perm(c, perms, shared, errp);
2186 }
2187 
2188 void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2189                                const BdrvChildRole *role,
2190                                BlockReopenQueue *reopen_queue,
2191                                uint64_t perm, uint64_t shared,
2192                                uint64_t *nperm, uint64_t *nshared)
2193 {
2194     *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
2195     *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
2196 }
2197 
2198 void bdrv_format_default_perms(BlockDriverState *bs, BdrvChild *c,
2199                                const BdrvChildRole *role,
2200                                BlockReopenQueue *reopen_queue,
2201                                uint64_t perm, uint64_t shared,
2202                                uint64_t *nperm, uint64_t *nshared)
2203 {
2204     bool backing = (role == &child_backing);
2205     assert(role == &child_backing || role == &child_file);
2206 
2207     if (!backing) {
2208         int flags = bdrv_reopen_get_flags(reopen_queue, bs);
2209 
2210         /* Apart from the modifications below, the same permissions are
2211          * forwarded and left alone as for filters */
2212         bdrv_filter_default_perms(bs, c, role, reopen_queue, perm, shared,
2213                                   &perm, &shared);
2214 
2215         /* Format drivers may touch metadata even if the guest doesn't write */
2216         if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
2217             perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2218         }
2219 
2220         /* bs->file always needs to be consistent because of the metadata. We
2221          * can never allow other users to resize or write to it. */
2222         if (!(flags & BDRV_O_NO_IO)) {
2223             perm |= BLK_PERM_CONSISTENT_READ;
2224         }
2225         shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2226     } else {
2227         /* We want consistent read from backing files if the parent needs it.
2228          * No other operations are performed on backing files. */
2229         perm &= BLK_PERM_CONSISTENT_READ;
2230 
2231         /* If the parent can deal with changing data, we're okay with a
2232          * writable and resizable backing file. */
2233         /* TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too? */
2234         if (shared & BLK_PERM_WRITE) {
2235             shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
2236         } else {
2237             shared = 0;
2238         }
2239 
2240         shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_GRAPH_MOD |
2241                   BLK_PERM_WRITE_UNCHANGED;
2242     }
2243 
2244     if (bs->open_flags & BDRV_O_INACTIVE) {
2245         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
2246     }
2247 
2248     *nperm = perm;
2249     *nshared = shared;
2250 }
2251 
2252 uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
2253 {
2254     static const uint64_t permissions[] = {
2255         [BLOCK_PERMISSION_CONSISTENT_READ]  = BLK_PERM_CONSISTENT_READ,
2256         [BLOCK_PERMISSION_WRITE]            = BLK_PERM_WRITE,
2257         [BLOCK_PERMISSION_WRITE_UNCHANGED]  = BLK_PERM_WRITE_UNCHANGED,
2258         [BLOCK_PERMISSION_RESIZE]           = BLK_PERM_RESIZE,
2259         [BLOCK_PERMISSION_GRAPH_MOD]        = BLK_PERM_GRAPH_MOD,
2260     };
2261 
2262     QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
2263     QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
2264 
2265     assert(qapi_perm < BLOCK_PERMISSION__MAX);
2266 
2267     return permissions[qapi_perm];
2268 }
2269 
2270 static void bdrv_replace_child_noperm(BdrvChild *child,
2271                                       BlockDriverState *new_bs)
2272 {
2273     BlockDriverState *old_bs = child->bs;
2274     int new_bs_quiesce_counter;
2275     int drain_saldo;
2276 
2277     assert(!child->frozen);
2278 
2279     if (old_bs && new_bs) {
2280         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2281     }
2282 
2283     new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
2284     drain_saldo = new_bs_quiesce_counter - child->parent_quiesce_counter;
2285 
2286     /*
2287      * If the new child node is drained but the old one was not, flush
2288      * all outstanding requests to the old child node.
2289      */
2290     while (drain_saldo > 0 && child->role->drained_begin) {
2291         bdrv_parent_drained_begin_single(child, true);
2292         drain_saldo--;
2293     }
2294 
2295     if (old_bs) {
2296         /* Detach first so that the recursive drain sections coming from @child
2297          * are already gone and we only end the drain sections that came from
2298          * elsewhere. */
2299         if (child->role->detach) {
2300             child->role->detach(child);
2301         }
2302         QLIST_REMOVE(child, next_parent);
2303     }
2304 
2305     child->bs = new_bs;
2306 
2307     if (new_bs) {
2308         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2309 
2310         /*
2311          * Detaching the old node may have led to the new node's
2312          * quiesce_counter having been decreased.  Not a problem, we
2313          * just need to recognize this here and then invoke
2314          * drained_end appropriately more often.
2315          */
2316         assert(new_bs->quiesce_counter <= new_bs_quiesce_counter);
2317         drain_saldo += new_bs->quiesce_counter - new_bs_quiesce_counter;
2318 
2319         /* Attach only after starting new drained sections, so that recursive
2320          * drain sections coming from @child don't get an extra .drained_begin
2321          * callback. */
2322         if (child->role->attach) {
2323             child->role->attach(child);
2324         }
2325     }
2326 
2327     /*
2328      * If the old child node was drained but the new one is not, allow
2329      * requests to come in only after the new node has been attached.
2330      */
2331     while (drain_saldo < 0 && child->role->drained_end) {
2332         bdrv_parent_drained_end_single(child);
2333         drain_saldo++;
2334     }
2335 }
2336 
2337 /*
2338  * Updates @child to change its reference to point to @new_bs, including
2339  * checking and applying the necessary permisson updates both to the old node
2340  * and to @new_bs.
2341  *
2342  * NULL is passed as @new_bs for removing the reference before freeing @child.
2343  *
2344  * If @new_bs is not NULL, bdrv_check_perm() must be called beforehand, as this
2345  * function uses bdrv_set_perm() to update the permissions according to the new
2346  * reference that @new_bs gets.
2347  */
2348 static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
2349 {
2350     BlockDriverState *old_bs = child->bs;
2351     uint64_t perm, shared_perm;
2352 
2353     bdrv_replace_child_noperm(child, new_bs);
2354 
2355     /*
2356      * Start with the new node's permissions.  If @new_bs is a (direct
2357      * or indirect) child of @old_bs, we must complete the permission
2358      * update on @new_bs before we loosen the restrictions on @old_bs.
2359      * Otherwise, bdrv_check_perm() on @old_bs would re-initiate
2360      * updating the permissions of @new_bs, and thus not purely loosen
2361      * restrictions.
2362      */
2363     if (new_bs) {
2364         bdrv_get_cumulative_perm(new_bs, &perm, &shared_perm);
2365         bdrv_set_perm(new_bs, perm, shared_perm);
2366     }
2367 
2368     if (old_bs) {
2369         /* Update permissions for old node. This is guaranteed to succeed
2370          * because we're just taking a parent away, so we're loosening
2371          * restrictions. */
2372         bool tighten_restrictions;
2373         int ret;
2374 
2375         bdrv_get_cumulative_perm(old_bs, &perm, &shared_perm);
2376         ret = bdrv_check_perm(old_bs, NULL, perm, shared_perm, NULL,
2377                               &tighten_restrictions, NULL);
2378         assert(tighten_restrictions == false);
2379         if (ret < 0) {
2380             /* We only tried to loosen restrictions, so errors are not fatal */
2381             bdrv_abort_perm_update(old_bs);
2382         } else {
2383             bdrv_set_perm(old_bs, perm, shared_perm);
2384         }
2385 
2386         /* When the parent requiring a non-default AioContext is removed, the
2387          * node moves back to the main AioContext */
2388         bdrv_try_set_aio_context(old_bs, qemu_get_aio_context(), NULL);
2389     }
2390 }
2391 
2392 /*
2393  * This function steals the reference to child_bs from the caller.
2394  * That reference is later dropped by bdrv_root_unref_child().
2395  *
2396  * On failure NULL is returned, errp is set and the reference to
2397  * child_bs is also dropped.
2398  *
2399  * The caller must hold the AioContext lock @child_bs, but not that of @ctx
2400  * (unless @child_bs is already in @ctx).
2401  */
2402 BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
2403                                   const char *child_name,
2404                                   const BdrvChildRole *child_role,
2405                                   AioContext *ctx,
2406                                   uint64_t perm, uint64_t shared_perm,
2407                                   void *opaque, Error **errp)
2408 {
2409     BdrvChild *child;
2410     Error *local_err = NULL;
2411     int ret;
2412 
2413     ret = bdrv_check_update_perm(child_bs, NULL, perm, shared_perm, NULL, NULL,
2414                                  errp);
2415     if (ret < 0) {
2416         bdrv_abort_perm_update(child_bs);
2417         bdrv_unref(child_bs);
2418         return NULL;
2419     }
2420 
2421     child = g_new(BdrvChild, 1);
2422     *child = (BdrvChild) {
2423         .bs             = NULL,
2424         .name           = g_strdup(child_name),
2425         .role           = child_role,
2426         .perm           = perm,
2427         .shared_perm    = shared_perm,
2428         .opaque         = opaque,
2429     };
2430 
2431     /* If the AioContexts don't match, first try to move the subtree of
2432      * child_bs into the AioContext of the new parent. If this doesn't work,
2433      * try moving the parent into the AioContext of child_bs instead. */
2434     if (bdrv_get_aio_context(child_bs) != ctx) {
2435         ret = bdrv_try_set_aio_context(child_bs, ctx, &local_err);
2436         if (ret < 0 && child_role->can_set_aio_ctx) {
2437             GSList *ignore = g_slist_prepend(NULL, child);;
2438             ctx = bdrv_get_aio_context(child_bs);
2439             if (child_role->can_set_aio_ctx(child, ctx, &ignore, NULL)) {
2440                 error_free(local_err);
2441                 ret = 0;
2442                 g_slist_free(ignore);
2443                 ignore = g_slist_prepend(NULL, child);;
2444                 child_role->set_aio_ctx(child, ctx, &ignore);
2445             }
2446             g_slist_free(ignore);
2447         }
2448         if (ret < 0) {
2449             error_propagate(errp, local_err);
2450             g_free(child);
2451             bdrv_abort_perm_update(child_bs);
2452             return NULL;
2453         }
2454     }
2455 
2456     /* This performs the matching bdrv_set_perm() for the above check. */
2457     bdrv_replace_child(child, child_bs);
2458 
2459     return child;
2460 }
2461 
2462 /*
2463  * This function transfers the reference to child_bs from the caller
2464  * to parent_bs. That reference is later dropped by parent_bs on
2465  * bdrv_close() or if someone calls bdrv_unref_child().
2466  *
2467  * On failure NULL is returned, errp is set and the reference to
2468  * child_bs is also dropped.
2469  *
2470  * If @parent_bs and @child_bs are in different AioContexts, the caller must
2471  * hold the AioContext lock for @child_bs, but not for @parent_bs.
2472  */
2473 BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
2474                              BlockDriverState *child_bs,
2475                              const char *child_name,
2476                              const BdrvChildRole *child_role,
2477                              Error **errp)
2478 {
2479     BdrvChild *child;
2480     uint64_t perm, shared_perm;
2481 
2482     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
2483 
2484     assert(parent_bs->drv);
2485     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
2486                     perm, shared_perm, &perm, &shared_perm);
2487 
2488     child = bdrv_root_attach_child(child_bs, child_name, child_role,
2489                                    bdrv_get_aio_context(parent_bs),
2490                                    perm, shared_perm, parent_bs, errp);
2491     if (child == NULL) {
2492         return NULL;
2493     }
2494 
2495     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
2496     return child;
2497 }
2498 
2499 static void bdrv_detach_child(BdrvChild *child)
2500 {
2501     if (child->next.le_prev) {
2502         QLIST_REMOVE(child, next);
2503         child->next.le_prev = NULL;
2504     }
2505 
2506     bdrv_replace_child(child, NULL);
2507 
2508     g_free(child->name);
2509     g_free(child);
2510 }
2511 
2512 void bdrv_root_unref_child(BdrvChild *child)
2513 {
2514     BlockDriverState *child_bs;
2515 
2516     child_bs = child->bs;
2517     bdrv_detach_child(child);
2518     bdrv_unref(child_bs);
2519 }
2520 
2521 /**
2522  * Clear all inherits_from pointers from children and grandchildren of
2523  * @root that point to @root, where necessary.
2524  */
2525 static void bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child)
2526 {
2527     BdrvChild *c;
2528 
2529     if (child->bs->inherits_from == root) {
2530         /*
2531          * Remove inherits_from only when the last reference between root and
2532          * child->bs goes away.
2533          */
2534         QLIST_FOREACH(c, &root->children, next) {
2535             if (c != child && c->bs == child->bs) {
2536                 break;
2537             }
2538         }
2539         if (c == NULL) {
2540             child->bs->inherits_from = NULL;
2541         }
2542     }
2543 
2544     QLIST_FOREACH(c, &child->bs->children, next) {
2545         bdrv_unset_inherits_from(root, c);
2546     }
2547 }
2548 
2549 void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
2550 {
2551     if (child == NULL) {
2552         return;
2553     }
2554 
2555     bdrv_unset_inherits_from(parent, child);
2556     bdrv_root_unref_child(child);
2557 }
2558 
2559 
2560 static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
2561 {
2562     BdrvChild *c;
2563     QLIST_FOREACH(c, &bs->parents, next_parent) {
2564         if (c->role->change_media) {
2565             c->role->change_media(c, load);
2566         }
2567     }
2568 }
2569 
2570 /* Return true if you can reach parent going through child->inherits_from
2571  * recursively. If parent or child are NULL, return false */
2572 static bool bdrv_inherits_from_recursive(BlockDriverState *child,
2573                                          BlockDriverState *parent)
2574 {
2575     while (child && child != parent) {
2576         child = child->inherits_from;
2577     }
2578 
2579     return child != NULL;
2580 }
2581 
2582 /*
2583  * Sets the backing file link of a BDS. A new reference is created; callers
2584  * which don't need their own reference any more must call bdrv_unref().
2585  */
2586 void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
2587                          Error **errp)
2588 {
2589     bool update_inherits_from = bdrv_chain_contains(bs, backing_hd) &&
2590         bdrv_inherits_from_recursive(backing_hd, bs);
2591 
2592     if (bdrv_is_backing_chain_frozen(bs, backing_bs(bs), errp)) {
2593         return;
2594     }
2595 
2596     if (backing_hd) {
2597         bdrv_ref(backing_hd);
2598     }
2599 
2600     if (bs->backing) {
2601         bdrv_unref_child(bs, bs->backing);
2602     }
2603 
2604     if (!backing_hd) {
2605         bs->backing = NULL;
2606         goto out;
2607     }
2608 
2609     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing,
2610                                     errp);
2611     /* If backing_hd was already part of bs's backing chain, and
2612      * inherits_from pointed recursively to bs then let's update it to
2613      * point directly to bs (else it will become NULL). */
2614     if (bs->backing && update_inherits_from) {
2615         backing_hd->inherits_from = bs;
2616     }
2617 
2618 out:
2619     bdrv_refresh_limits(bs, NULL);
2620 }
2621 
2622 /*
2623  * Opens the backing file for a BlockDriverState if not yet open
2624  *
2625  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
2626  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2627  * itself, all options starting with "${bdref_key}." are considered part of the
2628  * BlockdevRef.
2629  *
2630  * TODO Can this be unified with bdrv_open_image()?
2631  */
2632 int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
2633                            const char *bdref_key, Error **errp)
2634 {
2635     char *backing_filename = NULL;
2636     char *bdref_key_dot;
2637     const char *reference = NULL;
2638     int ret = 0;
2639     bool implicit_backing = false;
2640     BlockDriverState *backing_hd;
2641     QDict *options;
2642     QDict *tmp_parent_options = NULL;
2643     Error *local_err = NULL;
2644 
2645     if (bs->backing != NULL) {
2646         goto free_exit;
2647     }
2648 
2649     /* NULL means an empty set of options */
2650     if (parent_options == NULL) {
2651         tmp_parent_options = qdict_new();
2652         parent_options = tmp_parent_options;
2653     }
2654 
2655     bs->open_flags &= ~BDRV_O_NO_BACKING;
2656 
2657     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2658     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
2659     g_free(bdref_key_dot);
2660 
2661     /*
2662      * Caution: while qdict_get_try_str() is fine, getting non-string
2663      * types would require more care.  When @parent_options come from
2664      * -blockdev or blockdev_add, its members are typed according to
2665      * the QAPI schema, but when they come from -drive, they're all
2666      * QString.
2667      */
2668     reference = qdict_get_try_str(parent_options, bdref_key);
2669     if (reference || qdict_haskey(options, "file.filename")) {
2670         /* keep backing_filename NULL */
2671     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
2672         qobject_unref(options);
2673         goto free_exit;
2674     } else {
2675         if (qdict_size(options) == 0) {
2676             /* If the user specifies options that do not modify the
2677              * backing file's behavior, we might still consider it the
2678              * implicit backing file.  But it's easier this way, and
2679              * just specifying some of the backing BDS's options is
2680              * only possible with -drive anyway (otherwise the QAPI
2681              * schema forces the user to specify everything). */
2682             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
2683         }
2684 
2685         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
2686         if (local_err) {
2687             ret = -EINVAL;
2688             error_propagate(errp, local_err);
2689             qobject_unref(options);
2690             goto free_exit;
2691         }
2692     }
2693 
2694     if (!bs->drv || !bs->drv->supports_backing) {
2695         ret = -EINVAL;
2696         error_setg(errp, "Driver doesn't support backing files");
2697         qobject_unref(options);
2698         goto free_exit;
2699     }
2700 
2701     if (!reference &&
2702         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
2703         qdict_put_str(options, "driver", bs->backing_format);
2704     }
2705 
2706     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
2707                                    &child_backing, errp);
2708     if (!backing_hd) {
2709         bs->open_flags |= BDRV_O_NO_BACKING;
2710         error_prepend(errp, "Could not open backing file: ");
2711         ret = -EINVAL;
2712         goto free_exit;
2713     }
2714 
2715     if (implicit_backing) {
2716         bdrv_refresh_filename(backing_hd);
2717         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
2718                 backing_hd->filename);
2719     }
2720 
2721     /* Hook up the backing file link; drop our reference, bs owns the
2722      * backing_hd reference now */
2723     bdrv_set_backing_hd(bs, backing_hd, &local_err);
2724     bdrv_unref(backing_hd);
2725     if (local_err) {
2726         error_propagate(errp, local_err);
2727         ret = -EINVAL;
2728         goto free_exit;
2729     }
2730 
2731     qdict_del(parent_options, bdref_key);
2732 
2733 free_exit:
2734     g_free(backing_filename);
2735     qobject_unref(tmp_parent_options);
2736     return ret;
2737 }
2738 
2739 static BlockDriverState *
2740 bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
2741                    BlockDriverState *parent, const BdrvChildRole *child_role,
2742                    bool allow_none, Error **errp)
2743 {
2744     BlockDriverState *bs = NULL;
2745     QDict *image_options;
2746     char *bdref_key_dot;
2747     const char *reference;
2748 
2749     assert(child_role != NULL);
2750 
2751     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
2752     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
2753     g_free(bdref_key_dot);
2754 
2755     /*
2756      * Caution: while qdict_get_try_str() is fine, getting non-string
2757      * types would require more care.  When @options come from
2758      * -blockdev or blockdev_add, its members are typed according to
2759      * the QAPI schema, but when they come from -drive, they're all
2760      * QString.
2761      */
2762     reference = qdict_get_try_str(options, bdref_key);
2763     if (!filename && !reference && !qdict_size(image_options)) {
2764         if (!allow_none) {
2765             error_setg(errp, "A block device must be specified for \"%s\"",
2766                        bdref_key);
2767         }
2768         qobject_unref(image_options);
2769         goto done;
2770     }
2771 
2772     bs = bdrv_open_inherit(filename, reference, image_options, 0,
2773                            parent, child_role, errp);
2774     if (!bs) {
2775         goto done;
2776     }
2777 
2778 done:
2779     qdict_del(options, bdref_key);
2780     return bs;
2781 }
2782 
2783 /*
2784  * Opens a disk image whose options are given as BlockdevRef in another block
2785  * device's options.
2786  *
2787  * If allow_none is true, no image will be opened if filename is false and no
2788  * BlockdevRef is given. NULL will be returned, but errp remains unset.
2789  *
2790  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
2791  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
2792  * itself, all options starting with "${bdref_key}." are considered part of the
2793  * BlockdevRef.
2794  *
2795  * The BlockdevRef will be removed from the options QDict.
2796  */
2797 BdrvChild *bdrv_open_child(const char *filename,
2798                            QDict *options, const char *bdref_key,
2799                            BlockDriverState *parent,
2800                            const BdrvChildRole *child_role,
2801                            bool allow_none, Error **errp)
2802 {
2803     BlockDriverState *bs;
2804 
2805     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_role,
2806                             allow_none, errp);
2807     if (bs == NULL) {
2808         return NULL;
2809     }
2810 
2811     return bdrv_attach_child(parent, bs, bdref_key, child_role, errp);
2812 }
2813 
2814 /* TODO Future callers may need to specify parent/child_role in order for
2815  * option inheritance to work. Existing callers use it for the root node. */
2816 BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
2817 {
2818     BlockDriverState *bs = NULL;
2819     Error *local_err = NULL;
2820     QObject *obj = NULL;
2821     QDict *qdict = NULL;
2822     const char *reference = NULL;
2823     Visitor *v = NULL;
2824 
2825     if (ref->type == QTYPE_QSTRING) {
2826         reference = ref->u.reference;
2827     } else {
2828         BlockdevOptions *options = &ref->u.definition;
2829         assert(ref->type == QTYPE_QDICT);
2830 
2831         v = qobject_output_visitor_new(&obj);
2832         visit_type_BlockdevOptions(v, NULL, &options, &local_err);
2833         if (local_err) {
2834             error_propagate(errp, local_err);
2835             goto fail;
2836         }
2837         visit_complete(v, &obj);
2838 
2839         qdict = qobject_to(QDict, obj);
2840         qdict_flatten(qdict);
2841 
2842         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
2843          * compatibility with other callers) rather than what we want as the
2844          * real defaults. Apply the defaults here instead. */
2845         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
2846         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
2847         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
2848         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
2849 
2850     }
2851 
2852     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, errp);
2853     obj = NULL;
2854 
2855 fail:
2856     qobject_unref(obj);
2857     visit_free(v);
2858     return bs;
2859 }
2860 
2861 static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
2862                                                    int flags,
2863                                                    QDict *snapshot_options,
2864                                                    Error **errp)
2865 {
2866     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
2867     char *tmp_filename = g_malloc0(PATH_MAX + 1);
2868     int64_t total_size;
2869     QemuOpts *opts = NULL;
2870     BlockDriverState *bs_snapshot = NULL;
2871     Error *local_err = NULL;
2872     int ret;
2873 
2874     /* if snapshot, we create a temporary backing file and open it
2875        instead of opening 'filename' directly */
2876 
2877     /* Get the required size from the image */
2878     total_size = bdrv_getlength(bs);
2879     if (total_size < 0) {
2880         error_setg_errno(errp, -total_size, "Could not get image size");
2881         goto out;
2882     }
2883 
2884     /* Create the temporary image */
2885     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
2886     if (ret < 0) {
2887         error_setg_errno(errp, -ret, "Could not get temporary filename");
2888         goto out;
2889     }
2890 
2891     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
2892                             &error_abort);
2893     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
2894     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
2895     qemu_opts_del(opts);
2896     if (ret < 0) {
2897         error_prepend(errp, "Could not create temporary overlay '%s': ",
2898                       tmp_filename);
2899         goto out;
2900     }
2901 
2902     /* Prepare options QDict for the temporary file */
2903     qdict_put_str(snapshot_options, "file.driver", "file");
2904     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
2905     qdict_put_str(snapshot_options, "driver", "qcow2");
2906 
2907     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
2908     snapshot_options = NULL;
2909     if (!bs_snapshot) {
2910         goto out;
2911     }
2912 
2913     /* bdrv_append() consumes a strong reference to bs_snapshot
2914      * (i.e. it will call bdrv_unref() on it) even on error, so in
2915      * order to be able to return one, we have to increase
2916      * bs_snapshot's refcount here */
2917     bdrv_ref(bs_snapshot);
2918     bdrv_append(bs_snapshot, bs, &local_err);
2919     if (local_err) {
2920         error_propagate(errp, local_err);
2921         bs_snapshot = NULL;
2922         goto out;
2923     }
2924 
2925 out:
2926     qobject_unref(snapshot_options);
2927     g_free(tmp_filename);
2928     return bs_snapshot;
2929 }
2930 
2931 /*
2932  * Opens a disk image (raw, qcow2, vmdk, ...)
2933  *
2934  * options is a QDict of options to pass to the block drivers, or NULL for an
2935  * empty set of options. The reference to the QDict belongs to the block layer
2936  * after the call (even on failure), so if the caller intends to reuse the
2937  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
2938  *
2939  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
2940  * If it is not NULL, the referenced BDS will be reused.
2941  *
2942  * The reference parameter may be used to specify an existing block device which
2943  * should be opened. If specified, neither options nor a filename may be given,
2944  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
2945  */
2946 static BlockDriverState *bdrv_open_inherit(const char *filename,
2947                                            const char *reference,
2948                                            QDict *options, int flags,
2949                                            BlockDriverState *parent,
2950                                            const BdrvChildRole *child_role,
2951                                            Error **errp)
2952 {
2953     int ret;
2954     BlockBackend *file = NULL;
2955     BlockDriverState *bs;
2956     BlockDriver *drv = NULL;
2957     BdrvChild *child;
2958     const char *drvname;
2959     const char *backing;
2960     Error *local_err = NULL;
2961     QDict *snapshot_options = NULL;
2962     int snapshot_flags = 0;
2963 
2964     assert(!child_role || !flags);
2965     assert(!child_role == !parent);
2966 
2967     if (reference) {
2968         bool options_non_empty = options ? qdict_size(options) : false;
2969         qobject_unref(options);
2970 
2971         if (filename || options_non_empty) {
2972             error_setg(errp, "Cannot reference an existing block device with "
2973                        "additional options or a new filename");
2974             return NULL;
2975         }
2976 
2977         bs = bdrv_lookup_bs(reference, reference, errp);
2978         if (!bs) {
2979             return NULL;
2980         }
2981 
2982         bdrv_ref(bs);
2983         return bs;
2984     }
2985 
2986     bs = bdrv_new();
2987 
2988     /* NULL means an empty set of options */
2989     if (options == NULL) {
2990         options = qdict_new();
2991     }
2992 
2993     /* json: syntax counts as explicit options, as if in the QDict */
2994     parse_json_protocol(options, &filename, &local_err);
2995     if (local_err) {
2996         goto fail;
2997     }
2998 
2999     bs->explicit_options = qdict_clone_shallow(options);
3000 
3001     if (child_role) {
3002         bs->inherits_from = parent;
3003         child_role->inherit_options(&flags, options,
3004                                     parent->open_flags, parent->options);
3005     }
3006 
3007     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
3008     if (local_err) {
3009         goto fail;
3010     }
3011 
3012     /*
3013      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
3014      * Caution: getting a boolean member of @options requires care.
3015      * When @options come from -blockdev or blockdev_add, members are
3016      * typed according to the QAPI schema, but when they come from
3017      * -drive, they're all QString.
3018      */
3019     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
3020         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
3021         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
3022     } else {
3023         flags &= ~BDRV_O_RDWR;
3024     }
3025 
3026     if (flags & BDRV_O_SNAPSHOT) {
3027         snapshot_options = qdict_new();
3028         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
3029                                    flags, options);
3030         /* Let bdrv_backing_options() override "read-only" */
3031         qdict_del(options, BDRV_OPT_READ_ONLY);
3032         bdrv_backing_options(&flags, options, flags, options);
3033     }
3034 
3035     bs->open_flags = flags;
3036     bs->options = options;
3037     options = qdict_clone_shallow(options);
3038 
3039     /* Find the right image format driver */
3040     /* See cautionary note on accessing @options above */
3041     drvname = qdict_get_try_str(options, "driver");
3042     if (drvname) {
3043         drv = bdrv_find_format(drvname);
3044         if (!drv) {
3045             error_setg(errp, "Unknown driver: '%s'", drvname);
3046             goto fail;
3047         }
3048     }
3049 
3050     assert(drvname || !(flags & BDRV_O_PROTOCOL));
3051 
3052     /* See cautionary note on accessing @options above */
3053     backing = qdict_get_try_str(options, "backing");
3054     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
3055         (backing && *backing == '\0'))
3056     {
3057         if (backing) {
3058             warn_report("Use of \"backing\": \"\" is deprecated; "
3059                         "use \"backing\": null instead");
3060         }
3061         flags |= BDRV_O_NO_BACKING;
3062         qdict_del(bs->explicit_options, "backing");
3063         qdict_del(bs->options, "backing");
3064         qdict_del(options, "backing");
3065     }
3066 
3067     /* Open image file without format layer. This BlockBackend is only used for
3068      * probing, the block drivers will do their own bdrv_open_child() for the
3069      * same BDS, which is why we put the node name back into options. */
3070     if ((flags & BDRV_O_PROTOCOL) == 0) {
3071         BlockDriverState *file_bs;
3072 
3073         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
3074                                      &child_file, true, &local_err);
3075         if (local_err) {
3076             goto fail;
3077         }
3078         if (file_bs != NULL) {
3079             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
3080              * looking at the header to guess the image format. This works even
3081              * in cases where a guest would not see a consistent state. */
3082             file = blk_new(bdrv_get_aio_context(file_bs), 0, BLK_PERM_ALL);
3083             blk_insert_bs(file, file_bs, &local_err);
3084             bdrv_unref(file_bs);
3085             if (local_err) {
3086                 goto fail;
3087             }
3088 
3089             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
3090         }
3091     }
3092 
3093     /* Image format probing */
3094     bs->probed = !drv;
3095     if (!drv && file) {
3096         ret = find_image_format(file, filename, &drv, &local_err);
3097         if (ret < 0) {
3098             goto fail;
3099         }
3100         /*
3101          * This option update would logically belong in bdrv_fill_options(),
3102          * but we first need to open bs->file for the probing to work, while
3103          * opening bs->file already requires the (mostly) final set of options
3104          * so that cache mode etc. can be inherited.
3105          *
3106          * Adding the driver later is somewhat ugly, but it's not an option
3107          * that would ever be inherited, so it's correct. We just need to make
3108          * sure to update both bs->options (which has the full effective
3109          * options for bs) and options (which has file.* already removed).
3110          */
3111         qdict_put_str(bs->options, "driver", drv->format_name);
3112         qdict_put_str(options, "driver", drv->format_name);
3113     } else if (!drv) {
3114         error_setg(errp, "Must specify either driver or file");
3115         goto fail;
3116     }
3117 
3118     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
3119     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
3120     /* file must be NULL if a protocol BDS is about to be created
3121      * (the inverse results in an error message from bdrv_open_common()) */
3122     assert(!(flags & BDRV_O_PROTOCOL) || !file);
3123 
3124     /* Open the image */
3125     ret = bdrv_open_common(bs, file, options, &local_err);
3126     if (ret < 0) {
3127         goto fail;
3128     }
3129 
3130     if (file) {
3131         blk_unref(file);
3132         file = NULL;
3133     }
3134 
3135     /* If there is a backing file, use it */
3136     if ((flags & BDRV_O_NO_BACKING) == 0) {
3137         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
3138         if (ret < 0) {
3139             goto close_and_fail;
3140         }
3141     }
3142 
3143     /* Remove all children options and references
3144      * from bs->options and bs->explicit_options */
3145     QLIST_FOREACH(child, &bs->children, next) {
3146         char *child_key_dot;
3147         child_key_dot = g_strdup_printf("%s.", child->name);
3148         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
3149         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
3150         qdict_del(bs->explicit_options, child->name);
3151         qdict_del(bs->options, child->name);
3152         g_free(child_key_dot);
3153     }
3154 
3155     /* Check if any unknown options were used */
3156     if (qdict_size(options) != 0) {
3157         const QDictEntry *entry = qdict_first(options);
3158         if (flags & BDRV_O_PROTOCOL) {
3159             error_setg(errp, "Block protocol '%s' doesn't support the option "
3160                        "'%s'", drv->format_name, entry->key);
3161         } else {
3162             error_setg(errp,
3163                        "Block format '%s' does not support the option '%s'",
3164                        drv->format_name, entry->key);
3165         }
3166 
3167         goto close_and_fail;
3168     }
3169 
3170     bdrv_parent_cb_change_media(bs, true);
3171 
3172     qobject_unref(options);
3173     options = NULL;
3174 
3175     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
3176      * temporary snapshot afterwards. */
3177     if (snapshot_flags) {
3178         BlockDriverState *snapshot_bs;
3179         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
3180                                                 snapshot_options, &local_err);
3181         snapshot_options = NULL;
3182         if (local_err) {
3183             goto close_and_fail;
3184         }
3185         /* We are not going to return bs but the overlay on top of it
3186          * (snapshot_bs); thus, we have to drop the strong reference to bs
3187          * (which we obtained by calling bdrv_new()). bs will not be deleted,
3188          * though, because the overlay still has a reference to it. */
3189         bdrv_unref(bs);
3190         bs = snapshot_bs;
3191     }
3192 
3193     return bs;
3194 
3195 fail:
3196     blk_unref(file);
3197     qobject_unref(snapshot_options);
3198     qobject_unref(bs->explicit_options);
3199     qobject_unref(bs->options);
3200     qobject_unref(options);
3201     bs->options = NULL;
3202     bs->explicit_options = NULL;
3203     bdrv_unref(bs);
3204     error_propagate(errp, local_err);
3205     return NULL;
3206 
3207 close_and_fail:
3208     bdrv_unref(bs);
3209     qobject_unref(snapshot_options);
3210     qobject_unref(options);
3211     error_propagate(errp, local_err);
3212     return NULL;
3213 }
3214 
3215 BlockDriverState *bdrv_open(const char *filename, const char *reference,
3216                             QDict *options, int flags, Error **errp)
3217 {
3218     return bdrv_open_inherit(filename, reference, options, flags, NULL,
3219                              NULL, errp);
3220 }
3221 
3222 /* Return true if the NULL-terminated @list contains @str */
3223 static bool is_str_in_list(const char *str, const char *const *list)
3224 {
3225     if (str && list) {
3226         int i;
3227         for (i = 0; list[i] != NULL; i++) {
3228             if (!strcmp(str, list[i])) {
3229                 return true;
3230             }
3231         }
3232     }
3233     return false;
3234 }
3235 
3236 /*
3237  * Check that every option set in @bs->options is also set in
3238  * @new_opts.
3239  *
3240  * Options listed in the common_options list and in
3241  * @bs->drv->mutable_opts are skipped.
3242  *
3243  * Return 0 on success, otherwise return -EINVAL and set @errp.
3244  */
3245 static int bdrv_reset_options_allowed(BlockDriverState *bs,
3246                                       const QDict *new_opts, Error **errp)
3247 {
3248     const QDictEntry *e;
3249     /* These options are common to all block drivers and are handled
3250      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
3251     const char *const common_options[] = {
3252         "node-name", "discard", "cache.direct", "cache.no-flush",
3253         "read-only", "auto-read-only", "detect-zeroes", NULL
3254     };
3255 
3256     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
3257         if (!qdict_haskey(new_opts, e->key) &&
3258             !is_str_in_list(e->key, common_options) &&
3259             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
3260             error_setg(errp, "Option '%s' cannot be reset "
3261                        "to its default value", e->key);
3262             return -EINVAL;
3263         }
3264     }
3265 
3266     return 0;
3267 }
3268 
3269 /*
3270  * Returns true if @child can be reached recursively from @bs
3271  */
3272 static bool bdrv_recurse_has_child(BlockDriverState *bs,
3273                                    BlockDriverState *child)
3274 {
3275     BdrvChild *c;
3276 
3277     if (bs == child) {
3278         return true;
3279     }
3280 
3281     QLIST_FOREACH(c, &bs->children, next) {
3282         if (bdrv_recurse_has_child(c->bs, child)) {
3283             return true;
3284         }
3285     }
3286 
3287     return false;
3288 }
3289 
3290 /*
3291  * Adds a BlockDriverState to a simple queue for an atomic, transactional
3292  * reopen of multiple devices.
3293  *
3294  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
3295  * already performed, or alternatively may be NULL a new BlockReopenQueue will
3296  * be created and initialized. This newly created BlockReopenQueue should be
3297  * passed back in for subsequent calls that are intended to be of the same
3298  * atomic 'set'.
3299  *
3300  * bs is the BlockDriverState to add to the reopen queue.
3301  *
3302  * options contains the changed options for the associated bs
3303  * (the BlockReopenQueue takes ownership)
3304  *
3305  * flags contains the open flags for the associated bs
3306  *
3307  * returns a pointer to bs_queue, which is either the newly allocated
3308  * bs_queue, or the existing bs_queue being used.
3309  *
3310  * bs must be drained between bdrv_reopen_queue() and bdrv_reopen_multiple().
3311  */
3312 static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
3313                                                  BlockDriverState *bs,
3314                                                  QDict *options,
3315                                                  const BdrvChildRole *role,
3316                                                  QDict *parent_options,
3317                                                  int parent_flags,
3318                                                  bool keep_old_opts)
3319 {
3320     assert(bs != NULL);
3321 
3322     BlockReopenQueueEntry *bs_entry;
3323     BdrvChild *child;
3324     QDict *old_options, *explicit_options, *options_copy;
3325     int flags;
3326     QemuOpts *opts;
3327 
3328     /* Make sure that the caller remembered to use a drained section. This is
3329      * important to avoid graph changes between the recursive queuing here and
3330      * bdrv_reopen_multiple(). */
3331     assert(bs->quiesce_counter > 0);
3332 
3333     if (bs_queue == NULL) {
3334         bs_queue = g_new0(BlockReopenQueue, 1);
3335         QTAILQ_INIT(bs_queue);
3336     }
3337 
3338     if (!options) {
3339         options = qdict_new();
3340     }
3341 
3342     /* Check if this BlockDriverState is already in the queue */
3343     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3344         if (bs == bs_entry->state.bs) {
3345             break;
3346         }
3347     }
3348 
3349     /*
3350      * Precedence of options:
3351      * 1. Explicitly passed in options (highest)
3352      * 2. Retained from explicitly set options of bs
3353      * 3. Inherited from parent node
3354      * 4. Retained from effective options of bs
3355      */
3356 
3357     /* Old explicitly set values (don't overwrite by inherited value) */
3358     if (bs_entry || keep_old_opts) {
3359         old_options = qdict_clone_shallow(bs_entry ?
3360                                           bs_entry->state.explicit_options :
3361                                           bs->explicit_options);
3362         bdrv_join_options(bs, options, old_options);
3363         qobject_unref(old_options);
3364     }
3365 
3366     explicit_options = qdict_clone_shallow(options);
3367 
3368     /* Inherit from parent node */
3369     if (parent_options) {
3370         flags = 0;
3371         role->inherit_options(&flags, options, parent_flags, parent_options);
3372     } else {
3373         flags = bdrv_get_flags(bs);
3374     }
3375 
3376     if (keep_old_opts) {
3377         /* Old values are used for options that aren't set yet */
3378         old_options = qdict_clone_shallow(bs->options);
3379         bdrv_join_options(bs, options, old_options);
3380         qobject_unref(old_options);
3381     }
3382 
3383     /* We have the final set of options so let's update the flags */
3384     options_copy = qdict_clone_shallow(options);
3385     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3386     qemu_opts_absorb_qdict(opts, options_copy, NULL);
3387     update_flags_from_options(&flags, opts);
3388     qemu_opts_del(opts);
3389     qobject_unref(options_copy);
3390 
3391     /* bdrv_open_inherit() sets and clears some additional flags internally */
3392     flags &= ~BDRV_O_PROTOCOL;
3393     if (flags & BDRV_O_RDWR) {
3394         flags |= BDRV_O_ALLOW_RDWR;
3395     }
3396 
3397     if (!bs_entry) {
3398         bs_entry = g_new0(BlockReopenQueueEntry, 1);
3399         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
3400     } else {
3401         qobject_unref(bs_entry->state.options);
3402         qobject_unref(bs_entry->state.explicit_options);
3403     }
3404 
3405     bs_entry->state.bs = bs;
3406     bs_entry->state.options = options;
3407     bs_entry->state.explicit_options = explicit_options;
3408     bs_entry->state.flags = flags;
3409 
3410     /* This needs to be overwritten in bdrv_reopen_prepare() */
3411     bs_entry->state.perm = UINT64_MAX;
3412     bs_entry->state.shared_perm = 0;
3413 
3414     /*
3415      * If keep_old_opts is false then it means that unspecified
3416      * options must be reset to their original value. We don't allow
3417      * resetting 'backing' but we need to know if the option is
3418      * missing in order to decide if we have to return an error.
3419      */
3420     if (!keep_old_opts) {
3421         bs_entry->state.backing_missing =
3422             !qdict_haskey(options, "backing") &&
3423             !qdict_haskey(options, "backing.driver");
3424     }
3425 
3426     QLIST_FOREACH(child, &bs->children, next) {
3427         QDict *new_child_options = NULL;
3428         bool child_keep_old = keep_old_opts;
3429 
3430         /* reopen can only change the options of block devices that were
3431          * implicitly created and inherited options. For other (referenced)
3432          * block devices, a syntax like "backing.foo" results in an error. */
3433         if (child->bs->inherits_from != bs) {
3434             continue;
3435         }
3436 
3437         /* Check if the options contain a child reference */
3438         if (qdict_haskey(options, child->name)) {
3439             const char *childref = qdict_get_try_str(options, child->name);
3440             /*
3441              * The current child must not be reopened if the child
3442              * reference is null or points to a different node.
3443              */
3444             if (g_strcmp0(childref, child->bs->node_name)) {
3445                 continue;
3446             }
3447             /*
3448              * If the child reference points to the current child then
3449              * reopen it with its existing set of options (note that
3450              * it can still inherit new options from the parent).
3451              */
3452             child_keep_old = true;
3453         } else {
3454             /* Extract child options ("child-name.*") */
3455             char *child_key_dot = g_strdup_printf("%s.", child->name);
3456             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
3457             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
3458             g_free(child_key_dot);
3459         }
3460 
3461         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
3462                                 child->role, options, flags, child_keep_old);
3463     }
3464 
3465     return bs_queue;
3466 }
3467 
3468 BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
3469                                     BlockDriverState *bs,
3470                                     QDict *options, bool keep_old_opts)
3471 {
3472     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, NULL, 0,
3473                                    keep_old_opts);
3474 }
3475 
3476 /*
3477  * Reopen multiple BlockDriverStates atomically & transactionally.
3478  *
3479  * The queue passed in (bs_queue) must have been built up previous
3480  * via bdrv_reopen_queue().
3481  *
3482  * Reopens all BDS specified in the queue, with the appropriate
3483  * flags.  All devices are prepared for reopen, and failure of any
3484  * device will cause all device changes to be abandoned, and intermediate
3485  * data cleaned up.
3486  *
3487  * If all devices prepare successfully, then the changes are committed
3488  * to all devices.
3489  *
3490  * All affected nodes must be drained between bdrv_reopen_queue() and
3491  * bdrv_reopen_multiple().
3492  */
3493 int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
3494 {
3495     int ret = -1;
3496     BlockReopenQueueEntry *bs_entry, *next;
3497 
3498     assert(bs_queue != NULL);
3499 
3500     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3501         assert(bs_entry->state.bs->quiesce_counter > 0);
3502         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, errp)) {
3503             goto cleanup;
3504         }
3505         bs_entry->prepared = true;
3506     }
3507 
3508     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
3509         BDRVReopenState *state = &bs_entry->state;
3510         ret = bdrv_check_perm(state->bs, bs_queue, state->perm,
3511                               state->shared_perm, NULL, NULL, errp);
3512         if (ret < 0) {
3513             goto cleanup_perm;
3514         }
3515         /* Check if new_backing_bs would accept the new permissions */
3516         if (state->replace_backing_bs && state->new_backing_bs) {
3517             uint64_t nperm, nshared;
3518             bdrv_child_perm(state->bs, state->new_backing_bs,
3519                             NULL, &child_backing, bs_queue,
3520                             state->perm, state->shared_perm,
3521                             &nperm, &nshared);
3522             ret = bdrv_check_update_perm(state->new_backing_bs, NULL,
3523                                          nperm, nshared, NULL, NULL, errp);
3524             if (ret < 0) {
3525                 goto cleanup_perm;
3526             }
3527         }
3528         bs_entry->perms_checked = true;
3529     }
3530 
3531     /*
3532      * If we reach this point, we have success and just need to apply the
3533      * changes.
3534      *
3535      * Reverse order is used to comfort qcow2 driver: on commit it need to write
3536      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
3537      * children are usually goes after parents in reopen-queue, so go from last
3538      * to first element.
3539      */
3540     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
3541         bdrv_reopen_commit(&bs_entry->state);
3542     }
3543 
3544     ret = 0;
3545 cleanup_perm:
3546     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3547         BDRVReopenState *state = &bs_entry->state;
3548 
3549         if (!bs_entry->perms_checked) {
3550             continue;
3551         }
3552 
3553         if (ret == 0) {
3554             bdrv_set_perm(state->bs, state->perm, state->shared_perm);
3555         } else {
3556             bdrv_abort_perm_update(state->bs);
3557             if (state->replace_backing_bs && state->new_backing_bs) {
3558                 bdrv_abort_perm_update(state->new_backing_bs);
3559             }
3560         }
3561     }
3562 cleanup:
3563     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
3564         if (ret) {
3565             if (bs_entry->prepared) {
3566                 bdrv_reopen_abort(&bs_entry->state);
3567             }
3568             qobject_unref(bs_entry->state.explicit_options);
3569             qobject_unref(bs_entry->state.options);
3570         }
3571         if (bs_entry->state.new_backing_bs) {
3572             bdrv_unref(bs_entry->state.new_backing_bs);
3573         }
3574         g_free(bs_entry);
3575     }
3576     g_free(bs_queue);
3577 
3578     return ret;
3579 }
3580 
3581 int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
3582                               Error **errp)
3583 {
3584     int ret;
3585     BlockReopenQueue *queue;
3586     QDict *opts = qdict_new();
3587 
3588     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
3589 
3590     bdrv_subtree_drained_begin(bs);
3591     queue = bdrv_reopen_queue(NULL, bs, opts, true);
3592     ret = bdrv_reopen_multiple(queue, errp);
3593     bdrv_subtree_drained_end(bs);
3594 
3595     return ret;
3596 }
3597 
3598 static BlockReopenQueueEntry *find_parent_in_reopen_queue(BlockReopenQueue *q,
3599                                                           BdrvChild *c)
3600 {
3601     BlockReopenQueueEntry *entry;
3602 
3603     QTAILQ_FOREACH(entry, q, entry) {
3604         BlockDriverState *bs = entry->state.bs;
3605         BdrvChild *child;
3606 
3607         QLIST_FOREACH(child, &bs->children, next) {
3608             if (child == c) {
3609                 return entry;
3610             }
3611         }
3612     }
3613 
3614     return NULL;
3615 }
3616 
3617 static void bdrv_reopen_perm(BlockReopenQueue *q, BlockDriverState *bs,
3618                              uint64_t *perm, uint64_t *shared)
3619 {
3620     BdrvChild *c;
3621     BlockReopenQueueEntry *parent;
3622     uint64_t cumulative_perms = 0;
3623     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
3624 
3625     QLIST_FOREACH(c, &bs->parents, next_parent) {
3626         parent = find_parent_in_reopen_queue(q, c);
3627         if (!parent) {
3628             cumulative_perms |= c->perm;
3629             cumulative_shared_perms &= c->shared_perm;
3630         } else {
3631             uint64_t nperm, nshared;
3632 
3633             bdrv_child_perm(parent->state.bs, bs, c, c->role, q,
3634                             parent->state.perm, parent->state.shared_perm,
3635                             &nperm, &nshared);
3636 
3637             cumulative_perms |= nperm;
3638             cumulative_shared_perms &= nshared;
3639         }
3640     }
3641     *perm = cumulative_perms;
3642     *shared = cumulative_shared_perms;
3643 }
3644 
3645 /*
3646  * Take a BDRVReopenState and check if the value of 'backing' in the
3647  * reopen_state->options QDict is valid or not.
3648  *
3649  * If 'backing' is missing from the QDict then return 0.
3650  *
3651  * If 'backing' contains the node name of the backing file of
3652  * reopen_state->bs then return 0.
3653  *
3654  * If 'backing' contains a different node name (or is null) then check
3655  * whether the current backing file can be replaced with the new one.
3656  * If that's the case then reopen_state->replace_backing_bs is set to
3657  * true and reopen_state->new_backing_bs contains a pointer to the new
3658  * backing BlockDriverState (or NULL).
3659  *
3660  * Return 0 on success, otherwise return < 0 and set @errp.
3661  */
3662 static int bdrv_reopen_parse_backing(BDRVReopenState *reopen_state,
3663                                      Error **errp)
3664 {
3665     BlockDriverState *bs = reopen_state->bs;
3666     BlockDriverState *overlay_bs, *new_backing_bs;
3667     QObject *value;
3668     const char *str;
3669 
3670     value = qdict_get(reopen_state->options, "backing");
3671     if (value == NULL) {
3672         return 0;
3673     }
3674 
3675     switch (qobject_type(value)) {
3676     case QTYPE_QNULL:
3677         new_backing_bs = NULL;
3678         break;
3679     case QTYPE_QSTRING:
3680         str = qobject_get_try_str(value);
3681         new_backing_bs = bdrv_lookup_bs(NULL, str, errp);
3682         if (new_backing_bs == NULL) {
3683             return -EINVAL;
3684         } else if (bdrv_recurse_has_child(new_backing_bs, bs)) {
3685             error_setg(errp, "Making '%s' a backing file of '%s' "
3686                        "would create a cycle", str, bs->node_name);
3687             return -EINVAL;
3688         }
3689         break;
3690     default:
3691         /* 'backing' does not allow any other data type */
3692         g_assert_not_reached();
3693     }
3694 
3695     /*
3696      * TODO: before removing the x- prefix from x-blockdev-reopen we
3697      * should move the new backing file into the right AioContext
3698      * instead of returning an error.
3699      */
3700     if (new_backing_bs) {
3701         if (bdrv_get_aio_context(new_backing_bs) != bdrv_get_aio_context(bs)) {
3702             error_setg(errp, "Cannot use a new backing file "
3703                        "with a different AioContext");
3704             return -EINVAL;
3705         }
3706     }
3707 
3708     /*
3709      * Find the "actual" backing file by skipping all links that point
3710      * to an implicit node, if any (e.g. a commit filter node).
3711      */
3712     overlay_bs = bs;
3713     while (backing_bs(overlay_bs) && backing_bs(overlay_bs)->implicit) {
3714         overlay_bs = backing_bs(overlay_bs);
3715     }
3716 
3717     /* If we want to replace the backing file we need some extra checks */
3718     if (new_backing_bs != backing_bs(overlay_bs)) {
3719         /* Check for implicit nodes between bs and its backing file */
3720         if (bs != overlay_bs) {
3721             error_setg(errp, "Cannot change backing link if '%s' has "
3722                        "an implicit backing file", bs->node_name);
3723             return -EPERM;
3724         }
3725         /* Check if the backing link that we want to replace is frozen */
3726         if (bdrv_is_backing_chain_frozen(overlay_bs, backing_bs(overlay_bs),
3727                                          errp)) {
3728             return -EPERM;
3729         }
3730         reopen_state->replace_backing_bs = true;
3731         if (new_backing_bs) {
3732             bdrv_ref(new_backing_bs);
3733             reopen_state->new_backing_bs = new_backing_bs;
3734         }
3735     }
3736 
3737     return 0;
3738 }
3739 
3740 /*
3741  * Prepares a BlockDriverState for reopen. All changes are staged in the
3742  * 'opaque' field of the BDRVReopenState, which is used and allocated by
3743  * the block driver layer .bdrv_reopen_prepare()
3744  *
3745  * bs is the BlockDriverState to reopen
3746  * flags are the new open flags
3747  * queue is the reopen queue
3748  *
3749  * Returns 0 on success, non-zero on error.  On error errp will be set
3750  * as well.
3751  *
3752  * On failure, bdrv_reopen_abort() will be called to clean up any data.
3753  * It is the responsibility of the caller to then call the abort() or
3754  * commit() for any other BDS that have been left in a prepare() state
3755  *
3756  */
3757 int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
3758                         Error **errp)
3759 {
3760     int ret = -1;
3761     int old_flags;
3762     Error *local_err = NULL;
3763     BlockDriver *drv;
3764     QemuOpts *opts;
3765     QDict *orig_reopen_opts;
3766     char *discard = NULL;
3767     bool read_only;
3768     bool drv_prepared = false;
3769 
3770     assert(reopen_state != NULL);
3771     assert(reopen_state->bs->drv != NULL);
3772     drv = reopen_state->bs->drv;
3773 
3774     /* This function and each driver's bdrv_reopen_prepare() remove
3775      * entries from reopen_state->options as they are processed, so
3776      * we need to make a copy of the original QDict. */
3777     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
3778 
3779     /* Process generic block layer options */
3780     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
3781     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
3782     if (local_err) {
3783         error_propagate(errp, local_err);
3784         ret = -EINVAL;
3785         goto error;
3786     }
3787 
3788     /* This was already called in bdrv_reopen_queue_child() so the flags
3789      * are up-to-date. This time we simply want to remove the options from
3790      * QemuOpts in order to indicate that they have been processed. */
3791     old_flags = reopen_state->flags;
3792     update_flags_from_options(&reopen_state->flags, opts);
3793     assert(old_flags == reopen_state->flags);
3794 
3795     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
3796     if (discard != NULL) {
3797         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
3798             error_setg(errp, "Invalid discard option");
3799             ret = -EINVAL;
3800             goto error;
3801         }
3802     }
3803 
3804     reopen_state->detect_zeroes =
3805         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
3806     if (local_err) {
3807         error_propagate(errp, local_err);
3808         ret = -EINVAL;
3809         goto error;
3810     }
3811 
3812     /* All other options (including node-name and driver) must be unchanged.
3813      * Put them back into the QDict, so that they are checked at the end
3814      * of this function. */
3815     qemu_opts_to_qdict(opts, reopen_state->options);
3816 
3817     /* If we are to stay read-only, do not allow permission change
3818      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
3819      * not set, or if the BDS still has copy_on_read enabled */
3820     read_only = !(reopen_state->flags & BDRV_O_RDWR);
3821     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
3822     if (local_err) {
3823         error_propagate(errp, local_err);
3824         goto error;
3825     }
3826 
3827     /* Calculate required permissions after reopening */
3828     bdrv_reopen_perm(queue, reopen_state->bs,
3829                      &reopen_state->perm, &reopen_state->shared_perm);
3830 
3831     ret = bdrv_flush(reopen_state->bs);
3832     if (ret) {
3833         error_setg_errno(errp, -ret, "Error flushing drive");
3834         goto error;
3835     }
3836 
3837     if (drv->bdrv_reopen_prepare) {
3838         /*
3839          * If a driver-specific option is missing, it means that we
3840          * should reset it to its default value.
3841          * But not all options allow that, so we need to check it first.
3842          */
3843         ret = bdrv_reset_options_allowed(reopen_state->bs,
3844                                          reopen_state->options, errp);
3845         if (ret) {
3846             goto error;
3847         }
3848 
3849         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
3850         if (ret) {
3851             if (local_err != NULL) {
3852                 error_propagate(errp, local_err);
3853             } else {
3854                 bdrv_refresh_filename(reopen_state->bs);
3855                 error_setg(errp, "failed while preparing to reopen image '%s'",
3856                            reopen_state->bs->filename);
3857             }
3858             goto error;
3859         }
3860     } else {
3861         /* It is currently mandatory to have a bdrv_reopen_prepare()
3862          * handler for each supported drv. */
3863         error_setg(errp, "Block format '%s' used by node '%s' "
3864                    "does not support reopening files", drv->format_name,
3865                    bdrv_get_device_or_node_name(reopen_state->bs));
3866         ret = -1;
3867         goto error;
3868     }
3869 
3870     drv_prepared = true;
3871 
3872     /*
3873      * We must provide the 'backing' option if the BDS has a backing
3874      * file or if the image file has a backing file name as part of
3875      * its metadata. Otherwise the 'backing' option can be omitted.
3876      */
3877     if (drv->supports_backing && reopen_state->backing_missing &&
3878         (backing_bs(reopen_state->bs) || reopen_state->bs->backing_file[0])) {
3879         error_setg(errp, "backing is missing for '%s'",
3880                    reopen_state->bs->node_name);
3881         ret = -EINVAL;
3882         goto error;
3883     }
3884 
3885     /*
3886      * Allow changing the 'backing' option. The new value can be
3887      * either a reference to an existing node (using its node name)
3888      * or NULL to simply detach the current backing file.
3889      */
3890     ret = bdrv_reopen_parse_backing(reopen_state, errp);
3891     if (ret < 0) {
3892         goto error;
3893     }
3894     qdict_del(reopen_state->options, "backing");
3895 
3896     /* Options that are not handled are only okay if they are unchanged
3897      * compared to the old state. It is expected that some options are only
3898      * used for the initial open, but not reopen (e.g. filename) */
3899     if (qdict_size(reopen_state->options)) {
3900         const QDictEntry *entry = qdict_first(reopen_state->options);
3901 
3902         do {
3903             QObject *new = entry->value;
3904             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
3905 
3906             /* Allow child references (child_name=node_name) as long as they
3907              * point to the current child (i.e. everything stays the same). */
3908             if (qobject_type(new) == QTYPE_QSTRING) {
3909                 BdrvChild *child;
3910                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
3911                     if (!strcmp(child->name, entry->key)) {
3912                         break;
3913                     }
3914                 }
3915 
3916                 if (child) {
3917                     const char *str = qobject_get_try_str(new);
3918                     if (!strcmp(child->bs->node_name, str)) {
3919                         continue; /* Found child with this name, skip option */
3920                     }
3921                 }
3922             }
3923 
3924             /*
3925              * TODO: When using -drive to specify blockdev options, all values
3926              * will be strings; however, when using -blockdev, blockdev-add or
3927              * filenames using the json:{} pseudo-protocol, they will be
3928              * correctly typed.
3929              * In contrast, reopening options are (currently) always strings
3930              * (because you can only specify them through qemu-io; all other
3931              * callers do not specify any options).
3932              * Therefore, when using anything other than -drive to create a BDS,
3933              * this cannot detect non-string options as unchanged, because
3934              * qobject_is_equal() always returns false for objects of different
3935              * type.  In the future, this should be remedied by correctly typing
3936              * all options.  For now, this is not too big of an issue because
3937              * the user can simply omit options which cannot be changed anyway,
3938              * so they will stay unchanged.
3939              */
3940             if (!qobject_is_equal(new, old)) {
3941                 error_setg(errp, "Cannot change the option '%s'", entry->key);
3942                 ret = -EINVAL;
3943                 goto error;
3944             }
3945         } while ((entry = qdict_next(reopen_state->options, entry)));
3946     }
3947 
3948     ret = 0;
3949 
3950     /* Restore the original reopen_state->options QDict */
3951     qobject_unref(reopen_state->options);
3952     reopen_state->options = qobject_ref(orig_reopen_opts);
3953 
3954 error:
3955     if (ret < 0 && drv_prepared) {
3956         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
3957          * call drv->bdrv_reopen_abort() before signaling an error
3958          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
3959          * when the respective bdrv_reopen_prepare() has failed) */
3960         if (drv->bdrv_reopen_abort) {
3961             drv->bdrv_reopen_abort(reopen_state);
3962         }
3963     }
3964     qemu_opts_del(opts);
3965     qobject_unref(orig_reopen_opts);
3966     g_free(discard);
3967     return ret;
3968 }
3969 
3970 /*
3971  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
3972  * makes them final by swapping the staging BlockDriverState contents into
3973  * the active BlockDriverState contents.
3974  */
3975 void bdrv_reopen_commit(BDRVReopenState *reopen_state)
3976 {
3977     BlockDriver *drv;
3978     BlockDriverState *bs;
3979     BdrvChild *child;
3980 
3981     assert(reopen_state != NULL);
3982     bs = reopen_state->bs;
3983     drv = bs->drv;
3984     assert(drv != NULL);
3985 
3986     /* If there are any driver level actions to take */
3987     if (drv->bdrv_reopen_commit) {
3988         drv->bdrv_reopen_commit(reopen_state);
3989     }
3990 
3991     /* set BDS specific flags now */
3992     qobject_unref(bs->explicit_options);
3993     qobject_unref(bs->options);
3994 
3995     bs->explicit_options   = reopen_state->explicit_options;
3996     bs->options            = reopen_state->options;
3997     bs->open_flags         = reopen_state->flags;
3998     bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
3999     bs->detect_zeroes      = reopen_state->detect_zeroes;
4000 
4001     if (reopen_state->replace_backing_bs) {
4002         qdict_del(bs->explicit_options, "backing");
4003         qdict_del(bs->options, "backing");
4004     }
4005 
4006     /* Remove child references from bs->options and bs->explicit_options.
4007      * Child options were already removed in bdrv_reopen_queue_child() */
4008     QLIST_FOREACH(child, &bs->children, next) {
4009         qdict_del(bs->explicit_options, child->name);
4010         qdict_del(bs->options, child->name);
4011     }
4012 
4013     /*
4014      * Change the backing file if a new one was specified. We do this
4015      * after updating bs->options, so bdrv_refresh_filename() (called
4016      * from bdrv_set_backing_hd()) has the new values.
4017      */
4018     if (reopen_state->replace_backing_bs) {
4019         BlockDriverState *old_backing_bs = backing_bs(bs);
4020         assert(!old_backing_bs || !old_backing_bs->implicit);
4021         /* Abort the permission update on the backing bs we're detaching */
4022         if (old_backing_bs) {
4023             bdrv_abort_perm_update(old_backing_bs);
4024         }
4025         bdrv_set_backing_hd(bs, reopen_state->new_backing_bs, &error_abort);
4026     }
4027 
4028     bdrv_refresh_limits(bs, NULL);
4029 }
4030 
4031 /*
4032  * Abort the reopen, and delete and free the staged changes in
4033  * reopen_state
4034  */
4035 void bdrv_reopen_abort(BDRVReopenState *reopen_state)
4036 {
4037     BlockDriver *drv;
4038 
4039     assert(reopen_state != NULL);
4040     drv = reopen_state->bs->drv;
4041     assert(drv != NULL);
4042 
4043     if (drv->bdrv_reopen_abort) {
4044         drv->bdrv_reopen_abort(reopen_state);
4045     }
4046 }
4047 
4048 
4049 static void bdrv_close(BlockDriverState *bs)
4050 {
4051     BdrvAioNotifier *ban, *ban_next;
4052     BdrvChild *child, *next;
4053 
4054     assert(!bs->refcnt);
4055 
4056     bdrv_drained_begin(bs); /* complete I/O */
4057     bdrv_flush(bs);
4058     bdrv_drain(bs); /* in case flush left pending I/O */
4059 
4060     if (bs->drv) {
4061         if (bs->drv->bdrv_close) {
4062             bs->drv->bdrv_close(bs);
4063         }
4064         bs->drv = NULL;
4065     }
4066 
4067     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
4068         bdrv_unref_child(bs, child);
4069     }
4070 
4071     bs->backing = NULL;
4072     bs->file = NULL;
4073     g_free(bs->opaque);
4074     bs->opaque = NULL;
4075     atomic_set(&bs->copy_on_read, 0);
4076     bs->backing_file[0] = '\0';
4077     bs->backing_format[0] = '\0';
4078     bs->total_sectors = 0;
4079     bs->encrypted = false;
4080     bs->sg = false;
4081     qobject_unref(bs->options);
4082     qobject_unref(bs->explicit_options);
4083     bs->options = NULL;
4084     bs->explicit_options = NULL;
4085     qobject_unref(bs->full_open_options);
4086     bs->full_open_options = NULL;
4087 
4088     bdrv_release_named_dirty_bitmaps(bs);
4089     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
4090 
4091     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
4092         g_free(ban);
4093     }
4094     QLIST_INIT(&bs->aio_notifiers);
4095     bdrv_drained_end(bs);
4096 }
4097 
4098 void bdrv_close_all(void)
4099 {
4100     assert(job_next(NULL) == NULL);
4101     nbd_export_close_all();
4102 
4103     /* Drop references from requests still in flight, such as canceled block
4104      * jobs whose AIO context has not been polled yet */
4105     bdrv_drain_all();
4106 
4107     blk_remove_all_bs();
4108     blockdev_close_all_bdrv_states();
4109 
4110     assert(QTAILQ_EMPTY(&all_bdrv_states));
4111 }
4112 
4113 static bool should_update_child(BdrvChild *c, BlockDriverState *to)
4114 {
4115     GQueue *queue;
4116     GHashTable *found;
4117     bool ret;
4118 
4119     if (c->role->stay_at_node) {
4120         return false;
4121     }
4122 
4123     /* If the child @c belongs to the BDS @to, replacing the current
4124      * c->bs by @to would mean to create a loop.
4125      *
4126      * Such a case occurs when appending a BDS to a backing chain.
4127      * For instance, imagine the following chain:
4128      *
4129      *   guest device -> node A -> further backing chain...
4130      *
4131      * Now we create a new BDS B which we want to put on top of this
4132      * chain, so we first attach A as its backing node:
4133      *
4134      *                   node B
4135      *                     |
4136      *                     v
4137      *   guest device -> node A -> further backing chain...
4138      *
4139      * Finally we want to replace A by B.  When doing that, we want to
4140      * replace all pointers to A by pointers to B -- except for the
4141      * pointer from B because (1) that would create a loop, and (2)
4142      * that pointer should simply stay intact:
4143      *
4144      *   guest device -> node B
4145      *                     |
4146      *                     v
4147      *                   node A -> further backing chain...
4148      *
4149      * In general, when replacing a node A (c->bs) by a node B (@to),
4150      * if A is a child of B, that means we cannot replace A by B there
4151      * because that would create a loop.  Silently detaching A from B
4152      * is also not really an option.  So overall just leaving A in
4153      * place there is the most sensible choice.
4154      *
4155      * We would also create a loop in any cases where @c is only
4156      * indirectly referenced by @to. Prevent this by returning false
4157      * if @c is found (by breadth-first search) anywhere in the whole
4158      * subtree of @to.
4159      */
4160 
4161     ret = true;
4162     found = g_hash_table_new(NULL, NULL);
4163     g_hash_table_add(found, to);
4164     queue = g_queue_new();
4165     g_queue_push_tail(queue, to);
4166 
4167     while (!g_queue_is_empty(queue)) {
4168         BlockDriverState *v = g_queue_pop_head(queue);
4169         BdrvChild *c2;
4170 
4171         QLIST_FOREACH(c2, &v->children, next) {
4172             if (c2 == c) {
4173                 ret = false;
4174                 break;
4175             }
4176 
4177             if (g_hash_table_contains(found, c2->bs)) {
4178                 continue;
4179             }
4180 
4181             g_queue_push_tail(queue, c2->bs);
4182             g_hash_table_add(found, c2->bs);
4183         }
4184     }
4185 
4186     g_queue_free(queue);
4187     g_hash_table_destroy(found);
4188 
4189     return ret;
4190 }
4191 
4192 void bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
4193                        Error **errp)
4194 {
4195     BdrvChild *c, *next;
4196     GSList *list = NULL, *p;
4197     uint64_t perm = 0, shared = BLK_PERM_ALL;
4198     int ret;
4199 
4200     /* Make sure that @from doesn't go away until we have successfully attached
4201      * all of its parents to @to. */
4202     bdrv_ref(from);
4203 
4204     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4205     bdrv_drained_begin(from);
4206 
4207     /* Put all parents into @list and calculate their cumulative permissions */
4208     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
4209         assert(c->bs == from);
4210         if (!should_update_child(c, to)) {
4211             continue;
4212         }
4213         if (c->frozen) {
4214             error_setg(errp, "Cannot change '%s' link to '%s'",
4215                        c->name, from->node_name);
4216             goto out;
4217         }
4218         list = g_slist_prepend(list, c);
4219         perm |= c->perm;
4220         shared &= c->shared_perm;
4221     }
4222 
4223     /* Check whether the required permissions can be granted on @to, ignoring
4224      * all BdrvChild in @list so that they can't block themselves. */
4225     ret = bdrv_check_update_perm(to, NULL, perm, shared, list, NULL, errp);
4226     if (ret < 0) {
4227         bdrv_abort_perm_update(to);
4228         goto out;
4229     }
4230 
4231     /* Now actually perform the change. We performed the permission check for
4232      * all elements of @list at once, so set the permissions all at once at the
4233      * very end. */
4234     for (p = list; p != NULL; p = p->next) {
4235         c = p->data;
4236 
4237         bdrv_ref(to);
4238         bdrv_replace_child_noperm(c, to);
4239         bdrv_unref(from);
4240     }
4241 
4242     bdrv_get_cumulative_perm(to, &perm, &shared);
4243     bdrv_set_perm(to, perm, shared);
4244 
4245 out:
4246     g_slist_free(list);
4247     bdrv_drained_end(from);
4248     bdrv_unref(from);
4249 }
4250 
4251 /*
4252  * Add new bs contents at the top of an image chain while the chain is
4253  * live, while keeping required fields on the top layer.
4254  *
4255  * This will modify the BlockDriverState fields, and swap contents
4256  * between bs_new and bs_top. Both bs_new and bs_top are modified.
4257  *
4258  * bs_new must not be attached to a BlockBackend.
4259  *
4260  * This function does not create any image files.
4261  *
4262  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
4263  * that's what the callers commonly need. bs_new will be referenced by the old
4264  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
4265  * reference of its own, it must call bdrv_ref().
4266  */
4267 void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
4268                  Error **errp)
4269 {
4270     Error *local_err = NULL;
4271 
4272     bdrv_set_backing_hd(bs_new, bs_top, &local_err);
4273     if (local_err) {
4274         error_propagate(errp, local_err);
4275         goto out;
4276     }
4277 
4278     bdrv_replace_node(bs_top, bs_new, &local_err);
4279     if (local_err) {
4280         error_propagate(errp, local_err);
4281         bdrv_set_backing_hd(bs_new, NULL, &error_abort);
4282         goto out;
4283     }
4284 
4285     /* bs_new is now referenced by its new parents, we don't need the
4286      * additional reference any more. */
4287 out:
4288     bdrv_unref(bs_new);
4289 }
4290 
4291 static void bdrv_delete(BlockDriverState *bs)
4292 {
4293     assert(bdrv_op_blocker_is_empty(bs));
4294     assert(!bs->refcnt);
4295 
4296     /* remove from list, if necessary */
4297     if (bs->node_name[0] != '\0') {
4298         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
4299     }
4300     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
4301 
4302     bdrv_close(bs);
4303 
4304     g_free(bs);
4305 }
4306 
4307 /*
4308  * Run consistency checks on an image
4309  *
4310  * Returns 0 if the check could be completed (it doesn't mean that the image is
4311  * free of errors) or -errno when an internal error occurred. The results of the
4312  * check are stored in res.
4313  */
4314 static int coroutine_fn bdrv_co_check(BlockDriverState *bs,
4315                                       BdrvCheckResult *res, BdrvCheckMode fix)
4316 {
4317     if (bs->drv == NULL) {
4318         return -ENOMEDIUM;
4319     }
4320     if (bs->drv->bdrv_co_check == NULL) {
4321         return -ENOTSUP;
4322     }
4323 
4324     memset(res, 0, sizeof(*res));
4325     return bs->drv->bdrv_co_check(bs, res, fix);
4326 }
4327 
4328 typedef struct CheckCo {
4329     BlockDriverState *bs;
4330     BdrvCheckResult *res;
4331     BdrvCheckMode fix;
4332     int ret;
4333 } CheckCo;
4334 
4335 static void coroutine_fn bdrv_check_co_entry(void *opaque)
4336 {
4337     CheckCo *cco = opaque;
4338     cco->ret = bdrv_co_check(cco->bs, cco->res, cco->fix);
4339     aio_wait_kick();
4340 }
4341 
4342 int bdrv_check(BlockDriverState *bs,
4343                BdrvCheckResult *res, BdrvCheckMode fix)
4344 {
4345     Coroutine *co;
4346     CheckCo cco = {
4347         .bs = bs,
4348         .res = res,
4349         .ret = -EINPROGRESS,
4350         .fix = fix,
4351     };
4352 
4353     if (qemu_in_coroutine()) {
4354         /* Fast-path if already in coroutine context */
4355         bdrv_check_co_entry(&cco);
4356     } else {
4357         co = qemu_coroutine_create(bdrv_check_co_entry, &cco);
4358         bdrv_coroutine_enter(bs, co);
4359         BDRV_POLL_WHILE(bs, cco.ret == -EINPROGRESS);
4360     }
4361 
4362     return cco.ret;
4363 }
4364 
4365 /*
4366  * Return values:
4367  * 0        - success
4368  * -EINVAL  - backing format specified, but no file
4369  * -ENOSPC  - can't update the backing file because no space is left in the
4370  *            image file header
4371  * -ENOTSUP - format driver doesn't support changing the backing file
4372  */
4373 int bdrv_change_backing_file(BlockDriverState *bs,
4374     const char *backing_file, const char *backing_fmt)
4375 {
4376     BlockDriver *drv = bs->drv;
4377     int ret;
4378 
4379     if (!drv) {
4380         return -ENOMEDIUM;
4381     }
4382 
4383     /* Backing file format doesn't make sense without a backing file */
4384     if (backing_fmt && !backing_file) {
4385         return -EINVAL;
4386     }
4387 
4388     if (drv->bdrv_change_backing_file != NULL) {
4389         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
4390     } else {
4391         ret = -ENOTSUP;
4392     }
4393 
4394     if (ret == 0) {
4395         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
4396         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
4397         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
4398                 backing_file ?: "");
4399     }
4400     return ret;
4401 }
4402 
4403 /*
4404  * Finds the image layer in the chain that has 'bs' as its backing file.
4405  *
4406  * active is the current topmost image.
4407  *
4408  * Returns NULL if bs is not found in active's image chain,
4409  * or if active == bs.
4410  *
4411  * Returns the bottommost base image if bs == NULL.
4412  */
4413 BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
4414                                     BlockDriverState *bs)
4415 {
4416     while (active && bs != backing_bs(active)) {
4417         active = backing_bs(active);
4418     }
4419 
4420     return active;
4421 }
4422 
4423 /* Given a BDS, searches for the base layer. */
4424 BlockDriverState *bdrv_find_base(BlockDriverState *bs)
4425 {
4426     return bdrv_find_overlay(bs, NULL);
4427 }
4428 
4429 /*
4430  * Return true if at least one of the backing links between @bs and
4431  * @base is frozen. @errp is set if that's the case.
4432  * @base must be reachable from @bs, or NULL.
4433  */
4434 bool bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
4435                                   Error **errp)
4436 {
4437     BlockDriverState *i;
4438 
4439     for (i = bs; i != base; i = backing_bs(i)) {
4440         if (i->backing && i->backing->frozen) {
4441             error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
4442                        i->backing->name, i->node_name,
4443                        backing_bs(i)->node_name);
4444             return true;
4445         }
4446     }
4447 
4448     return false;
4449 }
4450 
4451 /*
4452  * Freeze all backing links between @bs and @base.
4453  * If any of the links is already frozen the operation is aborted and
4454  * none of the links are modified.
4455  * @base must be reachable from @bs, or NULL.
4456  * Returns 0 on success. On failure returns < 0 and sets @errp.
4457  */
4458 int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
4459                               Error **errp)
4460 {
4461     BlockDriverState *i;
4462 
4463     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
4464         return -EPERM;
4465     }
4466 
4467     for (i = bs; i != base; i = backing_bs(i)) {
4468         if (i->backing && backing_bs(i)->never_freeze) {
4469             error_setg(errp, "Cannot freeze '%s' link to '%s'",
4470                        i->backing->name, backing_bs(i)->node_name);
4471             return -EPERM;
4472         }
4473     }
4474 
4475     for (i = bs; i != base; i = backing_bs(i)) {
4476         if (i->backing) {
4477             i->backing->frozen = true;
4478         }
4479     }
4480 
4481     return 0;
4482 }
4483 
4484 /*
4485  * Unfreeze all backing links between @bs and @base. The caller must
4486  * ensure that all links are frozen before using this function.
4487  * @base must be reachable from @bs, or NULL.
4488  */
4489 void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
4490 {
4491     BlockDriverState *i;
4492 
4493     for (i = bs; i != base; i = backing_bs(i)) {
4494         if (i->backing) {
4495             assert(i->backing->frozen);
4496             i->backing->frozen = false;
4497         }
4498     }
4499 }
4500 
4501 /*
4502  * Drops images above 'base' up to and including 'top', and sets the image
4503  * above 'top' to have base as its backing file.
4504  *
4505  * Requires that the overlay to 'top' is opened r/w, so that the backing file
4506  * information in 'bs' can be properly updated.
4507  *
4508  * E.g., this will convert the following chain:
4509  * bottom <- base <- intermediate <- top <- active
4510  *
4511  * to
4512  *
4513  * bottom <- base <- active
4514  *
4515  * It is allowed for bottom==base, in which case it converts:
4516  *
4517  * base <- intermediate <- top <- active
4518  *
4519  * to
4520  *
4521  * base <- active
4522  *
4523  * If backing_file_str is non-NULL, it will be used when modifying top's
4524  * overlay image metadata.
4525  *
4526  * Error conditions:
4527  *  if active == top, that is considered an error
4528  *
4529  */
4530 int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
4531                            const char *backing_file_str)
4532 {
4533     BlockDriverState *explicit_top = top;
4534     bool update_inherits_from;
4535     BdrvChild *c, *next;
4536     Error *local_err = NULL;
4537     int ret = -EIO;
4538 
4539     bdrv_ref(top);
4540     bdrv_subtree_drained_begin(top);
4541 
4542     if (!top->drv || !base->drv) {
4543         goto exit;
4544     }
4545 
4546     /* Make sure that base is in the backing chain of top */
4547     if (!bdrv_chain_contains(top, base)) {
4548         goto exit;
4549     }
4550 
4551     /* This function changes all links that point to top and makes
4552      * them point to base. Check that none of them is frozen. */
4553     QLIST_FOREACH(c, &top->parents, next_parent) {
4554         if (c->frozen) {
4555             goto exit;
4556         }
4557     }
4558 
4559     /* If 'base' recursively inherits from 'top' then we should set
4560      * base->inherits_from to top->inherits_from after 'top' and all
4561      * other intermediate nodes have been dropped.
4562      * If 'top' is an implicit node (e.g. "commit_top") we should skip
4563      * it because no one inherits from it. We use explicit_top for that. */
4564     while (explicit_top && explicit_top->implicit) {
4565         explicit_top = backing_bs(explicit_top);
4566     }
4567     update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
4568 
4569     /* success - we can delete the intermediate states, and link top->base */
4570     /* TODO Check graph modification op blockers (BLK_PERM_GRAPH_MOD) once
4571      * we've figured out how they should work. */
4572     if (!backing_file_str) {
4573         bdrv_refresh_filename(base);
4574         backing_file_str = base->filename;
4575     }
4576 
4577     QLIST_FOREACH_SAFE(c, &top->parents, next_parent, next) {
4578         /* Check whether we are allowed to switch c from top to base */
4579         GSList *ignore_children = g_slist_prepend(NULL, c);
4580         ret = bdrv_check_update_perm(base, NULL, c->perm, c->shared_perm,
4581                                      ignore_children, NULL, &local_err);
4582         g_slist_free(ignore_children);
4583         if (ret < 0) {
4584             error_report_err(local_err);
4585             goto exit;
4586         }
4587 
4588         /* If so, update the backing file path in the image file */
4589         if (c->role->update_filename) {
4590             ret = c->role->update_filename(c, base, backing_file_str,
4591                                            &local_err);
4592             if (ret < 0) {
4593                 bdrv_abort_perm_update(base);
4594                 error_report_err(local_err);
4595                 goto exit;
4596             }
4597         }
4598 
4599         /* Do the actual switch in the in-memory graph.
4600          * Completes bdrv_check_update_perm() transaction internally. */
4601         bdrv_ref(base);
4602         bdrv_replace_child(c, base);
4603         bdrv_unref(top);
4604     }
4605 
4606     if (update_inherits_from) {
4607         base->inherits_from = explicit_top->inherits_from;
4608     }
4609 
4610     ret = 0;
4611 exit:
4612     bdrv_subtree_drained_end(top);
4613     bdrv_unref(top);
4614     return ret;
4615 }
4616 
4617 /**
4618  * Length of a allocated file in bytes. Sparse files are counted by actual
4619  * allocated space. Return < 0 if error or unknown.
4620  */
4621 int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
4622 {
4623     BlockDriver *drv = bs->drv;
4624     if (!drv) {
4625         return -ENOMEDIUM;
4626     }
4627     if (drv->bdrv_get_allocated_file_size) {
4628         return drv->bdrv_get_allocated_file_size(bs);
4629     }
4630     if (bs->file) {
4631         return bdrv_get_allocated_file_size(bs->file->bs);
4632     }
4633     return -ENOTSUP;
4634 }
4635 
4636 /*
4637  * bdrv_measure:
4638  * @drv: Format driver
4639  * @opts: Creation options for new image
4640  * @in_bs: Existing image containing data for new image (may be NULL)
4641  * @errp: Error object
4642  * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
4643  *          or NULL on error
4644  *
4645  * Calculate file size required to create a new image.
4646  *
4647  * If @in_bs is given then space for allocated clusters and zero clusters
4648  * from that image are included in the calculation.  If @opts contains a
4649  * backing file that is shared by @in_bs then backing clusters may be omitted
4650  * from the calculation.
4651  *
4652  * If @in_bs is NULL then the calculation includes no allocated clusters
4653  * unless a preallocation option is given in @opts.
4654  *
4655  * Note that @in_bs may use a different BlockDriver from @drv.
4656  *
4657  * If an error occurs the @errp pointer is set.
4658  */
4659 BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
4660                                BlockDriverState *in_bs, Error **errp)
4661 {
4662     if (!drv->bdrv_measure) {
4663         error_setg(errp, "Block driver '%s' does not support size measurement",
4664                    drv->format_name);
4665         return NULL;
4666     }
4667 
4668     return drv->bdrv_measure(opts, in_bs, errp);
4669 }
4670 
4671 /**
4672  * Return number of sectors on success, -errno on error.
4673  */
4674 int64_t bdrv_nb_sectors(BlockDriverState *bs)
4675 {
4676     BlockDriver *drv = bs->drv;
4677 
4678     if (!drv)
4679         return -ENOMEDIUM;
4680 
4681     if (drv->has_variable_length) {
4682         int ret = refresh_total_sectors(bs, bs->total_sectors);
4683         if (ret < 0) {
4684             return ret;
4685         }
4686     }
4687     return bs->total_sectors;
4688 }
4689 
4690 /**
4691  * Return length in bytes on success, -errno on error.
4692  * The length is always a multiple of BDRV_SECTOR_SIZE.
4693  */
4694 int64_t bdrv_getlength(BlockDriverState *bs)
4695 {
4696     int64_t ret = bdrv_nb_sectors(bs);
4697 
4698     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
4699     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
4700 }
4701 
4702 /* return 0 as number of sectors if no device present or error */
4703 void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
4704 {
4705     int64_t nb_sectors = bdrv_nb_sectors(bs);
4706 
4707     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
4708 }
4709 
4710 bool bdrv_is_sg(BlockDriverState *bs)
4711 {
4712     return bs->sg;
4713 }
4714 
4715 bool bdrv_is_encrypted(BlockDriverState *bs)
4716 {
4717     if (bs->backing && bs->backing->bs->encrypted) {
4718         return true;
4719     }
4720     return bs->encrypted;
4721 }
4722 
4723 const char *bdrv_get_format_name(BlockDriverState *bs)
4724 {
4725     return bs->drv ? bs->drv->format_name : NULL;
4726 }
4727 
4728 static int qsort_strcmp(const void *a, const void *b)
4729 {
4730     return strcmp(*(char *const *)a, *(char *const *)b);
4731 }
4732 
4733 void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
4734                          void *opaque, bool read_only)
4735 {
4736     BlockDriver *drv;
4737     int count = 0;
4738     int i;
4739     const char **formats = NULL;
4740 
4741     QLIST_FOREACH(drv, &bdrv_drivers, list) {
4742         if (drv->format_name) {
4743             bool found = false;
4744             int i = count;
4745 
4746             if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
4747                 continue;
4748             }
4749 
4750             while (formats && i && !found) {
4751                 found = !strcmp(formats[--i], drv->format_name);
4752             }
4753 
4754             if (!found) {
4755                 formats = g_renew(const char *, formats, count + 1);
4756                 formats[count++] = drv->format_name;
4757             }
4758         }
4759     }
4760 
4761     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
4762         const char *format_name = block_driver_modules[i].format_name;
4763 
4764         if (format_name) {
4765             bool found = false;
4766             int j = count;
4767 
4768             if (use_bdrv_whitelist &&
4769                 !bdrv_format_is_whitelisted(format_name, read_only)) {
4770                 continue;
4771             }
4772 
4773             while (formats && j && !found) {
4774                 found = !strcmp(formats[--j], format_name);
4775             }
4776 
4777             if (!found) {
4778                 formats = g_renew(const char *, formats, count + 1);
4779                 formats[count++] = format_name;
4780             }
4781         }
4782     }
4783 
4784     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
4785 
4786     for (i = 0; i < count; i++) {
4787         it(opaque, formats[i]);
4788     }
4789 
4790     g_free(formats);
4791 }
4792 
4793 /* This function is to find a node in the bs graph */
4794 BlockDriverState *bdrv_find_node(const char *node_name)
4795 {
4796     BlockDriverState *bs;
4797 
4798     assert(node_name);
4799 
4800     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4801         if (!strcmp(node_name, bs->node_name)) {
4802             return bs;
4803         }
4804     }
4805     return NULL;
4806 }
4807 
4808 /* Put this QMP function here so it can access the static graph_bdrv_states. */
4809 BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
4810 {
4811     BlockDeviceInfoList *list, *entry;
4812     BlockDriverState *bs;
4813 
4814     list = NULL;
4815     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4816         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
4817         if (!info) {
4818             qapi_free_BlockDeviceInfoList(list);
4819             return NULL;
4820         }
4821         entry = g_malloc0(sizeof(*entry));
4822         entry->value = info;
4823         entry->next = list;
4824         list = entry;
4825     }
4826 
4827     return list;
4828 }
4829 
4830 #define QAPI_LIST_ADD(list, element) do { \
4831     typeof(list) _tmp = g_new(typeof(*(list)), 1); \
4832     _tmp->value = (element); \
4833     _tmp->next = (list); \
4834     (list) = _tmp; \
4835 } while (0)
4836 
4837 typedef struct XDbgBlockGraphConstructor {
4838     XDbgBlockGraph *graph;
4839     GHashTable *graph_nodes;
4840 } XDbgBlockGraphConstructor;
4841 
4842 static XDbgBlockGraphConstructor *xdbg_graph_new(void)
4843 {
4844     XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
4845 
4846     gr->graph = g_new0(XDbgBlockGraph, 1);
4847     gr->graph_nodes = g_hash_table_new(NULL, NULL);
4848 
4849     return gr;
4850 }
4851 
4852 static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
4853 {
4854     XDbgBlockGraph *graph = gr->graph;
4855 
4856     g_hash_table_destroy(gr->graph_nodes);
4857     g_free(gr);
4858 
4859     return graph;
4860 }
4861 
4862 static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
4863 {
4864     uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
4865 
4866     if (ret != 0) {
4867         return ret;
4868     }
4869 
4870     /*
4871      * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
4872      * answer of g_hash_table_lookup.
4873      */
4874     ret = g_hash_table_size(gr->graph_nodes) + 1;
4875     g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
4876 
4877     return ret;
4878 }
4879 
4880 static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
4881                                 XDbgBlockGraphNodeType type, const char *name)
4882 {
4883     XDbgBlockGraphNode *n;
4884 
4885     n = g_new0(XDbgBlockGraphNode, 1);
4886 
4887     n->id = xdbg_graph_node_num(gr, node);
4888     n->type = type;
4889     n->name = g_strdup(name);
4890 
4891     QAPI_LIST_ADD(gr->graph->nodes, n);
4892 }
4893 
4894 static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
4895                                 const BdrvChild *child)
4896 {
4897     BlockPermission qapi_perm;
4898     XDbgBlockGraphEdge *edge;
4899 
4900     edge = g_new0(XDbgBlockGraphEdge, 1);
4901 
4902     edge->parent = xdbg_graph_node_num(gr, parent);
4903     edge->child = xdbg_graph_node_num(gr, child->bs);
4904     edge->name = g_strdup(child->name);
4905 
4906     for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
4907         uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
4908 
4909         if (flag & child->perm) {
4910             QAPI_LIST_ADD(edge->perm, qapi_perm);
4911         }
4912         if (flag & child->shared_perm) {
4913             QAPI_LIST_ADD(edge->shared_perm, qapi_perm);
4914         }
4915     }
4916 
4917     QAPI_LIST_ADD(gr->graph->edges, edge);
4918 }
4919 
4920 
4921 XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
4922 {
4923     BlockBackend *blk;
4924     BlockJob *job;
4925     BlockDriverState *bs;
4926     BdrvChild *child;
4927     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
4928 
4929     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
4930         char *allocated_name = NULL;
4931         const char *name = blk_name(blk);
4932 
4933         if (!*name) {
4934             name = allocated_name = blk_get_attached_dev_id(blk);
4935         }
4936         xdbg_graph_add_node(gr, blk, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
4937                            name);
4938         g_free(allocated_name);
4939         if (blk_root(blk)) {
4940             xdbg_graph_add_edge(gr, blk, blk_root(blk));
4941         }
4942     }
4943 
4944     for (job = block_job_next(NULL); job; job = block_job_next(job)) {
4945         GSList *el;
4946 
4947         xdbg_graph_add_node(gr, job, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
4948                            job->job.id);
4949         for (el = job->nodes; el; el = el->next) {
4950             xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
4951         }
4952     }
4953 
4954     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
4955         xdbg_graph_add_node(gr, bs, X_DBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
4956                            bs->node_name);
4957         QLIST_FOREACH(child, &bs->children, next) {
4958             xdbg_graph_add_edge(gr, bs, child);
4959         }
4960     }
4961 
4962     return xdbg_graph_finalize(gr);
4963 }
4964 
4965 BlockDriverState *bdrv_lookup_bs(const char *device,
4966                                  const char *node_name,
4967                                  Error **errp)
4968 {
4969     BlockBackend *blk;
4970     BlockDriverState *bs;
4971 
4972     if (device) {
4973         blk = blk_by_name(device);
4974 
4975         if (blk) {
4976             bs = blk_bs(blk);
4977             if (!bs) {
4978                 error_setg(errp, "Device '%s' has no medium", device);
4979             }
4980 
4981             return bs;
4982         }
4983     }
4984 
4985     if (node_name) {
4986         bs = bdrv_find_node(node_name);
4987 
4988         if (bs) {
4989             return bs;
4990         }
4991     }
4992 
4993     error_setg(errp, "Cannot find device=%s nor node_name=%s",
4994                      device ? device : "",
4995                      node_name ? node_name : "");
4996     return NULL;
4997 }
4998 
4999 /* If 'base' is in the same chain as 'top', return true. Otherwise,
5000  * return false.  If either argument is NULL, return false. */
5001 bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
5002 {
5003     while (top && top != base) {
5004         top = backing_bs(top);
5005     }
5006 
5007     return top != NULL;
5008 }
5009 
5010 BlockDriverState *bdrv_next_node(BlockDriverState *bs)
5011 {
5012     if (!bs) {
5013         return QTAILQ_FIRST(&graph_bdrv_states);
5014     }
5015     return QTAILQ_NEXT(bs, node_list);
5016 }
5017 
5018 BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
5019 {
5020     if (!bs) {
5021         return QTAILQ_FIRST(&all_bdrv_states);
5022     }
5023     return QTAILQ_NEXT(bs, bs_list);
5024 }
5025 
5026 const char *bdrv_get_node_name(const BlockDriverState *bs)
5027 {
5028     return bs->node_name;
5029 }
5030 
5031 const char *bdrv_get_parent_name(const BlockDriverState *bs)
5032 {
5033     BdrvChild *c;
5034     const char *name;
5035 
5036     /* If multiple parents have a name, just pick the first one. */
5037     QLIST_FOREACH(c, &bs->parents, next_parent) {
5038         if (c->role->get_name) {
5039             name = c->role->get_name(c);
5040             if (name && *name) {
5041                 return name;
5042             }
5043         }
5044     }
5045 
5046     return NULL;
5047 }
5048 
5049 /* TODO check what callers really want: bs->node_name or blk_name() */
5050 const char *bdrv_get_device_name(const BlockDriverState *bs)
5051 {
5052     return bdrv_get_parent_name(bs) ?: "";
5053 }
5054 
5055 /* This can be used to identify nodes that might not have a device
5056  * name associated. Since node and device names live in the same
5057  * namespace, the result is unambiguous. The exception is if both are
5058  * absent, then this returns an empty (non-null) string. */
5059 const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
5060 {
5061     return bdrv_get_parent_name(bs) ?: bs->node_name;
5062 }
5063 
5064 int bdrv_get_flags(BlockDriverState *bs)
5065 {
5066     return bs->open_flags;
5067 }
5068 
5069 int bdrv_has_zero_init_1(BlockDriverState *bs)
5070 {
5071     return 1;
5072 }
5073 
5074 int bdrv_has_zero_init(BlockDriverState *bs)
5075 {
5076     if (!bs->drv) {
5077         return 0;
5078     }
5079 
5080     /* If BS is a copy on write image, it is initialized to
5081        the contents of the base image, which may not be zeroes.  */
5082     if (bs->backing) {
5083         return 0;
5084     }
5085     if (bs->drv->bdrv_has_zero_init) {
5086         return bs->drv->bdrv_has_zero_init(bs);
5087     }
5088     if (bs->file && bs->drv->is_filter) {
5089         return bdrv_has_zero_init(bs->file->bs);
5090     }
5091 
5092     /* safe default */
5093     return 0;
5094 }
5095 
5096 int bdrv_has_zero_init_truncate(BlockDriverState *bs)
5097 {
5098     if (!bs->drv) {
5099         return 0;
5100     }
5101 
5102     if (bs->backing) {
5103         /* Depends on the backing image length, but better safe than sorry */
5104         return 0;
5105     }
5106     if (bs->drv->bdrv_has_zero_init_truncate) {
5107         return bs->drv->bdrv_has_zero_init_truncate(bs);
5108     }
5109     if (bs->file && bs->drv->is_filter) {
5110         return bdrv_has_zero_init_truncate(bs->file->bs);
5111     }
5112 
5113     /* safe default */
5114     return 0;
5115 }
5116 
5117 bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
5118 {
5119     BlockDriverInfo bdi;
5120 
5121     if (bs->backing) {
5122         return false;
5123     }
5124 
5125     if (bdrv_get_info(bs, &bdi) == 0) {
5126         return bdi.unallocated_blocks_are_zero;
5127     }
5128 
5129     return false;
5130 }
5131 
5132 bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
5133 {
5134     if (!(bs->open_flags & BDRV_O_UNMAP)) {
5135         return false;
5136     }
5137 
5138     return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
5139 }
5140 
5141 void bdrv_get_backing_filename(BlockDriverState *bs,
5142                                char *filename, int filename_size)
5143 {
5144     pstrcpy(filename, filename_size, bs->backing_file);
5145 }
5146 
5147 int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
5148 {
5149     BlockDriver *drv = bs->drv;
5150     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
5151     if (!drv) {
5152         return -ENOMEDIUM;
5153     }
5154     if (!drv->bdrv_get_info) {
5155         if (bs->file && drv->is_filter) {
5156             return bdrv_get_info(bs->file->bs, bdi);
5157         }
5158         return -ENOTSUP;
5159     }
5160     memset(bdi, 0, sizeof(*bdi));
5161     return drv->bdrv_get_info(bs, bdi);
5162 }
5163 
5164 ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
5165                                           Error **errp)
5166 {
5167     BlockDriver *drv = bs->drv;
5168     if (drv && drv->bdrv_get_specific_info) {
5169         return drv->bdrv_get_specific_info(bs, errp);
5170     }
5171     return NULL;
5172 }
5173 
5174 BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
5175 {
5176     BlockDriver *drv = bs->drv;
5177     if (!drv || !drv->bdrv_get_specific_stats) {
5178         return NULL;
5179     }
5180     return drv->bdrv_get_specific_stats(bs);
5181 }
5182 
5183 void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
5184 {
5185     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
5186         return;
5187     }
5188 
5189     bs->drv->bdrv_debug_event(bs, event);
5190 }
5191 
5192 static BlockDriverState *bdrv_find_debug_node(BlockDriverState *bs)
5193 {
5194     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
5195         if (bs->file) {
5196             bs = bs->file->bs;
5197             continue;
5198         }
5199 
5200         if (bs->drv->is_filter && bs->backing) {
5201             bs = bs->backing->bs;
5202             continue;
5203         }
5204 
5205         break;
5206     }
5207 
5208     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
5209         assert(bs->drv->bdrv_debug_remove_breakpoint);
5210         return bs;
5211     }
5212 
5213     return NULL;
5214 }
5215 
5216 int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
5217                           const char *tag)
5218 {
5219     bs = bdrv_find_debug_node(bs);
5220     if (bs) {
5221         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
5222     }
5223 
5224     return -ENOTSUP;
5225 }
5226 
5227 int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
5228 {
5229     bs = bdrv_find_debug_node(bs);
5230     if (bs) {
5231         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
5232     }
5233 
5234     return -ENOTSUP;
5235 }
5236 
5237 int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
5238 {
5239     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
5240         bs = bs->file ? bs->file->bs : NULL;
5241     }
5242 
5243     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
5244         return bs->drv->bdrv_debug_resume(bs, tag);
5245     }
5246 
5247     return -ENOTSUP;
5248 }
5249 
5250 bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
5251 {
5252     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
5253         bs = bs->file ? bs->file->bs : NULL;
5254     }
5255 
5256     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
5257         return bs->drv->bdrv_debug_is_suspended(bs, tag);
5258     }
5259 
5260     return false;
5261 }
5262 
5263 /* backing_file can either be relative, or absolute, or a protocol.  If it is
5264  * relative, it must be relative to the chain.  So, passing in bs->filename
5265  * from a BDS as backing_file should not be done, as that may be relative to
5266  * the CWD rather than the chain. */
5267 BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
5268         const char *backing_file)
5269 {
5270     char *filename_full = NULL;
5271     char *backing_file_full = NULL;
5272     char *filename_tmp = NULL;
5273     int is_protocol = 0;
5274     BlockDriverState *curr_bs = NULL;
5275     BlockDriverState *retval = NULL;
5276 
5277     if (!bs || !bs->drv || !backing_file) {
5278         return NULL;
5279     }
5280 
5281     filename_full     = g_malloc(PATH_MAX);
5282     backing_file_full = g_malloc(PATH_MAX);
5283 
5284     is_protocol = path_has_protocol(backing_file);
5285 
5286     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
5287 
5288         /* If either of the filename paths is actually a protocol, then
5289          * compare unmodified paths; otherwise make paths relative */
5290         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
5291             char *backing_file_full_ret;
5292 
5293             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
5294                 retval = curr_bs->backing->bs;
5295                 break;
5296             }
5297             /* Also check against the full backing filename for the image */
5298             backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
5299                                                                    NULL);
5300             if (backing_file_full_ret) {
5301                 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
5302                 g_free(backing_file_full_ret);
5303                 if (equal) {
5304                     retval = curr_bs->backing->bs;
5305                     break;
5306                 }
5307             }
5308         } else {
5309             /* If not an absolute filename path, make it relative to the current
5310              * image's filename path */
5311             filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
5312                                                        NULL);
5313             /* We are going to compare canonicalized absolute pathnames */
5314             if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
5315                 g_free(filename_tmp);
5316                 continue;
5317             }
5318             g_free(filename_tmp);
5319 
5320             /* We need to make sure the backing filename we are comparing against
5321              * is relative to the current image filename (or absolute) */
5322             filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
5323             if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
5324                 g_free(filename_tmp);
5325                 continue;
5326             }
5327             g_free(filename_tmp);
5328 
5329             if (strcmp(backing_file_full, filename_full) == 0) {
5330                 retval = curr_bs->backing->bs;
5331                 break;
5332             }
5333         }
5334     }
5335 
5336     g_free(filename_full);
5337     g_free(backing_file_full);
5338     return retval;
5339 }
5340 
5341 void bdrv_init(void)
5342 {
5343     module_call_init(MODULE_INIT_BLOCK);
5344 }
5345 
5346 void bdrv_init_with_whitelist(void)
5347 {
5348     use_bdrv_whitelist = 1;
5349     bdrv_init();
5350 }
5351 
5352 static void coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs,
5353                                                   Error **errp)
5354 {
5355     BdrvChild *child, *parent;
5356     uint64_t perm, shared_perm;
5357     Error *local_err = NULL;
5358     int ret;
5359     BdrvDirtyBitmap *bm;
5360 
5361     if (!bs->drv)  {
5362         return;
5363     }
5364 
5365     QLIST_FOREACH(child, &bs->children, next) {
5366         bdrv_co_invalidate_cache(child->bs, &local_err);
5367         if (local_err) {
5368             error_propagate(errp, local_err);
5369             return;
5370         }
5371     }
5372 
5373     /*
5374      * Update permissions, they may differ for inactive nodes.
5375      *
5376      * Note that the required permissions of inactive images are always a
5377      * subset of the permissions required after activating the image. This
5378      * allows us to just get the permissions upfront without restricting
5379      * drv->bdrv_invalidate_cache().
5380      *
5381      * It also means that in error cases, we don't have to try and revert to
5382      * the old permissions (which is an operation that could fail, too). We can
5383      * just keep the extended permissions for the next time that an activation
5384      * of the image is tried.
5385      */
5386     if (bs->open_flags & BDRV_O_INACTIVE) {
5387         bs->open_flags &= ~BDRV_O_INACTIVE;
5388         bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5389         ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL, NULL, &local_err);
5390         if (ret < 0) {
5391             bs->open_flags |= BDRV_O_INACTIVE;
5392             error_propagate(errp, local_err);
5393             return;
5394         }
5395         bdrv_set_perm(bs, perm, shared_perm);
5396 
5397         if (bs->drv->bdrv_co_invalidate_cache) {
5398             bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
5399             if (local_err) {
5400                 bs->open_flags |= BDRV_O_INACTIVE;
5401                 error_propagate(errp, local_err);
5402                 return;
5403             }
5404         }
5405 
5406         FOR_EACH_DIRTY_BITMAP(bs, bm) {
5407             bdrv_dirty_bitmap_skip_store(bm, false);
5408         }
5409 
5410         ret = refresh_total_sectors(bs, bs->total_sectors);
5411         if (ret < 0) {
5412             bs->open_flags |= BDRV_O_INACTIVE;
5413             error_setg_errno(errp, -ret, "Could not refresh total sector count");
5414             return;
5415         }
5416     }
5417 
5418     QLIST_FOREACH(parent, &bs->parents, next_parent) {
5419         if (parent->role->activate) {
5420             parent->role->activate(parent, &local_err);
5421             if (local_err) {
5422                 bs->open_flags |= BDRV_O_INACTIVE;
5423                 error_propagate(errp, local_err);
5424                 return;
5425             }
5426         }
5427     }
5428 }
5429 
5430 typedef struct InvalidateCacheCo {
5431     BlockDriverState *bs;
5432     Error **errp;
5433     bool done;
5434 } InvalidateCacheCo;
5435 
5436 static void coroutine_fn bdrv_invalidate_cache_co_entry(void *opaque)
5437 {
5438     InvalidateCacheCo *ico = opaque;
5439     bdrv_co_invalidate_cache(ico->bs, ico->errp);
5440     ico->done = true;
5441     aio_wait_kick();
5442 }
5443 
5444 void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
5445 {
5446     Coroutine *co;
5447     InvalidateCacheCo ico = {
5448         .bs = bs,
5449         .done = false,
5450         .errp = errp
5451     };
5452 
5453     if (qemu_in_coroutine()) {
5454         /* Fast-path if already in coroutine context */
5455         bdrv_invalidate_cache_co_entry(&ico);
5456     } else {
5457         co = qemu_coroutine_create(bdrv_invalidate_cache_co_entry, &ico);
5458         bdrv_coroutine_enter(bs, co);
5459         BDRV_POLL_WHILE(bs, !ico.done);
5460     }
5461 }
5462 
5463 void bdrv_invalidate_cache_all(Error **errp)
5464 {
5465     BlockDriverState *bs;
5466     Error *local_err = NULL;
5467     BdrvNextIterator it;
5468 
5469     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5470         AioContext *aio_context = bdrv_get_aio_context(bs);
5471 
5472         aio_context_acquire(aio_context);
5473         bdrv_invalidate_cache(bs, &local_err);
5474         aio_context_release(aio_context);
5475         if (local_err) {
5476             error_propagate(errp, local_err);
5477             bdrv_next_cleanup(&it);
5478             return;
5479         }
5480     }
5481 }
5482 
5483 static bool bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
5484 {
5485     BdrvChild *parent;
5486 
5487     QLIST_FOREACH(parent, &bs->parents, next_parent) {
5488         if (parent->role->parent_is_bds) {
5489             BlockDriverState *parent_bs = parent->opaque;
5490             if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
5491                 return true;
5492             }
5493         }
5494     }
5495 
5496     return false;
5497 }
5498 
5499 static int bdrv_inactivate_recurse(BlockDriverState *bs)
5500 {
5501     BdrvChild *child, *parent;
5502     bool tighten_restrictions;
5503     uint64_t perm, shared_perm;
5504     int ret;
5505 
5506     if (!bs->drv) {
5507         return -ENOMEDIUM;
5508     }
5509 
5510     /* Make sure that we don't inactivate a child before its parent.
5511      * It will be covered by recursion from the yet active parent. */
5512     if (bdrv_has_bds_parent(bs, true)) {
5513         return 0;
5514     }
5515 
5516     assert(!(bs->open_flags & BDRV_O_INACTIVE));
5517 
5518     /* Inactivate this node */
5519     if (bs->drv->bdrv_inactivate) {
5520         ret = bs->drv->bdrv_inactivate(bs);
5521         if (ret < 0) {
5522             return ret;
5523         }
5524     }
5525 
5526     QLIST_FOREACH(parent, &bs->parents, next_parent) {
5527         if (parent->role->inactivate) {
5528             ret = parent->role->inactivate(parent);
5529             if (ret < 0) {
5530                 return ret;
5531             }
5532         }
5533     }
5534 
5535     bs->open_flags |= BDRV_O_INACTIVE;
5536 
5537     /* Update permissions, they may differ for inactive nodes */
5538     bdrv_get_cumulative_perm(bs, &perm, &shared_perm);
5539     ret = bdrv_check_perm(bs, NULL, perm, shared_perm, NULL,
5540                           &tighten_restrictions, NULL);
5541     assert(tighten_restrictions == false);
5542     if (ret < 0) {
5543         /* We only tried to loosen restrictions, so errors are not fatal */
5544         bdrv_abort_perm_update(bs);
5545     } else {
5546         bdrv_set_perm(bs, perm, shared_perm);
5547     }
5548 
5549 
5550     /* Recursively inactivate children */
5551     QLIST_FOREACH(child, &bs->children, next) {
5552         ret = bdrv_inactivate_recurse(child->bs);
5553         if (ret < 0) {
5554             return ret;
5555         }
5556     }
5557 
5558     return 0;
5559 }
5560 
5561 int bdrv_inactivate_all(void)
5562 {
5563     BlockDriverState *bs = NULL;
5564     BdrvNextIterator it;
5565     int ret = 0;
5566     GSList *aio_ctxs = NULL, *ctx;
5567 
5568     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5569         AioContext *aio_context = bdrv_get_aio_context(bs);
5570 
5571         if (!g_slist_find(aio_ctxs, aio_context)) {
5572             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
5573             aio_context_acquire(aio_context);
5574         }
5575     }
5576 
5577     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
5578         /* Nodes with BDS parents are covered by recursion from the last
5579          * parent that gets inactivated. Don't inactivate them a second
5580          * time if that has already happened. */
5581         if (bdrv_has_bds_parent(bs, false)) {
5582             continue;
5583         }
5584         ret = bdrv_inactivate_recurse(bs);
5585         if (ret < 0) {
5586             bdrv_next_cleanup(&it);
5587             goto out;
5588         }
5589     }
5590 
5591 out:
5592     for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
5593         AioContext *aio_context = ctx->data;
5594         aio_context_release(aio_context);
5595     }
5596     g_slist_free(aio_ctxs);
5597 
5598     return ret;
5599 }
5600 
5601 /**************************************************************/
5602 /* removable device support */
5603 
5604 /**
5605  * Return TRUE if the media is present
5606  */
5607 bool bdrv_is_inserted(BlockDriverState *bs)
5608 {
5609     BlockDriver *drv = bs->drv;
5610     BdrvChild *child;
5611 
5612     if (!drv) {
5613         return false;
5614     }
5615     if (drv->bdrv_is_inserted) {
5616         return drv->bdrv_is_inserted(bs);
5617     }
5618     QLIST_FOREACH(child, &bs->children, next) {
5619         if (!bdrv_is_inserted(child->bs)) {
5620             return false;
5621         }
5622     }
5623     return true;
5624 }
5625 
5626 /**
5627  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
5628  */
5629 void bdrv_eject(BlockDriverState *bs, bool eject_flag)
5630 {
5631     BlockDriver *drv = bs->drv;
5632 
5633     if (drv && drv->bdrv_eject) {
5634         drv->bdrv_eject(bs, eject_flag);
5635     }
5636 }
5637 
5638 /**
5639  * Lock or unlock the media (if it is locked, the user won't be able
5640  * to eject it manually).
5641  */
5642 void bdrv_lock_medium(BlockDriverState *bs, bool locked)
5643 {
5644     BlockDriver *drv = bs->drv;
5645 
5646     trace_bdrv_lock_medium(bs, locked);
5647 
5648     if (drv && drv->bdrv_lock_medium) {
5649         drv->bdrv_lock_medium(bs, locked);
5650     }
5651 }
5652 
5653 /* Get a reference to bs */
5654 void bdrv_ref(BlockDriverState *bs)
5655 {
5656     bs->refcnt++;
5657 }
5658 
5659 /* Release a previously grabbed reference to bs.
5660  * If after releasing, reference count is zero, the BlockDriverState is
5661  * deleted. */
5662 void bdrv_unref(BlockDriverState *bs)
5663 {
5664     if (!bs) {
5665         return;
5666     }
5667     assert(bs->refcnt > 0);
5668     if (--bs->refcnt == 0) {
5669         bdrv_delete(bs);
5670     }
5671 }
5672 
5673 struct BdrvOpBlocker {
5674     Error *reason;
5675     QLIST_ENTRY(BdrvOpBlocker) list;
5676 };
5677 
5678 bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5679 {
5680     BdrvOpBlocker *blocker;
5681     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5682     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5683         blocker = QLIST_FIRST(&bs->op_blockers[op]);
5684         error_propagate_prepend(errp, error_copy(blocker->reason),
5685                                 "Node '%s' is busy: ",
5686                                 bdrv_get_device_or_node_name(bs));
5687         return true;
5688     }
5689     return false;
5690 }
5691 
5692 void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5693 {
5694     BdrvOpBlocker *blocker;
5695     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5696 
5697     blocker = g_new0(BdrvOpBlocker, 1);
5698     blocker->reason = reason;
5699     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5700 }
5701 
5702 void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5703 {
5704     BdrvOpBlocker *blocker, *next;
5705     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5706     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5707         if (blocker->reason == reason) {
5708             QLIST_REMOVE(blocker, list);
5709             g_free(blocker);
5710         }
5711     }
5712 }
5713 
5714 void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5715 {
5716     int i;
5717     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5718         bdrv_op_block(bs, i, reason);
5719     }
5720 }
5721 
5722 void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5723 {
5724     int i;
5725     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5726         bdrv_op_unblock(bs, i, reason);
5727     }
5728 }
5729 
5730 bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5731 {
5732     int i;
5733 
5734     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5735         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5736             return false;
5737         }
5738     }
5739     return true;
5740 }
5741 
5742 void bdrv_img_create(const char *filename, const char *fmt,
5743                      const char *base_filename, const char *base_fmt,
5744                      char *options, uint64_t img_size, int flags, bool quiet,
5745                      Error **errp)
5746 {
5747     QemuOptsList *create_opts = NULL;
5748     QemuOpts *opts = NULL;
5749     const char *backing_fmt, *backing_file;
5750     int64_t size;
5751     BlockDriver *drv, *proto_drv;
5752     Error *local_err = NULL;
5753     int ret = 0;
5754 
5755     /* Find driver and parse its options */
5756     drv = bdrv_find_format(fmt);
5757     if (!drv) {
5758         error_setg(errp, "Unknown file format '%s'", fmt);
5759         return;
5760     }
5761 
5762     proto_drv = bdrv_find_protocol(filename, true, errp);
5763     if (!proto_drv) {
5764         return;
5765     }
5766 
5767     if (!drv->create_opts) {
5768         error_setg(errp, "Format driver '%s' does not support image creation",
5769                    drv->format_name);
5770         return;
5771     }
5772 
5773     if (!proto_drv->create_opts) {
5774         error_setg(errp, "Protocol driver '%s' does not support image creation",
5775                    proto_drv->format_name);
5776         return;
5777     }
5778 
5779     /* Create parameter list */
5780     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5781     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5782 
5783     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
5784 
5785     /* Parse -o options */
5786     if (options) {
5787         qemu_opts_do_parse(opts, options, NULL, &local_err);
5788         if (local_err) {
5789             goto out;
5790         }
5791     }
5792 
5793     if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
5794         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
5795     } else if (img_size != UINT64_C(-1)) {
5796         error_setg(errp, "The image size must be specified only once");
5797         goto out;
5798     }
5799 
5800     if (base_filename) {
5801         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
5802         if (local_err) {
5803             error_setg(errp, "Backing file not supported for file format '%s'",
5804                        fmt);
5805             goto out;
5806         }
5807     }
5808 
5809     if (base_fmt) {
5810         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
5811         if (local_err) {
5812             error_setg(errp, "Backing file format not supported for file "
5813                              "format '%s'", fmt);
5814             goto out;
5815         }
5816     }
5817 
5818     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
5819     if (backing_file) {
5820         if (!strcmp(filename, backing_file)) {
5821             error_setg(errp, "Error: Trying to create an image with the "
5822                              "same filename as the backing file");
5823             goto out;
5824         }
5825     }
5826 
5827     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
5828 
5829     /* The size for the image must always be specified, unless we have a backing
5830      * file and we have not been forbidden from opening it. */
5831     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
5832     if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
5833         BlockDriverState *bs;
5834         char *full_backing;
5835         int back_flags;
5836         QDict *backing_options = NULL;
5837 
5838         full_backing =
5839             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
5840                                                          &local_err);
5841         if (local_err) {
5842             goto out;
5843         }
5844         assert(full_backing);
5845 
5846         /* backing files always opened read-only */
5847         back_flags = flags;
5848         back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5849 
5850         backing_options = qdict_new();
5851         if (backing_fmt) {
5852             qdict_put_str(backing_options, "driver", backing_fmt);
5853         }
5854         qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
5855 
5856         bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
5857                        &local_err);
5858         g_free(full_backing);
5859         if (!bs && size != -1) {
5860             /* Couldn't open BS, but we have a size, so it's nonfatal */
5861             warn_reportf_err(local_err,
5862                             "Could not verify backing image. "
5863                             "This may become an error in future versions.\n");
5864             local_err = NULL;
5865         } else if (!bs) {
5866             /* Couldn't open bs, do not have size */
5867             error_append_hint(&local_err,
5868                               "Could not open backing image to determine size.\n");
5869             goto out;
5870         } else {
5871             if (size == -1) {
5872                 /* Opened BS, have no size */
5873                 size = bdrv_getlength(bs);
5874                 if (size < 0) {
5875                     error_setg_errno(errp, -size, "Could not get size of '%s'",
5876                                      backing_file);
5877                     bdrv_unref(bs);
5878                     goto out;
5879                 }
5880                 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
5881             }
5882             bdrv_unref(bs);
5883         }
5884     } /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
5885 
5886     if (size == -1) {
5887         error_setg(errp, "Image creation needs a size parameter");
5888         goto out;
5889     }
5890 
5891     if (!quiet) {
5892         printf("Formatting '%s', fmt=%s ", filename, fmt);
5893         qemu_opts_print(opts, " ");
5894         puts("");
5895     }
5896 
5897     ret = bdrv_create(drv, filename, opts, &local_err);
5898 
5899     if (ret == -EFBIG) {
5900         /* This is generally a better message than whatever the driver would
5901          * deliver (especially because of the cluster_size_hint), since that
5902          * is most probably not much different from "image too large". */
5903         const char *cluster_size_hint = "";
5904         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
5905             cluster_size_hint = " (try using a larger cluster size)";
5906         }
5907         error_setg(errp, "The image size is too large for file format '%s'"
5908                    "%s", fmt, cluster_size_hint);
5909         error_free(local_err);
5910         local_err = NULL;
5911     }
5912 
5913 out:
5914     qemu_opts_del(opts);
5915     qemu_opts_free(create_opts);
5916     error_propagate(errp, local_err);
5917 }
5918 
5919 AioContext *bdrv_get_aio_context(BlockDriverState *bs)
5920 {
5921     return bs ? bs->aio_context : qemu_get_aio_context();
5922 }
5923 
5924 void bdrv_coroutine_enter(BlockDriverState *bs, Coroutine *co)
5925 {
5926     aio_co_enter(bdrv_get_aio_context(bs), co);
5927 }
5928 
5929 static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
5930 {
5931     QLIST_REMOVE(ban, list);
5932     g_free(ban);
5933 }
5934 
5935 static void bdrv_detach_aio_context(BlockDriverState *bs)
5936 {
5937     BdrvAioNotifier *baf, *baf_tmp;
5938 
5939     assert(!bs->walking_aio_notifiers);
5940     bs->walking_aio_notifiers = true;
5941     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
5942         if (baf->deleted) {
5943             bdrv_do_remove_aio_context_notifier(baf);
5944         } else {
5945             baf->detach_aio_context(baf->opaque);
5946         }
5947     }
5948     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
5949      * remove remaining aio notifiers if we aren't called again.
5950      */
5951     bs->walking_aio_notifiers = false;
5952 
5953     if (bs->drv && bs->drv->bdrv_detach_aio_context) {
5954         bs->drv->bdrv_detach_aio_context(bs);
5955     }
5956 
5957     if (bs->quiesce_counter) {
5958         aio_enable_external(bs->aio_context);
5959     }
5960     bs->aio_context = NULL;
5961 }
5962 
5963 static void bdrv_attach_aio_context(BlockDriverState *bs,
5964                                     AioContext *new_context)
5965 {
5966     BdrvAioNotifier *ban, *ban_tmp;
5967 
5968     if (bs->quiesce_counter) {
5969         aio_disable_external(new_context);
5970     }
5971 
5972     bs->aio_context = new_context;
5973 
5974     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
5975         bs->drv->bdrv_attach_aio_context(bs, new_context);
5976     }
5977 
5978     assert(!bs->walking_aio_notifiers);
5979     bs->walking_aio_notifiers = true;
5980     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
5981         if (ban->deleted) {
5982             bdrv_do_remove_aio_context_notifier(ban);
5983         } else {
5984             ban->attached_aio_context(new_context, ban->opaque);
5985         }
5986     }
5987     bs->walking_aio_notifiers = false;
5988 }
5989 
5990 /*
5991  * Changes the AioContext used for fd handlers, timers, and BHs by this
5992  * BlockDriverState and all its children and parents.
5993  *
5994  * Must be called from the main AioContext.
5995  *
5996  * The caller must own the AioContext lock for the old AioContext of bs, but it
5997  * must not own the AioContext lock for new_context (unless new_context is the
5998  * same as the current context of bs).
5999  *
6000  * @ignore will accumulate all visited BdrvChild object. The caller is
6001  * responsible for freeing the list afterwards.
6002  */
6003 void bdrv_set_aio_context_ignore(BlockDriverState *bs,
6004                                  AioContext *new_context, GSList **ignore)
6005 {
6006     AioContext *old_context = bdrv_get_aio_context(bs);
6007     BdrvChild *child;
6008 
6009     g_assert(qemu_get_current_aio_context() == qemu_get_aio_context());
6010 
6011     if (old_context == new_context) {
6012         return;
6013     }
6014 
6015     bdrv_drained_begin(bs);
6016 
6017     QLIST_FOREACH(child, &bs->children, next) {
6018         if (g_slist_find(*ignore, child)) {
6019             continue;
6020         }
6021         *ignore = g_slist_prepend(*ignore, child);
6022         bdrv_set_aio_context_ignore(child->bs, new_context, ignore);
6023     }
6024     QLIST_FOREACH(child, &bs->parents, next_parent) {
6025         if (g_slist_find(*ignore, child)) {
6026             continue;
6027         }
6028         assert(child->role->set_aio_ctx);
6029         *ignore = g_slist_prepend(*ignore, child);
6030         child->role->set_aio_ctx(child, new_context, ignore);
6031     }
6032 
6033     bdrv_detach_aio_context(bs);
6034 
6035     /* Acquire the new context, if necessary */
6036     if (qemu_get_aio_context() != new_context) {
6037         aio_context_acquire(new_context);
6038     }
6039 
6040     bdrv_attach_aio_context(bs, new_context);
6041 
6042     /*
6043      * If this function was recursively called from
6044      * bdrv_set_aio_context_ignore(), there may be nodes in the
6045      * subtree that have not yet been moved to the new AioContext.
6046      * Release the old one so bdrv_drained_end() can poll them.
6047      */
6048     if (qemu_get_aio_context() != old_context) {
6049         aio_context_release(old_context);
6050     }
6051 
6052     bdrv_drained_end(bs);
6053 
6054     if (qemu_get_aio_context() != old_context) {
6055         aio_context_acquire(old_context);
6056     }
6057     if (qemu_get_aio_context() != new_context) {
6058         aio_context_release(new_context);
6059     }
6060 }
6061 
6062 static bool bdrv_parent_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6063                                             GSList **ignore, Error **errp)
6064 {
6065     if (g_slist_find(*ignore, c)) {
6066         return true;
6067     }
6068     *ignore = g_slist_prepend(*ignore, c);
6069 
6070     /* A BdrvChildRole that doesn't handle AioContext changes cannot
6071      * tolerate any AioContext changes */
6072     if (!c->role->can_set_aio_ctx) {
6073         char *user = bdrv_child_user_desc(c);
6074         error_setg(errp, "Changing iothreads is not supported by %s", user);
6075         g_free(user);
6076         return false;
6077     }
6078     if (!c->role->can_set_aio_ctx(c, ctx, ignore, errp)) {
6079         assert(!errp || *errp);
6080         return false;
6081     }
6082     return true;
6083 }
6084 
6085 bool bdrv_child_can_set_aio_context(BdrvChild *c, AioContext *ctx,
6086                                     GSList **ignore, Error **errp)
6087 {
6088     if (g_slist_find(*ignore, c)) {
6089         return true;
6090     }
6091     *ignore = g_slist_prepend(*ignore, c);
6092     return bdrv_can_set_aio_context(c->bs, ctx, ignore, errp);
6093 }
6094 
6095 /* @ignore will accumulate all visited BdrvChild object. The caller is
6096  * responsible for freeing the list afterwards. */
6097 bool bdrv_can_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6098                               GSList **ignore, Error **errp)
6099 {
6100     BdrvChild *c;
6101 
6102     if (bdrv_get_aio_context(bs) == ctx) {
6103         return true;
6104     }
6105 
6106     QLIST_FOREACH(c, &bs->parents, next_parent) {
6107         if (!bdrv_parent_can_set_aio_context(c, ctx, ignore, errp)) {
6108             return false;
6109         }
6110     }
6111     QLIST_FOREACH(c, &bs->children, next) {
6112         if (!bdrv_child_can_set_aio_context(c, ctx, ignore, errp)) {
6113             return false;
6114         }
6115     }
6116 
6117     return true;
6118 }
6119 
6120 int bdrv_child_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6121                                    BdrvChild *ignore_child, Error **errp)
6122 {
6123     GSList *ignore;
6124     bool ret;
6125 
6126     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6127     ret = bdrv_can_set_aio_context(bs, ctx, &ignore, errp);
6128     g_slist_free(ignore);
6129 
6130     if (!ret) {
6131         return -EPERM;
6132     }
6133 
6134     ignore = ignore_child ? g_slist_prepend(NULL, ignore_child) : NULL;
6135     bdrv_set_aio_context_ignore(bs, ctx, &ignore);
6136     g_slist_free(ignore);
6137 
6138     return 0;
6139 }
6140 
6141 int bdrv_try_set_aio_context(BlockDriverState *bs, AioContext *ctx,
6142                              Error **errp)
6143 {
6144     return bdrv_child_try_set_aio_context(bs, ctx, NULL, errp);
6145 }
6146 
6147 void bdrv_add_aio_context_notifier(BlockDriverState *bs,
6148         void (*attached_aio_context)(AioContext *new_context, void *opaque),
6149         void (*detach_aio_context)(void *opaque), void *opaque)
6150 {
6151     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
6152     *ban = (BdrvAioNotifier){
6153         .attached_aio_context = attached_aio_context,
6154         .detach_aio_context   = detach_aio_context,
6155         .opaque               = opaque
6156     };
6157 
6158     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
6159 }
6160 
6161 void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
6162                                       void (*attached_aio_context)(AioContext *,
6163                                                                    void *),
6164                                       void (*detach_aio_context)(void *),
6165                                       void *opaque)
6166 {
6167     BdrvAioNotifier *ban, *ban_next;
6168 
6169     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
6170         if (ban->attached_aio_context == attached_aio_context &&
6171             ban->detach_aio_context   == detach_aio_context   &&
6172             ban->opaque               == opaque               &&
6173             ban->deleted              == false)
6174         {
6175             if (bs->walking_aio_notifiers) {
6176                 ban->deleted = true;
6177             } else {
6178                 bdrv_do_remove_aio_context_notifier(ban);
6179             }
6180             return;
6181         }
6182     }
6183 
6184     abort();
6185 }
6186 
6187 int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
6188                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
6189                        Error **errp)
6190 {
6191     if (!bs->drv) {
6192         error_setg(errp, "Node is ejected");
6193         return -ENOMEDIUM;
6194     }
6195     if (!bs->drv->bdrv_amend_options) {
6196         error_setg(errp, "Block driver '%s' does not support option amendment",
6197                    bs->drv->format_name);
6198         return -ENOTSUP;
6199     }
6200     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque, errp);
6201 }
6202 
6203 /* This function will be called by the bdrv_recurse_is_first_non_filter method
6204  * of block filter and by bdrv_is_first_non_filter.
6205  * It is used to test if the given bs is the candidate or recurse more in the
6206  * node graph.
6207  */
6208 bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
6209                                       BlockDriverState *candidate)
6210 {
6211     /* return false if basic checks fails */
6212     if (!bs || !bs->drv) {
6213         return false;
6214     }
6215 
6216     /* the code reached a non block filter driver -> check if the bs is
6217      * the same as the candidate. It's the recursion termination condition.
6218      */
6219     if (!bs->drv->is_filter) {
6220         return bs == candidate;
6221     }
6222     /* Down this path the driver is a block filter driver */
6223 
6224     /* If the block filter recursion method is defined use it to recurse down
6225      * the node graph.
6226      */
6227     if (bs->drv->bdrv_recurse_is_first_non_filter) {
6228         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
6229     }
6230 
6231     /* the driver is a block filter but don't allow to recurse -> return false
6232      */
6233     return false;
6234 }
6235 
6236 /* This function checks if the candidate is the first non filter bs down it's
6237  * bs chain. Since we don't have pointers to parents it explore all bs chains
6238  * from the top. Some filters can choose not to pass down the recursion.
6239  */
6240 bool bdrv_is_first_non_filter(BlockDriverState *candidate)
6241 {
6242     BlockDriverState *bs;
6243     BdrvNextIterator it;
6244 
6245     /* walk down the bs forest recursively */
6246     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
6247         bool perm;
6248 
6249         /* try to recurse in this top level bs */
6250         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
6251 
6252         /* candidate is the first non filter */
6253         if (perm) {
6254             bdrv_next_cleanup(&it);
6255             return true;
6256         }
6257     }
6258 
6259     return false;
6260 }
6261 
6262 BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
6263                                         const char *node_name, Error **errp)
6264 {
6265     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
6266     AioContext *aio_context;
6267 
6268     if (!to_replace_bs) {
6269         error_setg(errp, "Node name '%s' not found", node_name);
6270         return NULL;
6271     }
6272 
6273     aio_context = bdrv_get_aio_context(to_replace_bs);
6274     aio_context_acquire(aio_context);
6275 
6276     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
6277         to_replace_bs = NULL;
6278         goto out;
6279     }
6280 
6281     /* We don't want arbitrary node of the BDS chain to be replaced only the top
6282      * most non filter in order to prevent data corruption.
6283      * Another benefit is that this tests exclude backing files which are
6284      * blocked by the backing blockers.
6285      */
6286     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
6287         error_setg(errp, "Only top most non filter can be replaced");
6288         to_replace_bs = NULL;
6289         goto out;
6290     }
6291 
6292 out:
6293     aio_context_release(aio_context);
6294     return to_replace_bs;
6295 }
6296 
6297 /**
6298  * Iterates through the list of runtime option keys that are said to
6299  * be "strong" for a BDS.  An option is called "strong" if it changes
6300  * a BDS's data.  For example, the null block driver's "size" and
6301  * "read-zeroes" options are strong, but its "latency-ns" option is
6302  * not.
6303  *
6304  * If a key returned by this function ends with a dot, all options
6305  * starting with that prefix are strong.
6306  */
6307 static const char *const *strong_options(BlockDriverState *bs,
6308                                          const char *const *curopt)
6309 {
6310     static const char *const global_options[] = {
6311         "driver", "filename", NULL
6312     };
6313 
6314     if (!curopt) {
6315         return &global_options[0];
6316     }
6317 
6318     curopt++;
6319     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
6320         curopt = bs->drv->strong_runtime_opts;
6321     }
6322 
6323     return (curopt && *curopt) ? curopt : NULL;
6324 }
6325 
6326 /**
6327  * Copies all strong runtime options from bs->options to the given
6328  * QDict.  The set of strong option keys is determined by invoking
6329  * strong_options().
6330  *
6331  * Returns true iff any strong option was present in bs->options (and
6332  * thus copied to the target QDict) with the exception of "filename"
6333  * and "driver".  The caller is expected to use this value to decide
6334  * whether the existence of strong options prevents the generation of
6335  * a plain filename.
6336  */
6337 static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
6338 {
6339     bool found_any = false;
6340     const char *const *option_name = NULL;
6341 
6342     if (!bs->drv) {
6343         return false;
6344     }
6345 
6346     while ((option_name = strong_options(bs, option_name))) {
6347         bool option_given = false;
6348 
6349         assert(strlen(*option_name) > 0);
6350         if ((*option_name)[strlen(*option_name) - 1] != '.') {
6351             QObject *entry = qdict_get(bs->options, *option_name);
6352             if (!entry) {
6353                 continue;
6354             }
6355 
6356             qdict_put_obj(d, *option_name, qobject_ref(entry));
6357             option_given = true;
6358         } else {
6359             const QDictEntry *entry;
6360             for (entry = qdict_first(bs->options); entry;
6361                  entry = qdict_next(bs->options, entry))
6362             {
6363                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
6364                     qdict_put_obj(d, qdict_entry_key(entry),
6365                                   qobject_ref(qdict_entry_value(entry)));
6366                     option_given = true;
6367                 }
6368             }
6369         }
6370 
6371         /* While "driver" and "filename" need to be included in a JSON filename,
6372          * their existence does not prohibit generation of a plain filename. */
6373         if (!found_any && option_given &&
6374             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
6375         {
6376             found_any = true;
6377         }
6378     }
6379 
6380     if (!qdict_haskey(d, "driver")) {
6381         /* Drivers created with bdrv_new_open_driver() may not have a
6382          * @driver option.  Add it here. */
6383         qdict_put_str(d, "driver", bs->drv->format_name);
6384     }
6385 
6386     return found_any;
6387 }
6388 
6389 /* Note: This function may return false positives; it may return true
6390  * even if opening the backing file specified by bs's image header
6391  * would result in exactly bs->backing. */
6392 static bool bdrv_backing_overridden(BlockDriverState *bs)
6393 {
6394     if (bs->backing) {
6395         return strcmp(bs->auto_backing_file,
6396                       bs->backing->bs->filename);
6397     } else {
6398         /* No backing BDS, so if the image header reports any backing
6399          * file, it must have been suppressed */
6400         return bs->auto_backing_file[0] != '\0';
6401     }
6402 }
6403 
6404 /* Updates the following BDS fields:
6405  *  - exact_filename: A filename which may be used for opening a block device
6406  *                    which (mostly) equals the given BDS (even without any
6407  *                    other options; so reading and writing must return the same
6408  *                    results, but caching etc. may be different)
6409  *  - full_open_options: Options which, when given when opening a block device
6410  *                       (without a filename), result in a BDS (mostly)
6411  *                       equalling the given one
6412  *  - filename: If exact_filename is set, it is copied here. Otherwise,
6413  *              full_open_options is converted to a JSON object, prefixed with
6414  *              "json:" (for use through the JSON pseudo protocol) and put here.
6415  */
6416 void bdrv_refresh_filename(BlockDriverState *bs)
6417 {
6418     BlockDriver *drv = bs->drv;
6419     BdrvChild *child;
6420     QDict *opts;
6421     bool backing_overridden;
6422     bool generate_json_filename; /* Whether our default implementation should
6423                                     fill exact_filename (false) or not (true) */
6424 
6425     if (!drv) {
6426         return;
6427     }
6428 
6429     /* This BDS's file name may depend on any of its children's file names, so
6430      * refresh those first */
6431     QLIST_FOREACH(child, &bs->children, next) {
6432         bdrv_refresh_filename(child->bs);
6433     }
6434 
6435     if (bs->implicit) {
6436         /* For implicit nodes, just copy everything from the single child */
6437         child = QLIST_FIRST(&bs->children);
6438         assert(QLIST_NEXT(child, next) == NULL);
6439 
6440         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
6441                 child->bs->exact_filename);
6442         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
6443 
6444         bs->full_open_options = qobject_ref(child->bs->full_open_options);
6445 
6446         return;
6447     }
6448 
6449     backing_overridden = bdrv_backing_overridden(bs);
6450 
6451     if (bs->open_flags & BDRV_O_NO_IO) {
6452         /* Without I/O, the backing file does not change anything.
6453          * Therefore, in such a case (primarily qemu-img), we can
6454          * pretend the backing file has not been overridden even if
6455          * it technically has been. */
6456         backing_overridden = false;
6457     }
6458 
6459     /* Gather the options QDict */
6460     opts = qdict_new();
6461     generate_json_filename = append_strong_runtime_options(opts, bs);
6462     generate_json_filename |= backing_overridden;
6463 
6464     if (drv->bdrv_gather_child_options) {
6465         /* Some block drivers may not want to present all of their children's
6466          * options, or name them differently from BdrvChild.name */
6467         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
6468     } else {
6469         QLIST_FOREACH(child, &bs->children, next) {
6470             if (child->role == &child_backing && !backing_overridden) {
6471                 /* We can skip the backing BDS if it has not been overridden */
6472                 continue;
6473             }
6474 
6475             qdict_put(opts, child->name,
6476                       qobject_ref(child->bs->full_open_options));
6477         }
6478 
6479         if (backing_overridden && !bs->backing) {
6480             /* Force no backing file */
6481             qdict_put_null(opts, "backing");
6482         }
6483     }
6484 
6485     qobject_unref(bs->full_open_options);
6486     bs->full_open_options = opts;
6487 
6488     if (drv->bdrv_refresh_filename) {
6489         /* Obsolete information is of no use here, so drop the old file name
6490          * information before refreshing it */
6491         bs->exact_filename[0] = '\0';
6492 
6493         drv->bdrv_refresh_filename(bs);
6494     } else if (bs->file) {
6495         /* Try to reconstruct valid information from the underlying file */
6496 
6497         bs->exact_filename[0] = '\0';
6498 
6499         /*
6500          * We can use the underlying file's filename if:
6501          * - it has a filename,
6502          * - the file is a protocol BDS, and
6503          * - opening that file (as this BDS's format) will automatically create
6504          *   the BDS tree we have right now, that is:
6505          *   - the user did not significantly change this BDS's behavior with
6506          *     some explicit (strong) options
6507          *   - no non-file child of this BDS has been overridden by the user
6508          *   Both of these conditions are represented by generate_json_filename.
6509          */
6510         if (bs->file->bs->exact_filename[0] &&
6511             bs->file->bs->drv->bdrv_file_open &&
6512             !generate_json_filename)
6513         {
6514             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
6515         }
6516     }
6517 
6518     if (bs->exact_filename[0]) {
6519         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
6520     } else {
6521         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
6522         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
6523                  qstring_get_str(json));
6524         qobject_unref(json);
6525     }
6526 }
6527 
6528 char *bdrv_dirname(BlockDriverState *bs, Error **errp)
6529 {
6530     BlockDriver *drv = bs->drv;
6531 
6532     if (!drv) {
6533         error_setg(errp, "Node '%s' is ejected", bs->node_name);
6534         return NULL;
6535     }
6536 
6537     if (drv->bdrv_dirname) {
6538         return drv->bdrv_dirname(bs, errp);
6539     }
6540 
6541     if (bs->file) {
6542         return bdrv_dirname(bs->file->bs, errp);
6543     }
6544 
6545     bdrv_refresh_filename(bs);
6546     if (bs->exact_filename[0] != '\0') {
6547         return path_combine(bs->exact_filename, "");
6548     }
6549 
6550     error_setg(errp, "Cannot generate a base directory for %s nodes",
6551                drv->format_name);
6552     return NULL;
6553 }
6554 
6555 /*
6556  * Hot add/remove a BDS's child. So the user can take a child offline when
6557  * it is broken and take a new child online
6558  */
6559 void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
6560                     Error **errp)
6561 {
6562 
6563     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
6564         error_setg(errp, "The node %s does not support adding a child",
6565                    bdrv_get_device_or_node_name(parent_bs));
6566         return;
6567     }
6568 
6569     if (!QLIST_EMPTY(&child_bs->parents)) {
6570         error_setg(errp, "The node %s already has a parent",
6571                    child_bs->node_name);
6572         return;
6573     }
6574 
6575     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
6576 }
6577 
6578 void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
6579 {
6580     BdrvChild *tmp;
6581 
6582     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
6583         error_setg(errp, "The node %s does not support removing a child",
6584                    bdrv_get_device_or_node_name(parent_bs));
6585         return;
6586     }
6587 
6588     QLIST_FOREACH(tmp, &parent_bs->children, next) {
6589         if (tmp == child) {
6590             break;
6591         }
6592     }
6593 
6594     if (!tmp) {
6595         error_setg(errp, "The node %s does not have a child named %s",
6596                    bdrv_get_device_or_node_name(parent_bs),
6597                    bdrv_get_device_or_node_name(child->bs));
6598         return;
6599     }
6600 
6601     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
6602 }
6603