OSDN Git Service

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