OSDN Git Service

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