OSDN Git Service

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