xref: /openbmc/qemu/block.c (revision b8eada54b2ad8a7d98d93d5ab4d3e888c5880097)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5c20555e1SVladimir Sementsov-Ogievskiy  * Copyright (c) 2020 Virtuozzo International GmbH.
6fc01f7e7Sbellard  *
7fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
8fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
9fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
10fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
12fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
13fc01f7e7Sbellard  *
14fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
15fc01f7e7Sbellard  * all copies or substantial portions of the Software.
16fc01f7e7Sbellard  *
17fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23fc01f7e7Sbellard  * THE SOFTWARE.
24fc01f7e7Sbellard  */
25e688df6bSMarkus Armbruster 
26d38ea87aSPeter Maydell #include "qemu/osdep.h"
270ab8ed18SDaniel P. Berrange #include "block/trace.h"
28737e150eSPaolo Bonzini #include "block/block_int.h"
29737e150eSPaolo Bonzini #include "block/blockjob.h"
30e2c1c34fSMarkus Armbruster #include "block/dirty-bitmap.h"
310c9b70d5SMax Reitz #include "block/fuse.h"
32cd7fca95SKevin Wolf #include "block/nbd.h"
33609f45eaSMax Reitz #include "block/qdict.h"
34d49b6836SMarkus Armbruster #include "qemu/error-report.h"
355e5733e5SMarc-André Lureau #include "block/module_block.h"
36db725815SMarkus Armbruster #include "qemu/main-loop.h"
371de7afc9SPaolo Bonzini #include "qemu/module.h"
38e688df6bSMarkus Armbruster #include "qapi/error.h"
39452fcdbcSMarkus Armbruster #include "qapi/qmp/qdict.h"
407b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
41e59a0cf1SMax Reitz #include "qapi/qmp/qnull.h"
42fc81fa1eSMarkus Armbruster #include "qapi/qmp/qstring.h"
43e1d74bc6SKevin Wolf #include "qapi/qobject-output-visitor.h"
44e1d74bc6SKevin Wolf #include "qapi/qapi-visit-block-core.h"
45bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
461de7afc9SPaolo Bonzini #include "qemu/notify.h"
47922a01a0SMarkus Armbruster #include "qemu/option.h"
4810817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
49c13163fbSBenoît Canet #include "block/qapi.h"
501de7afc9SPaolo Bonzini #include "qemu/timer.h"
51f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
52f348b6d1SVeronia Bahaa #include "qemu/id.h"
530bc329fbSHanna Reitz #include "qemu/range.h"
540bc329fbSHanna Reitz #include "qemu/rcu.h"
5521c2283eSVladimir Sementsov-Ogievskiy #include "block/coroutines.h"
56fc01f7e7Sbellard 
5771e72a19SJuan Quintela #ifdef CONFIG_BSD
587674e7bfSbellard #include <sys/ioctl.h>
5972cf2d4fSBlue Swirl #include <sys/queue.h>
60feccdceeSJoelle van Dyne #if defined(HAVE_SYS_DISK_H)
617674e7bfSbellard #include <sys/disk.h>
627674e7bfSbellard #endif
63c5e97233Sblueswir1 #endif
647674e7bfSbellard 
6549dc768dSaliguori #ifdef _WIN32
6649dc768dSaliguori #include <windows.h>
6749dc768dSaliguori #endif
6849dc768dSaliguori 
691c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
701c9805a3SStefan Hajnoczi 
713b491a90SEmanuele Giuseppe Esposito /* Protected by BQL */
72dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
73dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
74dc364f4cSBenoît Canet 
753b491a90SEmanuele Giuseppe Esposito /* Protected by BQL */
762c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
772c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
782c1d04e0SMax Reitz 
793b491a90SEmanuele Giuseppe Esposito /* Protected by BQL */
808a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
818a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
82ea2384d3Sbellard 
835b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
845b363937SMax Reitz                                            const char *reference,
855b363937SMax Reitz                                            QDict *options, int flags,
86f3930ed0SKevin Wolf                                            BlockDriverState *parent,
87bd86fb99SMax Reitz                                            const BdrvChildClass *child_class,
88272c02eaSMax Reitz                                            BdrvChildRole child_role,
897ead9469SKevin Wolf                                            bool parse_filename,
905b363937SMax Reitz                                            Error **errp);
91f3930ed0SKevin Wolf 
92bfb8aa6dSKevin Wolf static bool bdrv_recurse_has_child(BlockDriverState *bs,
93bfb8aa6dSKevin Wolf                                    BlockDriverState *child);
94bfb8aa6dSKevin Wolf 
95ad29eb3dSKevin Wolf static void GRAPH_WRLOCK
96ad29eb3dSKevin Wolf bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs);
97ad29eb3dSKevin Wolf 
982f64e1fcSKevin Wolf static void GRAPH_WRLOCK
992f64e1fcSKevin Wolf bdrv_remove_child(BdrvChild *child, Transaction *tran);
1000978623eSVladimir Sementsov-Ogievskiy 
10172373e40SVladimir Sementsov-Ogievskiy static int bdrv_reopen_prepare(BDRVReopenState *reopen_state,
10272373e40SVladimir Sementsov-Ogievskiy                                BlockReopenQueue *queue,
103ecd30d2dSAlberto Garcia                                Transaction *change_child_tran, Error **errp);
10453e96d1eSVladimir Sementsov-Ogievskiy static void bdrv_reopen_commit(BDRVReopenState *reopen_state);
10553e96d1eSVladimir Sementsov-Ogievskiy static void bdrv_reopen_abort(BDRVReopenState *reopen_state);
10653e96d1eSVladimir Sementsov-Ogievskiy 
107fa8fc1d0SEmanuele Giuseppe Esposito static bool bdrv_backing_overridden(BlockDriverState *bs);
108fa8fc1d0SEmanuele Giuseppe Esposito 
1097e8c182fSEmanuele Giuseppe Esposito static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
110e08cc001SEmanuele Giuseppe Esposito                                     GHashTable *visited, Transaction *tran,
1117e8c182fSEmanuele Giuseppe Esposito                                     Error **errp);
1127e8c182fSEmanuele Giuseppe Esposito 
113eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
114eb852011SMarkus Armbruster static int use_bdrv_whitelist;
115eb852011SMarkus Armbruster 
1169e0b22f4SStefan Hajnoczi #ifdef _WIN32
1179e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1189e0b22f4SStefan Hajnoczi {
1199e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1209e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1219e0b22f4SStefan Hajnoczi             filename[1] == ':');
1229e0b22f4SStefan Hajnoczi }
1239e0b22f4SStefan Hajnoczi 
1249e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1259e0b22f4SStefan Hajnoczi {
1269e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1279e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1289e0b22f4SStefan Hajnoczi         return 1;
1299e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1309e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1319e0b22f4SStefan Hajnoczi         return 1;
1329e0b22f4SStefan Hajnoczi     return 0;
1339e0b22f4SStefan Hajnoczi }
1349e0b22f4SStefan Hajnoczi #endif
1359e0b22f4SStefan Hajnoczi 
136339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
137339064d5SKevin Wolf {
138339064d5SKevin Wolf     if (!bs || !bs->drv) {
139459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
1408e3b0cbbSMarc-André Lureau         return MAX(4096, qemu_real_host_page_size());
141339064d5SKevin Wolf     }
142384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
143339064d5SKevin Wolf 
144339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
145339064d5SKevin Wolf }
146339064d5SKevin Wolf 
1474196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1484196d2f0SDenis V. Lunev {
1494196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
150459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
1518e3b0cbbSMarc-André Lureau         return MAX(4096, qemu_real_host_page_size());
1524196d2f0SDenis V. Lunev     }
153384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
1544196d2f0SDenis V. Lunev 
1554196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1564196d2f0SDenis V. Lunev }
1574196d2f0SDenis V. Lunev 
1589e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1595c98415bSMax Reitz int path_has_protocol(const char *path)
1609e0b22f4SStefan Hajnoczi {
161947995c0SPaolo Bonzini     const char *p;
162947995c0SPaolo Bonzini 
1639e0b22f4SStefan Hajnoczi #ifdef _WIN32
1649e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1659e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1669e0b22f4SStefan Hajnoczi         return 0;
1679e0b22f4SStefan Hajnoczi     }
168947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
169947995c0SPaolo Bonzini #else
170947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1719e0b22f4SStefan Hajnoczi #endif
1729e0b22f4SStefan Hajnoczi 
173947995c0SPaolo Bonzini     return *p == ':';
1749e0b22f4SStefan Hajnoczi }
1759e0b22f4SStefan Hajnoczi 
17683f64091Sbellard int path_is_absolute(const char *path)
17783f64091Sbellard {
17821664424Sbellard #ifdef _WIN32
17921664424Sbellard     /* specific case for names like: "\\.\d:" */
180f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
18121664424Sbellard         return 1;
182f53f4da9SPaolo Bonzini     }
183f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1843b9f94e1Sbellard #else
185f53f4da9SPaolo Bonzini     return (*path == '/');
1863b9f94e1Sbellard #endif
18783f64091Sbellard }
18883f64091Sbellard 
189009b03aaSMax Reitz /* if filename is absolute, just return its duplicate. Otherwise, build a
19083f64091Sbellard    path to it by considering it is relative to base_path. URL are
19183f64091Sbellard    supported. */
192009b03aaSMax Reitz char *path_combine(const char *base_path, const char *filename)
19383f64091Sbellard {
194009b03aaSMax Reitz     const char *protocol_stripped = NULL;
19583f64091Sbellard     const char *p, *p1;
196009b03aaSMax Reitz     char *result;
19783f64091Sbellard     int len;
19883f64091Sbellard 
19983f64091Sbellard     if (path_is_absolute(filename)) {
200009b03aaSMax Reitz         return g_strdup(filename);
201009b03aaSMax Reitz     }
2020d54a6feSMax Reitz 
2030d54a6feSMax Reitz     if (path_has_protocol(base_path)) {
2040d54a6feSMax Reitz         protocol_stripped = strchr(base_path, ':');
2050d54a6feSMax Reitz         if (protocol_stripped) {
2060d54a6feSMax Reitz             protocol_stripped++;
2070d54a6feSMax Reitz         }
2080d54a6feSMax Reitz     }
2090d54a6feSMax Reitz     p = protocol_stripped ?: base_path;
2100d54a6feSMax Reitz 
2113b9f94e1Sbellard     p1 = strrchr(base_path, '/');
2123b9f94e1Sbellard #ifdef _WIN32
2133b9f94e1Sbellard     {
2143b9f94e1Sbellard         const char *p2;
2153b9f94e1Sbellard         p2 = strrchr(base_path, '\\');
216009b03aaSMax Reitz         if (!p1 || p2 > p1) {
2173b9f94e1Sbellard             p1 = p2;
2183b9f94e1Sbellard         }
21983f64091Sbellard     }
220009b03aaSMax Reitz #endif
221009b03aaSMax Reitz     if (p1) {
222009b03aaSMax Reitz         p1++;
223009b03aaSMax Reitz     } else {
224009b03aaSMax Reitz         p1 = base_path;
225009b03aaSMax Reitz     }
226009b03aaSMax Reitz     if (p1 > p) {
227009b03aaSMax Reitz         p = p1;
228009b03aaSMax Reitz     }
229009b03aaSMax Reitz     len = p - base_path;
230009b03aaSMax Reitz 
231009b03aaSMax Reitz     result = g_malloc(len + strlen(filename) + 1);
232009b03aaSMax Reitz     memcpy(result, base_path, len);
233009b03aaSMax Reitz     strcpy(result + len, filename);
234009b03aaSMax Reitz 
235009b03aaSMax Reitz     return result;
236009b03aaSMax Reitz }
237009b03aaSMax Reitz 
23803c320d8SMax Reitz /*
23903c320d8SMax Reitz  * Helper function for bdrv_parse_filename() implementations to remove optional
24003c320d8SMax Reitz  * protocol prefixes (especially "file:") from a filename and for putting the
24103c320d8SMax Reitz  * stripped filename into the options QDict if there is such a prefix.
24203c320d8SMax Reitz  */
24303c320d8SMax Reitz void bdrv_parse_filename_strip_prefix(const char *filename, const char *prefix,
24403c320d8SMax Reitz                                       QDict *options)
24503c320d8SMax Reitz {
24603c320d8SMax Reitz     if (strstart(filename, prefix, &filename)) {
24703c320d8SMax Reitz         /* Stripping the explicit protocol prefix may result in a protocol
24803c320d8SMax Reitz          * prefix being (wrongly) detected (if the filename contains a colon) */
24903c320d8SMax Reitz         if (path_has_protocol(filename)) {
25018cf67c5SMarkus Armbruster             GString *fat_filename;
25103c320d8SMax Reitz 
25203c320d8SMax Reitz             /* This means there is some colon before the first slash; therefore,
25303c320d8SMax Reitz              * this cannot be an absolute path */
25403c320d8SMax Reitz             assert(!path_is_absolute(filename));
25503c320d8SMax Reitz 
25603c320d8SMax Reitz             /* And we can thus fix the protocol detection issue by prefixing it
25703c320d8SMax Reitz              * by "./" */
25818cf67c5SMarkus Armbruster             fat_filename = g_string_new("./");
25918cf67c5SMarkus Armbruster             g_string_append(fat_filename, filename);
26003c320d8SMax Reitz 
26118cf67c5SMarkus Armbruster             assert(!path_has_protocol(fat_filename->str));
26203c320d8SMax Reitz 
26318cf67c5SMarkus Armbruster             qdict_put(options, "filename",
26418cf67c5SMarkus Armbruster                       qstring_from_gstring(fat_filename));
26503c320d8SMax Reitz         } else {
26603c320d8SMax Reitz             /* If no protocol prefix was detected, we can use the shortened
26703c320d8SMax Reitz              * filename as-is */
26803c320d8SMax Reitz             qdict_put_str(options, "filename", filename);
26903c320d8SMax Reitz         }
27003c320d8SMax Reitz     }
27103c320d8SMax Reitz }
27203c320d8SMax Reitz 
27303c320d8SMax Reitz 
2749c5e6594SKevin Wolf /* Returns whether the image file is opened as read-only. Note that this can
2759c5e6594SKevin Wolf  * return false and writing to the image file is still not possible because the
2769c5e6594SKevin Wolf  * image is inactivated. */
27793ed524eSJeff Cody bool bdrv_is_read_only(BlockDriverState *bs)
27893ed524eSJeff Cody {
279384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
280975da073SVladimir Sementsov-Ogievskiy     return !(bs->open_flags & BDRV_O_RDWR);
28193ed524eSJeff Cody }
28293ed524eSJeff Cody 
2834026f1c4SKevin Wolf static int GRAPH_RDLOCK
2844026f1c4SKevin Wolf bdrv_can_set_read_only(BlockDriverState *bs, bool read_only,
28554a32bfeSKevin Wolf                        bool ignore_allow_rdw, Error **errp)
286fe5241bfSJeff Cody {
287384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
288384a48fbSEmanuele Giuseppe Esposito 
289e2b8247aSJeff Cody     /* Do not set read_only if copy_on_read is enabled */
290e2b8247aSJeff Cody     if (bs->copy_on_read && read_only) {
291e2b8247aSJeff Cody         error_setg(errp, "Can't set node '%s' to r/o with copy-on-read enabled",
292e2b8247aSJeff Cody                    bdrv_get_device_or_node_name(bs));
293e2b8247aSJeff Cody         return -EINVAL;
294e2b8247aSJeff Cody     }
295e2b8247aSJeff Cody 
296d6fcdf06SJeff Cody     /* Do not clear read_only if it is prohibited */
29754a32bfeSKevin Wolf     if (!read_only && !(bs->open_flags & BDRV_O_ALLOW_RDWR) &&
29854a32bfeSKevin Wolf         !ignore_allow_rdw)
29954a32bfeSKevin Wolf     {
300d6fcdf06SJeff Cody         error_setg(errp, "Node '%s' is read only",
301d6fcdf06SJeff Cody                    bdrv_get_device_or_node_name(bs));
302d6fcdf06SJeff Cody         return -EPERM;
303d6fcdf06SJeff Cody     }
304d6fcdf06SJeff Cody 
30545803a03SJeff Cody     return 0;
30645803a03SJeff Cody }
30745803a03SJeff Cody 
308eaa2410fSKevin Wolf /*
309eaa2410fSKevin Wolf  * Called by a driver that can only provide a read-only image.
310eaa2410fSKevin Wolf  *
311eaa2410fSKevin Wolf  * Returns 0 if the node is already read-only or it could switch the node to
312eaa2410fSKevin Wolf  * read-only because BDRV_O_AUTO_RDONLY is set.
313eaa2410fSKevin Wolf  *
314eaa2410fSKevin Wolf  * Returns -EACCES if the node is read-write and BDRV_O_AUTO_RDONLY is not set
315eaa2410fSKevin Wolf  * or bdrv_can_set_read_only() forbids making the node read-only. If @errmsg
316eaa2410fSKevin Wolf  * is not NULL, it is used as the error message for the Error object.
317eaa2410fSKevin Wolf  */
318eaa2410fSKevin Wolf int bdrv_apply_auto_read_only(BlockDriverState *bs, const char *errmsg,
319eaa2410fSKevin Wolf                               Error **errp)
32045803a03SJeff Cody {
32145803a03SJeff Cody     int ret = 0;
322384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
32345803a03SJeff Cody 
324eaa2410fSKevin Wolf     if (!(bs->open_flags & BDRV_O_RDWR)) {
325eaa2410fSKevin Wolf         return 0;
326eaa2410fSKevin Wolf     }
327eaa2410fSKevin Wolf     if (!(bs->open_flags & BDRV_O_AUTO_RDONLY)) {
328eaa2410fSKevin Wolf         goto fail;
329eaa2410fSKevin Wolf     }
330eaa2410fSKevin Wolf 
331eaa2410fSKevin Wolf     ret = bdrv_can_set_read_only(bs, true, false, NULL);
33245803a03SJeff Cody     if (ret < 0) {
333eaa2410fSKevin Wolf         goto fail;
33445803a03SJeff Cody     }
33545803a03SJeff Cody 
336eeae6a59SKevin Wolf     bs->open_flags &= ~BDRV_O_RDWR;
337eeae6a59SKevin Wolf 
338e2b8247aSJeff Cody     return 0;
339eaa2410fSKevin Wolf 
340eaa2410fSKevin Wolf fail:
341eaa2410fSKevin Wolf     error_setg(errp, "%s", errmsg ?: "Image is read-only");
342eaa2410fSKevin Wolf     return -EACCES;
343fe5241bfSJeff Cody }
344fe5241bfSJeff Cody 
345645ae7d8SMax Reitz /*
346645ae7d8SMax Reitz  * If @backing is empty, this function returns NULL without setting
347645ae7d8SMax Reitz  * @errp.  In all other cases, NULL will only be returned with @errp
348645ae7d8SMax Reitz  * set.
349645ae7d8SMax Reitz  *
350645ae7d8SMax Reitz  * Therefore, a return value of NULL without @errp set means that
351645ae7d8SMax Reitz  * there is no backing file; if @errp is set, there is one but its
352645ae7d8SMax Reitz  * absolute filename cannot be generated.
353645ae7d8SMax Reitz  */
354645ae7d8SMax Reitz char *bdrv_get_full_backing_filename_from_filename(const char *backed,
3550a82855aSMax Reitz                                                    const char *backing,
3569f07429eSMax Reitz                                                    Error **errp)
3570a82855aSMax Reitz {
358645ae7d8SMax Reitz     if (backing[0] == '\0') {
359645ae7d8SMax Reitz         return NULL;
360645ae7d8SMax Reitz     } else if (path_has_protocol(backing) || path_is_absolute(backing)) {
361645ae7d8SMax Reitz         return g_strdup(backing);
3629f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
3639f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
3649f07429eSMax Reitz                    backed);
365645ae7d8SMax Reitz         return NULL;
3660a82855aSMax Reitz     } else {
367645ae7d8SMax Reitz         return path_combine(backed, backing);
3680a82855aSMax Reitz     }
3690a82855aSMax Reitz }
3700a82855aSMax Reitz 
3719f4793d8SMax Reitz /*
3729f4793d8SMax Reitz  * If @filename is empty or NULL, this function returns NULL without
3739f4793d8SMax Reitz  * setting @errp.  In all other cases, NULL will only be returned with
3749f4793d8SMax Reitz  * @errp set.
3759f4793d8SMax Reitz  */
376b7cfc7d5SKevin Wolf static char * GRAPH_RDLOCK
377b7cfc7d5SKevin Wolf bdrv_make_absolute_filename(BlockDriverState *relative_to,
3789f4793d8SMax Reitz                             const char *filename, Error **errp)
3799f4793d8SMax Reitz {
3808df68616SMax Reitz     char *dir, *full_name;
3819f4793d8SMax Reitz 
3828df68616SMax Reitz     if (!filename || filename[0] == '\0') {
3838df68616SMax Reitz         return NULL;
3848df68616SMax Reitz     } else if (path_has_protocol(filename) || path_is_absolute(filename)) {
3858df68616SMax Reitz         return g_strdup(filename);
3868df68616SMax Reitz     }
3879f4793d8SMax Reitz 
3888df68616SMax Reitz     dir = bdrv_dirname(relative_to, errp);
3898df68616SMax Reitz     if (!dir) {
3908df68616SMax Reitz         return NULL;
3918df68616SMax Reitz     }
3929f4793d8SMax Reitz 
3938df68616SMax Reitz     full_name = g_strconcat(dir, filename, NULL);
3948df68616SMax Reitz     g_free(dir);
3958df68616SMax Reitz     return full_name;
3969f4793d8SMax Reitz }
3979f4793d8SMax Reitz 
3986b6833c1SMax Reitz char *bdrv_get_full_backing_filename(BlockDriverState *bs, Error **errp)
399dc5a1371SPaolo Bonzini {
400f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4019f4793d8SMax Reitz     return bdrv_make_absolute_filename(bs, bs->backing_file, errp);
402dc5a1371SPaolo Bonzini }
403dc5a1371SPaolo Bonzini 
4040eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
4050eb7217eSStefan Hajnoczi {
406a15f08dcSPhilippe Mathieu-Daudé     assert(bdrv->format_name);
407f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4088a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
409ea2384d3Sbellard }
410b338082bSbellard 
411e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
412e4e9986bSMarkus Armbruster {
413e4e9986bSMarkus Armbruster     BlockDriverState *bs;
414e4e9986bSMarkus Armbruster     int i;
415e4e9986bSMarkus Armbruster 
416f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
417f791bf7fSEmanuele Giuseppe Esposito 
4185839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
419e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
420fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
421fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
422fbe40ff7SFam Zheng     }
423fa9185fcSStefan Hajnoczi     qemu_mutex_init(&bs->reqs_lock);
4242119882cSPaolo Bonzini     qemu_mutex_init(&bs->dirty_bitmap_mutex);
4259fcb0251SFam Zheng     bs->refcnt = 1;
426dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
427d7d512f6SPaolo Bonzini 
4283ff2f67aSEvgeny Yakovlev     qemu_co_queue_init(&bs->flush_queue);
4293ff2f67aSEvgeny Yakovlev 
4300bc329fbSHanna Reitz     qemu_co_mutex_init(&bs->bsc_modify_lock);
4310bc329fbSHanna Reitz     bs->block_status_cache = g_new0(BdrvBlockStatusCache, 1);
4320bc329fbSHanna Reitz 
4330f12264eSKevin Wolf     for (i = 0; i < bdrv_drain_all_count; i++) {
4340f12264eSKevin Wolf         bdrv_drained_begin(bs);
4350f12264eSKevin Wolf     }
4360f12264eSKevin Wolf 
4372c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
4382c1d04e0SMax Reitz 
439b338082bSbellard     return bs;
440b338082bSbellard }
441b338082bSbellard 
44288d88798SMarc Mari static BlockDriver *bdrv_do_find_format(const char *format_name)
443ea2384d3Sbellard {
444ea2384d3Sbellard     BlockDriver *drv1;
445bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
44688d88798SMarc Mari 
4478a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
4488a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
449ea2384d3Sbellard             return drv1;
450ea2384d3Sbellard         }
4518a22f02aSStefan Hajnoczi     }
45288d88798SMarc Mari 
453ea2384d3Sbellard     return NULL;
454ea2384d3Sbellard }
455ea2384d3Sbellard 
45688d88798SMarc Mari BlockDriver *bdrv_find_format(const char *format_name)
45788d88798SMarc Mari {
45888d88798SMarc Mari     BlockDriver *drv1;
45988d88798SMarc Mari     int i;
46088d88798SMarc Mari 
461f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
462f791bf7fSEmanuele Giuseppe Esposito 
46388d88798SMarc Mari     drv1 = bdrv_do_find_format(format_name);
46488d88798SMarc Mari     if (drv1) {
46588d88798SMarc Mari         return drv1;
46688d88798SMarc Mari     }
46788d88798SMarc Mari 
46888d88798SMarc Mari     /* The driver isn't registered, maybe we need to load a module */
46988d88798SMarc Mari     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
47088d88798SMarc Mari         if (!strcmp(block_driver_modules[i].format_name, format_name)) {
471c551fb0bSClaudio Fontana             Error *local_err = NULL;
472c551fb0bSClaudio Fontana             int rv = block_module_load(block_driver_modules[i].library_name,
473c551fb0bSClaudio Fontana                                        &local_err);
474c551fb0bSClaudio Fontana             if (rv > 0) {
475c551fb0bSClaudio Fontana                 return bdrv_do_find_format(format_name);
476c551fb0bSClaudio Fontana             } else if (rv < 0) {
477c551fb0bSClaudio Fontana                 error_report_err(local_err);
478c551fb0bSClaudio Fontana             }
47988d88798SMarc Mari             break;
48088d88798SMarc Mari         }
48188d88798SMarc Mari     }
482c551fb0bSClaudio Fontana     return NULL;
48388d88798SMarc Mari }
48488d88798SMarc Mari 
4859ac404c5SAndrey Shinkevich static int bdrv_format_is_whitelisted(const char *format_name, bool read_only)
486eb852011SMarkus Armbruster {
487b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
488b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
489859aef02SPaolo Bonzini         NULL
490b64ec4e4SFam Zheng     };
491b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
492b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
493859aef02SPaolo Bonzini         NULL
494eb852011SMarkus Armbruster     };
495eb852011SMarkus Armbruster     const char **p;
496eb852011SMarkus Armbruster 
497b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
498eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
499b64ec4e4SFam Zheng     }
500eb852011SMarkus Armbruster 
501b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
5029ac404c5SAndrey Shinkevich         if (!strcmp(format_name, *p)) {
503eb852011SMarkus Armbruster             return 1;
504eb852011SMarkus Armbruster         }
505eb852011SMarkus Armbruster     }
506b64ec4e4SFam Zheng     if (read_only) {
507b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
5089ac404c5SAndrey Shinkevich             if (!strcmp(format_name, *p)) {
509b64ec4e4SFam Zheng                 return 1;
510b64ec4e4SFam Zheng             }
511b64ec4e4SFam Zheng         }
512b64ec4e4SFam Zheng     }
513eb852011SMarkus Armbruster     return 0;
514eb852011SMarkus Armbruster }
515eb852011SMarkus Armbruster 
5169ac404c5SAndrey Shinkevich int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
5179ac404c5SAndrey Shinkevich {
518f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5199ac404c5SAndrey Shinkevich     return bdrv_format_is_whitelisted(drv->format_name, read_only);
5209ac404c5SAndrey Shinkevich }
5219ac404c5SAndrey Shinkevich 
522e6ff69bfSDaniel P. Berrange bool bdrv_uses_whitelist(void)
523e6ff69bfSDaniel P. Berrange {
524e6ff69bfSDaniel P. Berrange     return use_bdrv_whitelist;
525e6ff69bfSDaniel P. Berrange }
526e6ff69bfSDaniel P. Berrange 
5275b7e1542SZhi Yong Wu typedef struct CreateCo {
5285b7e1542SZhi Yong Wu     BlockDriver *drv;
5295b7e1542SZhi Yong Wu     char *filename;
53083d0521aSChunyan Liu     QemuOpts *opts;
5315b7e1542SZhi Yong Wu     int ret;
532cc84d90fSMax Reitz     Error *err;
5335b7e1542SZhi Yong Wu } CreateCo;
5345b7e1542SZhi Yong Wu 
535741443ebSEmanuele Giuseppe Esposito int coroutine_fn bdrv_co_create(BlockDriver *drv, const char *filename,
53684bdf21fSEmanuele Giuseppe Esposito                                 QemuOpts *opts, Error **errp)
53784bdf21fSEmanuele Giuseppe Esposito {
53846ff64a8SZhao Liu     ERRP_GUARD();
53984bdf21fSEmanuele Giuseppe Esposito     int ret;
54084bdf21fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
54184bdf21fSEmanuele Giuseppe Esposito 
54284bdf21fSEmanuele Giuseppe Esposito     if (!drv->bdrv_co_create_opts) {
54384bdf21fSEmanuele Giuseppe Esposito         error_setg(errp, "Driver '%s' does not support image creation",
54484bdf21fSEmanuele Giuseppe Esposito                    drv->format_name);
54584bdf21fSEmanuele Giuseppe Esposito         return -ENOTSUP;
54684bdf21fSEmanuele Giuseppe Esposito     }
54784bdf21fSEmanuele Giuseppe Esposito 
54884bdf21fSEmanuele Giuseppe Esposito     ret = drv->bdrv_co_create_opts(drv, filename, opts, errp);
54984bdf21fSEmanuele Giuseppe Esposito     if (ret < 0 && !*errp) {
55084bdf21fSEmanuele Giuseppe Esposito         error_setg_errno(errp, -ret, "Could not create image");
55184bdf21fSEmanuele Giuseppe Esposito     }
55284bdf21fSEmanuele Giuseppe Esposito 
55384bdf21fSEmanuele Giuseppe Esposito     return ret;
55484bdf21fSEmanuele Giuseppe Esposito }
55584bdf21fSEmanuele Giuseppe Esposito 
556fd17146cSMax Reitz /**
557fd17146cSMax Reitz  * Helper function for bdrv_create_file_fallback(): Resize @blk to at
558fd17146cSMax Reitz  * least the given @minimum_size.
559fd17146cSMax Reitz  *
560fd17146cSMax Reitz  * On success, return @blk's actual length.
561fd17146cSMax Reitz  * Otherwise, return -errno.
562fd17146cSMax Reitz  */
56384569a7dSPaolo Bonzini static int64_t coroutine_fn GRAPH_UNLOCKED
56484569a7dSPaolo Bonzini create_file_fallback_truncate(BlockBackend *blk, int64_t minimum_size,
56584569a7dSPaolo Bonzini                               Error **errp)
566fd17146cSMax Reitz {
567fd17146cSMax Reitz     Error *local_err = NULL;
568fd17146cSMax Reitz     int64_t size;
569fd17146cSMax Reitz     int ret;
570fd17146cSMax Reitz 
571bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
572bdb73476SEmanuele Giuseppe Esposito 
57384569a7dSPaolo Bonzini     ret = blk_co_truncate(blk, minimum_size, false, PREALLOC_MODE_OFF, 0,
5748c6242b6SKevin Wolf                           &local_err);
575fd17146cSMax Reitz     if (ret < 0 && ret != -ENOTSUP) {
576fd17146cSMax Reitz         error_propagate(errp, local_err);
577fd17146cSMax Reitz         return ret;
578fd17146cSMax Reitz     }
579fd17146cSMax Reitz 
58084569a7dSPaolo Bonzini     size = blk_co_getlength(blk);
581fd17146cSMax Reitz     if (size < 0) {
582fd17146cSMax Reitz         error_free(local_err);
583fd17146cSMax Reitz         error_setg_errno(errp, -size,
584fd17146cSMax Reitz                          "Failed to inquire the new image file's length");
585fd17146cSMax Reitz         return size;
586fd17146cSMax Reitz     }
587fd17146cSMax Reitz 
588fd17146cSMax Reitz     if (size < minimum_size) {
589fd17146cSMax Reitz         /* Need to grow the image, but we failed to do that */
590fd17146cSMax Reitz         error_propagate(errp, local_err);
591fd17146cSMax Reitz         return -ENOTSUP;
592fd17146cSMax Reitz     }
593fd17146cSMax Reitz 
594fd17146cSMax Reitz     error_free(local_err);
595fd17146cSMax Reitz     local_err = NULL;
596fd17146cSMax Reitz 
597fd17146cSMax Reitz     return size;
598fd17146cSMax Reitz }
599fd17146cSMax Reitz 
600fd17146cSMax Reitz /**
601fd17146cSMax Reitz  * Helper function for bdrv_create_file_fallback(): Zero the first
602fd17146cSMax Reitz  * sector to remove any potentially pre-existing image header.
603fd17146cSMax Reitz  */
604881a4c55SPaolo Bonzini static int coroutine_fn
605881a4c55SPaolo Bonzini create_file_fallback_zero_first_sector(BlockBackend *blk,
606fd17146cSMax Reitz                                        int64_t current_size,
607fd17146cSMax Reitz                                        Error **errp)
608fd17146cSMax Reitz {
609fd17146cSMax Reitz     int64_t bytes_to_clear;
610fd17146cSMax Reitz     int ret;
611fd17146cSMax Reitz 
612bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
613bdb73476SEmanuele Giuseppe Esposito 
614fd17146cSMax Reitz     bytes_to_clear = MIN(current_size, BDRV_SECTOR_SIZE);
615fd17146cSMax Reitz     if (bytes_to_clear) {
616ce47ff20SAlberto Faria         ret = blk_co_pwrite_zeroes(blk, 0, bytes_to_clear, BDRV_REQ_MAY_UNMAP);
617fd17146cSMax Reitz         if (ret < 0) {
618fd17146cSMax Reitz             error_setg_errno(errp, -ret,
619fd17146cSMax Reitz                              "Failed to clear the new image's first sector");
620fd17146cSMax Reitz             return ret;
621fd17146cSMax Reitz         }
622fd17146cSMax Reitz     }
623fd17146cSMax Reitz 
624fd17146cSMax Reitz     return 0;
625fd17146cSMax Reitz }
626fd17146cSMax Reitz 
6275a5e7f8cSMaxim Levitsky /**
6285a5e7f8cSMaxim Levitsky  * Simple implementation of bdrv_co_create_opts for protocol drivers
6295a5e7f8cSMaxim Levitsky  * which only support creation via opening a file
6305a5e7f8cSMaxim Levitsky  * (usually existing raw storage device)
6315a5e7f8cSMaxim Levitsky  */
6325a5e7f8cSMaxim Levitsky int coroutine_fn bdrv_co_create_opts_simple(BlockDriver *drv,
6335a5e7f8cSMaxim Levitsky                                             const char *filename,
6345a5e7f8cSMaxim Levitsky                                             QemuOpts *opts,
6355a5e7f8cSMaxim Levitsky                                             Error **errp)
636fd17146cSMax Reitz {
6377b22e055SZhao Liu     ERRP_GUARD();
638fd17146cSMax Reitz     BlockBackend *blk;
639eeea1faaSMax Reitz     QDict *options;
640fd17146cSMax Reitz     int64_t size = 0;
641fd17146cSMax Reitz     char *buf = NULL;
642fd17146cSMax Reitz     PreallocMode prealloc;
643fd17146cSMax Reitz     Error *local_err = NULL;
644fd17146cSMax Reitz     int ret;
645fd17146cSMax Reitz 
646b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
647b4ad82aaSEmanuele Giuseppe Esposito 
648fd17146cSMax Reitz     size = qemu_opt_get_size_del(opts, BLOCK_OPT_SIZE, 0);
649fd17146cSMax Reitz     buf = qemu_opt_get_del(opts, BLOCK_OPT_PREALLOC);
650fd17146cSMax Reitz     prealloc = qapi_enum_parse(&PreallocMode_lookup, buf,
651fd17146cSMax Reitz                                PREALLOC_MODE_OFF, &local_err);
652fd17146cSMax Reitz     g_free(buf);
653fd17146cSMax Reitz     if (local_err) {
654fd17146cSMax Reitz         error_propagate(errp, local_err);
655fd17146cSMax Reitz         return -EINVAL;
656fd17146cSMax Reitz     }
657fd17146cSMax Reitz 
658fd17146cSMax Reitz     if (prealloc != PREALLOC_MODE_OFF) {
659fd17146cSMax Reitz         error_setg(errp, "Unsupported preallocation mode '%s'",
660fd17146cSMax Reitz                    PreallocMode_str(prealloc));
661fd17146cSMax Reitz         return -ENOTSUP;
662fd17146cSMax Reitz     }
663fd17146cSMax Reitz 
664eeea1faaSMax Reitz     options = qdict_new();
665fd17146cSMax Reitz     qdict_put_str(options, "driver", drv->format_name);
666fd17146cSMax Reitz 
667be1a732cSKevin Wolf     blk = blk_co_new_open(filename, NULL, options,
668fd17146cSMax Reitz                           BDRV_O_RDWR | BDRV_O_RESIZE, errp);
669fd17146cSMax Reitz     if (!blk) {
67081624867SHanna Czenczek         error_prepend(errp, "Protocol driver '%s' does not support creating "
67181624867SHanna Czenczek                       "new images, so an existing image must be selected as "
67281624867SHanna Czenczek                       "the target; however, opening the given target as an "
67381624867SHanna Czenczek                       "existing image failed: ",
674fd17146cSMax Reitz                       drv->format_name);
675fd17146cSMax Reitz         return -EINVAL;
676fd17146cSMax Reitz     }
677fd17146cSMax Reitz 
678fd17146cSMax Reitz     size = create_file_fallback_truncate(blk, size, errp);
679fd17146cSMax Reitz     if (size < 0) {
680fd17146cSMax Reitz         ret = size;
681fd17146cSMax Reitz         goto out;
682fd17146cSMax Reitz     }
683fd17146cSMax Reitz 
684fd17146cSMax Reitz     ret = create_file_fallback_zero_first_sector(blk, size, errp);
685fd17146cSMax Reitz     if (ret < 0) {
686fd17146cSMax Reitz         goto out;
687fd17146cSMax Reitz     }
688fd17146cSMax Reitz 
689fd17146cSMax Reitz     ret = 0;
690fd17146cSMax Reitz out:
691b2ab5f54SKevin Wolf     blk_co_unref(blk);
692fd17146cSMax Reitz     return ret;
693fd17146cSMax Reitz }
694fd17146cSMax Reitz 
6952475a0d0SEmanuele Giuseppe Esposito int coroutine_fn bdrv_co_create_file(const char *filename, QemuOpts *opts,
6962475a0d0SEmanuele Giuseppe Esposito                                      Error **errp)
69784a12e66SChristoph Hellwig {
698729222afSStefano Garzarella     QemuOpts *protocol_opts;
69984a12e66SChristoph Hellwig     BlockDriver *drv;
700729222afSStefano Garzarella     QDict *qdict;
701729222afSStefano Garzarella     int ret;
70284a12e66SChristoph Hellwig 
703f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
704f791bf7fSEmanuele Giuseppe Esposito 
705b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
70684a12e66SChristoph Hellwig     if (drv == NULL) {
70716905d71SStefan Hajnoczi         return -ENOENT;
70884a12e66SChristoph Hellwig     }
70984a12e66SChristoph Hellwig 
710729222afSStefano Garzarella     if (!drv->create_opts) {
711729222afSStefano Garzarella         error_setg(errp, "Driver '%s' does not support image creation",
712729222afSStefano Garzarella                    drv->format_name);
713729222afSStefano Garzarella         return -ENOTSUP;
714729222afSStefano Garzarella     }
715729222afSStefano Garzarella 
716729222afSStefano Garzarella     /*
717729222afSStefano Garzarella      * 'opts' contains a QemuOptsList with a combination of format and protocol
718729222afSStefano Garzarella      * default values.
719729222afSStefano Garzarella      *
720729222afSStefano Garzarella      * The format properly removes its options, but the default values remain
721729222afSStefano Garzarella      * in 'opts->list'.  So if the protocol has options with the same name
722729222afSStefano Garzarella      * (e.g. rbd has 'cluster_size' as qcow2), it will see the default values
723729222afSStefano Garzarella      * of the format, since for overlapping options, the format wins.
724729222afSStefano Garzarella      *
725729222afSStefano Garzarella      * To avoid this issue, lets convert QemuOpts to QDict, in this way we take
726729222afSStefano Garzarella      * only the set options, and then convert it back to QemuOpts, using the
727729222afSStefano Garzarella      * create_opts of the protocol. So the new QemuOpts, will contain only the
728729222afSStefano Garzarella      * protocol defaults.
729729222afSStefano Garzarella      */
730729222afSStefano Garzarella     qdict = qemu_opts_to_qdict(opts, NULL);
731729222afSStefano Garzarella     protocol_opts = qemu_opts_from_qdict(drv->create_opts, qdict, errp);
732729222afSStefano Garzarella     if (protocol_opts == NULL) {
733729222afSStefano Garzarella         ret = -EINVAL;
734729222afSStefano Garzarella         goto out;
735729222afSStefano Garzarella     }
736729222afSStefano Garzarella 
7372475a0d0SEmanuele Giuseppe Esposito     ret = bdrv_co_create(drv, filename, protocol_opts, errp);
738729222afSStefano Garzarella out:
739729222afSStefano Garzarella     qemu_opts_del(protocol_opts);
740729222afSStefano Garzarella     qobject_unref(qdict);
741729222afSStefano Garzarella     return ret;
74284a12e66SChristoph Hellwig }
74384a12e66SChristoph Hellwig 
744e1d7f8bbSDaniel Henrique Barboza int coroutine_fn bdrv_co_delete_file(BlockDriverState *bs, Error **errp)
745e1d7f8bbSDaniel Henrique Barboza {
746e1d7f8bbSDaniel Henrique Barboza     Error *local_err = NULL;
747e1d7f8bbSDaniel Henrique Barboza     int ret;
748e1d7f8bbSDaniel Henrique Barboza 
749384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
750e1d7f8bbSDaniel Henrique Barboza     assert(bs != NULL);
75148aef794SKevin Wolf     assert_bdrv_graph_readable();
752e1d7f8bbSDaniel Henrique Barboza 
753e1d7f8bbSDaniel Henrique Barboza     if (!bs->drv) {
754e1d7f8bbSDaniel Henrique Barboza         error_setg(errp, "Block node '%s' is not opened", bs->filename);
755e1d7f8bbSDaniel Henrique Barboza         return -ENOMEDIUM;
756e1d7f8bbSDaniel Henrique Barboza     }
757e1d7f8bbSDaniel Henrique Barboza 
758e1d7f8bbSDaniel Henrique Barboza     if (!bs->drv->bdrv_co_delete_file) {
759e1d7f8bbSDaniel Henrique Barboza         error_setg(errp, "Driver '%s' does not support image deletion",
760e1d7f8bbSDaniel Henrique Barboza                    bs->drv->format_name);
761e1d7f8bbSDaniel Henrique Barboza         return -ENOTSUP;
762e1d7f8bbSDaniel Henrique Barboza     }
763e1d7f8bbSDaniel Henrique Barboza 
764e1d7f8bbSDaniel Henrique Barboza     ret = bs->drv->bdrv_co_delete_file(bs, &local_err);
765e1d7f8bbSDaniel Henrique Barboza     if (ret < 0) {
766e1d7f8bbSDaniel Henrique Barboza         error_propagate(errp, local_err);
767e1d7f8bbSDaniel Henrique Barboza     }
768e1d7f8bbSDaniel Henrique Barboza 
769e1d7f8bbSDaniel Henrique Barboza     return ret;
770e1d7f8bbSDaniel Henrique Barboza }
771e1d7f8bbSDaniel Henrique Barboza 
772a890f08eSMaxim Levitsky void coroutine_fn bdrv_co_delete_file_noerr(BlockDriverState *bs)
773a890f08eSMaxim Levitsky {
774a890f08eSMaxim Levitsky     Error *local_err = NULL;
775a890f08eSMaxim Levitsky     int ret;
776384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
777a890f08eSMaxim Levitsky 
778a890f08eSMaxim Levitsky     if (!bs) {
779a890f08eSMaxim Levitsky         return;
780a890f08eSMaxim Levitsky     }
781a890f08eSMaxim Levitsky 
782a890f08eSMaxim Levitsky     ret = bdrv_co_delete_file(bs, &local_err);
783a890f08eSMaxim Levitsky     /*
784a890f08eSMaxim Levitsky      * ENOTSUP will happen if the block driver doesn't support
785a890f08eSMaxim Levitsky      * the 'bdrv_co_delete_file' interface. This is a predictable
786a890f08eSMaxim Levitsky      * scenario and shouldn't be reported back to the user.
787a890f08eSMaxim Levitsky      */
788a890f08eSMaxim Levitsky     if (ret == -ENOTSUP) {
789a890f08eSMaxim Levitsky         error_free(local_err);
790a890f08eSMaxim Levitsky     } else if (ret < 0) {
791a890f08eSMaxim Levitsky         error_report_err(local_err);
792a890f08eSMaxim Levitsky     }
793a890f08eSMaxim Levitsky }
794a890f08eSMaxim Levitsky 
795892b7de8SEkaterina Tumanova /**
796892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
797892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
798892b7de8SEkaterina Tumanova  * On failure return -errno.
799892b7de8SEkaterina Tumanova  * @bs must not be empty.
800892b7de8SEkaterina Tumanova  */
801892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
802892b7de8SEkaterina Tumanova {
803892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
80493393e69SMax Reitz     BlockDriverState *filtered = bdrv_filter_bs(bs);
805f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
806892b7de8SEkaterina Tumanova 
807892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
808892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
80993393e69SMax Reitz     } else if (filtered) {
81093393e69SMax Reitz         return bdrv_probe_blocksizes(filtered, bsz);
811892b7de8SEkaterina Tumanova     }
812892b7de8SEkaterina Tumanova 
813892b7de8SEkaterina Tumanova     return -ENOTSUP;
814892b7de8SEkaterina Tumanova }
815892b7de8SEkaterina Tumanova 
816892b7de8SEkaterina Tumanova /**
817892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
818892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
819892b7de8SEkaterina Tumanova  * On failure return -errno.
820892b7de8SEkaterina Tumanova  * @bs must not be empty.
821892b7de8SEkaterina Tumanova  */
822892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
823892b7de8SEkaterina Tumanova {
824892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
825f5a3a270SKevin Wolf     BlockDriverState *filtered;
826f5a3a270SKevin Wolf 
827f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
828f5a3a270SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
829892b7de8SEkaterina Tumanova 
830892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
831892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
832f5a3a270SKevin Wolf     }
833f5a3a270SKevin Wolf 
834f5a3a270SKevin Wolf     filtered = bdrv_filter_bs(bs);
835f5a3a270SKevin Wolf     if (filtered) {
83693393e69SMax Reitz         return bdrv_probe_geometry(filtered, geo);
837892b7de8SEkaterina Tumanova     }
838892b7de8SEkaterina Tumanova 
839892b7de8SEkaterina Tumanova     return -ENOTSUP;
840892b7de8SEkaterina Tumanova }
841892b7de8SEkaterina Tumanova 
842eba25057SJim Meyering /*
843eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
84469fbfff9SBin Meng  * Return the actual file name used upon success, otherwise NULL.
84569fbfff9SBin Meng  * This string should be freed with g_free() when not needed any longer.
84669fbfff9SBin Meng  *
84769fbfff9SBin Meng  * Note: creating a temporary file for the caller to (re)open is
84869fbfff9SBin Meng  * inherently racy. Use g_file_open_tmp() instead whenever practical.
849eba25057SJim Meyering  */
85069fbfff9SBin Meng char *create_tmp_file(Error **errp)
851eba25057SJim Meyering {
852ea2384d3Sbellard     int fd;
8537ccfb2ebSblueswir1     const char *tmpdir;
85469fbfff9SBin Meng     g_autofree char *filename = NULL;
85569fbfff9SBin Meng 
85669fbfff9SBin Meng     tmpdir = g_get_tmp_dir();
85769fbfff9SBin Meng #ifndef _WIN32
85869fbfff9SBin Meng     /*
85969fbfff9SBin Meng      * See commit 69bef79 ("block: use /var/tmp instead of /tmp for -snapshot")
86069fbfff9SBin Meng      *
86169fbfff9SBin Meng      * This function is used to create temporary disk images (like -snapshot),
86269fbfff9SBin Meng      * so the files can become very large. /tmp is often a tmpfs where as
86369fbfff9SBin Meng      * /var/tmp is usually on a disk, so more appropriate for disk images.
86469fbfff9SBin Meng      */
86569fbfff9SBin Meng     if (!g_strcmp0(tmpdir, "/tmp")) {
86669bef793SAmit Shah         tmpdir = "/var/tmp";
86769bef793SAmit Shah     }
868d5249393Sbellard #endif
86969fbfff9SBin Meng 
87069fbfff9SBin Meng     filename = g_strdup_printf("%s/vl.XXXXXX", tmpdir);
87169fbfff9SBin Meng     fd = g_mkstemp(filename);
872ea2384d3Sbellard     if (fd < 0) {
87369fbfff9SBin Meng         error_setg_errno(errp, errno, "Could not open temporary file '%s'",
87469fbfff9SBin Meng                          filename);
87569fbfff9SBin Meng         return NULL;
876ea2384d3Sbellard     }
8776b6471eeSBin Meng     close(fd);
87869fbfff9SBin Meng 
87969fbfff9SBin Meng     return g_steal_pointer(&filename);
880eba25057SJim Meyering }
881ea2384d3Sbellard 
882f3a5d3f8SChristoph Hellwig /*
883f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
884f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
885f3a5d3f8SChristoph Hellwig  */
886f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
887f3a5d3f8SChristoph Hellwig {
888508c7cb3SChristoph Hellwig     int score_max = 0, score;
889508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
890bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
891f3a5d3f8SChristoph Hellwig 
8928a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
893508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
894508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
895508c7cb3SChristoph Hellwig             if (score > score_max) {
896508c7cb3SChristoph Hellwig                 score_max = score;
897508c7cb3SChristoph Hellwig                 drv = d;
898f3a5d3f8SChristoph Hellwig             }
899508c7cb3SChristoph Hellwig         }
900f3a5d3f8SChristoph Hellwig     }
901f3a5d3f8SChristoph Hellwig 
902508c7cb3SChristoph Hellwig     return drv;
903f3a5d3f8SChristoph Hellwig }
904f3a5d3f8SChristoph Hellwig 
90588d88798SMarc Mari static BlockDriver *bdrv_do_find_protocol(const char *protocol)
90688d88798SMarc Mari {
90788d88798SMarc Mari     BlockDriver *drv1;
908bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
90988d88798SMarc Mari 
91088d88798SMarc Mari     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
91188d88798SMarc Mari         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
91288d88798SMarc Mari             return drv1;
91388d88798SMarc Mari         }
91488d88798SMarc Mari     }
91588d88798SMarc Mari 
91688d88798SMarc Mari     return NULL;
91788d88798SMarc Mari }
91888d88798SMarc Mari 
91998289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
920b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
921b65a5e12SMax Reitz                                 Error **errp)
92284a12e66SChristoph Hellwig {
92384a12e66SChristoph Hellwig     BlockDriver *drv1;
92484a12e66SChristoph Hellwig     char protocol[128];
92584a12e66SChristoph Hellwig     int len;
92684a12e66SChristoph Hellwig     const char *p;
92788d88798SMarc Mari     int i;
92884a12e66SChristoph Hellwig 
929f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
93066f82ceeSKevin Wolf 
93139508e7aSChristoph Hellwig     /*
93239508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
93339508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
93439508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
93539508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
93639508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
93739508e7aSChristoph Hellwig      */
93884a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
93939508e7aSChristoph Hellwig     if (drv1) {
94084a12e66SChristoph Hellwig         return drv1;
94184a12e66SChristoph Hellwig     }
94239508e7aSChristoph Hellwig 
94398289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
944ef810437SMax Reitz         return &bdrv_file;
94539508e7aSChristoph Hellwig     }
94698289620SKevin Wolf 
9479e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
9489e0b22f4SStefan Hajnoczi     assert(p != NULL);
94984a12e66SChristoph Hellwig     len = p - filename;
95084a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
95184a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
95284a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
95384a12e66SChristoph Hellwig     protocol[len] = '\0';
95488d88798SMarc Mari 
95588d88798SMarc Mari     drv1 = bdrv_do_find_protocol(protocol);
95688d88798SMarc Mari     if (drv1) {
95784a12e66SChristoph Hellwig         return drv1;
95884a12e66SChristoph Hellwig     }
95988d88798SMarc Mari 
96088d88798SMarc Mari     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
96188d88798SMarc Mari         if (block_driver_modules[i].protocol_name &&
96288d88798SMarc Mari             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
963c551fb0bSClaudio Fontana             int rv = block_module_load(block_driver_modules[i].library_name, errp);
964c551fb0bSClaudio Fontana             if (rv > 0) {
965c551fb0bSClaudio Fontana                 drv1 = bdrv_do_find_protocol(protocol);
966c551fb0bSClaudio Fontana             } else if (rv < 0) {
967c551fb0bSClaudio Fontana                 return NULL;
968c551fb0bSClaudio Fontana             }
96988d88798SMarc Mari             break;
97088d88798SMarc Mari         }
97184a12e66SChristoph Hellwig     }
972b65a5e12SMax Reitz 
97388d88798SMarc Mari     if (!drv1) {
974b65a5e12SMax Reitz         error_setg(errp, "Unknown protocol '%s'", protocol);
97588d88798SMarc Mari     }
97688d88798SMarc Mari     return drv1;
97784a12e66SChristoph Hellwig }
97884a12e66SChristoph Hellwig 
979c6684249SMarkus Armbruster /*
980c6684249SMarkus Armbruster  * Guess image format by probing its contents.
981c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
982c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
983c6684249SMarkus Armbruster  *
984c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
9857cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
9867cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
987c6684249SMarkus Armbruster  * @filename    is its filename.
988c6684249SMarkus Armbruster  *
989c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
990c6684249SMarkus Armbruster  * probing score.
991c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
992c6684249SMarkus Armbruster  */
99338f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
994c6684249SMarkus Armbruster                             const char *filename)
995c6684249SMarkus Armbruster {
996c6684249SMarkus Armbruster     int score_max = 0, score;
997c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
998967d7905SEmanuele Giuseppe Esposito     IO_CODE();
999c6684249SMarkus Armbruster 
1000c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
1001c6684249SMarkus Armbruster         if (d->bdrv_probe) {
1002c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
1003c6684249SMarkus Armbruster             if (score > score_max) {
1004c6684249SMarkus Armbruster                 score_max = score;
1005c6684249SMarkus Armbruster                 drv = d;
1006c6684249SMarkus Armbruster             }
1007c6684249SMarkus Armbruster         }
1008c6684249SMarkus Armbruster     }
1009c6684249SMarkus Armbruster 
1010c6684249SMarkus Armbruster     return drv;
1011c6684249SMarkus Armbruster }
1012c6684249SMarkus Armbruster 
10135696c6e3SKevin Wolf static int find_image_format(BlockBackend *file, const char *filename,
101434b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
1015ea2384d3Sbellard {
1016c6684249SMarkus Armbruster     BlockDriver *drv;
10177cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
1018f500a6d3SKevin Wolf     int ret = 0;
1019f8ea0b00SNicholas Bellinger 
1020bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1021bdb73476SEmanuele Giuseppe Esposito 
102208a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
10235696c6e3SKevin Wolf     if (blk_is_sg(file) || !blk_is_inserted(file) || blk_getlength(file) == 0) {
1024ef810437SMax Reitz         *pdrv = &bdrv_raw;
1025c98ac35dSStefan Weil         return ret;
10261a396859SNicholas A. Bellinger     }
1027f8ea0b00SNicholas Bellinger 
1028a9262f55SAlberto Faria     ret = blk_pread(file, 0, sizeof(buf), buf, 0);
1029ea2384d3Sbellard     if (ret < 0) {
103034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
103134b5d2c6SMax Reitz                          "format");
1032c98ac35dSStefan Weil         *pdrv = NULL;
1033c98ac35dSStefan Weil         return ret;
1034ea2384d3Sbellard     }
1035ea2384d3Sbellard 
1036bf5b16faSAlberto Faria     drv = bdrv_probe_all(buf, sizeof(buf), filename);
1037c98ac35dSStefan Weil     if (!drv) {
103834b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
103934b5d2c6SMax Reitz                    "driver found");
1040bf5b16faSAlberto Faria         *pdrv = NULL;
1041bf5b16faSAlberto Faria         return -ENOENT;
1042c98ac35dSStefan Weil     }
1043bf5b16faSAlberto Faria 
1044c98ac35dSStefan Weil     *pdrv = drv;
1045bf5b16faSAlberto Faria     return 0;
1046ea2384d3Sbellard }
1047ea2384d3Sbellard 
104851762288SStefan Hajnoczi /**
104951762288SStefan Hajnoczi  * Set the current 'total_sectors' value
105065a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
105151762288SStefan Hajnoczi  */
1052c86422c5SEmanuele Giuseppe Esposito int coroutine_fn bdrv_co_refresh_total_sectors(BlockDriverState *bs,
1053c86422c5SEmanuele Giuseppe Esposito                                                int64_t hint)
105451762288SStefan Hajnoczi {
105551762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
1056967d7905SEmanuele Giuseppe Esposito     IO_CODE();
10578ab8140aSKevin Wolf     assert_bdrv_graph_readable();
105851762288SStefan Hajnoczi 
1059d470ad42SMax Reitz     if (!drv) {
1060d470ad42SMax Reitz         return -ENOMEDIUM;
1061d470ad42SMax Reitz     }
1062d470ad42SMax Reitz 
1063c86422c5SEmanuele Giuseppe Esposito     /* Do not attempt drv->bdrv_co_getlength() on scsi-generic devices */
1064b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
1065396759adSNicholas Bellinger         return 0;
1066396759adSNicholas Bellinger 
106751762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
1068c86422c5SEmanuele Giuseppe Esposito     if (drv->bdrv_co_getlength) {
1069c86422c5SEmanuele Giuseppe Esposito         int64_t length = drv->bdrv_co_getlength(bs);
107051762288SStefan Hajnoczi         if (length < 0) {
107151762288SStefan Hajnoczi             return length;
107251762288SStefan Hajnoczi         }
10737e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
107451762288SStefan Hajnoczi     }
107551762288SStefan Hajnoczi 
107651762288SStefan Hajnoczi     bs->total_sectors = hint;
10778b117001SVladimir Sementsov-Ogievskiy 
10788b117001SVladimir Sementsov-Ogievskiy     if (bs->total_sectors * BDRV_SECTOR_SIZE > BDRV_MAX_LENGTH) {
10798b117001SVladimir Sementsov-Ogievskiy         return -EFBIG;
10808b117001SVladimir Sementsov-Ogievskiy     }
10818b117001SVladimir Sementsov-Ogievskiy 
108251762288SStefan Hajnoczi     return 0;
108351762288SStefan Hajnoczi }
108451762288SStefan Hajnoczi 
1085c3993cdcSStefan Hajnoczi /**
1086cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
1087cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
1088cddff5baSKevin Wolf  */
1089cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
1090cddff5baSKevin Wolf                               QDict *old_options)
1091cddff5baSKevin Wolf {
1092da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1093cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
1094cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
1095cddff5baSKevin Wolf     } else {
1096cddff5baSKevin Wolf         qdict_join(options, old_options, false);
1097cddff5baSKevin Wolf     }
1098cddff5baSKevin Wolf }
1099cddff5baSKevin Wolf 
1100543770bdSAlberto Garcia static BlockdevDetectZeroesOptions bdrv_parse_detect_zeroes(QemuOpts *opts,
1101543770bdSAlberto Garcia                                                             int open_flags,
1102543770bdSAlberto Garcia                                                             Error **errp)
1103543770bdSAlberto Garcia {
1104543770bdSAlberto Garcia     Error *local_err = NULL;
1105543770bdSAlberto Garcia     char *value = qemu_opt_get_del(opts, "detect-zeroes");
1106543770bdSAlberto Garcia     BlockdevDetectZeroesOptions detect_zeroes =
1107543770bdSAlberto Garcia         qapi_enum_parse(&BlockdevDetectZeroesOptions_lookup, value,
1108543770bdSAlberto Garcia                         BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF, &local_err);
1109bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1110543770bdSAlberto Garcia     g_free(value);
1111543770bdSAlberto Garcia     if (local_err) {
1112543770bdSAlberto Garcia         error_propagate(errp, local_err);
1113543770bdSAlberto Garcia         return detect_zeroes;
1114543770bdSAlberto Garcia     }
1115543770bdSAlberto Garcia 
1116543770bdSAlberto Garcia     if (detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1117543770bdSAlberto Garcia         !(open_flags & BDRV_O_UNMAP))
1118543770bdSAlberto Garcia     {
1119543770bdSAlberto Garcia         error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1120543770bdSAlberto Garcia                    "without setting discard operation to unmap");
1121543770bdSAlberto Garcia     }
1122543770bdSAlberto Garcia 
1123543770bdSAlberto Garcia     return detect_zeroes;
1124543770bdSAlberto Garcia }
1125543770bdSAlberto Garcia 
1126cddff5baSKevin Wolf /**
1127f80f2673SAarushi Mehta  * Set open flags for aio engine
1128f80f2673SAarushi Mehta  *
1129f80f2673SAarushi Mehta  * Return 0 on success, -1 if the engine specified is invalid
1130f80f2673SAarushi Mehta  */
1131f80f2673SAarushi Mehta int bdrv_parse_aio(const char *mode, int *flags)
1132f80f2673SAarushi Mehta {
1133f80f2673SAarushi Mehta     if (!strcmp(mode, "threads")) {
1134f80f2673SAarushi Mehta         /* do nothing, default */
1135f80f2673SAarushi Mehta     } else if (!strcmp(mode, "native")) {
1136f80f2673SAarushi Mehta         *flags |= BDRV_O_NATIVE_AIO;
1137f80f2673SAarushi Mehta #ifdef CONFIG_LINUX_IO_URING
1138f80f2673SAarushi Mehta     } else if (!strcmp(mode, "io_uring")) {
1139f80f2673SAarushi Mehta         *flags |= BDRV_O_IO_URING;
1140f80f2673SAarushi Mehta #endif
1141f80f2673SAarushi Mehta     } else {
1142f80f2673SAarushi Mehta         return -1;
1143f80f2673SAarushi Mehta     }
1144f80f2673SAarushi Mehta 
1145f80f2673SAarushi Mehta     return 0;
1146f80f2673SAarushi Mehta }
1147f80f2673SAarushi Mehta 
1148f80f2673SAarushi Mehta /**
11499e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
11509e8f1835SPaolo Bonzini  *
11519e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
11529e8f1835SPaolo Bonzini  */
11539e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
11549e8f1835SPaolo Bonzini {
11559e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
11569e8f1835SPaolo Bonzini 
11579e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
11589e8f1835SPaolo Bonzini         /* do nothing */
11599e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
11609e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
11619e8f1835SPaolo Bonzini     } else {
11629e8f1835SPaolo Bonzini         return -1;
11639e8f1835SPaolo Bonzini     }
11649e8f1835SPaolo Bonzini 
11659e8f1835SPaolo Bonzini     return 0;
11669e8f1835SPaolo Bonzini }
11679e8f1835SPaolo Bonzini 
11689e8f1835SPaolo Bonzini /**
1169c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
1170c3993cdcSStefan Hajnoczi  *
1171c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
1172c3993cdcSStefan Hajnoczi  */
117353e8ae01SKevin Wolf int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
1174c3993cdcSStefan Hajnoczi {
1175c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
1176c3993cdcSStefan Hajnoczi 
1177c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
117853e8ae01SKevin Wolf         *writethrough = false;
117953e8ae01SKevin Wolf         *flags |= BDRV_O_NOCACHE;
118092196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
118153e8ae01SKevin Wolf         *writethrough = true;
118292196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
1183c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
118453e8ae01SKevin Wolf         *writethrough = false;
1185c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
118653e8ae01SKevin Wolf         *writethrough = false;
1187c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
1188c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
118953e8ae01SKevin Wolf         *writethrough = true;
1190c3993cdcSStefan Hajnoczi     } else {
1191c3993cdcSStefan Hajnoczi         return -1;
1192c3993cdcSStefan Hajnoczi     }
1193c3993cdcSStefan Hajnoczi 
1194c3993cdcSStefan Hajnoczi     return 0;
1195c3993cdcSStefan Hajnoczi }
1196c3993cdcSStefan Hajnoczi 
1197b5411555SKevin Wolf static char *bdrv_child_get_parent_desc(BdrvChild *c)
1198b5411555SKevin Wolf {
1199b5411555SKevin Wolf     BlockDriverState *parent = c->opaque;
12002c0a3acbSVladimir Sementsov-Ogievskiy     return g_strdup_printf("node '%s'", bdrv_get_node_name(parent));
1201b5411555SKevin Wolf }
1202b5411555SKevin Wolf 
1203d05ab380SEmanuele Giuseppe Esposito static void GRAPH_RDLOCK bdrv_child_cb_drained_begin(BdrvChild *child)
120420018e12SKevin Wolf {
120520018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
1206a82a3bd1SKevin Wolf     bdrv_do_drained_begin_quiesce(bs, NULL);
120720018e12SKevin Wolf }
120820018e12SKevin Wolf 
1209d05ab380SEmanuele Giuseppe Esposito static bool GRAPH_RDLOCK bdrv_child_cb_drained_poll(BdrvChild *child)
121089bd0305SKevin Wolf {
121189bd0305SKevin Wolf     BlockDriverState *bs = child->opaque;
1212299403aeSKevin Wolf     return bdrv_drain_poll(bs, NULL, false);
121389bd0305SKevin Wolf }
121489bd0305SKevin Wolf 
1215d05ab380SEmanuele Giuseppe Esposito static void GRAPH_RDLOCK bdrv_child_cb_drained_end(BdrvChild *child)
121620018e12SKevin Wolf {
121720018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
12182f65df6eSKevin Wolf     bdrv_drained_end(bs);
121920018e12SKevin Wolf }
122020018e12SKevin Wolf 
122138701b6aSKevin Wolf static int bdrv_child_cb_inactivate(BdrvChild *child)
122238701b6aSKevin Wolf {
122338701b6aSKevin Wolf     BlockDriverState *bs = child->opaque;
1224bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
122538701b6aSKevin Wolf     assert(bs->open_flags & BDRV_O_INACTIVE);
122638701b6aSKevin Wolf     return 0;
122738701b6aSKevin Wolf }
122838701b6aSKevin Wolf 
122927633e74SEmanuele Giuseppe Esposito static bool bdrv_child_cb_change_aio_ctx(BdrvChild *child, AioContext *ctx,
123027633e74SEmanuele Giuseppe Esposito                                          GHashTable *visited, Transaction *tran,
123127633e74SEmanuele Giuseppe Esposito                                          Error **errp)
12325d231849SKevin Wolf {
12335d231849SKevin Wolf     BlockDriverState *bs = child->opaque;
123427633e74SEmanuele Giuseppe Esposito     return bdrv_change_aio_context(bs, ctx, visited, tran, errp);
123553a7d041SKevin Wolf }
123653a7d041SKevin Wolf 
12370b50cc88SKevin Wolf /*
123873176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
123973176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
124073176beeSKevin Wolf  * flags like a backing file)
1241b1e6fc08SKevin Wolf  */
124273176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
124373176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
1244b1e6fc08SKevin Wolf {
1245bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
124673176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
124773176beeSKevin Wolf 
124873176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
124973176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
125073176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
125141869044SKevin Wolf 
12523f48686fSKevin Wolf     /* Copy the read-only and discard options from the parent */
1253f87a0e29SAlberto Garcia     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
12543f48686fSKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_DISCARD);
1255f87a0e29SAlberto Garcia 
125641869044SKevin Wolf     /* aio=native doesn't work for cache.direct=off, so disable it for the
125741869044SKevin Wolf      * temporary snapshot */
125841869044SKevin Wolf     *child_flags &= ~BDRV_O_NATIVE_AIO;
1259b1e6fc08SKevin Wolf }
1260b1e6fc08SKevin Wolf 
1261b7cfc7d5SKevin Wolf static void GRAPH_WRLOCK bdrv_backing_attach(BdrvChild *c)
1262db95dbbaSKevin Wolf {
1263db95dbbaSKevin Wolf     BlockDriverState *parent = c->opaque;
1264db95dbbaSKevin Wolf     BlockDriverState *backing_hd = c->bs;
1265db95dbbaSKevin Wolf 
1266bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1267db95dbbaSKevin Wolf     assert(!parent->backing_blocker);
1268db95dbbaSKevin Wolf     error_setg(&parent->backing_blocker,
1269db95dbbaSKevin Wolf                "node is used as backing hd of '%s'",
1270db95dbbaSKevin Wolf                bdrv_get_device_or_node_name(parent));
1271db95dbbaSKevin Wolf 
1272f30c66baSMax Reitz     bdrv_refresh_filename(backing_hd);
1273f30c66baSMax Reitz 
1274db95dbbaSKevin Wolf     parent->open_flags &= ~BDRV_O_NO_BACKING;
1275db95dbbaSKevin Wolf 
1276db95dbbaSKevin Wolf     bdrv_op_block_all(backing_hd, parent->backing_blocker);
1277db95dbbaSKevin Wolf     /* Otherwise we won't be able to commit or stream */
1278db95dbbaSKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1279db95dbbaSKevin Wolf                     parent->backing_blocker);
1280db95dbbaSKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
1281db95dbbaSKevin Wolf                     parent->backing_blocker);
1282db95dbbaSKevin Wolf     /*
1283db95dbbaSKevin Wolf      * We do backup in 3 ways:
1284db95dbbaSKevin Wolf      * 1. drive backup
1285db95dbbaSKevin Wolf      *    The target bs is new opened, and the source is top BDS
1286db95dbbaSKevin Wolf      * 2. blockdev backup
1287db95dbbaSKevin Wolf      *    Both the source and the target are top BDSes.
1288db95dbbaSKevin Wolf      * 3. internal backup(used for block replication)
1289db95dbbaSKevin Wolf      *    Both the source and the target are backing file
1290db95dbbaSKevin Wolf      *
1291db95dbbaSKevin Wolf      * In case 1 and 2, neither the source nor the target is the backing file.
1292db95dbbaSKevin Wolf      * In case 3, we will block the top BDS, so there is only one block job
1293db95dbbaSKevin Wolf      * for the top BDS and its backing chain.
1294db95dbbaSKevin Wolf      */
1295db95dbbaSKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1296db95dbbaSKevin Wolf                     parent->backing_blocker);
1297db95dbbaSKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1298db95dbbaSKevin Wolf                     parent->backing_blocker);
1299ca2f1234SMax Reitz }
1300d736f119SKevin Wolf 
1301db95dbbaSKevin Wolf static void bdrv_backing_detach(BdrvChild *c)
1302db95dbbaSKevin Wolf {
1303db95dbbaSKevin Wolf     BlockDriverState *parent = c->opaque;
1304db95dbbaSKevin Wolf 
1305bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1306db95dbbaSKevin Wolf     assert(parent->backing_blocker);
1307db95dbbaSKevin Wolf     bdrv_op_unblock_all(c->bs, parent->backing_blocker);
1308db95dbbaSKevin Wolf     error_free(parent->backing_blocker);
1309db95dbbaSKevin Wolf     parent->backing_blocker = NULL;
131048e08288SMax Reitz }
1311d736f119SKevin Wolf 
13126858eba0SKevin Wolf static int bdrv_backing_update_filename(BdrvChild *c, BlockDriverState *base,
13134b028cbeSPeter Krempa                                         const char *filename,
13144b028cbeSPeter Krempa                                         bool backing_mask_protocol,
13154b028cbeSPeter Krempa                                         Error **errp)
13166858eba0SKevin Wolf {
13176858eba0SKevin Wolf     BlockDriverState *parent = c->opaque;
1318e94d3dbaSAlberto Garcia     bool read_only = bdrv_is_read_only(parent);
13196858eba0SKevin Wolf     int ret;
13204b028cbeSPeter Krempa     const char *format_name;
1321bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
13226858eba0SKevin Wolf 
1323e94d3dbaSAlberto Garcia     if (read_only) {
1324e94d3dbaSAlberto Garcia         ret = bdrv_reopen_set_read_only(parent, false, errp);
132561f09ceaSKevin Wolf         if (ret < 0) {
132661f09ceaSKevin Wolf             return ret;
132761f09ceaSKevin Wolf         }
132861f09ceaSKevin Wolf     }
132961f09ceaSKevin Wolf 
13304b028cbeSPeter Krempa     if (base->drv) {
13314b028cbeSPeter Krempa         /*
13324b028cbeSPeter Krempa          * If the new base image doesn't have a format driver layer, which we
13334b028cbeSPeter Krempa          * detect by the fact that @base is a protocol driver, we record
13344b028cbeSPeter Krempa          * 'raw' as the format instead of putting the protocol name as the
13354b028cbeSPeter Krempa          * backing format
13364b028cbeSPeter Krempa          */
13374b028cbeSPeter Krempa         if (backing_mask_protocol && base->drv->protocol_name) {
13384b028cbeSPeter Krempa             format_name = "raw";
13394b028cbeSPeter Krempa         } else {
13404b028cbeSPeter Krempa             format_name = base->drv->format_name;
13414b028cbeSPeter Krempa         }
13424b028cbeSPeter Krempa     } else {
13434b028cbeSPeter Krempa         format_name = "";
13444b028cbeSPeter Krempa     }
13454b028cbeSPeter Krempa 
13464b028cbeSPeter Krempa     ret = bdrv_change_backing_file(parent, filename, format_name, false);
13476858eba0SKevin Wolf     if (ret < 0) {
134864730694SKevin Wolf         error_setg_errno(errp, -ret, "Could not update backing file link");
13496858eba0SKevin Wolf     }
13506858eba0SKevin Wolf 
1351e94d3dbaSAlberto Garcia     if (read_only) {
1352e94d3dbaSAlberto Garcia         bdrv_reopen_set_read_only(parent, true, NULL);
135361f09ceaSKevin Wolf     }
135461f09ceaSKevin Wolf 
13556858eba0SKevin Wolf     return ret;
13566858eba0SKevin Wolf }
13576858eba0SKevin Wolf 
1358fae8bd39SMax Reitz /*
1359fae8bd39SMax Reitz  * Returns the options and flags that a generic child of a BDS should
1360fae8bd39SMax Reitz  * get, based on the given options and flags for the parent BDS.
1361fae8bd39SMax Reitz  */
136200ff7ffdSMax Reitz static void bdrv_inherited_options(BdrvChildRole role, bool parent_is_format,
1363fae8bd39SMax Reitz                                    int *child_flags, QDict *child_options,
1364fae8bd39SMax Reitz                                    int parent_flags, QDict *parent_options)
1365fae8bd39SMax Reitz {
1366fae8bd39SMax Reitz     int flags = parent_flags;
1367bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1368fae8bd39SMax Reitz 
1369fae8bd39SMax Reitz     /*
1370fae8bd39SMax Reitz      * First, decide whether to set, clear, or leave BDRV_O_PROTOCOL.
1371fae8bd39SMax Reitz      * Generally, the question to answer is: Should this child be
1372fae8bd39SMax Reitz      * format-probed by default?
1373fae8bd39SMax Reitz      */
1374fae8bd39SMax Reitz 
1375fae8bd39SMax Reitz     /*
1376fae8bd39SMax Reitz      * Pure and non-filtered data children of non-format nodes should
1377fae8bd39SMax Reitz      * be probed by default (even when the node itself has BDRV_O_PROTOCOL
1378fae8bd39SMax Reitz      * set).  This only affects a very limited set of drivers (namely
1379fae8bd39SMax Reitz      * quorum and blkverify when this comment was written).
1380fae8bd39SMax Reitz      * Force-clear BDRV_O_PROTOCOL then.
1381fae8bd39SMax Reitz      */
1382fae8bd39SMax Reitz     if (!parent_is_format &&
1383fae8bd39SMax Reitz         (role & BDRV_CHILD_DATA) &&
1384fae8bd39SMax Reitz         !(role & (BDRV_CHILD_METADATA | BDRV_CHILD_FILTERED)))
1385fae8bd39SMax Reitz     {
1386fae8bd39SMax Reitz         flags &= ~BDRV_O_PROTOCOL;
1387fae8bd39SMax Reitz     }
1388fae8bd39SMax Reitz 
1389fae8bd39SMax Reitz     /*
1390fae8bd39SMax Reitz      * All children of format nodes (except for COW children) and all
1391fae8bd39SMax Reitz      * metadata children in general should never be format-probed.
1392fae8bd39SMax Reitz      * Force-set BDRV_O_PROTOCOL then.
1393fae8bd39SMax Reitz      */
1394fae8bd39SMax Reitz     if ((parent_is_format && !(role & BDRV_CHILD_COW)) ||
1395fae8bd39SMax Reitz         (role & BDRV_CHILD_METADATA))
1396fae8bd39SMax Reitz     {
1397fae8bd39SMax Reitz         flags |= BDRV_O_PROTOCOL;
1398fae8bd39SMax Reitz     }
1399fae8bd39SMax Reitz 
1400fae8bd39SMax Reitz     /*
1401fae8bd39SMax Reitz      * If the cache mode isn't explicitly set, inherit direct and no-flush from
1402fae8bd39SMax Reitz      * the parent.
1403fae8bd39SMax Reitz      */
1404fae8bd39SMax Reitz     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
1405fae8bd39SMax Reitz     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
1406fae8bd39SMax Reitz     qdict_copy_default(child_options, parent_options, BDRV_OPT_FORCE_SHARE);
1407fae8bd39SMax Reitz 
1408fae8bd39SMax Reitz     if (role & BDRV_CHILD_COW) {
1409fae8bd39SMax Reitz         /* backing files are opened read-only by default */
1410fae8bd39SMax Reitz         qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
1411fae8bd39SMax Reitz         qdict_set_default_str(child_options, BDRV_OPT_AUTO_READ_ONLY, "off");
1412fae8bd39SMax Reitz     } else {
1413fae8bd39SMax Reitz         /* Inherit the read-only option from the parent if it's not set */
1414fae8bd39SMax Reitz         qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
1415fae8bd39SMax Reitz         qdict_copy_default(child_options, parent_options,
1416fae8bd39SMax Reitz                            BDRV_OPT_AUTO_READ_ONLY);
1417fae8bd39SMax Reitz     }
1418fae8bd39SMax Reitz 
1419fae8bd39SMax Reitz     /*
1420fae8bd39SMax Reitz      * bdrv_co_pdiscard() respects unmap policy for the parent, so we
1421fae8bd39SMax Reitz      * can default to enable it on lower layers regardless of the
1422fae8bd39SMax Reitz      * parent option.
1423fae8bd39SMax Reitz      */
1424fae8bd39SMax Reitz     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
1425fae8bd39SMax Reitz 
1426fae8bd39SMax Reitz     /* Clear flags that only apply to the top layer */
1427fae8bd39SMax Reitz     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
1428fae8bd39SMax Reitz 
1429fae8bd39SMax Reitz     if (role & BDRV_CHILD_METADATA) {
1430fae8bd39SMax Reitz         flags &= ~BDRV_O_NO_IO;
1431fae8bd39SMax Reitz     }
1432fae8bd39SMax Reitz     if (role & BDRV_CHILD_COW) {
1433fae8bd39SMax Reitz         flags &= ~BDRV_O_TEMPORARY;
1434fae8bd39SMax Reitz     }
1435fae8bd39SMax Reitz 
1436fae8bd39SMax Reitz     *child_flags = flags;
1437fae8bd39SMax Reitz }
1438fae8bd39SMax Reitz 
1439303de47bSKevin Wolf static void GRAPH_WRLOCK bdrv_child_cb_attach(BdrvChild *child)
1440ca2f1234SMax Reitz {
1441ca2f1234SMax Reitz     BlockDriverState *bs = child->opaque;
1442ca2f1234SMax Reitz 
14433f35f82eSEmanuele Giuseppe Esposito     assert_bdrv_graph_writable();
1444a225369bSHanna Reitz     QLIST_INSERT_HEAD(&bs->children, child, next);
14455bb04747SVladimir Sementsov-Ogievskiy     if (bs->drv->is_filter || (child->role & BDRV_CHILD_FILTERED)) {
14465bb04747SVladimir Sementsov-Ogievskiy         /*
14475bb04747SVladimir Sementsov-Ogievskiy          * Here we handle filters and block/raw-format.c when it behave like
14485bb04747SVladimir Sementsov-Ogievskiy          * filter. They generally have a single PRIMARY child, which is also the
14495bb04747SVladimir Sementsov-Ogievskiy          * FILTERED child, and that they may have multiple more children, which
14505bb04747SVladimir Sementsov-Ogievskiy          * are neither PRIMARY nor FILTERED. And never we have a COW child here.
14515bb04747SVladimir Sementsov-Ogievskiy          * So bs->file will be the PRIMARY child, unless the PRIMARY child goes
14525bb04747SVladimir Sementsov-Ogievskiy          * into bs->backing on exceptional cases; and bs->backing will be
14535bb04747SVladimir Sementsov-Ogievskiy          * nothing else.
14545bb04747SVladimir Sementsov-Ogievskiy          */
14555bb04747SVladimir Sementsov-Ogievskiy         assert(!(child->role & BDRV_CHILD_COW));
14565bb04747SVladimir Sementsov-Ogievskiy         if (child->role & BDRV_CHILD_PRIMARY) {
14575bb04747SVladimir Sementsov-Ogievskiy             assert(child->role & BDRV_CHILD_FILTERED);
14585bb04747SVladimir Sementsov-Ogievskiy             assert(!bs->backing);
14595bb04747SVladimir Sementsov-Ogievskiy             assert(!bs->file);
1460a225369bSHanna Reitz 
14615bb04747SVladimir Sementsov-Ogievskiy             if (bs->drv->filtered_child_is_backing) {
14625bb04747SVladimir Sementsov-Ogievskiy                 bs->backing = child;
14635bb04747SVladimir Sementsov-Ogievskiy             } else {
14645bb04747SVladimir Sementsov-Ogievskiy                 bs->file = child;
14655bb04747SVladimir Sementsov-Ogievskiy             }
14665bb04747SVladimir Sementsov-Ogievskiy         } else {
14675bb04747SVladimir Sementsov-Ogievskiy             assert(!(child->role & BDRV_CHILD_FILTERED));
14685bb04747SVladimir Sementsov-Ogievskiy         }
14695bb04747SVladimir Sementsov-Ogievskiy     } else if (child->role & BDRV_CHILD_COW) {
14705bb04747SVladimir Sementsov-Ogievskiy         assert(bs->drv->supports_backing);
14715bb04747SVladimir Sementsov-Ogievskiy         assert(!(child->role & BDRV_CHILD_PRIMARY));
14725bb04747SVladimir Sementsov-Ogievskiy         assert(!bs->backing);
14735bb04747SVladimir Sementsov-Ogievskiy         bs->backing = child;
1474ca2f1234SMax Reitz         bdrv_backing_attach(child);
14755bb04747SVladimir Sementsov-Ogievskiy     } else if (child->role & BDRV_CHILD_PRIMARY) {
14765bb04747SVladimir Sementsov-Ogievskiy         assert(!bs->file);
14775bb04747SVladimir Sementsov-Ogievskiy         bs->file = child;
1478ca2f1234SMax Reitz     }
1479ca2f1234SMax Reitz }
1480ca2f1234SMax Reitz 
1481303de47bSKevin Wolf static void GRAPH_WRLOCK bdrv_child_cb_detach(BdrvChild *child)
148248e08288SMax Reitz {
148348e08288SMax Reitz     BlockDriverState *bs = child->opaque;
148448e08288SMax Reitz 
148548e08288SMax Reitz     if (child->role & BDRV_CHILD_COW) {
148648e08288SMax Reitz         bdrv_backing_detach(child);
148748e08288SMax Reitz     }
148848e08288SMax Reitz 
14893f35f82eSEmanuele Giuseppe Esposito     assert_bdrv_graph_writable();
1490a225369bSHanna Reitz     QLIST_REMOVE(child, next);
14915bb04747SVladimir Sementsov-Ogievskiy     if (child == bs->backing) {
14925bb04747SVladimir Sementsov-Ogievskiy         assert(child != bs->file);
14935bb04747SVladimir Sementsov-Ogievskiy         bs->backing = NULL;
14945bb04747SVladimir Sementsov-Ogievskiy     } else if (child == bs->file) {
14955bb04747SVladimir Sementsov-Ogievskiy         bs->file = NULL;
14965bb04747SVladimir Sementsov-Ogievskiy     }
149748e08288SMax Reitz }
149848e08288SMax Reitz 
149943483550SMax Reitz static int bdrv_child_cb_update_filename(BdrvChild *c, BlockDriverState *base,
15004b028cbeSPeter Krempa                                          const char *filename,
15014b028cbeSPeter Krempa                                          bool backing_mask_protocol,
15024b028cbeSPeter Krempa                                          Error **errp)
150343483550SMax Reitz {
150443483550SMax Reitz     if (c->role & BDRV_CHILD_COW) {
15054b028cbeSPeter Krempa         return bdrv_backing_update_filename(c, base, filename,
15064b028cbeSPeter Krempa                                             backing_mask_protocol,
15074b028cbeSPeter Krempa                                             errp);
150843483550SMax Reitz     }
150943483550SMax Reitz     return 0;
151043483550SMax Reitz }
151143483550SMax Reitz 
1512fb62b588SVladimir Sementsov-Ogievskiy AioContext *child_of_bds_get_parent_aio_context(BdrvChild *c)
15133ca1f322SVladimir Sementsov-Ogievskiy {
15143ca1f322SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = c->opaque;
1515384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
15163ca1f322SVladimir Sementsov-Ogievskiy 
15173ca1f322SVladimir Sementsov-Ogievskiy     return bdrv_get_aio_context(bs);
15183ca1f322SVladimir Sementsov-Ogievskiy }
15193ca1f322SVladimir Sementsov-Ogievskiy 
152043483550SMax Reitz const BdrvChildClass child_of_bds = {
152143483550SMax Reitz     .parent_is_bds   = true,
152243483550SMax Reitz     .get_parent_desc = bdrv_child_get_parent_desc,
152343483550SMax Reitz     .inherit_options = bdrv_inherited_options,
152443483550SMax Reitz     .drained_begin   = bdrv_child_cb_drained_begin,
152543483550SMax Reitz     .drained_poll    = bdrv_child_cb_drained_poll,
152643483550SMax Reitz     .drained_end     = bdrv_child_cb_drained_end,
152743483550SMax Reitz     .attach          = bdrv_child_cb_attach,
152843483550SMax Reitz     .detach          = bdrv_child_cb_detach,
152943483550SMax Reitz     .inactivate      = bdrv_child_cb_inactivate,
153027633e74SEmanuele Giuseppe Esposito     .change_aio_ctx  = bdrv_child_cb_change_aio_ctx,
153143483550SMax Reitz     .update_filename = bdrv_child_cb_update_filename,
1532fb62b588SVladimir Sementsov-Ogievskiy     .get_parent_aio_context = child_of_bds_get_parent_aio_context,
153343483550SMax Reitz };
153443483550SMax Reitz 
15353ca1f322SVladimir Sementsov-Ogievskiy AioContext *bdrv_child_get_parent_aio_context(BdrvChild *c)
15363ca1f322SVladimir Sementsov-Ogievskiy {
1537d5f8d79cSHanna Reitz     IO_CODE();
15383ca1f322SVladimir Sementsov-Ogievskiy     return c->klass->get_parent_aio_context(c);
15393ca1f322SVladimir Sementsov-Ogievskiy }
15403ca1f322SVladimir Sementsov-Ogievskiy 
15417b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
15427b272452SKevin Wolf {
154361de4c68SKevin Wolf     int open_flags = flags;
1544bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
15457b272452SKevin Wolf 
15467b272452SKevin Wolf     /*
15477b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
15487b272452SKevin Wolf      * image.
15497b272452SKevin Wolf      */
155020cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
15517b272452SKevin Wolf 
15527b272452SKevin Wolf     return open_flags;
15537b272452SKevin Wolf }
15547b272452SKevin Wolf 
155591a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
155691a097e7SKevin Wolf {
1557bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1558bdb73476SEmanuele Giuseppe Esposito 
15592a3d4331SAlberto Garcia     *flags &= ~(BDRV_O_CACHE_MASK | BDRV_O_RDWR | BDRV_O_AUTO_RDONLY);
156091a097e7SKevin Wolf 
156157f9db9aSAlberto Garcia     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
156291a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
156391a097e7SKevin Wolf     }
156491a097e7SKevin Wolf 
156557f9db9aSAlberto Garcia     if (qemu_opt_get_bool_del(opts, BDRV_OPT_CACHE_DIRECT, false)) {
156691a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
156791a097e7SKevin Wolf     }
1568f87a0e29SAlberto Garcia 
156957f9db9aSAlberto Garcia     if (!qemu_opt_get_bool_del(opts, BDRV_OPT_READ_ONLY, false)) {
1570f87a0e29SAlberto Garcia         *flags |= BDRV_O_RDWR;
1571f87a0e29SAlberto Garcia     }
1572f87a0e29SAlberto Garcia 
1573e35bdc12SKevin Wolf     if (qemu_opt_get_bool_del(opts, BDRV_OPT_AUTO_READ_ONLY, false)) {
1574e35bdc12SKevin Wolf         *flags |= BDRV_O_AUTO_RDONLY;
1575e35bdc12SKevin Wolf     }
157691a097e7SKevin Wolf }
157791a097e7SKevin Wolf 
157891a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
157991a097e7SKevin Wolf {
1580bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
158191a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
158246f5ac20SEric Blake         qdict_put_bool(options, BDRV_OPT_CACHE_DIRECT, flags & BDRV_O_NOCACHE);
158391a097e7SKevin Wolf     }
158491a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
158546f5ac20SEric Blake         qdict_put_bool(options, BDRV_OPT_CACHE_NO_FLUSH,
158646f5ac20SEric Blake                        flags & BDRV_O_NO_FLUSH);
158791a097e7SKevin Wolf     }
1588f87a0e29SAlberto Garcia     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
158946f5ac20SEric Blake         qdict_put_bool(options, BDRV_OPT_READ_ONLY, !(flags & BDRV_O_RDWR));
1590f87a0e29SAlberto Garcia     }
1591e35bdc12SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_AUTO_READ_ONLY)) {
1592e35bdc12SKevin Wolf         qdict_put_bool(options, BDRV_OPT_AUTO_READ_ONLY,
1593e35bdc12SKevin Wolf                        flags & BDRV_O_AUTO_RDONLY);
1594e35bdc12SKevin Wolf     }
159591a097e7SKevin Wolf }
159691a097e7SKevin Wolf 
1597636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
15986913c0c2SBenoît Canet                                   const char *node_name,
15996913c0c2SBenoît Canet                                   Error **errp)
16006913c0c2SBenoît Canet {
160115489c76SJeff Cody     char *gen_node_name = NULL;
1602bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
16036913c0c2SBenoît Canet 
160415489c76SJeff Cody     if (!node_name) {
160515489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
160615489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
160715489c76SJeff Cody         /*
160815489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
160915489c76SJeff Cody          * generated (generated names use characters not available to the user)
161015489c76SJeff Cody          */
1611785ec4b1SConnor Kuehl         error_setg(errp, "Invalid node-name: '%s'", node_name);
1612636ea370SKevin Wolf         return;
16136913c0c2SBenoît Canet     }
16146913c0c2SBenoît Canet 
16150c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
16167f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
16170c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
16180c5e94eeSBenoît Canet                    node_name);
161915489c76SJeff Cody         goto out;
16200c5e94eeSBenoît Canet     }
16210c5e94eeSBenoît Canet 
16226913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
16236913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
1624785ec4b1SConnor Kuehl         error_setg(errp, "Duplicate nodes with node-name='%s'", node_name);
162515489c76SJeff Cody         goto out;
16266913c0c2SBenoît Canet     }
16276913c0c2SBenoît Canet 
1628824808ddSKevin Wolf     /* Make sure that the node name isn't truncated */
1629824808ddSKevin Wolf     if (strlen(node_name) >= sizeof(bs->node_name)) {
1630824808ddSKevin Wolf         error_setg(errp, "Node name too long");
1631824808ddSKevin Wolf         goto out;
1632824808ddSKevin Wolf     }
1633824808ddSKevin Wolf 
16346913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
16356913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
16366913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
163715489c76SJeff Cody out:
163815489c76SJeff Cody     g_free(gen_node_name);
16396913c0c2SBenoît Canet }
16406913c0c2SBenoît Canet 
16411a30b0f5SKevin Wolf static int no_coroutine_fn GRAPH_UNLOCKED
16421a30b0f5SKevin Wolf bdrv_open_driver(BlockDriverState *bs, BlockDriver *drv, const char *node_name,
16431a30b0f5SKevin Wolf                  QDict *options, int open_flags, Error **errp)
164401a56501SKevin Wolf {
164501a56501SKevin Wolf     Error *local_err = NULL;
16460f12264eSKevin Wolf     int i, ret;
1647da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
164801a56501SKevin Wolf 
164901a56501SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
165001a56501SKevin Wolf     if (local_err) {
165101a56501SKevin Wolf         error_propagate(errp, local_err);
165201a56501SKevin Wolf         return -EINVAL;
165301a56501SKevin Wolf     }
165401a56501SKevin Wolf 
165501a56501SKevin Wolf     bs->drv = drv;
165601a56501SKevin Wolf     bs->opaque = g_malloc0(drv->instance_size);
165701a56501SKevin Wolf 
165801a56501SKevin Wolf     assert(!drv->bdrv_needs_filename || bs->filename[0]);
165944b424dcSPaolo Bonzini     if (drv->bdrv_open) {
166001a56501SKevin Wolf         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
1661680c7f96SKevin Wolf     } else {
1662680c7f96SKevin Wolf         ret = 0;
166301a56501SKevin Wolf     }
166401a56501SKevin Wolf 
166501a56501SKevin Wolf     if (ret < 0) {
166601a56501SKevin Wolf         if (local_err) {
166701a56501SKevin Wolf             error_propagate(errp, local_err);
166801a56501SKevin Wolf         } else if (bs->filename[0]) {
166901a56501SKevin Wolf             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
167001a56501SKevin Wolf         } else {
167101a56501SKevin Wolf             error_setg_errno(errp, -ret, "Could not open image");
167201a56501SKevin Wolf         }
1673180ca19aSManos Pitsidianakis         goto open_failed;
167401a56501SKevin Wolf     }
167501a56501SKevin Wolf 
1676e8b65355SStefan Hajnoczi     assert(!(bs->supported_read_flags & ~BDRV_REQ_MASK));
1677e8b65355SStefan Hajnoczi     assert(!(bs->supported_write_flags & ~BDRV_REQ_MASK));
1678e8b65355SStefan Hajnoczi 
1679e8b65355SStefan Hajnoczi     /*
1680e8b65355SStefan Hajnoczi      * Always allow the BDRV_REQ_REGISTERED_BUF optimization hint. This saves
1681e8b65355SStefan Hajnoczi      * drivers that pass read/write requests through to a child the trouble of
1682e8b65355SStefan Hajnoczi      * declaring support explicitly.
1683e8b65355SStefan Hajnoczi      *
1684e8b65355SStefan Hajnoczi      * Drivers must not propagate this flag accidentally when they initiate I/O
1685e8b65355SStefan Hajnoczi      * to a bounce buffer. That case should be rare though.
1686e8b65355SStefan Hajnoczi      */
1687e8b65355SStefan Hajnoczi     bs->supported_read_flags |= BDRV_REQ_REGISTERED_BUF;
1688e8b65355SStefan Hajnoczi     bs->supported_write_flags |= BDRV_REQ_REGISTERED_BUF;
1689e8b65355SStefan Hajnoczi 
1690c057960cSEmanuele Giuseppe Esposito     ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
169101a56501SKevin Wolf     if (ret < 0) {
169201a56501SKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
1693180ca19aSManos Pitsidianakis         return ret;
169401a56501SKevin Wolf     }
169501a56501SKevin Wolf 
1696e19b157fSKevin Wolf     bdrv_graph_rdlock_main_loop();
16971e4c797cSVladimir Sementsov-Ogievskiy     bdrv_refresh_limits(bs, NULL, &local_err);
1698e19b157fSKevin Wolf     bdrv_graph_rdunlock_main_loop();
1699e19b157fSKevin Wolf 
170001a56501SKevin Wolf     if (local_err) {
170101a56501SKevin Wolf         error_propagate(errp, local_err);
1702180ca19aSManos Pitsidianakis         return -EINVAL;
170301a56501SKevin Wolf     }
170401a56501SKevin Wolf 
170501a56501SKevin Wolf     assert(bdrv_opt_mem_align(bs) != 0);
170601a56501SKevin Wolf     assert(bdrv_min_mem_align(bs) != 0);
170701a56501SKevin Wolf     assert(is_power_of_2(bs->bl.request_alignment));
170801a56501SKevin Wolf 
17090f12264eSKevin Wolf     for (i = 0; i < bs->quiesce_counter; i++) {
17105e8ac217SKevin Wolf         if (drv->bdrv_drain_begin) {
17115e8ac217SKevin Wolf             drv->bdrv_drain_begin(bs);
17120f12264eSKevin Wolf         }
17130f12264eSKevin Wolf     }
17140f12264eSKevin Wolf 
171501a56501SKevin Wolf     return 0;
1716180ca19aSManos Pitsidianakis open_failed:
1717180ca19aSManos Pitsidianakis     bs->drv = NULL;
17181f051dcbSKevin Wolf 
17196bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
17201f051dcbSKevin Wolf     if (bs->file != NULL) {
1721180ca19aSManos Pitsidianakis         bdrv_unref_child(bs, bs->file);
17225bb04747SVladimir Sementsov-Ogievskiy         assert(!bs->file);
1723180ca19aSManos Pitsidianakis     }
17246bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
17251f051dcbSKevin Wolf 
172601a56501SKevin Wolf     g_free(bs->opaque);
172701a56501SKevin Wolf     bs->opaque = NULL;
172801a56501SKevin Wolf     return ret;
172901a56501SKevin Wolf }
173001a56501SKevin Wolf 
1731621d1737SVladimir Sementsov-Ogievskiy /*
1732621d1737SVladimir Sementsov-Ogievskiy  * Create and open a block node.
1733621d1737SVladimir Sementsov-Ogievskiy  *
1734621d1737SVladimir Sementsov-Ogievskiy  * @options is a QDict of options to pass to the block drivers, or NULL for an
1735621d1737SVladimir Sementsov-Ogievskiy  * empty set of options. The reference to the QDict belongs to the block layer
1736621d1737SVladimir Sementsov-Ogievskiy  * after the call (even on failure), so if the caller intends to reuse the
1737621d1737SVladimir Sementsov-Ogievskiy  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
1738621d1737SVladimir Sementsov-Ogievskiy  */
1739621d1737SVladimir Sementsov-Ogievskiy BlockDriverState *bdrv_new_open_driver_opts(BlockDriver *drv,
1740621d1737SVladimir Sementsov-Ogievskiy                                             const char *node_name,
1741621d1737SVladimir Sementsov-Ogievskiy                                             QDict *options, int flags,
1742621d1737SVladimir Sementsov-Ogievskiy                                             Error **errp)
1743680c7f96SKevin Wolf {
1744680c7f96SKevin Wolf     BlockDriverState *bs;
1745680c7f96SKevin Wolf     int ret;
1746680c7f96SKevin Wolf 
1747f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1748f791bf7fSEmanuele Giuseppe Esposito 
1749680c7f96SKevin Wolf     bs = bdrv_new();
1750680c7f96SKevin Wolf     bs->open_flags = flags;
1751621d1737SVladimir Sementsov-Ogievskiy     bs->options = options ?: qdict_new();
1752621d1737SVladimir Sementsov-Ogievskiy     bs->explicit_options = qdict_clone_shallow(bs->options);
1753680c7f96SKevin Wolf     bs->opaque = NULL;
1754680c7f96SKevin Wolf 
1755680c7f96SKevin Wolf     update_options_from_flags(bs->options, flags);
1756680c7f96SKevin Wolf 
1757680c7f96SKevin Wolf     ret = bdrv_open_driver(bs, drv, node_name, bs->options, flags, errp);
1758680c7f96SKevin Wolf     if (ret < 0) {
1759cb3e7f08SMarc-André Lureau         qobject_unref(bs->explicit_options);
1760180ca19aSManos Pitsidianakis         bs->explicit_options = NULL;
1761cb3e7f08SMarc-André Lureau         qobject_unref(bs->options);
1762180ca19aSManos Pitsidianakis         bs->options = NULL;
1763680c7f96SKevin Wolf         bdrv_unref(bs);
1764680c7f96SKevin Wolf         return NULL;
1765680c7f96SKevin Wolf     }
1766680c7f96SKevin Wolf 
1767680c7f96SKevin Wolf     return bs;
1768680c7f96SKevin Wolf }
1769680c7f96SKevin Wolf 
1770621d1737SVladimir Sementsov-Ogievskiy /* Create and open a block node. */
1771621d1737SVladimir Sementsov-Ogievskiy BlockDriverState *bdrv_new_open_driver(BlockDriver *drv, const char *node_name,
1772621d1737SVladimir Sementsov-Ogievskiy                                        int flags, Error **errp)
1773621d1737SVladimir Sementsov-Ogievskiy {
1774f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
1775621d1737SVladimir Sementsov-Ogievskiy     return bdrv_new_open_driver_opts(drv, node_name, NULL, flags, errp);
1776621d1737SVladimir Sementsov-Ogievskiy }
1777621d1737SVladimir Sementsov-Ogievskiy 
1778c5f3014bSKevin Wolf QemuOptsList bdrv_runtime_opts = {
177918edf289SKevin Wolf     .name = "bdrv_common",
178018edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
178118edf289SKevin Wolf     .desc = {
178218edf289SKevin Wolf         {
178318edf289SKevin Wolf             .name = "node-name",
178418edf289SKevin Wolf             .type = QEMU_OPT_STRING,
178518edf289SKevin Wolf             .help = "Node name of the block device node",
178618edf289SKevin Wolf         },
178762392ebbSKevin Wolf         {
178862392ebbSKevin Wolf             .name = "driver",
178962392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
179062392ebbSKevin Wolf             .help = "Block driver to use for the node",
179162392ebbSKevin Wolf         },
179291a097e7SKevin Wolf         {
179391a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
179491a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
179591a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
179691a097e7SKevin Wolf         },
179791a097e7SKevin Wolf         {
179891a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
179991a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
180091a097e7SKevin Wolf             .help = "Ignore flush requests",
180191a097e7SKevin Wolf         },
1802f87a0e29SAlberto Garcia         {
1803f87a0e29SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
1804f87a0e29SAlberto Garcia             .type = QEMU_OPT_BOOL,
1805f87a0e29SAlberto Garcia             .help = "Node is opened in read-only mode",
1806f87a0e29SAlberto Garcia         },
1807692e01a2SKevin Wolf         {
1808e35bdc12SKevin Wolf             .name = BDRV_OPT_AUTO_READ_ONLY,
1809e35bdc12SKevin Wolf             .type = QEMU_OPT_BOOL,
1810e35bdc12SKevin Wolf             .help = "Node can become read-only if opening read-write fails",
1811e35bdc12SKevin Wolf         },
1812e35bdc12SKevin Wolf         {
1813692e01a2SKevin Wolf             .name = "detect-zeroes",
1814692e01a2SKevin Wolf             .type = QEMU_OPT_STRING,
1815692e01a2SKevin Wolf             .help = "try to optimize zero writes (off, on, unmap)",
1816692e01a2SKevin Wolf         },
1817818584a4SKevin Wolf         {
1818415bbca8SAlberto Garcia             .name = BDRV_OPT_DISCARD,
1819818584a4SKevin Wolf             .type = QEMU_OPT_STRING,
1820818584a4SKevin Wolf             .help = "discard operation (ignore/off, unmap/on)",
1821818584a4SKevin Wolf         },
18225a9347c6SFam Zheng         {
18235a9347c6SFam Zheng             .name = BDRV_OPT_FORCE_SHARE,
18245a9347c6SFam Zheng             .type = QEMU_OPT_BOOL,
18255a9347c6SFam Zheng             .help = "always accept other writers (default: off)",
18265a9347c6SFam Zheng         },
182718edf289SKevin Wolf         { /* end of list */ }
182818edf289SKevin Wolf     },
182918edf289SKevin Wolf };
183018edf289SKevin Wolf 
18315a5e7f8cSMaxim Levitsky QemuOptsList bdrv_create_opts_simple = {
18325a5e7f8cSMaxim Levitsky     .name = "simple-create-opts",
18335a5e7f8cSMaxim Levitsky     .head = QTAILQ_HEAD_INITIALIZER(bdrv_create_opts_simple.head),
1834fd17146cSMax Reitz     .desc = {
1835fd17146cSMax Reitz         {
1836fd17146cSMax Reitz             .name = BLOCK_OPT_SIZE,
1837fd17146cSMax Reitz             .type = QEMU_OPT_SIZE,
1838fd17146cSMax Reitz             .help = "Virtual disk size"
1839fd17146cSMax Reitz         },
1840fd17146cSMax Reitz         {
1841fd17146cSMax Reitz             .name = BLOCK_OPT_PREALLOC,
1842fd17146cSMax Reitz             .type = QEMU_OPT_STRING,
1843fd17146cSMax Reitz             .help = "Preallocation mode (allowed values: off)"
1844fd17146cSMax Reitz         },
1845fd17146cSMax Reitz         { /* end of list */ }
1846fd17146cSMax Reitz     }
1847fd17146cSMax Reitz };
1848fd17146cSMax Reitz 
1849b6ce07aaSKevin Wolf /*
185057915332SKevin Wolf  * Common part for opening disk images and files
1851b6ad491aSKevin Wolf  *
1852b6ad491aSKevin Wolf  * Removes all processed options from *options.
185357915332SKevin Wolf  */
18545696c6e3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockBackend *file,
185582dc8b41SKevin Wolf                             QDict *options, Error **errp)
185657915332SKevin Wolf {
185757915332SKevin Wolf     int ret, open_flags;
1858035fccdfSKevin Wolf     const char *filename;
185962392ebbSKevin Wolf     const char *driver_name = NULL;
18606913c0c2SBenoît Canet     const char *node_name = NULL;
1861818584a4SKevin Wolf     const char *discard;
186218edf289SKevin Wolf     QemuOpts *opts;
186362392ebbSKevin Wolf     BlockDriver *drv;
186434b5d2c6SMax Reitz     Error *local_err = NULL;
1865307261b2SVladimir Sementsov-Ogievskiy     bool ro;
186657915332SKevin Wolf 
18671f051dcbSKevin Wolf     GLOBAL_STATE_CODE();
18681f051dcbSKevin Wolf 
18691f051dcbSKevin Wolf     bdrv_graph_rdlock_main_loop();
18706405875cSPaolo Bonzini     assert(bs->file == NULL);
1871707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
18721f051dcbSKevin Wolf     bdrv_graph_rdunlock_main_loop();
187357915332SKevin Wolf 
187462392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1875af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, options, errp)) {
187662392ebbSKevin Wolf         ret = -EINVAL;
187762392ebbSKevin Wolf         goto fail_opts;
187862392ebbSKevin Wolf     }
187962392ebbSKevin Wolf 
18809b7e8691SAlberto Garcia     update_flags_from_options(&bs->open_flags, opts);
18819b7e8691SAlberto Garcia 
188262392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
188362392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
188462392ebbSKevin Wolf     assert(drv != NULL);
188562392ebbSKevin Wolf 
18865a9347c6SFam Zheng     bs->force_share = qemu_opt_get_bool(opts, BDRV_OPT_FORCE_SHARE, false);
18875a9347c6SFam Zheng 
18885a9347c6SFam Zheng     if (bs->force_share && (bs->open_flags & BDRV_O_RDWR)) {
18895a9347c6SFam Zheng         error_setg(errp,
18905a9347c6SFam Zheng                    BDRV_OPT_FORCE_SHARE
18915a9347c6SFam Zheng                    "=on can only be used with read-only images");
18925a9347c6SFam Zheng         ret = -EINVAL;
18935a9347c6SFam Zheng         goto fail_opts;
18945a9347c6SFam Zheng     }
18955a9347c6SFam Zheng 
189645673671SKevin Wolf     if (file != NULL) {
1897b7cfc7d5SKevin Wolf         bdrv_graph_rdlock_main_loop();
1898f30c66baSMax Reitz         bdrv_refresh_filename(blk_bs(file));
1899b7cfc7d5SKevin Wolf         bdrv_graph_rdunlock_main_loop();
1900b7cfc7d5SKevin Wolf 
19015696c6e3SKevin Wolf         filename = blk_bs(file)->filename;
190245673671SKevin Wolf     } else {
1903129c7d1cSMarkus Armbruster         /*
1904129c7d1cSMarkus Armbruster          * Caution: while qdict_get_try_str() is fine, getting
1905129c7d1cSMarkus Armbruster          * non-string types would require more care.  When @options
1906129c7d1cSMarkus Armbruster          * come from -blockdev or blockdev_add, its members are typed
1907129c7d1cSMarkus Armbruster          * according to the QAPI schema, but when they come from
1908129c7d1cSMarkus Armbruster          * -drive, they're all QString.
1909129c7d1cSMarkus Armbruster          */
191045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
191145673671SKevin Wolf     }
191245673671SKevin Wolf 
19134a008240SMax Reitz     if (drv->bdrv_needs_filename && (!filename || !filename[0])) {
1914765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
1915765003dbSKevin Wolf                    drv->format_name);
191618edf289SKevin Wolf         ret = -EINVAL;
191718edf289SKevin Wolf         goto fail_opts;
191818edf289SKevin Wolf     }
191918edf289SKevin Wolf 
192082dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
192182dc8b41SKevin Wolf                            drv->format_name);
192262392ebbSKevin Wolf 
1923307261b2SVladimir Sementsov-Ogievskiy     ro = bdrv_is_read_only(bs);
1924307261b2SVladimir Sementsov-Ogievskiy 
1925307261b2SVladimir Sementsov-Ogievskiy     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, ro)) {
1926307261b2SVladimir Sementsov-Ogievskiy         if (!ro && bdrv_is_whitelisted(drv, true)) {
1927018f9deaSKevin Wolf             bdrv_graph_rdlock_main_loop();
19288be25de6SKevin Wolf             ret = bdrv_apply_auto_read_only(bs, NULL, NULL);
1929018f9deaSKevin Wolf             bdrv_graph_rdunlock_main_loop();
19308be25de6SKevin Wolf         } else {
19318be25de6SKevin Wolf             ret = -ENOTSUP;
19328be25de6SKevin Wolf         }
19338be25de6SKevin Wolf         if (ret < 0) {
19348f94a6e4SKevin Wolf             error_setg(errp,
1935307261b2SVladimir Sementsov-Ogievskiy                        !ro && bdrv_is_whitelisted(drv, true)
19368f94a6e4SKevin Wolf                        ? "Driver '%s' can only be used for read-only devices"
19378f94a6e4SKevin Wolf                        : "Driver '%s' is not whitelisted",
19388f94a6e4SKevin Wolf                        drv->format_name);
193918edf289SKevin Wolf             goto fail_opts;
1940b64ec4e4SFam Zheng         }
19418be25de6SKevin Wolf     }
194257915332SKevin Wolf 
1943d3faa13eSPaolo Bonzini     /* bdrv_new() and bdrv_close() make it so */
1944d73415a3SStefan Hajnoczi     assert(qatomic_read(&bs->copy_on_read) == 0);
1945d3faa13eSPaolo Bonzini 
194682dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
1947307261b2SVladimir Sementsov-Ogievskiy         if (!ro) {
194853fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
19490ebd24e0SKevin Wolf         } else {
19500ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
195118edf289SKevin Wolf             ret = -EINVAL;
195218edf289SKevin Wolf             goto fail_opts;
19530ebd24e0SKevin Wolf         }
195453fec9d3SStefan Hajnoczi     }
195553fec9d3SStefan Hajnoczi 
1956415bbca8SAlberto Garcia     discard = qemu_opt_get(opts, BDRV_OPT_DISCARD);
1957818584a4SKevin Wolf     if (discard != NULL) {
1958818584a4SKevin Wolf         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1959818584a4SKevin Wolf             error_setg(errp, "Invalid discard option");
1960818584a4SKevin Wolf             ret = -EINVAL;
1961818584a4SKevin Wolf             goto fail_opts;
1962818584a4SKevin Wolf         }
1963818584a4SKevin Wolf     }
1964818584a4SKevin Wolf 
1965543770bdSAlberto Garcia     bs->detect_zeroes =
1966543770bdSAlberto Garcia         bdrv_parse_detect_zeroes(opts, bs->open_flags, &local_err);
1967692e01a2SKevin Wolf     if (local_err) {
1968692e01a2SKevin Wolf         error_propagate(errp, local_err);
1969692e01a2SKevin Wolf         ret = -EINVAL;
1970692e01a2SKevin Wolf         goto fail_opts;
1971692e01a2SKevin Wolf     }
1972692e01a2SKevin Wolf 
1973c2ad1b0cSKevin Wolf     if (filename != NULL) {
197457915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1975c2ad1b0cSKevin Wolf     } else {
1976c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
1977c2ad1b0cSKevin Wolf     }
197891af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
197957915332SKevin Wolf 
198066f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
198182dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
198201a56501SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
198366f82ceeSKevin Wolf 
198441770f6eSPaolo Bonzini     assert(!drv->protocol_name || file == NULL);
198501a56501SKevin Wolf     ret = bdrv_open_driver(bs, drv, node_name, options, open_flags, errp);
198657915332SKevin Wolf     if (ret < 0) {
198701a56501SKevin Wolf         goto fail_opts;
198834b5d2c6SMax Reitz     }
198918edf289SKevin Wolf 
199018edf289SKevin Wolf     qemu_opts_del(opts);
199157915332SKevin Wolf     return 0;
199257915332SKevin Wolf 
199318edf289SKevin Wolf fail_opts:
199418edf289SKevin Wolf     qemu_opts_del(opts);
199557915332SKevin Wolf     return ret;
199657915332SKevin Wolf }
199757915332SKevin Wolf 
19985e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
19995e5c4f63SKevin Wolf {
20007b22e055SZhao Liu     ERRP_GUARD();
20015e5c4f63SKevin Wolf     QObject *options_obj;
20025e5c4f63SKevin Wolf     QDict *options;
20035e5c4f63SKevin Wolf     int ret;
2004bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
20055e5c4f63SKevin Wolf 
20065e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
20075e5c4f63SKevin Wolf     assert(ret);
20085e5c4f63SKevin Wolf 
20095577fff7SMarkus Armbruster     options_obj = qobject_from_json(filename, errp);
20105e5c4f63SKevin Wolf     if (!options_obj) {
20115577fff7SMarkus Armbruster         error_prepend(errp, "Could not parse the JSON options: ");
20125577fff7SMarkus Armbruster         return NULL;
20135577fff7SMarkus Armbruster     }
20145e5c4f63SKevin Wolf 
20157dc847ebSMax Reitz     options = qobject_to(QDict, options_obj);
2016ca6b6e1eSMarkus Armbruster     if (!options) {
2017cb3e7f08SMarc-André Lureau         qobject_unref(options_obj);
20185e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
20195e5c4f63SKevin Wolf         return NULL;
20205e5c4f63SKevin Wolf     }
20215e5c4f63SKevin Wolf 
20225e5c4f63SKevin Wolf     qdict_flatten(options);
20235e5c4f63SKevin Wolf 
20245e5c4f63SKevin Wolf     return options;
20255e5c4f63SKevin Wolf }
20265e5c4f63SKevin Wolf 
2027de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
2028de3b53f0SKevin Wolf                                 Error **errp)
2029de3b53f0SKevin Wolf {
2030de3b53f0SKevin Wolf     QDict *json_options;
2031de3b53f0SKevin Wolf     Error *local_err = NULL;
2032bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2033de3b53f0SKevin Wolf 
2034de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
2035de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
2036de3b53f0SKevin Wolf         return;
2037de3b53f0SKevin Wolf     }
2038de3b53f0SKevin Wolf 
2039de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
2040de3b53f0SKevin Wolf     if (local_err) {
2041de3b53f0SKevin Wolf         error_propagate(errp, local_err);
2042de3b53f0SKevin Wolf         return;
2043de3b53f0SKevin Wolf     }
2044de3b53f0SKevin Wolf 
2045de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
2046de3b53f0SKevin Wolf      * specified directly */
2047de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
2048cb3e7f08SMarc-André Lureau     qobject_unref(json_options);
2049de3b53f0SKevin Wolf     *pfilename = NULL;
2050de3b53f0SKevin Wolf }
2051de3b53f0SKevin Wolf 
205257915332SKevin Wolf /*
2053f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
2054f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
205553a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
205653a29513SMax Reitz  * block driver has been specified explicitly.
2057f54120ffSKevin Wolf  */
2058de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
20597ead9469SKevin Wolf                              int *flags, bool allow_parse_filename,
20607ead9469SKevin Wolf                              Error **errp)
2061f54120ffSKevin Wolf {
2062f54120ffSKevin Wolf     const char *drvname;
206353a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
2064f54120ffSKevin Wolf     bool parse_filename = false;
2065053e1578SMax Reitz     BlockDriver *drv = NULL;
2066f54120ffSKevin Wolf     Error *local_err = NULL;
2067f54120ffSKevin Wolf 
2068da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2069da359909SEmanuele Giuseppe Esposito 
2070129c7d1cSMarkus Armbruster     /*
2071129c7d1cSMarkus Armbruster      * Caution: while qdict_get_try_str() is fine, getting non-string
2072129c7d1cSMarkus Armbruster      * types would require more care.  When @options come from
2073129c7d1cSMarkus Armbruster      * -blockdev or blockdev_add, its members are typed according to
2074129c7d1cSMarkus Armbruster      * the QAPI schema, but when they come from -drive, they're all
2075129c7d1cSMarkus Armbruster      * QString.
2076129c7d1cSMarkus Armbruster      */
207753a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
2078053e1578SMax Reitz     if (drvname) {
2079053e1578SMax Reitz         drv = bdrv_find_format(drvname);
2080053e1578SMax Reitz         if (!drv) {
2081053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
2082053e1578SMax Reitz             return -ENOENT;
2083053e1578SMax Reitz         }
208453a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
208553a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
208641770f6eSPaolo Bonzini         protocol = drv->protocol_name;
208753a29513SMax Reitz     }
208853a29513SMax Reitz 
208953a29513SMax Reitz     if (protocol) {
209053a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
209153a29513SMax Reitz     } else {
209253a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
209353a29513SMax Reitz     }
209453a29513SMax Reitz 
209591a097e7SKevin Wolf     /* Translate cache options from flags into options */
209691a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
209791a097e7SKevin Wolf 
2098f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
209917b005f1SKevin Wolf     if (protocol && filename) {
2100f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
210146f5ac20SEric Blake             qdict_put_str(*options, "filename", filename);
21027ead9469SKevin Wolf             parse_filename = allow_parse_filename;
2103f54120ffSKevin Wolf         } else {
2104f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
2105f54120ffSKevin Wolf                              "the same time");
2106f54120ffSKevin Wolf             return -EINVAL;
2107f54120ffSKevin Wolf         }
2108f54120ffSKevin Wolf     }
2109f54120ffSKevin Wolf 
2110f54120ffSKevin Wolf     /* Find the right block driver */
2111129c7d1cSMarkus Armbruster     /* See cautionary note on accessing @options above */
2112f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
2113f54120ffSKevin Wolf 
211417b005f1SKevin Wolf     if (!drvname && protocol) {
2115f54120ffSKevin Wolf         if (filename) {
2116b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
2117f54120ffSKevin Wolf             if (!drv) {
2118f54120ffSKevin Wolf                 return -EINVAL;
2119f54120ffSKevin Wolf             }
2120f54120ffSKevin Wolf 
2121f54120ffSKevin Wolf             drvname = drv->format_name;
212246f5ac20SEric Blake             qdict_put_str(*options, "driver", drvname);
2123f54120ffSKevin Wolf         } else {
2124f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
2125f54120ffSKevin Wolf             return -EINVAL;
2126f54120ffSKevin Wolf         }
212717b005f1SKevin Wolf     }
212817b005f1SKevin Wolf 
212917b005f1SKevin Wolf     assert(drv || !protocol);
2130f54120ffSKevin Wolf 
2131f54120ffSKevin Wolf     /* Driver-specific filename parsing */
213217b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
2133f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
2134f54120ffSKevin Wolf         if (local_err) {
2135f54120ffSKevin Wolf             error_propagate(errp, local_err);
2136f54120ffSKevin Wolf             return -EINVAL;
2137f54120ffSKevin Wolf         }
2138f54120ffSKevin Wolf 
2139f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
2140f54120ffSKevin Wolf             qdict_del(*options, "filename");
2141f54120ffSKevin Wolf         }
2142f54120ffSKevin Wolf     }
2143f54120ffSKevin Wolf 
2144f54120ffSKevin Wolf     return 0;
2145f54120ffSKevin Wolf }
2146f54120ffSKevin Wolf 
2147148eb13cSKevin Wolf typedef struct BlockReopenQueueEntry {
2148148eb13cSKevin Wolf      bool prepared;
2149148eb13cSKevin Wolf      BDRVReopenState state;
2150859443b0SVladimir Sementsov-Ogievskiy      QTAILQ_ENTRY(BlockReopenQueueEntry) entry;
2151148eb13cSKevin Wolf } BlockReopenQueueEntry;
2152148eb13cSKevin Wolf 
2153148eb13cSKevin Wolf /*
2154148eb13cSKevin Wolf  * Return the flags that @bs will have after the reopens in @q have
2155148eb13cSKevin Wolf  * successfully completed. If @q is NULL (or @bs is not contained in @q),
2156148eb13cSKevin Wolf  * return the current flags.
2157148eb13cSKevin Wolf  */
2158148eb13cSKevin Wolf static int bdrv_reopen_get_flags(BlockReopenQueue *q, BlockDriverState *bs)
2159148eb13cSKevin Wolf {
2160148eb13cSKevin Wolf     BlockReopenQueueEntry *entry;
2161148eb13cSKevin Wolf 
2162148eb13cSKevin Wolf     if (q != NULL) {
2163859443b0SVladimir Sementsov-Ogievskiy         QTAILQ_FOREACH(entry, q, entry) {
2164148eb13cSKevin Wolf             if (entry->state.bs == bs) {
2165148eb13cSKevin Wolf                 return entry->state.flags;
2166148eb13cSKevin Wolf             }
2167148eb13cSKevin Wolf         }
2168148eb13cSKevin Wolf     }
2169148eb13cSKevin Wolf 
2170148eb13cSKevin Wolf     return bs->open_flags;
2171148eb13cSKevin Wolf }
2172148eb13cSKevin Wolf 
2173148eb13cSKevin Wolf /* Returns whether the image file can be written to after the reopen queue @q
2174148eb13cSKevin Wolf  * has been successfully applied, or right now if @q is NULL. */
2175cc022140SMax Reitz static bool bdrv_is_writable_after_reopen(BlockDriverState *bs,
2176cc022140SMax Reitz                                           BlockReopenQueue *q)
2177148eb13cSKevin Wolf {
2178148eb13cSKevin Wolf     int flags = bdrv_reopen_get_flags(q, bs);
2179148eb13cSKevin Wolf 
2180148eb13cSKevin Wolf     return (flags & (BDRV_O_RDWR | BDRV_O_INACTIVE)) == BDRV_O_RDWR;
2181148eb13cSKevin Wolf }
2182148eb13cSKevin Wolf 
2183cc022140SMax Reitz /*
2184cc022140SMax Reitz  * Return whether the BDS can be written to.  This is not necessarily
2185cc022140SMax Reitz  * the same as !bdrv_is_read_only(bs), as inactivated images may not
2186cc022140SMax Reitz  * be written to but do not count as read-only images.
2187cc022140SMax Reitz  */
2188cc022140SMax Reitz bool bdrv_is_writable(BlockDriverState *bs)
2189cc022140SMax Reitz {
2190384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
2191cc022140SMax Reitz     return bdrv_is_writable_after_reopen(bs, NULL);
2192cc022140SMax Reitz }
2193cc022140SMax Reitz 
21943bf416baSVladimir Sementsov-Ogievskiy static char *bdrv_child_user_desc(BdrvChild *c)
21953bf416baSVladimir Sementsov-Ogievskiy {
2196f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
21973bf416baSVladimir Sementsov-Ogievskiy     return c->klass->get_parent_desc(c);
21983bf416baSVladimir Sementsov-Ogievskiy }
21993bf416baSVladimir Sementsov-Ogievskiy 
220030ebb9aaSVladimir Sementsov-Ogievskiy /*
220130ebb9aaSVladimir Sementsov-Ogievskiy  * Check that @a allows everything that @b needs. @a and @b must reference same
220230ebb9aaSVladimir Sementsov-Ogievskiy  * child node.
220330ebb9aaSVladimir Sementsov-Ogievskiy  */
22043bf416baSVladimir Sementsov-Ogievskiy static bool bdrv_a_allow_b(BdrvChild *a, BdrvChild *b, Error **errp)
22053bf416baSVladimir Sementsov-Ogievskiy {
220630ebb9aaSVladimir Sementsov-Ogievskiy     const char *child_bs_name;
220730ebb9aaSVladimir Sementsov-Ogievskiy     g_autofree char *a_user = NULL;
220830ebb9aaSVladimir Sementsov-Ogievskiy     g_autofree char *b_user = NULL;
220930ebb9aaSVladimir Sementsov-Ogievskiy     g_autofree char *perms = NULL;
221030ebb9aaSVladimir Sementsov-Ogievskiy 
221130ebb9aaSVladimir Sementsov-Ogievskiy     assert(a->bs);
221230ebb9aaSVladimir Sementsov-Ogievskiy     assert(a->bs == b->bs);
2213862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
22143bf416baSVladimir Sementsov-Ogievskiy 
22153bf416baSVladimir Sementsov-Ogievskiy     if ((b->perm & a->shared_perm) == b->perm) {
22163bf416baSVladimir Sementsov-Ogievskiy         return true;
22173bf416baSVladimir Sementsov-Ogievskiy     }
22183bf416baSVladimir Sementsov-Ogievskiy 
221930ebb9aaSVladimir Sementsov-Ogievskiy     child_bs_name = bdrv_get_node_name(b->bs);
222030ebb9aaSVladimir Sementsov-Ogievskiy     a_user = bdrv_child_user_desc(a);
222130ebb9aaSVladimir Sementsov-Ogievskiy     b_user = bdrv_child_user_desc(b);
222230ebb9aaSVladimir Sementsov-Ogievskiy     perms = bdrv_perm_names(b->perm & ~a->shared_perm);
222330ebb9aaSVladimir Sementsov-Ogievskiy 
222430ebb9aaSVladimir Sementsov-Ogievskiy     error_setg(errp, "Permission conflict on node '%s': permissions '%s' are "
222530ebb9aaSVladimir Sementsov-Ogievskiy                "both required by %s (uses node '%s' as '%s' child) and "
222630ebb9aaSVladimir Sementsov-Ogievskiy                "unshared by %s (uses node '%s' as '%s' child).",
222730ebb9aaSVladimir Sementsov-Ogievskiy                child_bs_name, perms,
222830ebb9aaSVladimir Sementsov-Ogievskiy                b_user, child_bs_name, b->name,
222930ebb9aaSVladimir Sementsov-Ogievskiy                a_user, child_bs_name, a->name);
22303bf416baSVladimir Sementsov-Ogievskiy 
22313bf416baSVladimir Sementsov-Ogievskiy     return false;
22323bf416baSVladimir Sementsov-Ogievskiy }
22333bf416baSVladimir Sementsov-Ogievskiy 
22343804e3cfSKevin Wolf static bool GRAPH_RDLOCK
22353804e3cfSKevin Wolf bdrv_parent_perms_conflict(BlockDriverState *bs, Error **errp)
22363bf416baSVladimir Sementsov-Ogievskiy {
22373bf416baSVladimir Sementsov-Ogievskiy     BdrvChild *a, *b;
2238862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
22393bf416baSVladimir Sementsov-Ogievskiy 
22403bf416baSVladimir Sementsov-Ogievskiy     /*
22413bf416baSVladimir Sementsov-Ogievskiy      * During the loop we'll look at each pair twice. That's correct because
22423bf416baSVladimir Sementsov-Ogievskiy      * bdrv_a_allow_b() is asymmetric and we should check each pair in both
22433bf416baSVladimir Sementsov-Ogievskiy      * directions.
22443bf416baSVladimir Sementsov-Ogievskiy      */
22453bf416baSVladimir Sementsov-Ogievskiy     QLIST_FOREACH(a, &bs->parents, next_parent) {
22463bf416baSVladimir Sementsov-Ogievskiy         QLIST_FOREACH(b, &bs->parents, next_parent) {
22479397c14fSVladimir Sementsov-Ogievskiy             if (a == b) {
22483bf416baSVladimir Sementsov-Ogievskiy                 continue;
22493bf416baSVladimir Sementsov-Ogievskiy             }
22503bf416baSVladimir Sementsov-Ogievskiy 
22513bf416baSVladimir Sementsov-Ogievskiy             if (!bdrv_a_allow_b(a, b, errp)) {
22523bf416baSVladimir Sementsov-Ogievskiy                 return true;
22533bf416baSVladimir Sementsov-Ogievskiy             }
22543bf416baSVladimir Sementsov-Ogievskiy         }
22553bf416baSVladimir Sementsov-Ogievskiy     }
22563bf416baSVladimir Sementsov-Ogievskiy 
22573bf416baSVladimir Sementsov-Ogievskiy     return false;
22583bf416baSVladimir Sementsov-Ogievskiy }
22593bf416baSVladimir Sementsov-Ogievskiy 
2260c629b6d2SKevin Wolf static void GRAPH_RDLOCK
2261c629b6d2SKevin Wolf bdrv_child_perm(BlockDriverState *bs, BlockDriverState *child_bs,
2262e5d8a406SMax Reitz                 BdrvChild *c, BdrvChildRole role,
2263e5d8a406SMax Reitz                 BlockReopenQueue *reopen_queue,
2264ffd1a5a2SFam Zheng                 uint64_t parent_perm, uint64_t parent_shared,
2265ffd1a5a2SFam Zheng                 uint64_t *nperm, uint64_t *nshared)
2266ffd1a5a2SFam Zheng {
22670b3ca76eSAlberto Garcia     assert(bs->drv && bs->drv->bdrv_child_perm);
2268da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2269e5d8a406SMax Reitz     bs->drv->bdrv_child_perm(bs, c, role, reopen_queue,
2270ffd1a5a2SFam Zheng                              parent_perm, parent_shared,
2271ffd1a5a2SFam Zheng                              nperm, nshared);
2272e0995dc3SKevin Wolf     /* TODO Take force_share from reopen_queue */
2273ffd1a5a2SFam Zheng     if (child_bs && child_bs->force_share) {
2274ffd1a5a2SFam Zheng         *nshared = BLK_PERM_ALL;
2275ffd1a5a2SFam Zheng     }
2276ffd1a5a2SFam Zheng }
2277ffd1a5a2SFam Zheng 
2278bd57f8f7SVladimir Sementsov-Ogievskiy /*
2279bd57f8f7SVladimir Sementsov-Ogievskiy  * Adds the whole subtree of @bs (including @bs itself) to the @list (except for
2280bd57f8f7SVladimir Sementsov-Ogievskiy  * nodes that are already in the @list, of course) so that final list is
2281bd57f8f7SVladimir Sementsov-Ogievskiy  * topologically sorted. Return the result (GSList @list object is updated, so
2282bd57f8f7SVladimir Sementsov-Ogievskiy  * don't use old reference after function call).
2283bd57f8f7SVladimir Sementsov-Ogievskiy  *
2284bd57f8f7SVladimir Sementsov-Ogievskiy  * On function start @list must be already topologically sorted and for any node
2285bd57f8f7SVladimir Sementsov-Ogievskiy  * in the @list the whole subtree of the node must be in the @list as well. The
2286bd57f8f7SVladimir Sementsov-Ogievskiy  * simplest way to satisfy this criteria: use only result of
2287bd57f8f7SVladimir Sementsov-Ogievskiy  * bdrv_topological_dfs() or NULL as @list parameter.
2288bd57f8f7SVladimir Sementsov-Ogievskiy  */
22893804e3cfSKevin Wolf static GSList * GRAPH_RDLOCK
22903804e3cfSKevin Wolf bdrv_topological_dfs(GSList *list, GHashTable *found, BlockDriverState *bs)
2291bd57f8f7SVladimir Sementsov-Ogievskiy {
2292bd57f8f7SVladimir Sementsov-Ogievskiy     BdrvChild *child;
2293bd57f8f7SVladimir Sementsov-Ogievskiy     g_autoptr(GHashTable) local_found = NULL;
2294bd57f8f7SVladimir Sementsov-Ogievskiy 
2295bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2296bdb73476SEmanuele Giuseppe Esposito 
2297bd57f8f7SVladimir Sementsov-Ogievskiy     if (!found) {
2298bd57f8f7SVladimir Sementsov-Ogievskiy         assert(!list);
2299bd57f8f7SVladimir Sementsov-Ogievskiy         found = local_found = g_hash_table_new(NULL, NULL);
2300bd57f8f7SVladimir Sementsov-Ogievskiy     }
2301bd57f8f7SVladimir Sementsov-Ogievskiy 
2302bd57f8f7SVladimir Sementsov-Ogievskiy     if (g_hash_table_contains(found, bs)) {
2303bd57f8f7SVladimir Sementsov-Ogievskiy         return list;
2304bd57f8f7SVladimir Sementsov-Ogievskiy     }
2305bd57f8f7SVladimir Sementsov-Ogievskiy     g_hash_table_add(found, bs);
2306bd57f8f7SVladimir Sementsov-Ogievskiy 
2307bd57f8f7SVladimir Sementsov-Ogievskiy     QLIST_FOREACH(child, &bs->children, next) {
2308bd57f8f7SVladimir Sementsov-Ogievskiy         list = bdrv_topological_dfs(list, found, child->bs);
2309bd57f8f7SVladimir Sementsov-Ogievskiy     }
2310bd57f8f7SVladimir Sementsov-Ogievskiy 
2311bd57f8f7SVladimir Sementsov-Ogievskiy     return g_slist_prepend(list, bs);
2312bd57f8f7SVladimir Sementsov-Ogievskiy }
2313bd57f8f7SVladimir Sementsov-Ogievskiy 
2314ecb776bdSVladimir Sementsov-Ogievskiy typedef struct BdrvChildSetPermState {
2315ecb776bdSVladimir Sementsov-Ogievskiy     BdrvChild *child;
2316ecb776bdSVladimir Sementsov-Ogievskiy     uint64_t old_perm;
2317ecb776bdSVladimir Sementsov-Ogievskiy     uint64_t old_shared_perm;
2318ecb776bdSVladimir Sementsov-Ogievskiy } BdrvChildSetPermState;
2319b0defa83SVladimir Sementsov-Ogievskiy 
2320b0defa83SVladimir Sementsov-Ogievskiy static void bdrv_child_set_perm_abort(void *opaque)
2321b0defa83SVladimir Sementsov-Ogievskiy {
2322ecb776bdSVladimir Sementsov-Ogievskiy     BdrvChildSetPermState *s = opaque;
2323ecb776bdSVladimir Sementsov-Ogievskiy 
2324862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2325862fded9SEmanuele Giuseppe Esposito 
2326ecb776bdSVladimir Sementsov-Ogievskiy     s->child->perm = s->old_perm;
2327ecb776bdSVladimir Sementsov-Ogievskiy     s->child->shared_perm = s->old_shared_perm;
2328b0defa83SVladimir Sementsov-Ogievskiy }
2329b0defa83SVladimir Sementsov-Ogievskiy 
2330b0defa83SVladimir Sementsov-Ogievskiy static TransactionActionDrv bdrv_child_set_pem_drv = {
2331b0defa83SVladimir Sementsov-Ogievskiy     .abort = bdrv_child_set_perm_abort,
2332ecb776bdSVladimir Sementsov-Ogievskiy     .clean = g_free,
2333b0defa83SVladimir Sementsov-Ogievskiy };
2334b0defa83SVladimir Sementsov-Ogievskiy 
2335ecb776bdSVladimir Sementsov-Ogievskiy static void bdrv_child_set_perm(BdrvChild *c, uint64_t perm,
2336b0defa83SVladimir Sementsov-Ogievskiy                                 uint64_t shared, Transaction *tran)
2337b0defa83SVladimir Sementsov-Ogievskiy {
2338ecb776bdSVladimir Sementsov-Ogievskiy     BdrvChildSetPermState *s = g_new(BdrvChildSetPermState, 1);
2339862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2340ecb776bdSVladimir Sementsov-Ogievskiy 
2341ecb776bdSVladimir Sementsov-Ogievskiy     *s = (BdrvChildSetPermState) {
2342ecb776bdSVladimir Sementsov-Ogievskiy         .child = c,
2343ecb776bdSVladimir Sementsov-Ogievskiy         .old_perm = c->perm,
2344ecb776bdSVladimir Sementsov-Ogievskiy         .old_shared_perm = c->shared_perm,
2345ecb776bdSVladimir Sementsov-Ogievskiy     };
2346b0defa83SVladimir Sementsov-Ogievskiy 
2347b0defa83SVladimir Sementsov-Ogievskiy     c->perm = perm;
2348b0defa83SVladimir Sementsov-Ogievskiy     c->shared_perm = shared;
2349b0defa83SVladimir Sementsov-Ogievskiy 
2350ecb776bdSVladimir Sementsov-Ogievskiy     tran_add(tran, &bdrv_child_set_pem_drv, s);
2351b0defa83SVladimir Sementsov-Ogievskiy }
2352b0defa83SVladimir Sementsov-Ogievskiy 
2353bce73bc2SKevin Wolf static void GRAPH_RDLOCK bdrv_drv_set_perm_commit(void *opaque)
23542513ef59SVladimir Sementsov-Ogievskiy {
23552513ef59SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = opaque;
23562513ef59SVladimir Sementsov-Ogievskiy     uint64_t cumulative_perms, cumulative_shared_perms;
2357da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
23582513ef59SVladimir Sementsov-Ogievskiy 
23592513ef59SVladimir Sementsov-Ogievskiy     if (bs->drv->bdrv_set_perm) {
23602513ef59SVladimir Sementsov-Ogievskiy         bdrv_get_cumulative_perm(bs, &cumulative_perms,
23612513ef59SVladimir Sementsov-Ogievskiy                                  &cumulative_shared_perms);
23622513ef59SVladimir Sementsov-Ogievskiy         bs->drv->bdrv_set_perm(bs, cumulative_perms, cumulative_shared_perms);
23632513ef59SVladimir Sementsov-Ogievskiy     }
23642513ef59SVladimir Sementsov-Ogievskiy }
23652513ef59SVladimir Sementsov-Ogievskiy 
2366bce73bc2SKevin Wolf static void GRAPH_RDLOCK bdrv_drv_set_perm_abort(void *opaque)
23672513ef59SVladimir Sementsov-Ogievskiy {
23682513ef59SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = opaque;
2369da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
23702513ef59SVladimir Sementsov-Ogievskiy 
23712513ef59SVladimir Sementsov-Ogievskiy     if (bs->drv->bdrv_abort_perm_update) {
23722513ef59SVladimir Sementsov-Ogievskiy         bs->drv->bdrv_abort_perm_update(bs);
23732513ef59SVladimir Sementsov-Ogievskiy     }
23742513ef59SVladimir Sementsov-Ogievskiy }
23752513ef59SVladimir Sementsov-Ogievskiy 
23762513ef59SVladimir Sementsov-Ogievskiy TransactionActionDrv bdrv_drv_set_perm_drv = {
23772513ef59SVladimir Sementsov-Ogievskiy     .abort = bdrv_drv_set_perm_abort,
23782513ef59SVladimir Sementsov-Ogievskiy     .commit = bdrv_drv_set_perm_commit,
23792513ef59SVladimir Sementsov-Ogievskiy };
23802513ef59SVladimir Sementsov-Ogievskiy 
2381bce73bc2SKevin Wolf /*
2382bce73bc2SKevin Wolf  * After calling this function, the transaction @tran may only be completed
2383bce73bc2SKevin Wolf  * while holding a reader lock for the graph.
2384bce73bc2SKevin Wolf  */
2385bce73bc2SKevin Wolf static int GRAPH_RDLOCK
2386bce73bc2SKevin Wolf bdrv_drv_set_perm(BlockDriverState *bs, uint64_t perm, uint64_t shared_perm,
2387bce73bc2SKevin Wolf                   Transaction *tran, Error **errp)
23882513ef59SVladimir Sementsov-Ogievskiy {
2389da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
23902513ef59SVladimir Sementsov-Ogievskiy     if (!bs->drv) {
23912513ef59SVladimir Sementsov-Ogievskiy         return 0;
23922513ef59SVladimir Sementsov-Ogievskiy     }
23932513ef59SVladimir Sementsov-Ogievskiy 
23942513ef59SVladimir Sementsov-Ogievskiy     if (bs->drv->bdrv_check_perm) {
23952513ef59SVladimir Sementsov-Ogievskiy         int ret = bs->drv->bdrv_check_perm(bs, perm, shared_perm, errp);
23962513ef59SVladimir Sementsov-Ogievskiy         if (ret < 0) {
23972513ef59SVladimir Sementsov-Ogievskiy             return ret;
23982513ef59SVladimir Sementsov-Ogievskiy         }
23992513ef59SVladimir Sementsov-Ogievskiy     }
24002513ef59SVladimir Sementsov-Ogievskiy 
24012513ef59SVladimir Sementsov-Ogievskiy     if (tran) {
24022513ef59SVladimir Sementsov-Ogievskiy         tran_add(tran, &bdrv_drv_set_perm_drv, bs);
24032513ef59SVladimir Sementsov-Ogievskiy     }
24042513ef59SVladimir Sementsov-Ogievskiy 
24052513ef59SVladimir Sementsov-Ogievskiy     return 0;
24062513ef59SVladimir Sementsov-Ogievskiy }
24072513ef59SVladimir Sementsov-Ogievskiy 
24080978623eSVladimir Sementsov-Ogievskiy typedef struct BdrvReplaceChildState {
24090978623eSVladimir Sementsov-Ogievskiy     BdrvChild *child;
24100978623eSVladimir Sementsov-Ogievskiy     BlockDriverState *old_bs;
24110978623eSVladimir Sementsov-Ogievskiy } BdrvReplaceChildState;
24120978623eSVladimir Sementsov-Ogievskiy 
24135661a00dSKevin Wolf static void GRAPH_WRLOCK bdrv_replace_child_commit(void *opaque)
24140978623eSVladimir Sementsov-Ogievskiy {
24150978623eSVladimir Sementsov-Ogievskiy     BdrvReplaceChildState *s = opaque;
2416bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
24170978623eSVladimir Sementsov-Ogievskiy 
24185661a00dSKevin Wolf     bdrv_schedule_unref(s->old_bs);
24190978623eSVladimir Sementsov-Ogievskiy }
24200978623eSVladimir Sementsov-Ogievskiy 
24215661a00dSKevin Wolf static void GRAPH_WRLOCK bdrv_replace_child_abort(void *opaque)
24220978623eSVladimir Sementsov-Ogievskiy {
24230978623eSVladimir Sementsov-Ogievskiy     BdrvReplaceChildState *s = opaque;
24240978623eSVladimir Sementsov-Ogievskiy     BlockDriverState *new_bs = s->child->bs;
24250978623eSVladimir Sementsov-Ogievskiy 
2426bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
24275661a00dSKevin Wolf     assert_bdrv_graph_writable();
2428ad29eb3dSKevin Wolf 
24290f0b1e29SVladimir Sementsov-Ogievskiy     /* old_bs reference is transparently moved from @s to @s->child */
243023987471SKevin Wolf     if (!s->child->bs) {
243123987471SKevin Wolf         /*
243223987471SKevin Wolf          * The parents were undrained when removing old_bs from the child. New
243323987471SKevin Wolf          * requests can't have been made, though, because the child was empty.
243423987471SKevin Wolf          *
243523987471SKevin Wolf          * TODO Make bdrv_replace_child_noperm() transactionable to avoid
243623987471SKevin Wolf          * undraining the parent in the first place. Once this is done, having
243723987471SKevin Wolf          * new_bs drained when calling bdrv_replace_child_tran() is not a
243823987471SKevin Wolf          * requirement any more.
243923987471SKevin Wolf          */
2440606ed756SKevin Wolf         bdrv_parent_drained_begin_single(s->child);
244123987471SKevin Wolf         assert(!bdrv_parent_drained_poll_single(s->child));
244223987471SKevin Wolf     }
244323987471SKevin Wolf     assert(s->child->quiesced_parent);
2444544acc7dSVladimir Sementsov-Ogievskiy     bdrv_replace_child_noperm(s->child, s->old_bs);
2445ad29eb3dSKevin Wolf 
24460978623eSVladimir Sementsov-Ogievskiy     bdrv_unref(new_bs);
24470978623eSVladimir Sementsov-Ogievskiy }
24480978623eSVladimir Sementsov-Ogievskiy 
24490978623eSVladimir Sementsov-Ogievskiy static TransactionActionDrv bdrv_replace_child_drv = {
24500978623eSVladimir Sementsov-Ogievskiy     .commit = bdrv_replace_child_commit,
24510978623eSVladimir Sementsov-Ogievskiy     .abort = bdrv_replace_child_abort,
24520978623eSVladimir Sementsov-Ogievskiy     .clean = g_free,
24530978623eSVladimir Sementsov-Ogievskiy };
24540978623eSVladimir Sementsov-Ogievskiy 
24550978623eSVladimir Sementsov-Ogievskiy /*
24564bf021dbSVladimir Sementsov-Ogievskiy  * bdrv_replace_child_tran
24570978623eSVladimir Sementsov-Ogievskiy  *
24580978623eSVladimir Sementsov-Ogievskiy  * Note: real unref of old_bs is done only on commit.
24594bf021dbSVladimir Sementsov-Ogievskiy  *
246023987471SKevin Wolf  * Both @child->bs and @new_bs (if non-NULL) must be drained. @new_bs must be
246123987471SKevin Wolf  * kept drained until the transaction is completed.
246223987471SKevin Wolf  *
24635661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
24645661a00dSKevin Wolf  * while holding a writer lock for the graph.
24655661a00dSKevin Wolf  *
24664bf021dbSVladimir Sementsov-Ogievskiy  * The function doesn't update permissions, caller is responsible for this.
24670978623eSVladimir Sementsov-Ogievskiy  */
24682f64e1fcSKevin Wolf static void GRAPH_WRLOCK
24692f64e1fcSKevin Wolf bdrv_replace_child_tran(BdrvChild *child, BlockDriverState *new_bs,
24704eba825aSVladimir Sementsov-Ogievskiy                         Transaction *tran)
24710978623eSVladimir Sementsov-Ogievskiy {
24720978623eSVladimir Sementsov-Ogievskiy     BdrvReplaceChildState *s = g_new(BdrvReplaceChildState, 1);
247323987471SKevin Wolf 
247423987471SKevin Wolf     assert(child->quiesced_parent);
247523987471SKevin Wolf     assert(!new_bs || new_bs->quiesce_counter);
247623987471SKevin Wolf 
24770978623eSVladimir Sementsov-Ogievskiy     *s = (BdrvReplaceChildState) {
24780f0b1e29SVladimir Sementsov-Ogievskiy         .child = child,
24790f0b1e29SVladimir Sementsov-Ogievskiy         .old_bs = child->bs,
24800978623eSVladimir Sementsov-Ogievskiy     };
24810978623eSVladimir Sementsov-Ogievskiy     tran_add(tran, &bdrv_replace_child_drv, s);
24820978623eSVladimir Sementsov-Ogievskiy 
24830978623eSVladimir Sementsov-Ogievskiy     if (new_bs) {
24840978623eSVladimir Sementsov-Ogievskiy         bdrv_ref(new_bs);
24850978623eSVladimir Sementsov-Ogievskiy     }
2486ad29eb3dSKevin Wolf 
2487544acc7dSVladimir Sementsov-Ogievskiy     bdrv_replace_child_noperm(child, new_bs);
24880f0b1e29SVladimir Sementsov-Ogievskiy     /* old_bs reference is transparently moved from @child to @s */
24890978623eSVladimir Sementsov-Ogievskiy }
24900978623eSVladimir Sementsov-Ogievskiy 
249133a610c3SKevin Wolf /*
2492c20555e1SVladimir Sementsov-Ogievskiy  * Refresh permissions in @bs subtree. The function is intended to be called
2493c20555e1SVladimir Sementsov-Ogievskiy  * after some graph modification that was done without permission update.
2494bce73bc2SKevin Wolf  *
2495bce73bc2SKevin Wolf  * After calling this function, the transaction @tran may only be completed
2496bce73bc2SKevin Wolf  * while holding a reader lock for the graph.
249733a610c3SKevin Wolf  */
2498bce73bc2SKevin Wolf static int GRAPH_RDLOCK
2499bce73bc2SKevin Wolf bdrv_node_refresh_perm(BlockDriverState *bs, BlockReopenQueue *q,
2500b1d2bbebSVladimir Sementsov-Ogievskiy                        Transaction *tran, Error **errp)
250133a610c3SKevin Wolf {
250233a610c3SKevin Wolf     BlockDriver *drv = bs->drv;
250333a610c3SKevin Wolf     BdrvChild *c;
250433a610c3SKevin Wolf     int ret;
2505c20555e1SVladimir Sementsov-Ogievskiy     uint64_t cumulative_perms, cumulative_shared_perms;
2506862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2507c20555e1SVladimir Sementsov-Ogievskiy 
2508c20555e1SVladimir Sementsov-Ogievskiy     bdrv_get_cumulative_perm(bs, &cumulative_perms, &cumulative_shared_perms);
250933a610c3SKevin Wolf 
251033a610c3SKevin Wolf     /* Write permissions never work with read-only images */
251133a610c3SKevin Wolf     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
2512cc022140SMax Reitz         !bdrv_is_writable_after_reopen(bs, q))
251333a610c3SKevin Wolf     {
2514481e0eeeSMax Reitz         if (!bdrv_is_writable_after_reopen(bs, NULL)) {
251533a610c3SKevin Wolf             error_setg(errp, "Block node is read-only");
2516481e0eeeSMax Reitz         } else {
2517c20555e1SVladimir Sementsov-Ogievskiy             error_setg(errp, "Read-only block node '%s' cannot support "
2518c20555e1SVladimir Sementsov-Ogievskiy                        "read-write users", bdrv_get_node_name(bs));
2519481e0eeeSMax Reitz         }
2520481e0eeeSMax Reitz 
252133a610c3SKevin Wolf         return -EPERM;
252233a610c3SKevin Wolf     }
252333a610c3SKevin Wolf 
25249c60a5d1SKevin Wolf     /*
25259c60a5d1SKevin Wolf      * Unaligned requests will automatically be aligned to bl.request_alignment
25269c60a5d1SKevin Wolf      * and without RESIZE we can't extend requests to write to space beyond the
25279c60a5d1SKevin Wolf      * end of the image, so it's required that the image size is aligned.
25289c60a5d1SKevin Wolf      */
25299c60a5d1SKevin Wolf     if ((cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) &&
25309c60a5d1SKevin Wolf         !(cumulative_perms & BLK_PERM_RESIZE))
25319c60a5d1SKevin Wolf     {
25329c60a5d1SKevin Wolf         if ((bs->total_sectors * BDRV_SECTOR_SIZE) % bs->bl.request_alignment) {
25339c60a5d1SKevin Wolf             error_setg(errp, "Cannot get 'write' permission without 'resize': "
25349c60a5d1SKevin Wolf                              "Image size is not a multiple of request "
25359c60a5d1SKevin Wolf                              "alignment");
25369c60a5d1SKevin Wolf             return -EPERM;
25379c60a5d1SKevin Wolf         }
25389c60a5d1SKevin Wolf     }
25399c60a5d1SKevin Wolf 
254033a610c3SKevin Wolf     /* Check this node */
254133a610c3SKevin Wolf     if (!drv) {
254233a610c3SKevin Wolf         return 0;
254333a610c3SKevin Wolf     }
254433a610c3SKevin Wolf 
2545b1d2bbebSVladimir Sementsov-Ogievskiy     ret = bdrv_drv_set_perm(bs, cumulative_perms, cumulative_shared_perms, tran,
25462513ef59SVladimir Sementsov-Ogievskiy                             errp);
25479530a25bSVladimir Sementsov-Ogievskiy     if (ret < 0) {
25489530a25bSVladimir Sementsov-Ogievskiy         return ret;
25499530a25bSVladimir Sementsov-Ogievskiy     }
255033a610c3SKevin Wolf 
255178e421c9SKevin Wolf     /* Drivers that never have children can omit .bdrv_child_perm() */
255233a610c3SKevin Wolf     if (!drv->bdrv_child_perm) {
255378e421c9SKevin Wolf         assert(QLIST_EMPTY(&bs->children));
255433a610c3SKevin Wolf         return 0;
255533a610c3SKevin Wolf     }
255633a610c3SKevin Wolf 
255733a610c3SKevin Wolf     /* Check all children */
255833a610c3SKevin Wolf     QLIST_FOREACH(c, &bs->children, next) {
255933a610c3SKevin Wolf         uint64_t cur_perm, cur_shared;
25609eab1544SMax Reitz 
2561e5d8a406SMax Reitz         bdrv_child_perm(bs, c->bs, c, c->role, q,
256233a610c3SKevin Wolf                         cumulative_perms, cumulative_shared_perms,
256333a610c3SKevin Wolf                         &cur_perm, &cur_shared);
2564ecb776bdSVladimir Sementsov-Ogievskiy         bdrv_child_set_perm(c, cur_perm, cur_shared, tran);
2565b1d2bbebSVladimir Sementsov-Ogievskiy     }
2566b1d2bbebSVladimir Sementsov-Ogievskiy 
2567b1d2bbebSVladimir Sementsov-Ogievskiy     return 0;
2568b1d2bbebSVladimir Sementsov-Ogievskiy }
2569b1d2bbebSVladimir Sementsov-Ogievskiy 
2570fb0ff4d1SVladimir Sementsov-Ogievskiy /*
2571fb0ff4d1SVladimir Sementsov-Ogievskiy  * @list is a product of bdrv_topological_dfs() (may be called several times) -
2572fb0ff4d1SVladimir Sementsov-Ogievskiy  * a topologically sorted subgraph.
2573bce73bc2SKevin Wolf  *
2574bce73bc2SKevin Wolf  * After calling this function, the transaction @tran may only be completed
2575bce73bc2SKevin Wolf  * while holding a reader lock for the graph.
2576fb0ff4d1SVladimir Sementsov-Ogievskiy  */
25773804e3cfSKevin Wolf static int GRAPH_RDLOCK
25783804e3cfSKevin Wolf bdrv_do_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
25793804e3cfSKevin Wolf                       Error **errp)
2580b1d2bbebSVladimir Sementsov-Ogievskiy {
2581b1d2bbebSVladimir Sementsov-Ogievskiy     int ret;
2582b1d2bbebSVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
2583862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2584b1d2bbebSVladimir Sementsov-Ogievskiy 
2585b1d2bbebSVladimir Sementsov-Ogievskiy     for ( ; list; list = list->next) {
2586b1d2bbebSVladimir Sementsov-Ogievskiy         bs = list->data;
2587b1d2bbebSVladimir Sementsov-Ogievskiy 
25889397c14fSVladimir Sementsov-Ogievskiy         if (bdrv_parent_perms_conflict(bs, errp)) {
2589b1d2bbebSVladimir Sementsov-Ogievskiy             return -EINVAL;
2590b1d2bbebSVladimir Sementsov-Ogievskiy         }
2591b1d2bbebSVladimir Sementsov-Ogievskiy 
2592c20555e1SVladimir Sementsov-Ogievskiy         ret = bdrv_node_refresh_perm(bs, q, tran, errp);
2593b1d2bbebSVladimir Sementsov-Ogievskiy         if (ret < 0) {
2594b1d2bbebSVladimir Sementsov-Ogievskiy             return ret;
2595b1d2bbebSVladimir Sementsov-Ogievskiy         }
2596bd57f8f7SVladimir Sementsov-Ogievskiy     }
25973ef45e02SVladimir Sementsov-Ogievskiy 
2598bd57f8f7SVladimir Sementsov-Ogievskiy     return 0;
2599bd57f8f7SVladimir Sementsov-Ogievskiy }
2600bd57f8f7SVladimir Sementsov-Ogievskiy 
2601fb0ff4d1SVladimir Sementsov-Ogievskiy /*
2602fb0ff4d1SVladimir Sementsov-Ogievskiy  * @list is any list of nodes. List is completed by all subtrees and
2603fb0ff4d1SVladimir Sementsov-Ogievskiy  * topologically sorted. It's not a problem if some node occurs in the @list
2604fb0ff4d1SVladimir Sementsov-Ogievskiy  * several times.
2605bce73bc2SKevin Wolf  *
2606bce73bc2SKevin Wolf  * After calling this function, the transaction @tran may only be completed
2607bce73bc2SKevin Wolf  * while holding a reader lock for the graph.
2608fb0ff4d1SVladimir Sementsov-Ogievskiy  */
26093804e3cfSKevin Wolf static int GRAPH_RDLOCK
26103804e3cfSKevin Wolf bdrv_list_refresh_perms(GSList *list, BlockReopenQueue *q, Transaction *tran,
26113804e3cfSKevin Wolf                         Error **errp)
2612fb0ff4d1SVladimir Sementsov-Ogievskiy {
2613fb0ff4d1SVladimir Sementsov-Ogievskiy     g_autoptr(GHashTable) found = g_hash_table_new(NULL, NULL);
2614fb0ff4d1SVladimir Sementsov-Ogievskiy     g_autoptr(GSList) refresh_list = NULL;
2615fb0ff4d1SVladimir Sementsov-Ogievskiy 
2616fb0ff4d1SVladimir Sementsov-Ogievskiy     for ( ; list; list = list->next) {
2617fb0ff4d1SVladimir Sementsov-Ogievskiy         refresh_list = bdrv_topological_dfs(refresh_list, found, list->data);
2618fb0ff4d1SVladimir Sementsov-Ogievskiy     }
2619fb0ff4d1SVladimir Sementsov-Ogievskiy 
2620fb0ff4d1SVladimir Sementsov-Ogievskiy     return bdrv_do_refresh_perms(refresh_list, q, tran, errp);
2621fb0ff4d1SVladimir Sementsov-Ogievskiy }
2622fb0ff4d1SVladimir Sementsov-Ogievskiy 
2623c7a0f2beSKevin Wolf void bdrv_get_cumulative_perm(BlockDriverState *bs, uint64_t *perm,
262433a610c3SKevin Wolf                               uint64_t *shared_perm)
262533a610c3SKevin Wolf {
262633a610c3SKevin Wolf     BdrvChild *c;
262733a610c3SKevin Wolf     uint64_t cumulative_perms = 0;
262833a610c3SKevin Wolf     uint64_t cumulative_shared_perms = BLK_PERM_ALL;
262933a610c3SKevin Wolf 
2630b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2631b4ad82aaSEmanuele Giuseppe Esposito 
263233a610c3SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
263333a610c3SKevin Wolf         cumulative_perms |= c->perm;
263433a610c3SKevin Wolf         cumulative_shared_perms &= c->shared_perm;
263533a610c3SKevin Wolf     }
263633a610c3SKevin Wolf 
263733a610c3SKevin Wolf     *perm = cumulative_perms;
263833a610c3SKevin Wolf     *shared_perm = cumulative_shared_perms;
263933a610c3SKevin Wolf }
264033a610c3SKevin Wolf 
26415176196cSFam Zheng char *bdrv_perm_names(uint64_t perm)
2642d083319fSKevin Wolf {
2643d083319fSKevin Wolf     struct perm_name {
2644d083319fSKevin Wolf         uint64_t perm;
2645d083319fSKevin Wolf         const char *name;
2646d083319fSKevin Wolf     } permissions[] = {
2647d083319fSKevin Wolf         { BLK_PERM_CONSISTENT_READ, "consistent read" },
2648d083319fSKevin Wolf         { BLK_PERM_WRITE,           "write" },
2649d083319fSKevin Wolf         { BLK_PERM_WRITE_UNCHANGED, "write unchanged" },
2650d083319fSKevin Wolf         { BLK_PERM_RESIZE,          "resize" },
2651d083319fSKevin Wolf         { 0, NULL }
2652d083319fSKevin Wolf     };
2653d083319fSKevin Wolf 
2654e2a7423aSAlberto Garcia     GString *result = g_string_sized_new(30);
2655d083319fSKevin Wolf     struct perm_name *p;
2656d083319fSKevin Wolf 
2657d083319fSKevin Wolf     for (p = permissions; p->name; p++) {
2658d083319fSKevin Wolf         if (perm & p->perm) {
2659e2a7423aSAlberto Garcia             if (result->len > 0) {
2660e2a7423aSAlberto Garcia                 g_string_append(result, ", ");
2661e2a7423aSAlberto Garcia             }
2662e2a7423aSAlberto Garcia             g_string_append(result, p->name);
2663d083319fSKevin Wolf         }
2664d083319fSKevin Wolf     }
2665d083319fSKevin Wolf 
2666e2a7423aSAlberto Garcia     return g_string_free(result, FALSE);
2667d083319fSKevin Wolf }
2668d083319fSKevin Wolf 
266933a610c3SKevin Wolf 
2670bce73bc2SKevin Wolf /*
2671bce73bc2SKevin Wolf  * @tran is allowed to be NULL. In this case no rollback is possible.
2672bce73bc2SKevin Wolf  *
2673bce73bc2SKevin Wolf  * After calling this function, the transaction @tran may only be completed
2674bce73bc2SKevin Wolf  * while holding a reader lock for the graph.
2675bce73bc2SKevin Wolf  */
26763804e3cfSKevin Wolf static int GRAPH_RDLOCK
26773804e3cfSKevin Wolf bdrv_refresh_perms(BlockDriverState *bs, Transaction *tran, Error **errp)
2678bb87e4d1SVladimir Sementsov-Ogievskiy {
2679bb87e4d1SVladimir Sementsov-Ogievskiy     int ret;
2680f1316edbSVladimir Sementsov-Ogievskiy     Transaction *local_tran = NULL;
2681b1d2bbebSVladimir Sementsov-Ogievskiy     g_autoptr(GSList) list = bdrv_topological_dfs(NULL, NULL, bs);
2682862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2683bb87e4d1SVladimir Sementsov-Ogievskiy 
2684f1316edbSVladimir Sementsov-Ogievskiy     if (!tran) {
2685f1316edbSVladimir Sementsov-Ogievskiy         tran = local_tran = tran_new();
2686f1316edbSVladimir Sementsov-Ogievskiy     }
2687f1316edbSVladimir Sementsov-Ogievskiy 
2688fb0ff4d1SVladimir Sementsov-Ogievskiy     ret = bdrv_do_refresh_perms(list, NULL, tran, errp);
2689f1316edbSVladimir Sementsov-Ogievskiy 
2690f1316edbSVladimir Sementsov-Ogievskiy     if (local_tran) {
2691f1316edbSVladimir Sementsov-Ogievskiy         tran_finalize(local_tran, ret);
2692f1316edbSVladimir Sementsov-Ogievskiy     }
2693b1d2bbebSVladimir Sementsov-Ogievskiy 
2694bb87e4d1SVladimir Sementsov-Ogievskiy     return ret;
2695bb87e4d1SVladimir Sementsov-Ogievskiy }
2696bb87e4d1SVladimir Sementsov-Ogievskiy 
269733a610c3SKevin Wolf int bdrv_child_try_set_perm(BdrvChild *c, uint64_t perm, uint64_t shared,
269833a610c3SKevin Wolf                             Error **errp)
269933a610c3SKevin Wolf {
27001046779eSMax Reitz     Error *local_err = NULL;
270183928dc4SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
270233a610c3SKevin Wolf     int ret;
270333a610c3SKevin Wolf 
2704b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2705b4ad82aaSEmanuele Giuseppe Esposito 
2706ecb776bdSVladimir Sementsov-Ogievskiy     bdrv_child_set_perm(c, perm, shared, tran);
270783928dc4SVladimir Sementsov-Ogievskiy 
2708f1316edbSVladimir Sementsov-Ogievskiy     ret = bdrv_refresh_perms(c->bs, tran, &local_err);
270983928dc4SVladimir Sementsov-Ogievskiy 
271083928dc4SVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
271183928dc4SVladimir Sementsov-Ogievskiy 
271233a610c3SKevin Wolf     if (ret < 0) {
2713071b474fSVladimir Sementsov-Ogievskiy         if ((perm & ~c->perm) || (c->shared_perm & ~shared)) {
2714071b474fSVladimir Sementsov-Ogievskiy             /* tighten permissions */
27151046779eSMax Reitz             error_propagate(errp, local_err);
27161046779eSMax Reitz         } else {
27171046779eSMax Reitz             /*
27181046779eSMax Reitz              * Our caller may intend to only loosen restrictions and
27191046779eSMax Reitz              * does not expect this function to fail.  Errors are not
27201046779eSMax Reitz              * fatal in such a case, so we can just hide them from our
27211046779eSMax Reitz              * caller.
27221046779eSMax Reitz              */
27231046779eSMax Reitz             error_free(local_err);
27241046779eSMax Reitz             ret = 0;
27251046779eSMax Reitz         }
272633a610c3SKevin Wolf     }
272733a610c3SKevin Wolf 
272883928dc4SVladimir Sementsov-Ogievskiy     return ret;
2729d5e6f437SKevin Wolf }
2730d5e6f437SKevin Wolf 
2731c1087f12SMax Reitz int bdrv_child_refresh_perms(BlockDriverState *bs, BdrvChild *c, Error **errp)
2732c1087f12SMax Reitz {
2733c1087f12SMax Reitz     uint64_t parent_perms, parent_shared;
2734c1087f12SMax Reitz     uint64_t perms, shared;
2735c1087f12SMax Reitz 
2736b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2737b4ad82aaSEmanuele Giuseppe Esposito 
2738c1087f12SMax Reitz     bdrv_get_cumulative_perm(bs, &parent_perms, &parent_shared);
2739e5d8a406SMax Reitz     bdrv_child_perm(bs, c->bs, c, c->role, NULL,
2740bf8e925eSMax Reitz                     parent_perms, parent_shared, &perms, &shared);
2741c1087f12SMax Reitz 
2742c1087f12SMax Reitz     return bdrv_child_try_set_perm(c, perms, shared, errp);
2743c1087f12SMax Reitz }
2744c1087f12SMax Reitz 
274587278af1SMax Reitz /*
274687278af1SMax Reitz  * Default implementation for .bdrv_child_perm() for block filters:
274787278af1SMax Reitz  * Forward CONSISTENT_READ, WRITE, WRITE_UNCHANGED, and RESIZE to the
274887278af1SMax Reitz  * filtered child.
274987278af1SMax Reitz  */
275087278af1SMax Reitz static void bdrv_filter_default_perms(BlockDriverState *bs, BdrvChild *c,
2751bf8e925eSMax Reitz                                       BdrvChildRole role,
2752e0995dc3SKevin Wolf                                       BlockReopenQueue *reopen_queue,
27536a1b9ee1SKevin Wolf                                       uint64_t perm, uint64_t shared,
27546a1b9ee1SKevin Wolf                                       uint64_t *nperm, uint64_t *nshared)
27556a1b9ee1SKevin Wolf {
2756862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
27576a1b9ee1SKevin Wolf     *nperm = perm & DEFAULT_PERM_PASSTHROUGH;
27586a1b9ee1SKevin Wolf     *nshared = (shared & DEFAULT_PERM_PASSTHROUGH) | DEFAULT_PERM_UNCHANGED;
27596a1b9ee1SKevin Wolf }
27606a1b9ee1SKevin Wolf 
276170082db4SMax Reitz static void bdrv_default_perms_for_cow(BlockDriverState *bs, BdrvChild *c,
276270082db4SMax Reitz                                        BdrvChildRole role,
276370082db4SMax Reitz                                        BlockReopenQueue *reopen_queue,
276470082db4SMax Reitz                                        uint64_t perm, uint64_t shared,
276570082db4SMax Reitz                                        uint64_t *nperm, uint64_t *nshared)
276670082db4SMax Reitz {
2767e5d8a406SMax Reitz     assert(role & BDRV_CHILD_COW);
2768862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
276970082db4SMax Reitz 
277070082db4SMax Reitz     /*
277170082db4SMax Reitz      * We want consistent read from backing files if the parent needs it.
277270082db4SMax Reitz      * No other operations are performed on backing files.
277370082db4SMax Reitz      */
277470082db4SMax Reitz     perm &= BLK_PERM_CONSISTENT_READ;
277570082db4SMax Reitz 
277670082db4SMax Reitz     /*
277770082db4SMax Reitz      * If the parent can deal with changing data, we're okay with a
277870082db4SMax Reitz      * writable and resizable backing file.
277970082db4SMax Reitz      * TODO Require !(perm & BLK_PERM_CONSISTENT_READ), too?
278070082db4SMax Reitz      */
278170082db4SMax Reitz     if (shared & BLK_PERM_WRITE) {
278270082db4SMax Reitz         shared = BLK_PERM_WRITE | BLK_PERM_RESIZE;
278370082db4SMax Reitz     } else {
278470082db4SMax Reitz         shared = 0;
278570082db4SMax Reitz     }
278670082db4SMax Reitz 
278764631f36SVladimir Sementsov-Ogievskiy     shared |= BLK_PERM_CONSISTENT_READ | BLK_PERM_WRITE_UNCHANGED;
278870082db4SMax Reitz 
278970082db4SMax Reitz     if (bs->open_flags & BDRV_O_INACTIVE) {
279070082db4SMax Reitz         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
279170082db4SMax Reitz     }
279270082db4SMax Reitz 
279370082db4SMax Reitz     *nperm = perm;
279470082db4SMax Reitz     *nshared = shared;
279570082db4SMax Reitz }
279670082db4SMax Reitz 
27976f838a4bSMax Reitz static void bdrv_default_perms_for_storage(BlockDriverState *bs, BdrvChild *c,
2798bf8e925eSMax Reitz                                            BdrvChildRole role,
2799e0995dc3SKevin Wolf                                            BlockReopenQueue *reopen_queue,
28006b1a044aSKevin Wolf                                            uint64_t perm, uint64_t shared,
28016b1a044aSKevin Wolf                                            uint64_t *nperm, uint64_t *nshared)
28026b1a044aSKevin Wolf {
28036f838a4bSMax Reitz     int flags;
28046b1a044aSKevin Wolf 
2805862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2806e5d8a406SMax Reitz     assert(role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA));
28075fbfabd3SKevin Wolf 
28086f838a4bSMax Reitz     flags = bdrv_reopen_get_flags(reopen_queue, bs);
28096f838a4bSMax Reitz 
28106f838a4bSMax Reitz     /*
28116f838a4bSMax Reitz      * Apart from the modifications below, the same permissions are
28126f838a4bSMax Reitz      * forwarded and left alone as for filters
28136f838a4bSMax Reitz      */
2814e5d8a406SMax Reitz     bdrv_filter_default_perms(bs, c, role, reopen_queue,
2815bd86fb99SMax Reitz                               perm, shared, &perm, &shared);
28166b1a044aSKevin Wolf 
2817f889054fSMax Reitz     if (role & BDRV_CHILD_METADATA) {
28186b1a044aSKevin Wolf         /* Format drivers may touch metadata even if the guest doesn't write */
2819cc022140SMax Reitz         if (bdrv_is_writable_after_reopen(bs, reopen_queue)) {
28206b1a044aSKevin Wolf             perm |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
28216b1a044aSKevin Wolf         }
28226b1a044aSKevin Wolf 
28236f838a4bSMax Reitz         /*
2824f889054fSMax Reitz          * bs->file always needs to be consistent because of the
2825f889054fSMax Reitz          * metadata. We can never allow other users to resize or write
2826f889054fSMax Reitz          * to it.
28276f838a4bSMax Reitz          */
28285fbfabd3SKevin Wolf         if (!(flags & BDRV_O_NO_IO)) {
28296b1a044aSKevin Wolf             perm |= BLK_PERM_CONSISTENT_READ;
28305fbfabd3SKevin Wolf         }
28316b1a044aSKevin Wolf         shared &= ~(BLK_PERM_WRITE | BLK_PERM_RESIZE);
2832f889054fSMax Reitz     }
2833f889054fSMax Reitz 
2834f889054fSMax Reitz     if (role & BDRV_CHILD_DATA) {
2835f889054fSMax Reitz         /*
2836f889054fSMax Reitz          * Technically, everything in this block is a subset of the
2837f889054fSMax Reitz          * BDRV_CHILD_METADATA path taken above, and so this could
2838f889054fSMax Reitz          * be an "else if" branch.  However, that is not obvious, and
2839f889054fSMax Reitz          * this function is not performance critical, therefore we let
2840f889054fSMax Reitz          * this be an independent "if".
2841f889054fSMax Reitz          */
2842f889054fSMax Reitz 
2843f889054fSMax Reitz         /*
2844f889054fSMax Reitz          * We cannot allow other users to resize the file because the
2845f889054fSMax Reitz          * format driver might have some assumptions about the size
2846f889054fSMax Reitz          * (e.g. because it is stored in metadata, or because the file
2847f889054fSMax Reitz          * is split into fixed-size data files).
2848f889054fSMax Reitz          */
2849f889054fSMax Reitz         shared &= ~BLK_PERM_RESIZE;
2850f889054fSMax Reitz 
2851f889054fSMax Reitz         /*
2852f889054fSMax Reitz          * WRITE_UNCHANGED often cannot be performed as such on the
2853f889054fSMax Reitz          * data file.  For example, the qcow2 driver may still need to
2854f889054fSMax Reitz          * write copied clusters on copy-on-read.
2855f889054fSMax Reitz          */
2856f889054fSMax Reitz         if (perm & BLK_PERM_WRITE_UNCHANGED) {
2857f889054fSMax Reitz             perm |= BLK_PERM_WRITE;
2858f889054fSMax Reitz         }
2859f889054fSMax Reitz 
2860f889054fSMax Reitz         /*
2861f889054fSMax Reitz          * If the data file is written to, the format driver may
2862f889054fSMax Reitz          * expect to be able to resize it by writing beyond the EOF.
2863f889054fSMax Reitz          */
2864f889054fSMax Reitz         if (perm & BLK_PERM_WRITE) {
2865f889054fSMax Reitz             perm |= BLK_PERM_RESIZE;
2866f889054fSMax Reitz         }
2867f889054fSMax Reitz     }
286833f2663bSMax Reitz 
286933f2663bSMax Reitz     if (bs->open_flags & BDRV_O_INACTIVE) {
287033f2663bSMax Reitz         shared |= BLK_PERM_WRITE | BLK_PERM_RESIZE;
287133f2663bSMax Reitz     }
287233f2663bSMax Reitz 
287333f2663bSMax Reitz     *nperm = perm;
287433f2663bSMax Reitz     *nshared = shared;
28756f838a4bSMax Reitz }
28766f838a4bSMax Reitz 
28772519f549SMax Reitz void bdrv_default_perms(BlockDriverState *bs, BdrvChild *c,
2878e5d8a406SMax Reitz                         BdrvChildRole role, BlockReopenQueue *reopen_queue,
28792519f549SMax Reitz                         uint64_t perm, uint64_t shared,
28802519f549SMax Reitz                         uint64_t *nperm, uint64_t *nshared)
28812519f549SMax Reitz {
2882b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
28832519f549SMax Reitz     if (role & BDRV_CHILD_FILTERED) {
28842519f549SMax Reitz         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
28852519f549SMax Reitz                          BDRV_CHILD_COW)));
2886e5d8a406SMax Reitz         bdrv_filter_default_perms(bs, c, role, reopen_queue,
28872519f549SMax Reitz                                   perm, shared, nperm, nshared);
28882519f549SMax Reitz     } else if (role & BDRV_CHILD_COW) {
28892519f549SMax Reitz         assert(!(role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA)));
2890e5d8a406SMax Reitz         bdrv_default_perms_for_cow(bs, c, role, reopen_queue,
28912519f549SMax Reitz                                    perm, shared, nperm, nshared);
28922519f549SMax Reitz     } else if (role & (BDRV_CHILD_METADATA | BDRV_CHILD_DATA)) {
2893e5d8a406SMax Reitz         bdrv_default_perms_for_storage(bs, c, role, reopen_queue,
28942519f549SMax Reitz                                        perm, shared, nperm, nshared);
28952519f549SMax Reitz     } else {
28962519f549SMax Reitz         g_assert_not_reached();
28972519f549SMax Reitz     }
28982519f549SMax Reitz }
28992519f549SMax Reitz 
29007b1d9c4dSMax Reitz uint64_t bdrv_qapi_perm_to_blk_perm(BlockPermission qapi_perm)
29017b1d9c4dSMax Reitz {
29027b1d9c4dSMax Reitz     static const uint64_t permissions[] = {
29037b1d9c4dSMax Reitz         [BLOCK_PERMISSION_CONSISTENT_READ]  = BLK_PERM_CONSISTENT_READ,
29047b1d9c4dSMax Reitz         [BLOCK_PERMISSION_WRITE]            = BLK_PERM_WRITE,
29057b1d9c4dSMax Reitz         [BLOCK_PERMISSION_WRITE_UNCHANGED]  = BLK_PERM_WRITE_UNCHANGED,
29067b1d9c4dSMax Reitz         [BLOCK_PERMISSION_RESIZE]           = BLK_PERM_RESIZE,
29077b1d9c4dSMax Reitz     };
29087b1d9c4dSMax Reitz 
29097b1d9c4dSMax Reitz     QEMU_BUILD_BUG_ON(ARRAY_SIZE(permissions) != BLOCK_PERMISSION__MAX);
29107b1d9c4dSMax Reitz     QEMU_BUILD_BUG_ON(1UL << ARRAY_SIZE(permissions) != BLK_PERM_ALL + 1);
29117b1d9c4dSMax Reitz 
29127b1d9c4dSMax Reitz     assert(qapi_perm < BLOCK_PERMISSION__MAX);
29137b1d9c4dSMax Reitz 
29147b1d9c4dSMax Reitz     return permissions[qapi_perm];
29157b1d9c4dSMax Reitz }
29167b1d9c4dSMax Reitz 
291723987471SKevin Wolf /*
291823987471SKevin Wolf  * Replaces the node that a BdrvChild points to without updating permissions.
291923987471SKevin Wolf  *
292023987471SKevin Wolf  * If @new_bs is non-NULL, the parent of @child must already be drained through
292123c983c8SStefan Hajnoczi  * @child.
292223987471SKevin Wolf  */
2923ad29eb3dSKevin Wolf static void GRAPH_WRLOCK
2924ad29eb3dSKevin Wolf bdrv_replace_child_noperm(BdrvChild *child, BlockDriverState *new_bs)
2925e9740bc6SKevin Wolf {
2926e9740bc6SKevin Wolf     BlockDriverState *old_bs = child->bs;
2927debc2927SMax Reitz     int new_bs_quiesce_counter;
2928e9740bc6SKevin Wolf 
29292cad1ebeSAlberto Garcia     assert(!child->frozen);
293023987471SKevin Wolf 
293123987471SKevin Wolf     /*
293223987471SKevin Wolf      * If we want to change the BdrvChild to point to a drained node as its new
293323987471SKevin Wolf      * child->bs, we need to make sure that its new parent is drained, too. In
293423987471SKevin Wolf      * other words, either child->quiesce_parent must already be true or we must
293523987471SKevin Wolf      * be able to set it and keep the parent's quiesce_counter consistent with
293623987471SKevin Wolf      * that, but without polling or starting new requests (this function
293723987471SKevin Wolf      * guarantees that it doesn't poll, and starting new requests would be
293823987471SKevin Wolf      * against the invariants of drain sections).
293923987471SKevin Wolf      *
294023987471SKevin Wolf      * To keep things simple, we pick the first option (child->quiesce_parent
294123987471SKevin Wolf      * must already be true). We also generalise the rule a bit to make it
294223987471SKevin Wolf      * easier to verify in callers and more likely to be covered in test cases:
294323987471SKevin Wolf      * The parent must be quiesced through this child even if new_bs isn't
294423987471SKevin Wolf      * currently drained.
294523987471SKevin Wolf      *
294623987471SKevin Wolf      * The only exception is for callers that always pass new_bs == NULL. In
294723987471SKevin Wolf      * this case, we obviously never need to consider the case of a drained
294823987471SKevin Wolf      * new_bs, so we can keep the callers simpler by allowing them not to drain
294923987471SKevin Wolf      * the parent.
295023987471SKevin Wolf      */
295123987471SKevin Wolf     assert(!new_bs || child->quiesced_parent);
2952bfb8aa6dSKevin Wolf     assert(old_bs != new_bs);
2953f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
29542cad1ebeSAlberto Garcia 
2955bb2614e9SFam Zheng     if (old_bs && new_bs) {
2956bb2614e9SFam Zheng         assert(bdrv_get_aio_context(old_bs) == bdrv_get_aio_context(new_bs));
2957bb2614e9SFam Zheng     }
2958debc2927SMax Reitz 
2959e9740bc6SKevin Wolf     if (old_bs) {
2960bd86fb99SMax Reitz         if (child->klass->detach) {
2961bd86fb99SMax Reitz             child->klass->detach(child);
2962d736f119SKevin Wolf         }
296336fe1331SKevin Wolf         QLIST_REMOVE(child, next_parent);
2964e9740bc6SKevin Wolf     }
2965e9740bc6SKevin Wolf 
2966e9740bc6SKevin Wolf     child->bs = new_bs;
296736fe1331SKevin Wolf 
296836fe1331SKevin Wolf     if (new_bs) {
296936fe1331SKevin Wolf         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
2970bd86fb99SMax Reitz         if (child->klass->attach) {
2971bd86fb99SMax Reitz             child->klass->attach(child);
2972db95dbbaSKevin Wolf         }
297336fe1331SKevin Wolf     }
2974debc2927SMax Reitz 
2975debc2927SMax Reitz     /*
297623987471SKevin Wolf      * If the parent was drained through this BdrvChild previously, but new_bs
297723987471SKevin Wolf      * is not drained, allow requests to come in only after the new node has
297823987471SKevin Wolf      * been attached.
2979debc2927SMax Reitz      */
298057e05be3SKevin Wolf     new_bs_quiesce_counter = (new_bs ? new_bs->quiesce_counter : 0);
298157e05be3SKevin Wolf     if (!new_bs_quiesce_counter && child->quiesced_parent) {
2982debc2927SMax Reitz         bdrv_parent_drained_end_single(child);
2983debc2927SMax Reitz     }
2984e9740bc6SKevin Wolf }
2985e9740bc6SKevin Wolf 
298604c9c3a5SHanna Reitz /**
298704c9c3a5SHanna Reitz  * Free the given @child.
298804c9c3a5SHanna Reitz  *
298904c9c3a5SHanna Reitz  * The child must be empty (i.e. `child->bs == NULL`) and it must be
299004c9c3a5SHanna Reitz  * unused (i.e. not in a children list).
299104c9c3a5SHanna Reitz  */
299204c9c3a5SHanna Reitz static void bdrv_child_free(BdrvChild *child)
2993548a74c0SVladimir Sementsov-Ogievskiy {
2994548a74c0SVladimir Sementsov-Ogievskiy     assert(!child->bs);
2995bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
2996680e0cc4SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
2997680e0cc4SKevin Wolf 
2998a225369bSHanna Reitz     assert(!child->next.le_prev); /* not in children list */
299904c9c3a5SHanna Reitz 
300004c9c3a5SHanna Reitz     g_free(child->name);
300104c9c3a5SHanna Reitz     g_free(child);
3002548a74c0SVladimir Sementsov-Ogievskiy }
3003548a74c0SVladimir Sementsov-Ogievskiy 
3004548a74c0SVladimir Sementsov-Ogievskiy typedef struct BdrvAttachChildCommonState {
30055bb04747SVladimir Sementsov-Ogievskiy     BdrvChild *child;
3006548a74c0SVladimir Sementsov-Ogievskiy     AioContext *old_parent_ctx;
3007548a74c0SVladimir Sementsov-Ogievskiy     AioContext *old_child_ctx;
3008548a74c0SVladimir Sementsov-Ogievskiy } BdrvAttachChildCommonState;
3009548a74c0SVladimir Sementsov-Ogievskiy 
30105661a00dSKevin Wolf static void GRAPH_WRLOCK bdrv_attach_child_common_abort(void *opaque)
3011548a74c0SVladimir Sementsov-Ogievskiy {
3012548a74c0SVladimir Sementsov-Ogievskiy     BdrvAttachChildCommonState *s = opaque;
30135bb04747SVladimir Sementsov-Ogievskiy     BlockDriverState *bs = s->child->bs;
3014548a74c0SVladimir Sementsov-Ogievskiy 
3015f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
30165661a00dSKevin Wolf     assert_bdrv_graph_writable();
3017ad29eb3dSKevin Wolf 
30185bb04747SVladimir Sementsov-Ogievskiy     bdrv_replace_child_noperm(s->child, NULL);
3019548a74c0SVladimir Sementsov-Ogievskiy 
3020548a74c0SVladimir Sementsov-Ogievskiy     if (bdrv_get_aio_context(bs) != s->old_child_ctx) {
3021142e6907SEmanuele Giuseppe Esposito         bdrv_try_change_aio_context(bs, s->old_child_ctx, NULL, &error_abort);
3022548a74c0SVladimir Sementsov-Ogievskiy     }
3023548a74c0SVladimir Sementsov-Ogievskiy 
30245bb04747SVladimir Sementsov-Ogievskiy     if (bdrv_child_get_parent_aio_context(s->child) != s->old_parent_ctx) {
3025f8be48adSEmanuele Giuseppe Esposito         Transaction *tran;
3026f8be48adSEmanuele Giuseppe Esposito         GHashTable *visited;
3027f8be48adSEmanuele Giuseppe Esposito         bool ret;
3028548a74c0SVladimir Sementsov-Ogievskiy 
3029f8be48adSEmanuele Giuseppe Esposito         tran = tran_new();
3030548a74c0SVladimir Sementsov-Ogievskiy 
3031f8be48adSEmanuele Giuseppe Esposito         /* No need to visit `child`, because it has been detached already */
3032f8be48adSEmanuele Giuseppe Esposito         visited = g_hash_table_new(NULL, NULL);
3033f8be48adSEmanuele Giuseppe Esposito         ret = s->child->klass->change_aio_ctx(s->child, s->old_parent_ctx,
3034f8be48adSEmanuele Giuseppe Esposito                                               visited, tran, &error_abort);
3035f8be48adSEmanuele Giuseppe Esposito         g_hash_table_destroy(visited);
3036f8be48adSEmanuele Giuseppe Esposito 
3037f8be48adSEmanuele Giuseppe Esposito         /* transaction is supposed to always succeed */
3038f8be48adSEmanuele Giuseppe Esposito         assert(ret == true);
3039f8be48adSEmanuele Giuseppe Esposito         tran_commit(tran);
3040548a74c0SVladimir Sementsov-Ogievskiy     }
3041548a74c0SVladimir Sementsov-Ogievskiy 
30425661a00dSKevin Wolf     bdrv_schedule_unref(bs);
30435bb04747SVladimir Sementsov-Ogievskiy     bdrv_child_free(s->child);
3044548a74c0SVladimir Sementsov-Ogievskiy }
3045548a74c0SVladimir Sementsov-Ogievskiy 
3046548a74c0SVladimir Sementsov-Ogievskiy static TransactionActionDrv bdrv_attach_child_common_drv = {
3047548a74c0SVladimir Sementsov-Ogievskiy     .abort = bdrv_attach_child_common_abort,
3048548a74c0SVladimir Sementsov-Ogievskiy     .clean = g_free,
3049548a74c0SVladimir Sementsov-Ogievskiy };
3050548a74c0SVladimir Sementsov-Ogievskiy 
3051548a74c0SVladimir Sementsov-Ogievskiy /*
3052548a74c0SVladimir Sementsov-Ogievskiy  * Common part of attaching bdrv child to bs or to blk or to job
3053f8d2ad78SVladimir Sementsov-Ogievskiy  *
30547ec390d5SVladimir Sementsov-Ogievskiy  * Function doesn't update permissions, caller is responsible for this.
30555bb04747SVladimir Sementsov-Ogievskiy  *
30565661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
30575661a00dSKevin Wolf  * while holding a writer lock for the graph.
30585661a00dSKevin Wolf  *
30595bb04747SVladimir Sementsov-Ogievskiy  * Returns new created child.
3060c066e808SKevin Wolf  *
306123c983c8SStefan Hajnoczi  * Both @parent_bs and @child_bs can move to a different AioContext in this
306223c983c8SStefan Hajnoczi  * function.
3063548a74c0SVladimir Sementsov-Ogievskiy  */
30647d4ca9d2SKevin Wolf static BdrvChild * GRAPH_WRLOCK
30657d4ca9d2SKevin Wolf bdrv_attach_child_common(BlockDriverState *child_bs,
3066548a74c0SVladimir Sementsov-Ogievskiy                          const char *child_name,
3067548a74c0SVladimir Sementsov-Ogievskiy                          const BdrvChildClass *child_class,
3068548a74c0SVladimir Sementsov-Ogievskiy                          BdrvChildRole child_role,
3069548a74c0SVladimir Sementsov-Ogievskiy                          uint64_t perm, uint64_t shared_perm,
30705bb04747SVladimir Sementsov-Ogievskiy                          void *opaque,
3071548a74c0SVladimir Sementsov-Ogievskiy                          Transaction *tran, Error **errp)
3072548a74c0SVladimir Sementsov-Ogievskiy {
3073548a74c0SVladimir Sementsov-Ogievskiy     BdrvChild *new_child;
3074b49f4755SStefan Hajnoczi     AioContext *parent_ctx;
3075548a74c0SVladimir Sementsov-Ogievskiy     AioContext *child_ctx = bdrv_get_aio_context(child_bs);
3076548a74c0SVladimir Sementsov-Ogievskiy 
3077da261b69SVladimir Sementsov-Ogievskiy     assert(child_class->get_parent_desc);
3078bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3079548a74c0SVladimir Sementsov-Ogievskiy 
3080548a74c0SVladimir Sementsov-Ogievskiy     new_child = g_new(BdrvChild, 1);
3081548a74c0SVladimir Sementsov-Ogievskiy     *new_child = (BdrvChild) {
3082548a74c0SVladimir Sementsov-Ogievskiy         .bs             = NULL,
3083548a74c0SVladimir Sementsov-Ogievskiy         .name           = g_strdup(child_name),
3084548a74c0SVladimir Sementsov-Ogievskiy         .klass          = child_class,
3085548a74c0SVladimir Sementsov-Ogievskiy         .role           = child_role,
3086548a74c0SVladimir Sementsov-Ogievskiy         .perm           = perm,
3087548a74c0SVladimir Sementsov-Ogievskiy         .shared_perm    = shared_perm,
3088548a74c0SVladimir Sementsov-Ogievskiy         .opaque         = opaque,
3089548a74c0SVladimir Sementsov-Ogievskiy     };
3090548a74c0SVladimir Sementsov-Ogievskiy 
3091548a74c0SVladimir Sementsov-Ogievskiy     /*
3092548a74c0SVladimir Sementsov-Ogievskiy      * If the AioContexts don't match, first try to move the subtree of
3093548a74c0SVladimir Sementsov-Ogievskiy      * child_bs into the AioContext of the new parent. If this doesn't work,
3094548a74c0SVladimir Sementsov-Ogievskiy      * try moving the parent into the AioContext of child_bs instead.
3095548a74c0SVladimir Sementsov-Ogievskiy      */
3096548a74c0SVladimir Sementsov-Ogievskiy     parent_ctx = bdrv_child_get_parent_aio_context(new_child);
3097548a74c0SVladimir Sementsov-Ogievskiy     if (child_ctx != parent_ctx) {
3098548a74c0SVladimir Sementsov-Ogievskiy         Error *local_err = NULL;
3099142e6907SEmanuele Giuseppe Esposito         int ret = bdrv_try_change_aio_context(child_bs, parent_ctx, NULL,
3100142e6907SEmanuele Giuseppe Esposito                                               &local_err);
3101548a74c0SVladimir Sementsov-Ogievskiy 
3102f8be48adSEmanuele Giuseppe Esposito         if (ret < 0 && child_class->change_aio_ctx) {
3103fb2575f9SMarkus Armbruster             Transaction *aio_ctx_tran = tran_new();
3104f8be48adSEmanuele Giuseppe Esposito             GHashTable *visited = g_hash_table_new(NULL, NULL);
3105f8be48adSEmanuele Giuseppe Esposito             bool ret_child;
3106f8be48adSEmanuele Giuseppe Esposito 
3107f8be48adSEmanuele Giuseppe Esposito             g_hash_table_add(visited, new_child);
3108f8be48adSEmanuele Giuseppe Esposito             ret_child = child_class->change_aio_ctx(new_child, child_ctx,
3109fb2575f9SMarkus Armbruster                                                     visited, aio_ctx_tran,
3110fb2575f9SMarkus Armbruster                                                     NULL);
3111f8be48adSEmanuele Giuseppe Esposito             if (ret_child == true) {
3112548a74c0SVladimir Sementsov-Ogievskiy                 error_free(local_err);
3113548a74c0SVladimir Sementsov-Ogievskiy                 ret = 0;
3114548a74c0SVladimir Sementsov-Ogievskiy             }
3115fb2575f9SMarkus Armbruster             tran_finalize(aio_ctx_tran, ret_child == true ? 0 : -1);
3116f8be48adSEmanuele Giuseppe Esposito             g_hash_table_destroy(visited);
3117548a74c0SVladimir Sementsov-Ogievskiy         }
3118548a74c0SVladimir Sementsov-Ogievskiy 
3119548a74c0SVladimir Sementsov-Ogievskiy         if (ret < 0) {
3120548a74c0SVladimir Sementsov-Ogievskiy             error_propagate(errp, local_err);
312104c9c3a5SHanna Reitz             bdrv_child_free(new_child);
31225bb04747SVladimir Sementsov-Ogievskiy             return NULL;
3123548a74c0SVladimir Sementsov-Ogievskiy         }
3124548a74c0SVladimir Sementsov-Ogievskiy     }
3125548a74c0SVladimir Sementsov-Ogievskiy 
3126548a74c0SVladimir Sementsov-Ogievskiy     bdrv_ref(child_bs);
312723987471SKevin Wolf     /*
312823987471SKevin Wolf      * Let every new BdrvChild start with a drained parent. Inserting the child
312923987471SKevin Wolf      * in the graph with bdrv_replace_child_noperm() will undrain it if
313023987471SKevin Wolf      * @child_bs is not drained.
313123987471SKevin Wolf      *
313223987471SKevin Wolf      * The child was only just created and is not yet visible in global state
313323987471SKevin Wolf      * until bdrv_replace_child_noperm() inserts it into the graph, so nobody
313423987471SKevin Wolf      * could have sent requests and polling is not necessary.
313523987471SKevin Wolf      *
313623987471SKevin Wolf      * Note that this means that the parent isn't fully drained yet, we only
313723987471SKevin Wolf      * stop new requests from coming in. This is fine, we don't care about the
313823987471SKevin Wolf      * old requests here, they are not for this child. If another place enters a
313923987471SKevin Wolf      * drain section for the same parent, but wants it to be fully quiesced, it
314023987471SKevin Wolf      * will not run most of the the code in .drained_begin() again (which is not
314123987471SKevin Wolf      * a problem, we already did this), but it will still poll until the parent
314223987471SKevin Wolf      * is fully quiesced, so it will not be negatively affected either.
314323987471SKevin Wolf      */
3144606ed756SKevin Wolf     bdrv_parent_drained_begin_single(new_child);
3145544acc7dSVladimir Sementsov-Ogievskiy     bdrv_replace_child_noperm(new_child, child_bs);
3146548a74c0SVladimir Sementsov-Ogievskiy 
3147548a74c0SVladimir Sementsov-Ogievskiy     BdrvAttachChildCommonState *s = g_new(BdrvAttachChildCommonState, 1);
3148548a74c0SVladimir Sementsov-Ogievskiy     *s = (BdrvAttachChildCommonState) {
31495bb04747SVladimir Sementsov-Ogievskiy         .child = new_child,
3150548a74c0SVladimir Sementsov-Ogievskiy         .old_parent_ctx = parent_ctx,
3151548a74c0SVladimir Sementsov-Ogievskiy         .old_child_ctx = child_ctx,
3152548a74c0SVladimir Sementsov-Ogievskiy     };
3153548a74c0SVladimir Sementsov-Ogievskiy     tran_add(tran, &bdrv_attach_child_common_drv, s);
3154548a74c0SVladimir Sementsov-Ogievskiy 
31555bb04747SVladimir Sementsov-Ogievskiy     return new_child;
3156548a74c0SVladimir Sementsov-Ogievskiy }
3157548a74c0SVladimir Sementsov-Ogievskiy 
3158f8d2ad78SVladimir Sementsov-Ogievskiy /*
31597ec390d5SVladimir Sementsov-Ogievskiy  * Function doesn't update permissions, caller is responsible for this.
3160c066e808SKevin Wolf  *
316123c983c8SStefan Hajnoczi  * Both @parent_bs and @child_bs can move to a different AioContext in this
316223c983c8SStefan Hajnoczi  * function.
31635661a00dSKevin Wolf  *
31645661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
31655661a00dSKevin Wolf  * while holding a writer lock for the graph.
3166f8d2ad78SVladimir Sementsov-Ogievskiy  */
31677d4ca9d2SKevin Wolf static BdrvChild * GRAPH_WRLOCK
31687d4ca9d2SKevin Wolf bdrv_attach_child_noperm(BlockDriverState *parent_bs,
3169aa5a04c7SVladimir Sementsov-Ogievskiy                          BlockDriverState *child_bs,
3170aa5a04c7SVladimir Sementsov-Ogievskiy                          const char *child_name,
3171aa5a04c7SVladimir Sementsov-Ogievskiy                          const BdrvChildClass *child_class,
3172aa5a04c7SVladimir Sementsov-Ogievskiy                          BdrvChildRole child_role,
3173aa5a04c7SVladimir Sementsov-Ogievskiy                          Transaction *tran,
3174aa5a04c7SVladimir Sementsov-Ogievskiy                          Error **errp)
3175aa5a04c7SVladimir Sementsov-Ogievskiy {
3176aa5a04c7SVladimir Sementsov-Ogievskiy     uint64_t perm, shared_perm;
3177aa5a04c7SVladimir Sementsov-Ogievskiy 
3178aa5a04c7SVladimir Sementsov-Ogievskiy     assert(parent_bs->drv);
3179bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3180aa5a04c7SVladimir Sementsov-Ogievskiy 
3181bfb8aa6dSKevin Wolf     if (bdrv_recurse_has_child(child_bs, parent_bs)) {
3182bfb8aa6dSKevin Wolf         error_setg(errp, "Making '%s' a %s child of '%s' would create a cycle",
3183bfb8aa6dSKevin Wolf                    child_bs->node_name, child_name, parent_bs->node_name);
31845bb04747SVladimir Sementsov-Ogievskiy         return NULL;
3185bfb8aa6dSKevin Wolf     }
3186bfb8aa6dSKevin Wolf 
3187aa5a04c7SVladimir Sementsov-Ogievskiy     bdrv_get_cumulative_perm(parent_bs, &perm, &shared_perm);
3188aa5a04c7SVladimir Sementsov-Ogievskiy     bdrv_child_perm(parent_bs, child_bs, NULL, child_role, NULL,
3189aa5a04c7SVladimir Sementsov-Ogievskiy                     perm, shared_perm, &perm, &shared_perm);
3190aa5a04c7SVladimir Sementsov-Ogievskiy 
31915bb04747SVladimir Sementsov-Ogievskiy     return bdrv_attach_child_common(child_bs, child_name, child_class,
3192aa5a04c7SVladimir Sementsov-Ogievskiy                                     child_role, perm, shared_perm, parent_bs,
31935bb04747SVladimir Sementsov-Ogievskiy                                     tran, errp);
3194aa5a04c7SVladimir Sementsov-Ogievskiy }
3195aa5a04c7SVladimir Sementsov-Ogievskiy 
3196b441dc71SAlberto Garcia /*
3197b441dc71SAlberto Garcia  * This function steals the reference to child_bs from the caller.
3198b441dc71SAlberto Garcia  * That reference is later dropped by bdrv_root_unref_child().
3199b441dc71SAlberto Garcia  *
3200b441dc71SAlberto Garcia  * On failure NULL is returned, errp is set and the reference to
3201b441dc71SAlberto Garcia  * child_bs is also dropped.
3202b441dc71SAlberto Garcia  */
3203f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
3204260fecf1SKevin Wolf                                   const char *child_name,
3205bd86fb99SMax Reitz                                   const BdrvChildClass *child_class,
3206258b7765SMax Reitz                                   BdrvChildRole child_role,
3207d5e6f437SKevin Wolf                                   uint64_t perm, uint64_t shared_perm,
3208d5e6f437SKevin Wolf                                   void *opaque, Error **errp)
3209df581792SKevin Wolf {
3210d5e6f437SKevin Wolf     int ret;
32115bb04747SVladimir Sementsov-Ogievskiy     BdrvChild *child;
3212548a74c0SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
3213d5e6f437SKevin Wolf 
3214b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3215b4ad82aaSEmanuele Giuseppe Esposito 
32165bb04747SVladimir Sementsov-Ogievskiy     child = bdrv_attach_child_common(child_bs, child_name, child_class,
3217548a74c0SVladimir Sementsov-Ogievskiy                                    child_role, perm, shared_perm, opaque,
32185bb04747SVladimir Sementsov-Ogievskiy                                    tran, errp);
32195bb04747SVladimir Sementsov-Ogievskiy     if (!child) {
32205bb04747SVladimir Sementsov-Ogievskiy         ret = -EINVAL;
3221e878bb12SKevin Wolf         goto out;
3222d5e6f437SKevin Wolf     }
3223d5e6f437SKevin Wolf 
3224f1316edbSVladimir Sementsov-Ogievskiy     ret = bdrv_refresh_perms(child_bs, tran, errp);
3225df581792SKevin Wolf 
3226e878bb12SKevin Wolf out:
3227e878bb12SKevin Wolf     tran_finalize(tran, ret);
3228f8d2ad78SVladimir Sementsov-Ogievskiy 
322903b9eacaSKevin Wolf     bdrv_schedule_unref(child_bs);
32305bb04747SVladimir Sementsov-Ogievskiy 
32315bb04747SVladimir Sementsov-Ogievskiy     return ret < 0 ? NULL : child;
3232df581792SKevin Wolf }
3233df581792SKevin Wolf 
3234b441dc71SAlberto Garcia /*
3235b441dc71SAlberto Garcia  * This function transfers the reference to child_bs from the caller
3236b441dc71SAlberto Garcia  * to parent_bs. That reference is later dropped by parent_bs on
3237b441dc71SAlberto Garcia  * bdrv_close() or if someone calls bdrv_unref_child().
3238b441dc71SAlberto Garcia  *
3239b441dc71SAlberto Garcia  * On failure NULL is returned, errp is set and the reference to
3240b441dc71SAlberto Garcia  * child_bs is also dropped.
3241b441dc71SAlberto Garcia  */
324298292c61SWen Congyang BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
3243f21d96d0SKevin Wolf                              BlockDriverState *child_bs,
3244f21d96d0SKevin Wolf                              const char *child_name,
3245bd86fb99SMax Reitz                              const BdrvChildClass *child_class,
3246258b7765SMax Reitz                              BdrvChildRole child_role,
32478b2ff529SKevin Wolf                              Error **errp)
3248f21d96d0SKevin Wolf {
3249aa5a04c7SVladimir Sementsov-Ogievskiy     int ret;
32505bb04747SVladimir Sementsov-Ogievskiy     BdrvChild *child;
3251aa5a04c7SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
3252d5e6f437SKevin Wolf 
3253f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3254f791bf7fSEmanuele Giuseppe Esposito 
32555bb04747SVladimir Sementsov-Ogievskiy     child = bdrv_attach_child_noperm(parent_bs, child_bs, child_name,
32565bb04747SVladimir Sementsov-Ogievskiy                                      child_class, child_role, tran, errp);
32575bb04747SVladimir Sementsov-Ogievskiy     if (!child) {
32585bb04747SVladimir Sementsov-Ogievskiy         ret = -EINVAL;
3259aa5a04c7SVladimir Sementsov-Ogievskiy         goto out;
3260d5e6f437SKevin Wolf     }
3261d5e6f437SKevin Wolf 
3262f1316edbSVladimir Sementsov-Ogievskiy     ret = bdrv_refresh_perms(parent_bs, tran, errp);
3263aa5a04c7SVladimir Sementsov-Ogievskiy     if (ret < 0) {
3264aa5a04c7SVladimir Sementsov-Ogievskiy         goto out;
3265aa5a04c7SVladimir Sementsov-Ogievskiy     }
3266aa5a04c7SVladimir Sementsov-Ogievskiy 
3267aa5a04c7SVladimir Sementsov-Ogievskiy out:
3268aa5a04c7SVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
3269aa5a04c7SVladimir Sementsov-Ogievskiy 
3270afdaeb9eSKevin Wolf     bdrv_schedule_unref(child_bs);
3271aa5a04c7SVladimir Sementsov-Ogievskiy 
32725bb04747SVladimir Sementsov-Ogievskiy     return ret < 0 ? NULL : child;
3273f21d96d0SKevin Wolf }
3274f21d96d0SKevin Wolf 
32757b99a266SMax Reitz /* Callers must ensure that child->frozen is false. */
3276f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
327733a60407SKevin Wolf {
327800eb93b5SVladimir Sementsov-Ogievskiy     BlockDriverState *child_bs = child->bs;
3279779020cbSKevin Wolf 
3280f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
328100eb93b5SVladimir Sementsov-Ogievskiy     bdrv_replace_child_noperm(child, NULL);
328200eb93b5SVladimir Sementsov-Ogievskiy     bdrv_child_free(child);
3283f791bf7fSEmanuele Giuseppe Esposito 
328400eb93b5SVladimir Sementsov-Ogievskiy     if (child_bs) {
328500eb93b5SVladimir Sementsov-Ogievskiy         /*
328600eb93b5SVladimir Sementsov-Ogievskiy          * Update permissions for old node. We're just taking a parent away, so
328700eb93b5SVladimir Sementsov-Ogievskiy          * we're loosening restrictions. Errors of permission update are not
328800eb93b5SVladimir Sementsov-Ogievskiy          * fatal in this case, ignore them.
328900eb93b5SVladimir Sementsov-Ogievskiy          */
3290f1316edbSVladimir Sementsov-Ogievskiy         bdrv_refresh_perms(child_bs, NULL, NULL);
329100eb93b5SVladimir Sementsov-Ogievskiy 
329200eb93b5SVladimir Sementsov-Ogievskiy         /*
329300eb93b5SVladimir Sementsov-Ogievskiy          * When the parent requiring a non-default AioContext is removed, the
329400eb93b5SVladimir Sementsov-Ogievskiy          * node moves back to the main AioContext
329500eb93b5SVladimir Sementsov-Ogievskiy          */
329600eb93b5SVladimir Sementsov-Ogievskiy         bdrv_try_change_aio_context(child_bs, qemu_get_aio_context(), NULL,
329700eb93b5SVladimir Sementsov-Ogievskiy                                     NULL);
329800eb93b5SVladimir Sementsov-Ogievskiy     }
329900eb93b5SVladimir Sementsov-Ogievskiy 
3300ede01e46SKevin Wolf     bdrv_schedule_unref(child_bs);
3301f21d96d0SKevin Wolf }
3302f21d96d0SKevin Wolf 
3303332b3a17SVladimir Sementsov-Ogievskiy typedef struct BdrvSetInheritsFrom {
3304332b3a17SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
3305332b3a17SVladimir Sementsov-Ogievskiy     BlockDriverState *old_inherits_from;
3306332b3a17SVladimir Sementsov-Ogievskiy } BdrvSetInheritsFrom;
3307332b3a17SVladimir Sementsov-Ogievskiy 
3308332b3a17SVladimir Sementsov-Ogievskiy static void bdrv_set_inherits_from_abort(void *opaque)
3309332b3a17SVladimir Sementsov-Ogievskiy {
3310332b3a17SVladimir Sementsov-Ogievskiy     BdrvSetInheritsFrom *s = opaque;
3311332b3a17SVladimir Sementsov-Ogievskiy 
3312332b3a17SVladimir Sementsov-Ogievskiy     s->bs->inherits_from = s->old_inherits_from;
3313332b3a17SVladimir Sementsov-Ogievskiy }
3314332b3a17SVladimir Sementsov-Ogievskiy 
3315332b3a17SVladimir Sementsov-Ogievskiy static TransactionActionDrv bdrv_set_inherits_from_drv = {
3316332b3a17SVladimir Sementsov-Ogievskiy     .abort = bdrv_set_inherits_from_abort,
3317332b3a17SVladimir Sementsov-Ogievskiy     .clean = g_free,
3318332b3a17SVladimir Sementsov-Ogievskiy };
3319332b3a17SVladimir Sementsov-Ogievskiy 
3320332b3a17SVladimir Sementsov-Ogievskiy /* @tran is allowed to be NULL. In this case no rollback is possible */
3321332b3a17SVladimir Sementsov-Ogievskiy static void bdrv_set_inherits_from(BlockDriverState *bs,
3322332b3a17SVladimir Sementsov-Ogievskiy                                    BlockDriverState *new_inherits_from,
3323332b3a17SVladimir Sementsov-Ogievskiy                                    Transaction *tran)
3324332b3a17SVladimir Sementsov-Ogievskiy {
3325332b3a17SVladimir Sementsov-Ogievskiy     if (tran) {
3326332b3a17SVladimir Sementsov-Ogievskiy         BdrvSetInheritsFrom *s = g_new(BdrvSetInheritsFrom, 1);
3327332b3a17SVladimir Sementsov-Ogievskiy 
3328332b3a17SVladimir Sementsov-Ogievskiy         *s = (BdrvSetInheritsFrom) {
3329332b3a17SVladimir Sementsov-Ogievskiy             .bs = bs,
3330332b3a17SVladimir Sementsov-Ogievskiy             .old_inherits_from = bs->inherits_from,
3331332b3a17SVladimir Sementsov-Ogievskiy         };
3332332b3a17SVladimir Sementsov-Ogievskiy 
3333332b3a17SVladimir Sementsov-Ogievskiy         tran_add(tran, &bdrv_set_inherits_from_drv, s);
3334332b3a17SVladimir Sementsov-Ogievskiy     }
3335332b3a17SVladimir Sementsov-Ogievskiy 
3336332b3a17SVladimir Sementsov-Ogievskiy     bs->inherits_from = new_inherits_from;
3337332b3a17SVladimir Sementsov-Ogievskiy }
3338332b3a17SVladimir Sementsov-Ogievskiy 
33393cf746b3SMax Reitz /**
33403cf746b3SMax Reitz  * Clear all inherits_from pointers from children and grandchildren of
33413cf746b3SMax Reitz  * @root that point to @root, where necessary.
3342332b3a17SVladimir Sementsov-Ogievskiy  * @tran is allowed to be NULL. In this case no rollback is possible
33433cf746b3SMax Reitz  */
334432a8aba3SKevin Wolf static void GRAPH_WRLOCK
334532a8aba3SKevin Wolf bdrv_unset_inherits_from(BlockDriverState *root, BdrvChild *child,
3346332b3a17SVladimir Sementsov-Ogievskiy                          Transaction *tran)
3347f21d96d0SKevin Wolf {
33484e4bf5c4SKevin Wolf     BdrvChild *c;
33494e4bf5c4SKevin Wolf 
33503cf746b3SMax Reitz     if (child->bs->inherits_from == root) {
33513cf746b3SMax Reitz         /*
33523cf746b3SMax Reitz          * Remove inherits_from only when the last reference between root and
33533cf746b3SMax Reitz          * child->bs goes away.
33543cf746b3SMax Reitz          */
33553cf746b3SMax Reitz         QLIST_FOREACH(c, &root->children, next) {
33564e4bf5c4SKevin Wolf             if (c != child && c->bs == child->bs) {
33574e4bf5c4SKevin Wolf                 break;
33584e4bf5c4SKevin Wolf             }
33594e4bf5c4SKevin Wolf         }
33604e4bf5c4SKevin Wolf         if (c == NULL) {
3361332b3a17SVladimir Sementsov-Ogievskiy             bdrv_set_inherits_from(child->bs, NULL, tran);
336233a60407SKevin Wolf         }
33634e4bf5c4SKevin Wolf     }
336433a60407SKevin Wolf 
33653cf746b3SMax Reitz     QLIST_FOREACH(c, &child->bs->children, next) {
3366332b3a17SVladimir Sementsov-Ogievskiy         bdrv_unset_inherits_from(root, c, tran);
33673cf746b3SMax Reitz     }
33683cf746b3SMax Reitz }
33693cf746b3SMax Reitz 
33707b99a266SMax Reitz /* Callers must ensure that child->frozen is false. */
33713cf746b3SMax Reitz void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
33723cf746b3SMax Reitz {
3373f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
33743cf746b3SMax Reitz     if (child == NULL) {
33753cf746b3SMax Reitz         return;
33763cf746b3SMax Reitz     }
33773cf746b3SMax Reitz 
3378332b3a17SVladimir Sementsov-Ogievskiy     bdrv_unset_inherits_from(parent, child, NULL);
3379f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
338033a60407SKevin Wolf }
338133a60407SKevin Wolf 
33825c8cab48SKevin Wolf 
3383356f4ef6SKevin Wolf static void GRAPH_RDLOCK
3384356f4ef6SKevin Wolf bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
33855c8cab48SKevin Wolf {
33865c8cab48SKevin Wolf     BdrvChild *c;
3387f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
33885c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
3389bd86fb99SMax Reitz         if (c->klass->change_media) {
3390bd86fb99SMax Reitz             c->klass->change_media(c, load);
33915c8cab48SKevin Wolf         }
33925c8cab48SKevin Wolf     }
33935c8cab48SKevin Wolf }
33945c8cab48SKevin Wolf 
33950065c455SAlberto Garcia /* Return true if you can reach parent going through child->inherits_from
33960065c455SAlberto Garcia  * recursively. If parent or child are NULL, return false */
33970065c455SAlberto Garcia static bool bdrv_inherits_from_recursive(BlockDriverState *child,
33980065c455SAlberto Garcia                                          BlockDriverState *parent)
33990065c455SAlberto Garcia {
34000065c455SAlberto Garcia     while (child && child != parent) {
34010065c455SAlberto Garcia         child = child->inherits_from;
34020065c455SAlberto Garcia     }
34030065c455SAlberto Garcia 
34040065c455SAlberto Garcia     return child != NULL;
34050065c455SAlberto Garcia }
34060065c455SAlberto Garcia 
34075db15a57SKevin Wolf /*
340825191e5fSMax Reitz  * Return the BdrvChildRole for @bs's backing child.  bs->backing is
340925191e5fSMax Reitz  * mostly used for COW backing children (role = COW), but also for
341025191e5fSMax Reitz  * filtered children (role = FILTERED | PRIMARY).
341125191e5fSMax Reitz  */
341225191e5fSMax Reitz static BdrvChildRole bdrv_backing_role(BlockDriverState *bs)
341325191e5fSMax Reitz {
341425191e5fSMax Reitz     if (bs->drv && bs->drv->is_filter) {
341525191e5fSMax Reitz         return BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
341625191e5fSMax Reitz     } else {
341725191e5fSMax Reitz         return BDRV_CHILD_COW;
341825191e5fSMax Reitz     }
341925191e5fSMax Reitz }
342025191e5fSMax Reitz 
342125191e5fSMax Reitz /*
3422e9238278SVladimir Sementsov-Ogievskiy  * Sets the bs->backing or bs->file link of a BDS. A new reference is created;
3423e9238278SVladimir Sementsov-Ogievskiy  * callers which don't need their own reference any more must call bdrv_unref().
34247ec390d5SVladimir Sementsov-Ogievskiy  *
34257d4ca9d2SKevin Wolf  * If the respective child is already present (i.e. we're detaching a node),
34267d4ca9d2SKevin Wolf  * that child node must be drained.
34277d4ca9d2SKevin Wolf  *
34287ec390d5SVladimir Sementsov-Ogievskiy  * Function doesn't update permissions, caller is responsible for this.
34294b408668SKevin Wolf  *
343023c983c8SStefan Hajnoczi  * Both @parent_bs and @child_bs can move to a different AioContext in this
343123c983c8SStefan Hajnoczi  * function.
34325661a00dSKevin Wolf  *
34335661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
34345661a00dSKevin Wolf  * while holding a writer lock for the graph.
34355db15a57SKevin Wolf  */
34367d4ca9d2SKevin Wolf static int GRAPH_WRLOCK
34377d4ca9d2SKevin Wolf bdrv_set_file_or_backing_noperm(BlockDriverState *parent_bs,
3438e9238278SVladimir Sementsov-Ogievskiy                                 BlockDriverState *child_bs,
3439e9238278SVladimir Sementsov-Ogievskiy                                 bool is_backing,
3440160333e1SVladimir Sementsov-Ogievskiy                                 Transaction *tran, Error **errp)
34418d24cce1SFam Zheng {
3442e9238278SVladimir Sementsov-Ogievskiy     bool update_inherits_from =
3443e9238278SVladimir Sementsov-Ogievskiy         bdrv_inherits_from_recursive(child_bs, parent_bs);
3444e9238278SVladimir Sementsov-Ogievskiy     BdrvChild *child = is_backing ? parent_bs->backing : parent_bs->file;
3445e9238278SVladimir Sementsov-Ogievskiy     BdrvChildRole role;
34460065c455SAlberto Garcia 
3447bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3448bdb73476SEmanuele Giuseppe Esposito 
3449e9238278SVladimir Sementsov-Ogievskiy     if (!parent_bs->drv) {
3450e9238278SVladimir Sementsov-Ogievskiy         /*
3451e9238278SVladimir Sementsov-Ogievskiy          * Node without drv is an object without a class :/. TODO: finally fix
3452e9238278SVladimir Sementsov-Ogievskiy          * qcow2 driver to never clear bs->drv and implement format corruption
3453e9238278SVladimir Sementsov-Ogievskiy          * handling in other way.
3454e9238278SVladimir Sementsov-Ogievskiy          */
3455e9238278SVladimir Sementsov-Ogievskiy         error_setg(errp, "Node corrupted");
3456e9238278SVladimir Sementsov-Ogievskiy         return -EINVAL;
3457e9238278SVladimir Sementsov-Ogievskiy     }
3458e9238278SVladimir Sementsov-Ogievskiy 
3459e9238278SVladimir Sementsov-Ogievskiy     if (child && child->frozen) {
3460e9238278SVladimir Sementsov-Ogievskiy         error_setg(errp, "Cannot change frozen '%s' link from '%s' to '%s'",
3461e9238278SVladimir Sementsov-Ogievskiy                    child->name, parent_bs->node_name, child->bs->node_name);
3462a1e708fcSVladimir Sementsov-Ogievskiy         return -EPERM;
34632cad1ebeSAlberto Garcia     }
34642cad1ebeSAlberto Garcia 
346525f78d9eSVladimir Sementsov-Ogievskiy     if (is_backing && !parent_bs->drv->is_filter &&
346625f78d9eSVladimir Sementsov-Ogievskiy         !parent_bs->drv->supports_backing)
346725f78d9eSVladimir Sementsov-Ogievskiy     {
346825f78d9eSVladimir Sementsov-Ogievskiy         error_setg(errp, "Driver '%s' of node '%s' does not support backing "
346925f78d9eSVladimir Sementsov-Ogievskiy                    "files", parent_bs->drv->format_name, parent_bs->node_name);
347025f78d9eSVladimir Sementsov-Ogievskiy         return -EINVAL;
347125f78d9eSVladimir Sementsov-Ogievskiy     }
347225f78d9eSVladimir Sementsov-Ogievskiy 
3473e9238278SVladimir Sementsov-Ogievskiy     if (parent_bs->drv->is_filter) {
3474e9238278SVladimir Sementsov-Ogievskiy         role = BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY;
3475e9238278SVladimir Sementsov-Ogievskiy     } else if (is_backing) {
3476e9238278SVladimir Sementsov-Ogievskiy         role = BDRV_CHILD_COW;
3477e9238278SVladimir Sementsov-Ogievskiy     } else {
3478e9238278SVladimir Sementsov-Ogievskiy         /*
3479e9238278SVladimir Sementsov-Ogievskiy          * We only can use same role as it is in existing child. We don't have
3480e9238278SVladimir Sementsov-Ogievskiy          * infrastructure to determine role of file child in generic way
3481e9238278SVladimir Sementsov-Ogievskiy          */
3482e9238278SVladimir Sementsov-Ogievskiy         if (!child) {
3483e9238278SVladimir Sementsov-Ogievskiy             error_setg(errp, "Cannot set file child to format node without "
3484e9238278SVladimir Sementsov-Ogievskiy                        "file child");
3485e9238278SVladimir Sementsov-Ogievskiy             return -EINVAL;
3486e9238278SVladimir Sementsov-Ogievskiy         }
3487e9238278SVladimir Sementsov-Ogievskiy         role = child->role;
3488826b6ca0SFam Zheng     }
3489826b6ca0SFam Zheng 
3490e9238278SVladimir Sementsov-Ogievskiy     if (child) {
34917d4ca9d2SKevin Wolf         assert(child->bs->quiesce_counter);
3492e9238278SVladimir Sementsov-Ogievskiy         bdrv_unset_inherits_from(parent_bs, child, tran);
349357f08941SVladimir Sementsov-Ogievskiy         bdrv_remove_child(child, tran);
3494e9238278SVladimir Sementsov-Ogievskiy     }
3495e9238278SVladimir Sementsov-Ogievskiy 
3496e9238278SVladimir Sementsov-Ogievskiy     if (!child_bs) {
34978d24cce1SFam Zheng         goto out;
34988d24cce1SFam Zheng     }
349912fa4af6SKevin Wolf 
35005bb04747SVladimir Sementsov-Ogievskiy     child = bdrv_attach_child_noperm(parent_bs, child_bs,
3501e9238278SVladimir Sementsov-Ogievskiy                                      is_backing ? "backing" : "file",
3502e9238278SVladimir Sementsov-Ogievskiy                                      &child_of_bds, role,
3503e9238278SVladimir Sementsov-Ogievskiy                                      tran, errp);
35045bb04747SVladimir Sementsov-Ogievskiy     if (!child) {
35055bb04747SVladimir Sementsov-Ogievskiy         return -EINVAL;
3506a1e708fcSVladimir Sementsov-Ogievskiy     }
3507a1e708fcSVladimir Sementsov-Ogievskiy 
3508160333e1SVladimir Sementsov-Ogievskiy 
3509160333e1SVladimir Sementsov-Ogievskiy     /*
3510e9238278SVladimir Sementsov-Ogievskiy      * If inherits_from pointed recursively to bs then let's update it to
3511160333e1SVladimir Sementsov-Ogievskiy      * point directly to bs (else it will become NULL).
3512160333e1SVladimir Sementsov-Ogievskiy      */
3513a1e708fcSVladimir Sementsov-Ogievskiy     if (update_inherits_from) {
3514e9238278SVladimir Sementsov-Ogievskiy         bdrv_set_inherits_from(child_bs, parent_bs, tran);
35150065c455SAlberto Garcia     }
3516826b6ca0SFam Zheng 
35178d24cce1SFam Zheng out:
3518e9238278SVladimir Sementsov-Ogievskiy     bdrv_refresh_limits(parent_bs, tran, NULL);
3519160333e1SVladimir Sementsov-Ogievskiy 
3520160333e1SVladimir Sementsov-Ogievskiy     return 0;
3521160333e1SVladimir Sementsov-Ogievskiy }
3522160333e1SVladimir Sementsov-Ogievskiy 
35234b408668SKevin Wolf /*
352423c983c8SStefan Hajnoczi  * Both @bs and @backing_hd can move to a different AioContext in this
352523c983c8SStefan Hajnoczi  * function.
35267d4ca9d2SKevin Wolf  *
35277d4ca9d2SKevin Wolf  * If a backing child is already present (i.e. we're detaching a node), that
35287d4ca9d2SKevin Wolf  * child node must be drained.
35294b408668SKevin Wolf  */
353092140b9fSKevin Wolf int bdrv_set_backing_hd_drained(BlockDriverState *bs,
353192140b9fSKevin Wolf                                 BlockDriverState *backing_hd,
3532160333e1SVladimir Sementsov-Ogievskiy                                 Error **errp)
3533160333e1SVladimir Sementsov-Ogievskiy {
3534160333e1SVladimir Sementsov-Ogievskiy     int ret;
3535160333e1SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
3536160333e1SVladimir Sementsov-Ogievskiy 
3537f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
353892140b9fSKevin Wolf     assert(bs->quiesce_counter > 0);
35397d4ca9d2SKevin Wolf     if (bs->backing) {
35407d4ca9d2SKevin Wolf         assert(bs->backing->bs->quiesce_counter > 0);
35417d4ca9d2SKevin Wolf     }
3542c0829cb1SVladimir Sementsov-Ogievskiy 
35433204c2e3SKevin Wolf     ret = bdrv_set_file_or_backing_noperm(bs, backing_hd, true, tran, errp);
3544160333e1SVladimir Sementsov-Ogievskiy     if (ret < 0) {
3545160333e1SVladimir Sementsov-Ogievskiy         goto out;
3546160333e1SVladimir Sementsov-Ogievskiy     }
3547160333e1SVladimir Sementsov-Ogievskiy 
3548f1316edbSVladimir Sementsov-Ogievskiy     ret = bdrv_refresh_perms(bs, tran, errp);
3549160333e1SVladimir Sementsov-Ogievskiy out:
3550160333e1SVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
355192140b9fSKevin Wolf     return ret;
355292140b9fSKevin Wolf }
3553a1e708fcSVladimir Sementsov-Ogievskiy 
355492140b9fSKevin Wolf int bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd,
355592140b9fSKevin Wolf                         Error **errp)
355692140b9fSKevin Wolf {
3557004915a9SKevin Wolf     BlockDriverState *drain_bs;
355892140b9fSKevin Wolf     int ret;
355992140b9fSKevin Wolf     GLOBAL_STATE_CODE();
356092140b9fSKevin Wolf 
3561004915a9SKevin Wolf     bdrv_graph_rdlock_main_loop();
3562004915a9SKevin Wolf     drain_bs = bs->backing ? bs->backing->bs : bs;
3563004915a9SKevin Wolf     bdrv_graph_rdunlock_main_loop();
3564004915a9SKevin Wolf 
35657d4ca9d2SKevin Wolf     bdrv_ref(drain_bs);
35667d4ca9d2SKevin Wolf     bdrv_drained_begin(drain_bs);
35676bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
356892140b9fSKevin Wolf     ret = bdrv_set_backing_hd_drained(bs, backing_hd, errp);
35696bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
35707d4ca9d2SKevin Wolf     bdrv_drained_end(drain_bs);
35717d4ca9d2SKevin Wolf     bdrv_unref(drain_bs);
3572c0829cb1SVladimir Sementsov-Ogievskiy 
3573a1e708fcSVladimir Sementsov-Ogievskiy     return ret;
35748d24cce1SFam Zheng }
35758d24cce1SFam Zheng 
357631ca6d07SKevin Wolf /*
357731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
357831ca6d07SKevin Wolf  *
3579d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
3580d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
3581d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
3582d9b7b057SKevin Wolf  * BlockdevRef.
3583d9b7b057SKevin Wolf  *
3584d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
358531ca6d07SKevin Wolf  */
3586d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
3587d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
35889156df12SPaolo Bonzini {
35897b22e055SZhao Liu     ERRP_GUARD();
35906b6833c1SMax Reitz     char *backing_filename = NULL;
3591d9b7b057SKevin Wolf     char *bdref_key_dot;
3592d9b7b057SKevin Wolf     const char *reference = NULL;
3593317fc44eSKevin Wolf     int ret = 0;
3594998c2019SMax Reitz     bool implicit_backing = false;
35958d24cce1SFam Zheng     BlockDriverState *backing_hd;
3596d9b7b057SKevin Wolf     QDict *options;
3597d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
359834b5d2c6SMax Reitz     Error *local_err = NULL;
35999156df12SPaolo Bonzini 
3600f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3601004915a9SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
3602f791bf7fSEmanuele Giuseppe Esposito 
3603760e0063SKevin Wolf     if (bs->backing != NULL) {
36041ba4b6a5SBenoît Canet         goto free_exit;
36059156df12SPaolo Bonzini     }
36069156df12SPaolo Bonzini 
360731ca6d07SKevin Wolf     /* NULL means an empty set of options */
3608d9b7b057SKevin Wolf     if (parent_options == NULL) {
3609d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
3610d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
361131ca6d07SKevin Wolf     }
361231ca6d07SKevin Wolf 
36139156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
3614d9b7b057SKevin Wolf 
3615d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3616d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
3617d9b7b057SKevin Wolf     g_free(bdref_key_dot);
3618d9b7b057SKevin Wolf 
3619129c7d1cSMarkus Armbruster     /*
3620129c7d1cSMarkus Armbruster      * Caution: while qdict_get_try_str() is fine, getting non-string
3621129c7d1cSMarkus Armbruster      * types would require more care.  When @parent_options come from
3622129c7d1cSMarkus Armbruster      * -blockdev or blockdev_add, its members are typed according to
3623129c7d1cSMarkus Armbruster      * the QAPI schema, but when they come from -drive, they're all
3624129c7d1cSMarkus Armbruster      * QString.
3625129c7d1cSMarkus Armbruster      */
3626d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
3627d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
36286b6833c1SMax Reitz         /* keep backing_filename NULL */
36291cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
3630cb3e7f08SMarc-André Lureau         qobject_unref(options);
36311ba4b6a5SBenoît Canet         goto free_exit;
3632dbecebddSFam Zheng     } else {
3633998c2019SMax Reitz         if (qdict_size(options) == 0) {
3634998c2019SMax Reitz             /* If the user specifies options that do not modify the
3635998c2019SMax Reitz              * backing file's behavior, we might still consider it the
3636998c2019SMax Reitz              * implicit backing file.  But it's easier this way, and
3637998c2019SMax Reitz              * just specifying some of the backing BDS's options is
3638998c2019SMax Reitz              * only possible with -drive anyway (otherwise the QAPI
3639998c2019SMax Reitz              * schema forces the user to specify everything). */
3640998c2019SMax Reitz             implicit_backing = !strcmp(bs->auto_backing_file, bs->backing_file);
3641998c2019SMax Reitz         }
3642998c2019SMax Reitz 
36436b6833c1SMax Reitz         backing_filename = bdrv_get_full_backing_filename(bs, &local_err);
36449f07429eSMax Reitz         if (local_err) {
36459f07429eSMax Reitz             ret = -EINVAL;
36469f07429eSMax Reitz             error_propagate(errp, local_err);
3647cb3e7f08SMarc-André Lureau             qobject_unref(options);
36489f07429eSMax Reitz             goto free_exit;
36499f07429eSMax Reitz         }
36509156df12SPaolo Bonzini     }
36519156df12SPaolo Bonzini 
36528ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
36538ee79e70SKevin Wolf         ret = -EINVAL;
36548ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
3655cb3e7f08SMarc-André Lureau         qobject_unref(options);
36568ee79e70SKevin Wolf         goto free_exit;
36578ee79e70SKevin Wolf     }
36588ee79e70SKevin Wolf 
36596bff597bSPeter Krempa     if (!reference &&
36606bff597bSPeter Krempa         bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
366146f5ac20SEric Blake         qdict_put_str(options, "driver", bs->backing_format);
36629156df12SPaolo Bonzini     }
36639156df12SPaolo Bonzini 
36646b6833c1SMax Reitz     backing_hd = bdrv_open_inherit(backing_filename, reference, options, 0, bs,
36657ead9469SKevin Wolf                                    &child_of_bds, bdrv_backing_role(bs), true,
36667ead9469SKevin Wolf                                    errp);
36675b363937SMax Reitz     if (!backing_hd) {
36689156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
3669e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
36705b363937SMax Reitz         ret = -EINVAL;
36711ba4b6a5SBenoît Canet         goto free_exit;
36729156df12SPaolo Bonzini     }
3673df581792SKevin Wolf 
3674998c2019SMax Reitz     if (implicit_backing) {
3675998c2019SMax Reitz         bdrv_refresh_filename(backing_hd);
3676998c2019SMax Reitz         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
3677998c2019SMax Reitz                 backing_hd->filename);
3678998c2019SMax Reitz     }
3679998c2019SMax Reitz 
36805db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
36815db15a57SKevin Wolf      * backing_hd reference now */
3682dc9c10a1SVladimir Sementsov-Ogievskiy     ret = bdrv_set_backing_hd(bs, backing_hd, errp);
36835db15a57SKevin Wolf     bdrv_unref(backing_hd);
36848aa04542SKevin Wolf 
3685dc9c10a1SVladimir Sementsov-Ogievskiy     if (ret < 0) {
368612fa4af6SKevin Wolf         goto free_exit;
368712fa4af6SKevin Wolf     }
3688d80ac658SPeter Feiner 
3689d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
3690d9b7b057SKevin Wolf 
36911ba4b6a5SBenoît Canet free_exit:
36921ba4b6a5SBenoît Canet     g_free(backing_filename);
3693cb3e7f08SMarc-André Lureau     qobject_unref(tmp_parent_options);
36941ba4b6a5SBenoît Canet     return ret;
36959156df12SPaolo Bonzini }
36969156df12SPaolo Bonzini 
36972d6b86afSKevin Wolf static BlockDriverState *
36982d6b86afSKevin Wolf bdrv_open_child_bs(const char *filename, QDict *options, const char *bdref_key,
3699bd86fb99SMax Reitz                    BlockDriverState *parent, const BdrvChildClass *child_class,
37007ead9469SKevin Wolf                    BdrvChildRole child_role, bool allow_none,
37017ead9469SKevin Wolf                    bool parse_filename, Error **errp)
3702da557aacSMax Reitz {
37032d6b86afSKevin Wolf     BlockDriverState *bs = NULL;
3704da557aacSMax Reitz     QDict *image_options;
3705da557aacSMax Reitz     char *bdref_key_dot;
3706da557aacSMax Reitz     const char *reference;
3707da557aacSMax Reitz 
3708bd86fb99SMax Reitz     assert(child_class != NULL);
3709f67503e5SMax Reitz 
3710da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
3711da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
3712da557aacSMax Reitz     g_free(bdref_key_dot);
3713da557aacSMax Reitz 
3714129c7d1cSMarkus Armbruster     /*
3715129c7d1cSMarkus Armbruster      * Caution: while qdict_get_try_str() is fine, getting non-string
3716129c7d1cSMarkus Armbruster      * types would require more care.  When @options come from
3717129c7d1cSMarkus Armbruster      * -blockdev or blockdev_add, its members are typed according to
3718129c7d1cSMarkus Armbruster      * the QAPI schema, but when they come from -drive, they're all
3719129c7d1cSMarkus Armbruster      * QString.
3720129c7d1cSMarkus Armbruster      */
3721da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
3722da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
3723b4b059f6SKevin Wolf         if (!allow_none) {
3724da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
3725da557aacSMax Reitz                        bdref_key);
3726da557aacSMax Reitz         }
3727cb3e7f08SMarc-André Lureau         qobject_unref(image_options);
3728da557aacSMax Reitz         goto done;
3729da557aacSMax Reitz     }
3730da557aacSMax Reitz 
37315b363937SMax Reitz     bs = bdrv_open_inherit(filename, reference, image_options, 0,
37327ead9469SKevin Wolf                            parent, child_class, child_role, parse_filename,
37337ead9469SKevin Wolf                            errp);
37345b363937SMax Reitz     if (!bs) {
3735df581792SKevin Wolf         goto done;
3736df581792SKevin Wolf     }
3737df581792SKevin Wolf 
3738da557aacSMax Reitz done:
3739da557aacSMax Reitz     qdict_del(options, bdref_key);
37402d6b86afSKevin Wolf     return bs;
37412d6b86afSKevin Wolf }
37422d6b86afSKevin Wolf 
37437ead9469SKevin Wolf static BdrvChild *bdrv_open_child_common(const char *filename,
37447ead9469SKevin Wolf                                          QDict *options, const char *bdref_key,
37457ead9469SKevin Wolf                                          BlockDriverState *parent,
37467ead9469SKevin Wolf                                          const BdrvChildClass *child_class,
37477ead9469SKevin Wolf                                          BdrvChildRole child_role,
37487ead9469SKevin Wolf                                          bool allow_none, bool parse_filename,
37497ead9469SKevin Wolf                                          Error **errp)
37507ead9469SKevin Wolf {
37517ead9469SKevin Wolf     BlockDriverState *bs;
37527ead9469SKevin Wolf     BdrvChild *child;
37537ead9469SKevin Wolf 
37547ead9469SKevin Wolf     GLOBAL_STATE_CODE();
37557ead9469SKevin Wolf 
37567ead9469SKevin Wolf     bs = bdrv_open_child_bs(filename, options, bdref_key, parent, child_class,
37577ead9469SKevin Wolf                             child_role, allow_none, parse_filename, errp);
37587ead9469SKevin Wolf     if (bs == NULL) {
37597ead9469SKevin Wolf         return NULL;
37607ead9469SKevin Wolf     }
37617ead9469SKevin Wolf 
37627ead9469SKevin Wolf     bdrv_graph_wrlock();
37637ead9469SKevin Wolf     child = bdrv_attach_child(parent, bs, bdref_key, child_class, child_role,
37647ead9469SKevin Wolf                               errp);
37657ead9469SKevin Wolf     bdrv_graph_wrunlock();
37667ead9469SKevin Wolf 
37677ead9469SKevin Wolf     return child;
37687ead9469SKevin Wolf }
37697ead9469SKevin Wolf 
37702d6b86afSKevin Wolf /*
37712d6b86afSKevin Wolf  * Opens a disk image whose options are given as BlockdevRef in another block
37722d6b86afSKevin Wolf  * device's options.
37732d6b86afSKevin Wolf  *
37742d6b86afSKevin Wolf  * If allow_none is true, no image will be opened if filename is false and no
37752d6b86afSKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
37762d6b86afSKevin Wolf  *
37772d6b86afSKevin Wolf  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
37782d6b86afSKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
37792d6b86afSKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
37802d6b86afSKevin Wolf  * BlockdevRef.
37812d6b86afSKevin Wolf  *
37822d6b86afSKevin Wolf  * The BlockdevRef will be removed from the options QDict.
3783aa269ff8SKevin Wolf  *
378423c983c8SStefan Hajnoczi  * @parent can move to a different AioContext in this function.
37852d6b86afSKevin Wolf  */
37862d6b86afSKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
37872d6b86afSKevin Wolf                            QDict *options, const char *bdref_key,
37882d6b86afSKevin Wolf                            BlockDriverState *parent,
3789bd86fb99SMax Reitz                            const BdrvChildClass *child_class,
3790258b7765SMax Reitz                            BdrvChildRole child_role,
37912d6b86afSKevin Wolf                            bool allow_none, Error **errp)
37922d6b86afSKevin Wolf {
37937ead9469SKevin Wolf     return bdrv_open_child_common(filename, options, bdref_key, parent,
37947ead9469SKevin Wolf                                   child_class, child_role, allow_none, false,
3795258b7765SMax Reitz                                   errp);
3796b4b059f6SKevin Wolf }
3797b4b059f6SKevin Wolf 
3798bd86fb99SMax Reitz /*
37997ead9469SKevin Wolf  * This does mostly the same as bdrv_open_child(), but for opening the primary
38007ead9469SKevin Wolf  * child of a node. A notable difference from bdrv_open_child() is that it
38017ead9469SKevin Wolf  * enables filename parsing for protocol names (including json:).
3802aa269ff8SKevin Wolf  *
380323c983c8SStefan Hajnoczi  * @parent can move to a different AioContext in this function.
380483930780SVladimir Sementsov-Ogievskiy  */
380583930780SVladimir Sementsov-Ogievskiy int bdrv_open_file_child(const char *filename,
380683930780SVladimir Sementsov-Ogievskiy                          QDict *options, const char *bdref_key,
380783930780SVladimir Sementsov-Ogievskiy                          BlockDriverState *parent, Error **errp)
380883930780SVladimir Sementsov-Ogievskiy {
380983930780SVladimir Sementsov-Ogievskiy     BdrvChildRole role;
381083930780SVladimir Sementsov-Ogievskiy 
381183930780SVladimir Sementsov-Ogievskiy     /* commit_top and mirror_top don't use this function */
381283930780SVladimir Sementsov-Ogievskiy     assert(!parent->drv->filtered_child_is_backing);
381383930780SVladimir Sementsov-Ogievskiy     role = parent->drv->is_filter ?
381483930780SVladimir Sementsov-Ogievskiy         (BDRV_CHILD_FILTERED | BDRV_CHILD_PRIMARY) : BDRV_CHILD_IMAGE;
381583930780SVladimir Sementsov-Ogievskiy 
38167ead9469SKevin Wolf     if (!bdrv_open_child_common(filename, options, bdref_key, parent,
38177ead9469SKevin Wolf                                 &child_of_bds, role, false, true, errp))
38185bb04747SVladimir Sementsov-Ogievskiy     {
38195bb04747SVladimir Sementsov-Ogievskiy         return -EINVAL;
38205bb04747SVladimir Sementsov-Ogievskiy     }
382183930780SVladimir Sementsov-Ogievskiy 
38225bb04747SVladimir Sementsov-Ogievskiy     return 0;
382383930780SVladimir Sementsov-Ogievskiy }
382483930780SVladimir Sementsov-Ogievskiy 
382583930780SVladimir Sementsov-Ogievskiy /*
3826bd86fb99SMax Reitz  * TODO Future callers may need to specify parent/child_class in order for
3827bd86fb99SMax Reitz  * option inheritance to work. Existing callers use it for the root node.
3828bd86fb99SMax Reitz  */
3829e1d74bc6SKevin Wolf BlockDriverState *bdrv_open_blockdev_ref(BlockdevRef *ref, Error **errp)
3830e1d74bc6SKevin Wolf {
3831e1d74bc6SKevin Wolf     BlockDriverState *bs = NULL;
3832e1d74bc6SKevin Wolf     QObject *obj = NULL;
3833e1d74bc6SKevin Wolf     QDict *qdict = NULL;
3834e1d74bc6SKevin Wolf     const char *reference = NULL;
3835e1d74bc6SKevin Wolf     Visitor *v = NULL;
3836e1d74bc6SKevin Wolf 
3837f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3838f791bf7fSEmanuele Giuseppe Esposito 
3839e1d74bc6SKevin Wolf     if (ref->type == QTYPE_QSTRING) {
3840e1d74bc6SKevin Wolf         reference = ref->u.reference;
3841e1d74bc6SKevin Wolf     } else {
3842e1d74bc6SKevin Wolf         BlockdevOptions *options = &ref->u.definition;
3843e1d74bc6SKevin Wolf         assert(ref->type == QTYPE_QDICT);
3844e1d74bc6SKevin Wolf 
3845e1d74bc6SKevin Wolf         v = qobject_output_visitor_new(&obj);
38461f584248SMarkus Armbruster         visit_type_BlockdevOptions(v, NULL, &options, &error_abort);
3847e1d74bc6SKevin Wolf         visit_complete(v, &obj);
3848e1d74bc6SKevin Wolf 
38497dc847ebSMax Reitz         qdict = qobject_to(QDict, obj);
3850e1d74bc6SKevin Wolf         qdict_flatten(qdict);
3851e1d74bc6SKevin Wolf 
3852e1d74bc6SKevin Wolf         /* bdrv_open_inherit() defaults to the values in bdrv_flags (for
3853e1d74bc6SKevin Wolf          * compatibility with other callers) rather than what we want as the
3854e1d74bc6SKevin Wolf          * real defaults. Apply the defaults here instead. */
3855e1d74bc6SKevin Wolf         qdict_set_default_str(qdict, BDRV_OPT_CACHE_DIRECT, "off");
3856e1d74bc6SKevin Wolf         qdict_set_default_str(qdict, BDRV_OPT_CACHE_NO_FLUSH, "off");
3857e1d74bc6SKevin Wolf         qdict_set_default_str(qdict, BDRV_OPT_READ_ONLY, "off");
3858e35bdc12SKevin Wolf         qdict_set_default_str(qdict, BDRV_OPT_AUTO_READ_ONLY, "off");
3859e35bdc12SKevin Wolf 
3860e1d74bc6SKevin Wolf     }
3861e1d74bc6SKevin Wolf 
38627ead9469SKevin Wolf     bs = bdrv_open_inherit(NULL, reference, qdict, 0, NULL, NULL, 0, false,
38637ead9469SKevin Wolf                            errp);
3864e1d74bc6SKevin Wolf     obj = NULL;
3865cb3e7f08SMarc-André Lureau     qobject_unref(obj);
3866e1d74bc6SKevin Wolf     visit_free(v);
3867e1d74bc6SKevin Wolf     return bs;
3868e1d74bc6SKevin Wolf }
3869e1d74bc6SKevin Wolf 
387066836189SMax Reitz static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
387166836189SMax Reitz                                                    int flags,
387266836189SMax Reitz                                                    QDict *snapshot_options,
387366836189SMax Reitz                                                    Error **errp)
3874b998875dSKevin Wolf {
38757b22e055SZhao Liu     ERRP_GUARD();
387669fbfff9SBin Meng     g_autofree char *tmp_filename = NULL;
3877b998875dSKevin Wolf     int64_t total_size;
387883d0521aSChunyan Liu     QemuOpts *opts = NULL;
3879ff6ed714SEric Blake     BlockDriverState *bs_snapshot = NULL;
3880b998875dSKevin Wolf     int ret;
3881b998875dSKevin Wolf 
3882bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
3883bdb73476SEmanuele Giuseppe Esposito 
3884b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
3885b998875dSKevin Wolf        instead of opening 'filename' directly */
3886b998875dSKevin Wolf 
3887b998875dSKevin Wolf     /* Get the required size from the image */
3888f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
3889f665f01fSKevin Wolf 
3890f187743aSKevin Wolf     if (total_size < 0) {
3891f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
38921ba4b6a5SBenoît Canet         goto out;
3893f187743aSKevin Wolf     }
3894b998875dSKevin Wolf 
3895b998875dSKevin Wolf     /* Create the temporary image */
389669fbfff9SBin Meng     tmp_filename = create_tmp_file(errp);
389769fbfff9SBin Meng     if (!tmp_filename) {
38981ba4b6a5SBenoît Canet         goto out;
3899b998875dSKevin Wolf     }
3900b998875dSKevin Wolf 
3901ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
3902c282e1fdSChunyan Liu                             &error_abort);
390339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
3904e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
390583d0521aSChunyan Liu     qemu_opts_del(opts);
3906b998875dSKevin Wolf     if (ret < 0) {
3907e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
3908e43bfd9cSMarkus Armbruster                       tmp_filename);
39091ba4b6a5SBenoît Canet         goto out;
3910b998875dSKevin Wolf     }
3911b998875dSKevin Wolf 
391273176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
391346f5ac20SEric Blake     qdict_put_str(snapshot_options, "file.driver", "file");
391446f5ac20SEric Blake     qdict_put_str(snapshot_options, "file.filename", tmp_filename);
391546f5ac20SEric Blake     qdict_put_str(snapshot_options, "driver", "qcow2");
3916b998875dSKevin Wolf 
39175b363937SMax Reitz     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
391873176beeSKevin Wolf     snapshot_options = NULL;
39195b363937SMax Reitz     if (!bs_snapshot) {
39201ba4b6a5SBenoît Canet         goto out;
3921b998875dSKevin Wolf     }
3922b998875dSKevin Wolf 
3923934aee14SVladimir Sementsov-Ogievskiy     ret = bdrv_append(bs_snapshot, bs, errp);
3924934aee14SVladimir Sementsov-Ogievskiy     if (ret < 0) {
3925ff6ed714SEric Blake         bs_snapshot = NULL;
3926b2c2832cSKevin Wolf         goto out;
3927b2c2832cSKevin Wolf     }
39281ba4b6a5SBenoît Canet 
39291ba4b6a5SBenoît Canet out:
3930cb3e7f08SMarc-André Lureau     qobject_unref(snapshot_options);
3931ff6ed714SEric Blake     return bs_snapshot;
3932b998875dSKevin Wolf }
3933b998875dSKevin Wolf 
3934da557aacSMax Reitz /*
3935b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
3936de9c0cecSKevin Wolf  *
3937de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
3938de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
3939de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
3940cb3e7f08SMarc-André Lureau  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
3941f67503e5SMax Reitz  *
3942f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
3943f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
3944ddf5636dSMax Reitz  *
3945ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
3946ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
3947ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
3948b6ce07aaSKevin Wolf  */
394932192301SKevin Wolf static BlockDriverState * no_coroutine_fn
395032192301SKevin Wolf bdrv_open_inherit(const char *filename, const char *reference, QDict *options,
395132192301SKevin Wolf                   int flags, BlockDriverState *parent,
395232192301SKevin Wolf                   const BdrvChildClass *child_class, BdrvChildRole child_role,
39537ead9469SKevin Wolf                   bool parse_filename, Error **errp)
3954ea2384d3Sbellard {
3955b6ce07aaSKevin Wolf     int ret;
39565696c6e3SKevin Wolf     BlockBackend *file = NULL;
39579a4f4c31SKevin Wolf     BlockDriverState *bs;
3958ce343771SMax Reitz     BlockDriver *drv = NULL;
39592f624b80SAlberto Garcia     BdrvChild *child;
396074fe54f2SKevin Wolf     const char *drvname;
39613e8c2e57SAlberto Garcia     const char *backing;
396234b5d2c6SMax Reitz     Error *local_err = NULL;
396373176beeSKevin Wolf     QDict *snapshot_options = NULL;
3964b1e6fc08SKevin Wolf     int snapshot_flags = 0;
396533e3963eSbellard 
3966bd86fb99SMax Reitz     assert(!child_class || !flags);
3967bd86fb99SMax Reitz     assert(!child_class == !parent);
3968f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
396932192301SKevin Wolf     assert(!qemu_in_coroutine());
3970f67503e5SMax Reitz 
3971356f4ef6SKevin Wolf     /* TODO We'll eventually have to take a writer lock in this function */
3972356f4ef6SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
3973356f4ef6SKevin Wolf 
3974ddf5636dSMax Reitz     if (reference) {
3975ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
3976cb3e7f08SMarc-André Lureau         qobject_unref(options);
3977ddf5636dSMax Reitz 
3978ddf5636dSMax Reitz         if (filename || options_non_empty) {
3979ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
3980ddf5636dSMax Reitz                        "additional options or a new filename");
39815b363937SMax Reitz             return NULL;
3982ddf5636dSMax Reitz         }
3983ddf5636dSMax Reitz 
3984ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
3985ddf5636dSMax Reitz         if (!bs) {
39865b363937SMax Reitz             return NULL;
3987ddf5636dSMax Reitz         }
398876b22320SKevin Wolf 
3989ddf5636dSMax Reitz         bdrv_ref(bs);
39905b363937SMax Reitz         return bs;
3991ddf5636dSMax Reitz     }
3992ddf5636dSMax Reitz 
3993e4e9986bSMarkus Armbruster     bs = bdrv_new();
3994f67503e5SMax Reitz 
3995de9c0cecSKevin Wolf     /* NULL means an empty set of options */
3996de9c0cecSKevin Wolf     if (options == NULL) {
3997de9c0cecSKevin Wolf         options = qdict_new();
3998de9c0cecSKevin Wolf     }
3999de9c0cecSKevin Wolf 
4000145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
40017ead9469SKevin Wolf     if (parse_filename) {
4002de3b53f0SKevin Wolf         parse_json_protocol(options, &filename, &local_err);
4003de3b53f0SKevin Wolf         if (local_err) {
4004de3b53f0SKevin Wolf             goto fail;
4005de3b53f0SKevin Wolf         }
40067ead9469SKevin Wolf     }
4007de3b53f0SKevin Wolf 
4008145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
4009145f598eSKevin Wolf 
4010bd86fb99SMax Reitz     if (child_class) {
40113cdc69d3SMax Reitz         bool parent_is_format;
40123cdc69d3SMax Reitz 
40133cdc69d3SMax Reitz         if (parent->drv) {
40143cdc69d3SMax Reitz             parent_is_format = parent->drv->is_format;
40153cdc69d3SMax Reitz         } else {
40163cdc69d3SMax Reitz             /*
40173cdc69d3SMax Reitz              * parent->drv is not set yet because this node is opened for
40183cdc69d3SMax Reitz              * (potential) format probing.  That means that @parent is going
40193cdc69d3SMax Reitz              * to be a format node.
40203cdc69d3SMax Reitz              */
40213cdc69d3SMax Reitz             parent_is_format = true;
40223cdc69d3SMax Reitz         }
40233cdc69d3SMax Reitz 
4024bddcec37SKevin Wolf         bs->inherits_from = parent;
40253cdc69d3SMax Reitz         child_class->inherit_options(child_role, parent_is_format,
40263cdc69d3SMax Reitz                                      &flags, options,
40278e2160e2SKevin Wolf                                      parent->open_flags, parent->options);
4028f3930ed0SKevin Wolf     }
4029f3930ed0SKevin Wolf 
40307ead9469SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, parse_filename,
40317ead9469SKevin Wolf                             &local_err);
4032dfde483eSPhilippe Mathieu-Daudé     if (ret < 0) {
4033462f5bcfSKevin Wolf         goto fail;
4034462f5bcfSKevin Wolf     }
4035462f5bcfSKevin Wolf 
4036129c7d1cSMarkus Armbruster     /*
4037129c7d1cSMarkus Armbruster      * Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
4038129c7d1cSMarkus Armbruster      * Caution: getting a boolean member of @options requires care.
4039129c7d1cSMarkus Armbruster      * When @options come from -blockdev or blockdev_add, members are
4040129c7d1cSMarkus Armbruster      * typed according to the QAPI schema, but when they come from
4041129c7d1cSMarkus Armbruster      * -drive, they're all QString.
4042129c7d1cSMarkus Armbruster      */
4043f87a0e29SAlberto Garcia     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
4044f87a0e29SAlberto Garcia         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
4045f87a0e29SAlberto Garcia         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
4046f87a0e29SAlberto Garcia     } else {
4047f87a0e29SAlberto Garcia         flags &= ~BDRV_O_RDWR;
404814499ea5SAlberto Garcia     }
404914499ea5SAlberto Garcia 
405014499ea5SAlberto Garcia     if (flags & BDRV_O_SNAPSHOT) {
405114499ea5SAlberto Garcia         snapshot_options = qdict_new();
405214499ea5SAlberto Garcia         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
405314499ea5SAlberto Garcia                                    flags, options);
4054f87a0e29SAlberto Garcia         /* Let bdrv_backing_options() override "read-only" */
4055f87a0e29SAlberto Garcia         qdict_del(options, BDRV_OPT_READ_ONLY);
405600ff7ffdSMax Reitz         bdrv_inherited_options(BDRV_CHILD_COW, true,
405700ff7ffdSMax Reitz                                &flags, options, flags, options);
405814499ea5SAlberto Garcia     }
405914499ea5SAlberto Garcia 
406062392ebbSKevin Wolf     bs->open_flags = flags;
406162392ebbSKevin Wolf     bs->options = options;
406262392ebbSKevin Wolf     options = qdict_clone_shallow(options);
406362392ebbSKevin Wolf 
406476c591b0SKevin Wolf     /* Find the right image format driver */
4065129c7d1cSMarkus Armbruster     /* See cautionary note on accessing @options above */
406676c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
406776c591b0SKevin Wolf     if (drvname) {
406876c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
406976c591b0SKevin Wolf         if (!drv) {
407076c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
407176c591b0SKevin Wolf             goto fail;
407276c591b0SKevin Wolf         }
407376c591b0SKevin Wolf     }
407476c591b0SKevin Wolf 
407576c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
407676c591b0SKevin Wolf 
4077129c7d1cSMarkus Armbruster     /* See cautionary note on accessing @options above */
40783e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
4079e59a0cf1SMax Reitz     if (qobject_to(QNull, qdict_get(options, "backing")) != NULL ||
4080e59a0cf1SMax Reitz         (backing && *backing == '\0'))
4081e59a0cf1SMax Reitz     {
40824f7be280SMax Reitz         if (backing) {
40834f7be280SMax Reitz             warn_report("Use of \"backing\": \"\" is deprecated; "
40844f7be280SMax Reitz                         "use \"backing\": null instead");
40854f7be280SMax Reitz         }
40863e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
4087ae0f57f0SKevin Wolf         qdict_del(bs->explicit_options, "backing");
4088ae0f57f0SKevin Wolf         qdict_del(bs->options, "backing");
40893e8c2e57SAlberto Garcia         qdict_del(options, "backing");
40903e8c2e57SAlberto Garcia     }
40913e8c2e57SAlberto Garcia 
40925696c6e3SKevin Wolf     /* Open image file without format layer. This BlockBackend is only used for
40934e4bf5c4SKevin Wolf      * probing, the block drivers will do their own bdrv_open_child() for the
40944e4bf5c4SKevin Wolf      * same BDS, which is why we put the node name back into options. */
4095f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
40965696c6e3SKevin Wolf         BlockDriverState *file_bs;
40975696c6e3SKevin Wolf 
40985696c6e3SKevin Wolf         file_bs = bdrv_open_child_bs(filename, options, "file", bs,
409958944401SMax Reitz                                      &child_of_bds, BDRV_CHILD_IMAGE,
41007ead9469SKevin Wolf                                      true, true, &local_err);
41011fdd6933SKevin Wolf         if (local_err) {
41028bfea15dSKevin Wolf             goto fail;
4103f500a6d3SKevin Wolf         }
41045696c6e3SKevin Wolf         if (file_bs != NULL) {
4105dacaa162SKevin Wolf             /* Not requesting BLK_PERM_CONSISTENT_READ because we're only
4106dacaa162SKevin Wolf              * looking at the header to guess the image format. This works even
4107dacaa162SKevin Wolf              * in cases where a guest would not see a consistent state. */
4108b49f4755SStefan Hajnoczi             AioContext *ctx = bdrv_get_aio_context(file_bs);
4109f665f01fSKevin Wolf             file = blk_new(ctx, 0, BLK_PERM_ALL);
4110d7086422SKevin Wolf             blk_insert_bs(file, file_bs, &local_err);
41115696c6e3SKevin Wolf             bdrv_unref(file_bs);
4112f665f01fSKevin Wolf 
4113d7086422SKevin Wolf             if (local_err) {
4114d7086422SKevin Wolf                 goto fail;
4115d7086422SKevin Wolf             }
41165696c6e3SKevin Wolf 
411746f5ac20SEric Blake             qdict_put_str(options, "file", bdrv_get_node_name(file_bs));
41184e4bf5c4SKevin Wolf         }
4119f4788adcSKevin Wolf     }
4120f500a6d3SKevin Wolf 
412176c591b0SKevin Wolf     /* Image format probing */
412238f3ef57SKevin Wolf     bs->probed = !drv;
412376c591b0SKevin Wolf     if (!drv && file) {
4124cf2ab8fcSKevin Wolf         ret = find_image_format(file, filename, &drv, &local_err);
412517b005f1SKevin Wolf         if (ret < 0) {
412617b005f1SKevin Wolf             goto fail;
412717b005f1SKevin Wolf         }
412862392ebbSKevin Wolf         /*
412962392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
413062392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
413162392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
413262392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
413362392ebbSKevin Wolf          *
413462392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
413562392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
413662392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
413762392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
413862392ebbSKevin Wolf          */
413946f5ac20SEric Blake         qdict_put_str(bs->options, "driver", drv->format_name);
414046f5ac20SEric Blake         qdict_put_str(options, "driver", drv->format_name);
414176c591b0SKevin Wolf     } else if (!drv) {
41422a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
41438bfea15dSKevin Wolf         goto fail;
41442a05cbe4SMax Reitz     }
4145f500a6d3SKevin Wolf 
414653a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
414741770f6eSPaolo Bonzini     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->protocol_name);
414853a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
414953a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
415053a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
415153a29513SMax Reitz 
4152b6ce07aaSKevin Wolf     /* Open the image */
415382dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
4154b6ce07aaSKevin Wolf     if (ret < 0) {
41558bfea15dSKevin Wolf         goto fail;
41566987307cSChristoph Hellwig     }
41576987307cSChristoph Hellwig 
41584e4bf5c4SKevin Wolf     if (file) {
41595696c6e3SKevin Wolf         blk_unref(file);
4160f500a6d3SKevin Wolf         file = NULL;
4161f500a6d3SKevin Wolf     }
4162f500a6d3SKevin Wolf 
4163b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
41649156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
4165d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
4166b6ce07aaSKevin Wolf         if (ret < 0) {
4167b6ad491aSKevin Wolf             goto close_and_fail;
4168b6ce07aaSKevin Wolf         }
4169b6ce07aaSKevin Wolf     }
4170b6ce07aaSKevin Wolf 
417150196d7aSAlberto Garcia     /* Remove all children options and references
417250196d7aSAlberto Garcia      * from bs->options and bs->explicit_options */
41732f624b80SAlberto Garcia     QLIST_FOREACH(child, &bs->children, next) {
41742f624b80SAlberto Garcia         char *child_key_dot;
41752f624b80SAlberto Garcia         child_key_dot = g_strdup_printf("%s.", child->name);
41762f624b80SAlberto Garcia         qdict_extract_subqdict(bs->explicit_options, NULL, child_key_dot);
41772f624b80SAlberto Garcia         qdict_extract_subqdict(bs->options, NULL, child_key_dot);
417850196d7aSAlberto Garcia         qdict_del(bs->explicit_options, child->name);
417950196d7aSAlberto Garcia         qdict_del(bs->options, child->name);
41802f624b80SAlberto Garcia         g_free(child_key_dot);
41812f624b80SAlberto Garcia     }
41822f624b80SAlberto Garcia 
4183b6ad491aSKevin Wolf     /* Check if any unknown options were used */
41847ad2757fSPaolo Bonzini     if (qdict_size(options) != 0) {
4185b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
41865acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
41875acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
41885acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
41895acd9d81SMax Reitz         } else {
4190d0e46a55SMax Reitz             error_setg(errp,
4191d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
4192d0e46a55SMax Reitz                        drv->format_name, entry->key);
41935acd9d81SMax Reitz         }
4194b6ad491aSKevin Wolf 
4195b6ad491aSKevin Wolf         goto close_and_fail;
4196b6ad491aSKevin Wolf     }
4197b6ad491aSKevin Wolf 
41985c8cab48SKevin Wolf     bdrv_parent_cb_change_media(bs, true);
4199b6ce07aaSKevin Wolf 
4200cb3e7f08SMarc-André Lureau     qobject_unref(options);
42018961be33SAlberto Garcia     options = NULL;
4202dd62f1caSKevin Wolf 
4203dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
4204dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
4205dd62f1caSKevin Wolf     if (snapshot_flags) {
420666836189SMax Reitz         BlockDriverState *snapshot_bs;
420766836189SMax Reitz         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
420866836189SMax Reitz                                                 snapshot_options, &local_err);
420973176beeSKevin Wolf         snapshot_options = NULL;
4210dd62f1caSKevin Wolf         if (local_err) {
4211dd62f1caSKevin Wolf             goto close_and_fail;
4212dd62f1caSKevin Wolf         }
421366836189SMax Reitz         /* We are not going to return bs but the overlay on top of it
421466836189SMax Reitz          * (snapshot_bs); thus, we have to drop the strong reference to bs
42155b363937SMax Reitz          * (which we obtained by calling bdrv_new()). bs will not be deleted,
42165b363937SMax Reitz          * though, because the overlay still has a reference to it. */
421766836189SMax Reitz         bdrv_unref(bs);
421866836189SMax Reitz         bs = snapshot_bs;
421966836189SMax Reitz     }
422066836189SMax Reitz 
42215b363937SMax Reitz     return bs;
4222b6ce07aaSKevin Wolf 
42238bfea15dSKevin Wolf fail:
42245696c6e3SKevin Wolf     blk_unref(file);
4225cb3e7f08SMarc-André Lureau     qobject_unref(snapshot_options);
4226cb3e7f08SMarc-André Lureau     qobject_unref(bs->explicit_options);
4227cb3e7f08SMarc-André Lureau     qobject_unref(bs->options);
4228cb3e7f08SMarc-André Lureau     qobject_unref(options);
4229de9c0cecSKevin Wolf     bs->options = NULL;
4230998cbd6aSManos Pitsidianakis     bs->explicit_options = NULL;
4231f67503e5SMax Reitz     bdrv_unref(bs);
423234b5d2c6SMax Reitz     error_propagate(errp, local_err);
42335b363937SMax Reitz     return NULL;
4234de9c0cecSKevin Wolf 
4235b6ad491aSKevin Wolf close_and_fail:
4236f67503e5SMax Reitz     bdrv_unref(bs);
4237cb3e7f08SMarc-André Lureau     qobject_unref(snapshot_options);
4238cb3e7f08SMarc-André Lureau     qobject_unref(options);
423934b5d2c6SMax Reitz     error_propagate(errp, local_err);
42405b363937SMax Reitz     return NULL;
4241b6ce07aaSKevin Wolf }
4242b6ce07aaSKevin Wolf 
42435b363937SMax Reitz BlockDriverState *bdrv_open(const char *filename, const char *reference,
42445b363937SMax Reitz                             QDict *options, int flags, Error **errp)
4245f3930ed0SKevin Wolf {
4246f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4247f791bf7fSEmanuele Giuseppe Esposito 
42485b363937SMax Reitz     return bdrv_open_inherit(filename, reference, options, flags, NULL,
42497ead9469SKevin Wolf                              NULL, 0, true, errp);
4250f3930ed0SKevin Wolf }
4251f3930ed0SKevin Wolf 
4252faf116b4SAlberto Garcia /* Return true if the NULL-terminated @list contains @str */
4253faf116b4SAlberto Garcia static bool is_str_in_list(const char *str, const char *const *list)
4254faf116b4SAlberto Garcia {
4255faf116b4SAlberto Garcia     if (str && list) {
4256faf116b4SAlberto Garcia         int i;
4257faf116b4SAlberto Garcia         for (i = 0; list[i] != NULL; i++) {
4258faf116b4SAlberto Garcia             if (!strcmp(str, list[i])) {
4259faf116b4SAlberto Garcia                 return true;
4260faf116b4SAlberto Garcia             }
4261faf116b4SAlberto Garcia         }
4262faf116b4SAlberto Garcia     }
4263faf116b4SAlberto Garcia     return false;
4264faf116b4SAlberto Garcia }
4265faf116b4SAlberto Garcia 
4266faf116b4SAlberto Garcia /*
4267faf116b4SAlberto Garcia  * Check that every option set in @bs->options is also set in
4268faf116b4SAlberto Garcia  * @new_opts.
4269faf116b4SAlberto Garcia  *
4270faf116b4SAlberto Garcia  * Options listed in the common_options list and in
4271faf116b4SAlberto Garcia  * @bs->drv->mutable_opts are skipped.
4272faf116b4SAlberto Garcia  *
4273faf116b4SAlberto Garcia  * Return 0 on success, otherwise return -EINVAL and set @errp.
4274faf116b4SAlberto Garcia  */
4275faf116b4SAlberto Garcia static int bdrv_reset_options_allowed(BlockDriverState *bs,
4276faf116b4SAlberto Garcia                                       const QDict *new_opts, Error **errp)
4277faf116b4SAlberto Garcia {
4278faf116b4SAlberto Garcia     const QDictEntry *e;
4279faf116b4SAlberto Garcia     /* These options are common to all block drivers and are handled
4280faf116b4SAlberto Garcia      * in bdrv_reopen_prepare() so they can be left out of @new_opts */
4281faf116b4SAlberto Garcia     const char *const common_options[] = {
4282faf116b4SAlberto Garcia         "node-name", "discard", "cache.direct", "cache.no-flush",
4283faf116b4SAlberto Garcia         "read-only", "auto-read-only", "detect-zeroes", NULL
4284faf116b4SAlberto Garcia     };
4285faf116b4SAlberto Garcia 
4286faf116b4SAlberto Garcia     for (e = qdict_first(bs->options); e; e = qdict_next(bs->options, e)) {
4287faf116b4SAlberto Garcia         if (!qdict_haskey(new_opts, e->key) &&
4288faf116b4SAlberto Garcia             !is_str_in_list(e->key, common_options) &&
4289faf116b4SAlberto Garcia             !is_str_in_list(e->key, bs->drv->mutable_opts)) {
4290faf116b4SAlberto Garcia             error_setg(errp, "Option '%s' cannot be reset "
4291faf116b4SAlberto Garcia                        "to its default value", e->key);
4292faf116b4SAlberto Garcia             return -EINVAL;
4293faf116b4SAlberto Garcia         }
4294faf116b4SAlberto Garcia     }
4295faf116b4SAlberto Garcia 
4296faf116b4SAlberto Garcia     return 0;
4297faf116b4SAlberto Garcia }
4298faf116b4SAlberto Garcia 
4299e971aa12SJeff Cody /*
4300cb828c31SAlberto Garcia  * Returns true if @child can be reached recursively from @bs
4301cb828c31SAlberto Garcia  */
4302ce433d29SKevin Wolf static bool GRAPH_RDLOCK
4303ce433d29SKevin Wolf bdrv_recurse_has_child(BlockDriverState *bs, BlockDriverState *child)
4304cb828c31SAlberto Garcia {
4305cb828c31SAlberto Garcia     BdrvChild *c;
4306cb828c31SAlberto Garcia 
4307cb828c31SAlberto Garcia     if (bs == child) {
4308cb828c31SAlberto Garcia         return true;
4309cb828c31SAlberto Garcia     }
4310cb828c31SAlberto Garcia 
4311cb828c31SAlberto Garcia     QLIST_FOREACH(c, &bs->children, next) {
4312cb828c31SAlberto Garcia         if (bdrv_recurse_has_child(c->bs, child)) {
4313cb828c31SAlberto Garcia             return true;
4314cb828c31SAlberto Garcia         }
4315cb828c31SAlberto Garcia     }
4316cb828c31SAlberto Garcia 
4317cb828c31SAlberto Garcia     return false;
4318cb828c31SAlberto Garcia }
4319cb828c31SAlberto Garcia 
4320cb828c31SAlberto Garcia /*
4321e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
4322e971aa12SJeff Cody  * reopen of multiple devices.
4323e971aa12SJeff Cody  *
4324859443b0SVladimir Sementsov-Ogievskiy  * bs_queue can either be an existing BlockReopenQueue that has had QTAILQ_INIT
4325e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
4326e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
4327e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
4328e971aa12SJeff Cody  * atomic 'set'.
4329e971aa12SJeff Cody  *
4330e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
4331e971aa12SJeff Cody  *
43324d2cb092SKevin Wolf  * options contains the changed options for the associated bs
43334d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
43344d2cb092SKevin Wolf  *
4335e971aa12SJeff Cody  * flags contains the open flags for the associated bs
4336e971aa12SJeff Cody  *
4337e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
4338e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
4339e971aa12SJeff Cody  *
4340d22933acSKevin Wolf  * bs is drained here and undrained by bdrv_reopen_queue_free().
43412e117866SKevin Wolf  *
43422e117866SKevin Wolf  * To be called with bs->aio_context locked.
4343e971aa12SJeff Cody  */
4344ce433d29SKevin Wolf static BlockReopenQueue * GRAPH_RDLOCK
4345ce433d29SKevin Wolf bdrv_reopen_queue_child(BlockReopenQueue *bs_queue, BlockDriverState *bs,
4346ce433d29SKevin Wolf                         QDict *options, const BdrvChildClass *klass,
4347ce433d29SKevin Wolf                         BdrvChildRole role, bool parent_is_format,
4348ce433d29SKevin Wolf                         QDict *parent_options, int parent_flags,
4349077e8e20SAlberto Garcia                         bool keep_old_opts)
4350e971aa12SJeff Cody {
4351e971aa12SJeff Cody     assert(bs != NULL);
4352e971aa12SJeff Cody 
4353e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
435467251a31SKevin Wolf     BdrvChild *child;
43559aa09dddSAlberto Garcia     QDict *old_options, *explicit_options, *options_copy;
43569aa09dddSAlberto Garcia     int flags;
43579aa09dddSAlberto Garcia     QemuOpts *opts;
435867251a31SKevin Wolf 
4359f0c28327SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
43601a63a907SKevin Wolf 
4361ce433d29SKevin Wolf     /*
4362ce433d29SKevin Wolf      * Strictly speaking, draining is illegal under GRAPH_RDLOCK. We know that
4363ce433d29SKevin Wolf      * we've been called with bdrv_graph_rdlock_main_loop(), though, so it's ok
4364ce433d29SKevin Wolf      * in practice.
4365ce433d29SKevin Wolf      */
4366d22933acSKevin Wolf     bdrv_drained_begin(bs);
4367d22933acSKevin Wolf 
4368e971aa12SJeff Cody     if (bs_queue == NULL) {
4369e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
4370859443b0SVladimir Sementsov-Ogievskiy         QTAILQ_INIT(bs_queue);
4371e971aa12SJeff Cody     }
4372e971aa12SJeff Cody 
43734d2cb092SKevin Wolf     if (!options) {
43744d2cb092SKevin Wolf         options = qdict_new();
43754d2cb092SKevin Wolf     }
43764d2cb092SKevin Wolf 
43775b7ba05fSAlberto Garcia     /* Check if this BlockDriverState is already in the queue */
4378859443b0SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
43795b7ba05fSAlberto Garcia         if (bs == bs_entry->state.bs) {
43805b7ba05fSAlberto Garcia             break;
43815b7ba05fSAlberto Garcia         }
43825b7ba05fSAlberto Garcia     }
43835b7ba05fSAlberto Garcia 
438428518102SKevin Wolf     /*
438528518102SKevin Wolf      * Precedence of options:
438628518102SKevin Wolf      * 1. Explicitly passed in options (highest)
43879aa09dddSAlberto Garcia      * 2. Retained from explicitly set options of bs
43889aa09dddSAlberto Garcia      * 3. Inherited from parent node
43899aa09dddSAlberto Garcia      * 4. Retained from effective options of bs
439028518102SKevin Wolf      */
439128518102SKevin Wolf 
4392145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
4393077e8e20SAlberto Garcia     if (bs_entry || keep_old_opts) {
4394077e8e20SAlberto Garcia         old_options = qdict_clone_shallow(bs_entry ?
4395077e8e20SAlberto Garcia                                           bs_entry->state.explicit_options :
4396077e8e20SAlberto Garcia                                           bs->explicit_options);
4397145f598eSKevin Wolf         bdrv_join_options(bs, options, old_options);
4398cb3e7f08SMarc-André Lureau         qobject_unref(old_options);
4399077e8e20SAlberto Garcia     }
4400145f598eSKevin Wolf 
4401145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
4402145f598eSKevin Wolf 
440328518102SKevin Wolf     /* Inherit from parent node */
440428518102SKevin Wolf     if (parent_options) {
44059aa09dddSAlberto Garcia         flags = 0;
44063cdc69d3SMax Reitz         klass->inherit_options(role, parent_is_format, &flags, options,
4407272c02eaSMax Reitz                                parent_flags, parent_options);
44089aa09dddSAlberto Garcia     } else {
44099aa09dddSAlberto Garcia         flags = bdrv_get_flags(bs);
441028518102SKevin Wolf     }
441128518102SKevin Wolf 
4412077e8e20SAlberto Garcia     if (keep_old_opts) {
441328518102SKevin Wolf         /* Old values are used for options that aren't set yet */
44144d2cb092SKevin Wolf         old_options = qdict_clone_shallow(bs->options);
4415cddff5baSKevin Wolf         bdrv_join_options(bs, options, old_options);
4416cb3e7f08SMarc-André Lureau         qobject_unref(old_options);
4417077e8e20SAlberto Garcia     }
44184d2cb092SKevin Wolf 
44199aa09dddSAlberto Garcia     /* We have the final set of options so let's update the flags */
44209aa09dddSAlberto Garcia     options_copy = qdict_clone_shallow(options);
44219aa09dddSAlberto Garcia     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
44229aa09dddSAlberto Garcia     qemu_opts_absorb_qdict(opts, options_copy, NULL);
44239aa09dddSAlberto Garcia     update_flags_from_options(&flags, opts);
44249aa09dddSAlberto Garcia     qemu_opts_del(opts);
44259aa09dddSAlberto Garcia     qobject_unref(options_copy);
44269aa09dddSAlberto Garcia 
4427fd452021SKevin Wolf     /* bdrv_open_inherit() sets and clears some additional flags internally */
4428f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
4429fd452021SKevin Wolf     if (flags & BDRV_O_RDWR) {
4430fd452021SKevin Wolf         flags |= BDRV_O_ALLOW_RDWR;
4431fd452021SKevin Wolf     }
4432f1f25a2eSKevin Wolf 
44331857c97bSKevin Wolf     if (!bs_entry) {
44341857c97bSKevin Wolf         bs_entry = g_new0(BlockReopenQueueEntry, 1);
4435859443b0SVladimir Sementsov-Ogievskiy         QTAILQ_INSERT_TAIL(bs_queue, bs_entry, entry);
44361857c97bSKevin Wolf     } else {
4437cb3e7f08SMarc-André Lureau         qobject_unref(bs_entry->state.options);
4438cb3e7f08SMarc-André Lureau         qobject_unref(bs_entry->state.explicit_options);
44391857c97bSKevin Wolf     }
44401857c97bSKevin Wolf 
44411857c97bSKevin Wolf     bs_entry->state.bs = bs;
44421857c97bSKevin Wolf     bs_entry->state.options = options;
44431857c97bSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
44441857c97bSKevin Wolf     bs_entry->state.flags = flags;
44451857c97bSKevin Wolf 
44468546632eSAlberto Garcia     /*
44478546632eSAlberto Garcia      * If keep_old_opts is false then it means that unspecified
44488546632eSAlberto Garcia      * options must be reset to their original value. We don't allow
44498546632eSAlberto Garcia      * resetting 'backing' but we need to know if the option is
44508546632eSAlberto Garcia      * missing in order to decide if we have to return an error.
44518546632eSAlberto Garcia      */
44528546632eSAlberto Garcia     if (!keep_old_opts) {
44538546632eSAlberto Garcia         bs_entry->state.backing_missing =
44548546632eSAlberto Garcia             !qdict_haskey(options, "backing") &&
44558546632eSAlberto Garcia             !qdict_haskey(options, "backing.driver");
44568546632eSAlberto Garcia     }
44578546632eSAlberto Garcia 
445867251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
44598546632eSAlberto Garcia         QDict *new_child_options = NULL;
44608546632eSAlberto Garcia         bool child_keep_old = keep_old_opts;
446167251a31SKevin Wolf 
44624c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
44634c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
44644c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
446567251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
446667251a31SKevin Wolf             continue;
446767251a31SKevin Wolf         }
446867251a31SKevin Wolf 
44698546632eSAlberto Garcia         /* Check if the options contain a child reference */
44708546632eSAlberto Garcia         if (qdict_haskey(options, child->name)) {
44718546632eSAlberto Garcia             const char *childref = qdict_get_try_str(options, child->name);
44728546632eSAlberto Garcia             /*
44738546632eSAlberto Garcia              * The current child must not be reopened if the child
44748546632eSAlberto Garcia              * reference is null or points to a different node.
44758546632eSAlberto Garcia              */
44768546632eSAlberto Garcia             if (g_strcmp0(childref, child->bs->node_name)) {
44778546632eSAlberto Garcia                 continue;
44788546632eSAlberto Garcia             }
44798546632eSAlberto Garcia             /*
44808546632eSAlberto Garcia              * If the child reference points to the current child then
44818546632eSAlberto Garcia              * reopen it with its existing set of options (note that
44828546632eSAlberto Garcia              * it can still inherit new options from the parent).
44838546632eSAlberto Garcia              */
44848546632eSAlberto Garcia             child_keep_old = true;
44858546632eSAlberto Garcia         } else {
44868546632eSAlberto Garcia             /* Extract child options ("child-name.*") */
44878546632eSAlberto Garcia             char *child_key_dot = g_strdup_printf("%s.", child->name);
44882f624b80SAlberto Garcia             qdict_extract_subqdict(explicit_options, NULL, child_key_dot);
44894c9dfe5dSKevin Wolf             qdict_extract_subqdict(options, &new_child_options, child_key_dot);
44904c9dfe5dSKevin Wolf             g_free(child_key_dot);
44918546632eSAlberto Garcia         }
44924c9dfe5dSKevin Wolf 
44939aa09dddSAlberto Garcia         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options,
44943cdc69d3SMax Reitz                                 child->klass, child->role, bs->drv->is_format,
44953cdc69d3SMax Reitz                                 options, flags, child_keep_old);
4496e971aa12SJeff Cody     }
4497e971aa12SJeff Cody 
4498e971aa12SJeff Cody     return bs_queue;
4499e971aa12SJeff Cody }
4500e971aa12SJeff Cody 
45012e117866SKevin Wolf /* To be called with bs->aio_context locked */
450228518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
450328518102SKevin Wolf                                     BlockDriverState *bs,
4504077e8e20SAlberto Garcia                                     QDict *options, bool keep_old_opts)
450528518102SKevin Wolf {
4506f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4507ce433d29SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
4508f791bf7fSEmanuele Giuseppe Esposito 
45093cdc69d3SMax Reitz     return bdrv_reopen_queue_child(bs_queue, bs, options, NULL, 0, false,
45103cdc69d3SMax Reitz                                    NULL, 0, keep_old_opts);
451128518102SKevin Wolf }
451228518102SKevin Wolf 
4513ab5b5228SAlberto Garcia void bdrv_reopen_queue_free(BlockReopenQueue *bs_queue)
4514ab5b5228SAlberto Garcia {
4515f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4516ab5b5228SAlberto Garcia     if (bs_queue) {
4517ab5b5228SAlberto Garcia         BlockReopenQueueEntry *bs_entry, *next;
4518ab5b5228SAlberto Garcia         QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
4519d22933acSKevin Wolf             bdrv_drained_end(bs_entry->state.bs);
4520ab5b5228SAlberto Garcia             qobject_unref(bs_entry->state.explicit_options);
4521ab5b5228SAlberto Garcia             qobject_unref(bs_entry->state.options);
4522ab5b5228SAlberto Garcia             g_free(bs_entry);
4523ab5b5228SAlberto Garcia         }
4524ab5b5228SAlberto Garcia         g_free(bs_queue);
4525ab5b5228SAlberto Garcia     }
4526ab5b5228SAlberto Garcia }
4527ab5b5228SAlberto Garcia 
4528e971aa12SJeff Cody /*
4529e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
4530e971aa12SJeff Cody  *
4531e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
4532e971aa12SJeff Cody  * via bdrv_reopen_queue().
4533e971aa12SJeff Cody  *
4534e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
4535e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
453650d6a8a3SStefan Weil  * device will cause all device changes to be abandoned, and intermediate
4537e971aa12SJeff Cody  * data cleaned up.
4538e971aa12SJeff Cody  *
4539e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
4540e971aa12SJeff Cody  * to all devices.
4541e971aa12SJeff Cody  *
45421a63a907SKevin Wolf  * All affected nodes must be drained between bdrv_reopen_queue() and
45431a63a907SKevin Wolf  * bdrv_reopen_multiple().
45446cf42ca2SKevin Wolf  *
45456cf42ca2SKevin Wolf  * To be called from the main thread, with all other AioContexts unlocked.
4546e971aa12SJeff Cody  */
45475019aeceSAlberto Garcia int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
4548e971aa12SJeff Cody {
4549e971aa12SJeff Cody     int ret = -1;
4550e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
455172373e40SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
455272373e40SVladimir Sementsov-Ogievskiy     g_autoptr(GSList) refresh_list = NULL;
4553e971aa12SJeff Cody 
45546cf42ca2SKevin Wolf     assert(qemu_get_current_aio_context() == qemu_get_aio_context());
4555e971aa12SJeff Cody     assert(bs_queue != NULL);
4556da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4557e971aa12SJeff Cody 
4558859443b0SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
4559a2aabf88SVladimir Sementsov-Ogievskiy         ret = bdrv_flush(bs_entry->state.bs);
4560a2aabf88SVladimir Sementsov-Ogievskiy         if (ret < 0) {
4561a2aabf88SVladimir Sementsov-Ogievskiy             error_setg_errno(errp, -ret, "Error flushing drive");
4562e3fc91aaSKevin Wolf             goto abort;
4563a2aabf88SVladimir Sementsov-Ogievskiy         }
4564a2aabf88SVladimir Sementsov-Ogievskiy     }
4565a2aabf88SVladimir Sementsov-Ogievskiy 
4566a2aabf88SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
45671a63a907SKevin Wolf         assert(bs_entry->state.bs->quiesce_counter > 0);
456872373e40SVladimir Sementsov-Ogievskiy         ret = bdrv_reopen_prepare(&bs_entry->state, bs_queue, tran, errp);
456972373e40SVladimir Sementsov-Ogievskiy         if (ret < 0) {
457072373e40SVladimir Sementsov-Ogievskiy             goto abort;
4571e971aa12SJeff Cody         }
4572e971aa12SJeff Cody         bs_entry->prepared = true;
4573e971aa12SJeff Cody     }
4574e971aa12SJeff Cody 
4575859443b0SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH(bs_entry, bs_queue, entry) {
457669b736e7SKevin Wolf         BDRVReopenState *state = &bs_entry->state;
457772373e40SVladimir Sementsov-Ogievskiy 
4578fb0ff4d1SVladimir Sementsov-Ogievskiy         refresh_list = g_slist_prepend(refresh_list, state->bs);
457972373e40SVladimir Sementsov-Ogievskiy         if (state->old_backing_bs) {
4580fb0ff4d1SVladimir Sementsov-Ogievskiy             refresh_list = g_slist_prepend(refresh_list, state->old_backing_bs);
458172373e40SVladimir Sementsov-Ogievskiy         }
4582ecd30d2dSAlberto Garcia         if (state->old_file_bs) {
4583fb0ff4d1SVladimir Sementsov-Ogievskiy             refresh_list = g_slist_prepend(refresh_list, state->old_file_bs);
4584ecd30d2dSAlberto Garcia         }
458572373e40SVladimir Sementsov-Ogievskiy     }
458672373e40SVladimir Sementsov-Ogievskiy 
458772373e40SVladimir Sementsov-Ogievskiy     /*
458872373e40SVladimir Sementsov-Ogievskiy      * Note that file-posix driver rely on permission update done during reopen
458972373e40SVladimir Sementsov-Ogievskiy      * (even if no permission changed), because it wants "new" permissions for
459072373e40SVladimir Sementsov-Ogievskiy      * reconfiguring the fd and that's why it does it in raw_check_perm(), not
459172373e40SVladimir Sementsov-Ogievskiy      * in raw_reopen_prepare() which is called with "old" permissions.
459272373e40SVladimir Sementsov-Ogievskiy      */
45933804e3cfSKevin Wolf     bdrv_graph_rdlock_main_loop();
459472373e40SVladimir Sementsov-Ogievskiy     ret = bdrv_list_refresh_perms(refresh_list, bs_queue, tran, errp);
45953804e3cfSKevin Wolf     bdrv_graph_rdunlock_main_loop();
45963804e3cfSKevin Wolf 
459769b736e7SKevin Wolf     if (ret < 0) {
459872373e40SVladimir Sementsov-Ogievskiy         goto abort;
459969b736e7SKevin Wolf     }
460069b736e7SKevin Wolf 
4601fcd6a4f4SVladimir Sementsov-Ogievskiy     /*
4602fcd6a4f4SVladimir Sementsov-Ogievskiy      * If we reach this point, we have success and just need to apply the
4603fcd6a4f4SVladimir Sementsov-Ogievskiy      * changes.
4604fcd6a4f4SVladimir Sementsov-Ogievskiy      *
4605fcd6a4f4SVladimir Sementsov-Ogievskiy      * Reverse order is used to comfort qcow2 driver: on commit it need to write
4606fcd6a4f4SVladimir Sementsov-Ogievskiy      * IN_USE flag to the image, to mark bitmaps in the image as invalid. But
4607fcd6a4f4SVladimir Sementsov-Ogievskiy      * children are usually goes after parents in reopen-queue, so go from last
4608fcd6a4f4SVladimir Sementsov-Ogievskiy      * to first element.
4609e971aa12SJeff Cody      */
4610fcd6a4f4SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
4611e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
4612e971aa12SJeff Cody     }
4613e971aa12SJeff Cody 
46146bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
461572373e40SVladimir Sementsov-Ogievskiy     tran_commit(tran);
46166bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
4617e971aa12SJeff Cody 
461817e1e2beSPeter Krempa     QTAILQ_FOREACH_REVERSE(bs_entry, bs_queue, entry) {
461917e1e2beSPeter Krempa         BlockDriverState *bs = bs_entry->state.bs;
462017e1e2beSPeter Krempa 
462172373e40SVladimir Sementsov-Ogievskiy         if (bs->drv->bdrv_reopen_commit_post) {
462217e1e2beSPeter Krempa             bs->drv->bdrv_reopen_commit_post(&bs_entry->state);
462317e1e2beSPeter Krempa         }
462417e1e2beSPeter Krempa     }
462572373e40SVladimir Sementsov-Ogievskiy 
462672373e40SVladimir Sementsov-Ogievskiy     ret = 0;
462772373e40SVladimir Sementsov-Ogievskiy     goto cleanup;
462872373e40SVladimir Sementsov-Ogievskiy 
462972373e40SVladimir Sementsov-Ogievskiy abort:
46306bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
463172373e40SVladimir Sementsov-Ogievskiy     tran_abort(tran);
46326bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
46337d4ca9d2SKevin Wolf 
4634859443b0SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
46351bab38e7SAlberto Garcia         if (bs_entry->prepared) {
4636e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
46371bab38e7SAlberto Garcia         }
46384c8350feSAlberto Garcia     }
463972373e40SVladimir Sementsov-Ogievskiy 
464072373e40SVladimir Sementsov-Ogievskiy cleanup:
4641ab5b5228SAlberto Garcia     bdrv_reopen_queue_free(bs_queue);
464240840e41SAlberto Garcia 
4643e971aa12SJeff Cody     return ret;
4644e971aa12SJeff Cody }
4645e971aa12SJeff Cody 
46466cf42ca2SKevin Wolf int bdrv_reopen(BlockDriverState *bs, QDict *opts, bool keep_old_opts,
46476cf42ca2SKevin Wolf                 Error **errp)
46486cf42ca2SKevin Wolf {
46496cf42ca2SKevin Wolf     BlockReopenQueue *queue;
46506cf42ca2SKevin Wolf 
4651f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4652f791bf7fSEmanuele Giuseppe Esposito 
46532e117866SKevin Wolf     queue = bdrv_reopen_queue(NULL, bs, opts, keep_old_opts);
46542e117866SKevin Wolf 
4655b49f4755SStefan Hajnoczi     return bdrv_reopen_multiple(queue, errp);
46566cf42ca2SKevin Wolf }
46576cf42ca2SKevin Wolf 
46586e1000a8SAlberto Garcia int bdrv_reopen_set_read_only(BlockDriverState *bs, bool read_only,
46596e1000a8SAlberto Garcia                               Error **errp)
46606e1000a8SAlberto Garcia {
46616e1000a8SAlberto Garcia     QDict *opts = qdict_new();
46626e1000a8SAlberto Garcia 
4663f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4664f791bf7fSEmanuele Giuseppe Esposito 
46656e1000a8SAlberto Garcia     qdict_put_bool(opts, BDRV_OPT_READ_ONLY, read_only);
46666e1000a8SAlberto Garcia 
46676cf42ca2SKevin Wolf     return bdrv_reopen(bs, opts, true, errp);
46686e1000a8SAlberto Garcia }
46696e1000a8SAlberto Garcia 
4670e971aa12SJeff Cody /*
4671cb828c31SAlberto Garcia  * Take a BDRVReopenState and check if the value of 'backing' in the
4672cb828c31SAlberto Garcia  * reopen_state->options QDict is valid or not.
4673cb828c31SAlberto Garcia  *
4674cb828c31SAlberto Garcia  * If 'backing' is missing from the QDict then return 0.
4675cb828c31SAlberto Garcia  *
4676cb828c31SAlberto Garcia  * If 'backing' contains the node name of the backing file of
4677cb828c31SAlberto Garcia  * reopen_state->bs then return 0.
4678cb828c31SAlberto Garcia  *
4679cb828c31SAlberto Garcia  * If 'backing' contains a different node name (or is null) then check
4680cb828c31SAlberto Garcia  * whether the current backing file can be replaced with the new one.
4681cb828c31SAlberto Garcia  * If that's the case then reopen_state->replace_backing_bs is set to
4682cb828c31SAlberto Garcia  * true and reopen_state->new_backing_bs contains a pointer to the new
4683cb828c31SAlberto Garcia  * backing BlockDriverState (or NULL).
4684cb828c31SAlberto Garcia  *
46855661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
46865661a00dSKevin Wolf  * while holding a writer lock for the graph.
46875661a00dSKevin Wolf  *
4688cb828c31SAlberto Garcia  * Return 0 on success, otherwise return < 0 and set @errp.
46894b408668SKevin Wolf  *
46904b408668SKevin Wolf  * @reopen_state->bs can move to a different AioContext in this function.
4691cb828c31SAlberto Garcia  */
4692ce433d29SKevin Wolf static int GRAPH_UNLOCKED
4693ce433d29SKevin Wolf bdrv_reopen_parse_file_or_backing(BDRVReopenState *reopen_state,
4694ecd30d2dSAlberto Garcia                                   bool is_backing, Transaction *tran,
4695cb828c31SAlberto Garcia                                   Error **errp)
4696cb828c31SAlberto Garcia {
4697cb828c31SAlberto Garcia     BlockDriverState *bs = reopen_state->bs;
4698ecd30d2dSAlberto Garcia     BlockDriverState *new_child_bs;
4699004915a9SKevin Wolf     BlockDriverState *old_child_bs;
4700004915a9SKevin Wolf 
4701ecd30d2dSAlberto Garcia     const char *child_name = is_backing ? "backing" : "file";
4702cb828c31SAlberto Garcia     QObject *value;
4703cb828c31SAlberto Garcia     const char *str;
4704ce433d29SKevin Wolf     bool has_child;
47054b408668SKevin Wolf     int ret;
4706cb828c31SAlberto Garcia 
4707bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4708bdb73476SEmanuele Giuseppe Esposito 
4709ecd30d2dSAlberto Garcia     value = qdict_get(reopen_state->options, child_name);
4710cb828c31SAlberto Garcia     if (value == NULL) {
4711cb828c31SAlberto Garcia         return 0;
4712cb828c31SAlberto Garcia     }
4713cb828c31SAlberto Garcia 
4714430da832SKevin Wolf     bdrv_graph_rdlock_main_loop();
4715430da832SKevin Wolf 
4716cb828c31SAlberto Garcia     switch (qobject_type(value)) {
4717cb828c31SAlberto Garcia     case QTYPE_QNULL:
4718ecd30d2dSAlberto Garcia         assert(is_backing); /* The 'file' option does not allow a null value */
4719ecd30d2dSAlberto Garcia         new_child_bs = NULL;
4720cb828c31SAlberto Garcia         break;
4721cb828c31SAlberto Garcia     case QTYPE_QSTRING:
4722410f44f5SMarkus Armbruster         str = qstring_get_str(qobject_to(QString, value));
4723ecd30d2dSAlberto Garcia         new_child_bs = bdrv_lookup_bs(NULL, str, errp);
4724ecd30d2dSAlberto Garcia         if (new_child_bs == NULL) {
4725430da832SKevin Wolf             ret = -EINVAL;
4726430da832SKevin Wolf             goto out_rdlock;
4727ce433d29SKevin Wolf         }
4728ce433d29SKevin Wolf 
4729ce433d29SKevin Wolf         has_child = bdrv_recurse_has_child(new_child_bs, bs);
4730ce433d29SKevin Wolf         if (has_child) {
4731ecd30d2dSAlberto Garcia             error_setg(errp, "Making '%s' a %s child of '%s' would create a "
4732ecd30d2dSAlberto Garcia                        "cycle", str, child_name, bs->node_name);
4733430da832SKevin Wolf             ret = -EINVAL;
4734430da832SKevin Wolf             goto out_rdlock;
4735cb828c31SAlberto Garcia         }
4736cb828c31SAlberto Garcia         break;
4737cb828c31SAlberto Garcia     default:
4738ecd30d2dSAlberto Garcia         /*
4739ecd30d2dSAlberto Garcia          * The options QDict has been flattened, so 'backing' and 'file'
4740ecd30d2dSAlberto Garcia          * do not allow any other data type here.
4741ecd30d2dSAlberto Garcia          */
4742cb828c31SAlberto Garcia         g_assert_not_reached();
4743cb828c31SAlberto Garcia     }
4744cb828c31SAlberto Garcia 
4745004915a9SKevin Wolf     old_child_bs = is_backing ? child_bs(bs->backing) : child_bs(bs->file);
4746ecd30d2dSAlberto Garcia     if (old_child_bs == new_child_bs) {
4747430da832SKevin Wolf         ret = 0;
4748430da832SKevin Wolf         goto out_rdlock;
4749cbfdb98cSVladimir Sementsov-Ogievskiy     }
4750cbfdb98cSVladimir Sementsov-Ogievskiy 
4751ecd30d2dSAlberto Garcia     if (old_child_bs) {
4752ecd30d2dSAlberto Garcia         if (bdrv_skip_implicit_filters(old_child_bs) == new_child_bs) {
4753430da832SKevin Wolf             ret = 0;
4754430da832SKevin Wolf             goto out_rdlock;
4755ecd30d2dSAlberto Garcia         }
4756ecd30d2dSAlberto Garcia 
4757ecd30d2dSAlberto Garcia         if (old_child_bs->implicit) {
4758ecd30d2dSAlberto Garcia             error_setg(errp, "Cannot replace implicit %s child of %s",
4759ecd30d2dSAlberto Garcia                        child_name, bs->node_name);
4760430da832SKevin Wolf             ret = -EPERM;
4761430da832SKevin Wolf             goto out_rdlock;
4762cbfdb98cSVladimir Sementsov-Ogievskiy         }
4763cbfdb98cSVladimir Sementsov-Ogievskiy     }
4764cbfdb98cSVladimir Sementsov-Ogievskiy 
4765ecd30d2dSAlberto Garcia     if (bs->drv->is_filter && !old_child_bs) {
4766cb828c31SAlberto Garcia         /*
476725f78d9eSVladimir Sementsov-Ogievskiy          * Filters always have a file or a backing child, so we are trying to
476825f78d9eSVladimir Sementsov-Ogievskiy          * change wrong child
47691d42f48cSMax Reitz          */
47701d42f48cSMax Reitz         error_setg(errp, "'%s' is a %s filter node that does not support a "
4771ecd30d2dSAlberto Garcia                    "%s child", bs->node_name, bs->drv->format_name, child_name);
4772430da832SKevin Wolf         ret = -EINVAL;
4773430da832SKevin Wolf         goto out_rdlock;
47741d42f48cSMax Reitz     }
47751d42f48cSMax Reitz 
4776ecd30d2dSAlberto Garcia     if (is_backing) {
4777ecd30d2dSAlberto Garcia         reopen_state->old_backing_bs = old_child_bs;
4778ecd30d2dSAlberto Garcia     } else {
4779ecd30d2dSAlberto Garcia         reopen_state->old_file_bs = old_child_bs;
4780ecd30d2dSAlberto Garcia     }
4781ecd30d2dSAlberto Garcia 
47827d4ca9d2SKevin Wolf     if (old_child_bs) {
47837d4ca9d2SKevin Wolf         bdrv_ref(old_child_bs);
47847d4ca9d2SKevin Wolf         bdrv_drained_begin(old_child_bs);
47857d4ca9d2SKevin Wolf     }
47867d4ca9d2SKevin Wolf 
4787430da832SKevin Wolf     bdrv_graph_rdunlock_main_loop();
47886bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
47897d4ca9d2SKevin Wolf 
47904b408668SKevin Wolf     ret = bdrv_set_file_or_backing_noperm(bs, new_child_bs, is_backing,
4791ecd30d2dSAlberto Garcia                                           tran, errp);
47924b408668SKevin Wolf 
47936bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
47947d4ca9d2SKevin Wolf 
47957d4ca9d2SKevin Wolf     if (old_child_bs) {
47967d4ca9d2SKevin Wolf         bdrv_drained_end(old_child_bs);
47977d4ca9d2SKevin Wolf         bdrv_unref(old_child_bs);
47987d4ca9d2SKevin Wolf     }
47997d4ca9d2SKevin Wolf 
48004b408668SKevin Wolf     return ret;
4801430da832SKevin Wolf 
4802430da832SKevin Wolf out_rdlock:
4803430da832SKevin Wolf     bdrv_graph_rdunlock_main_loop();
4804430da832SKevin Wolf     return ret;
4805cb828c31SAlberto Garcia }
4806cb828c31SAlberto Garcia 
4807cb828c31SAlberto Garcia /*
4808e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
4809e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
4810e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
4811e971aa12SJeff Cody  *
4812e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
4813e971aa12SJeff Cody  * flags are the new open flags
4814e971aa12SJeff Cody  * queue is the reopen queue
4815e971aa12SJeff Cody  *
4816e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
4817e971aa12SJeff Cody  * as well.
4818e971aa12SJeff Cody  *
4819e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
4820e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
4821e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
4822e971aa12SJeff Cody  *
48235661a00dSKevin Wolf  * After calling this function, the transaction @change_child_tran may only be
48245661a00dSKevin Wolf  * completed while holding a writer lock for the graph.
4825e971aa12SJeff Cody  */
4826ce433d29SKevin Wolf static int GRAPH_UNLOCKED
4827ce433d29SKevin Wolf bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
4828ecd30d2dSAlberto Garcia                     Transaction *change_child_tran, Error **errp)
4829e971aa12SJeff Cody {
4830e971aa12SJeff Cody     int ret = -1;
4831e6d79c41SAlberto Garcia     int old_flags;
4832e971aa12SJeff Cody     Error *local_err = NULL;
4833e971aa12SJeff Cody     BlockDriver *drv;
4834ccf9dc07SKevin Wolf     QemuOpts *opts;
48354c8350feSAlberto Garcia     QDict *orig_reopen_opts;
4836593b3071SAlberto Garcia     char *discard = NULL;
48373d8ce171SJeff Cody     bool read_only;
48389ad08c44SMax Reitz     bool drv_prepared = false;
4839e971aa12SJeff Cody 
4840e971aa12SJeff Cody     assert(reopen_state != NULL);
4841e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
4842da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
4843e971aa12SJeff Cody     drv = reopen_state->bs->drv;
4844e971aa12SJeff Cody 
48454c8350feSAlberto Garcia     /* This function and each driver's bdrv_reopen_prepare() remove
48464c8350feSAlberto Garcia      * entries from reopen_state->options as they are processed, so
48474c8350feSAlberto Garcia      * we need to make a copy of the original QDict. */
48484c8350feSAlberto Garcia     orig_reopen_opts = qdict_clone_shallow(reopen_state->options);
48494c8350feSAlberto Garcia 
4850ccf9dc07SKevin Wolf     /* Process generic block layer options */
4851ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
4852af175e85SMarkus Armbruster     if (!qemu_opts_absorb_qdict(opts, reopen_state->options, errp)) {
4853ccf9dc07SKevin Wolf         ret = -EINVAL;
4854ccf9dc07SKevin Wolf         goto error;
4855ccf9dc07SKevin Wolf     }
4856ccf9dc07SKevin Wolf 
4857e6d79c41SAlberto Garcia     /* This was already called in bdrv_reopen_queue_child() so the flags
4858e6d79c41SAlberto Garcia      * are up-to-date. This time we simply want to remove the options from
4859e6d79c41SAlberto Garcia      * QemuOpts in order to indicate that they have been processed. */
4860e6d79c41SAlberto Garcia     old_flags = reopen_state->flags;
486191a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
4862e6d79c41SAlberto Garcia     assert(old_flags == reopen_state->flags);
486391a097e7SKevin Wolf 
4864415bbca8SAlberto Garcia     discard = qemu_opt_get_del(opts, BDRV_OPT_DISCARD);
4865593b3071SAlberto Garcia     if (discard != NULL) {
4866593b3071SAlberto Garcia         if (bdrv_parse_discard_flags(discard, &reopen_state->flags) != 0) {
4867593b3071SAlberto Garcia             error_setg(errp, "Invalid discard option");
4868593b3071SAlberto Garcia             ret = -EINVAL;
4869593b3071SAlberto Garcia             goto error;
4870593b3071SAlberto Garcia         }
4871593b3071SAlberto Garcia     }
4872593b3071SAlberto Garcia 
4873543770bdSAlberto Garcia     reopen_state->detect_zeroes =
4874543770bdSAlberto Garcia         bdrv_parse_detect_zeroes(opts, reopen_state->flags, &local_err);
4875543770bdSAlberto Garcia     if (local_err) {
4876543770bdSAlberto Garcia         error_propagate(errp, local_err);
4877543770bdSAlberto Garcia         ret = -EINVAL;
4878543770bdSAlberto Garcia         goto error;
4879543770bdSAlberto Garcia     }
4880543770bdSAlberto Garcia 
488157f9db9aSAlberto Garcia     /* All other options (including node-name and driver) must be unchanged.
488257f9db9aSAlberto Garcia      * Put them back into the QDict, so that they are checked at the end
488357f9db9aSAlberto Garcia      * of this function. */
488457f9db9aSAlberto Garcia     qemu_opts_to_qdict(opts, reopen_state->options);
4885ccf9dc07SKevin Wolf 
48863d8ce171SJeff Cody     /* If we are to stay read-only, do not allow permission change
48873d8ce171SJeff Cody      * to r/w. Attempting to set to r/w may fail if either BDRV_O_ALLOW_RDWR is
48883d8ce171SJeff Cody      * not set, or if the BDS still has copy_on_read enabled */
48893d8ce171SJeff Cody     read_only = !(reopen_state->flags & BDRV_O_RDWR);
48904026f1c4SKevin Wolf 
48914026f1c4SKevin Wolf     bdrv_graph_rdlock_main_loop();
489254a32bfeSKevin Wolf     ret = bdrv_can_set_read_only(reopen_state->bs, read_only, true, &local_err);
48934026f1c4SKevin Wolf     bdrv_graph_rdunlock_main_loop();
48943d8ce171SJeff Cody     if (local_err) {
48953d8ce171SJeff Cody         error_propagate(errp, local_err);
4896e971aa12SJeff Cody         goto error;
4897e971aa12SJeff Cody     }
4898e971aa12SJeff Cody 
4899e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
4900faf116b4SAlberto Garcia         /*
4901faf116b4SAlberto Garcia          * If a driver-specific option is missing, it means that we
4902faf116b4SAlberto Garcia          * should reset it to its default value.
4903faf116b4SAlberto Garcia          * But not all options allow that, so we need to check it first.
4904faf116b4SAlberto Garcia          */
4905faf116b4SAlberto Garcia         ret = bdrv_reset_options_allowed(reopen_state->bs,
4906faf116b4SAlberto Garcia                                          reopen_state->options, errp);
4907faf116b4SAlberto Garcia         if (ret) {
4908faf116b4SAlberto Garcia             goto error;
4909faf116b4SAlberto Garcia         }
4910faf116b4SAlberto Garcia 
4911e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
4912e971aa12SJeff Cody         if (ret) {
4913e971aa12SJeff Cody             if (local_err != NULL) {
4914e971aa12SJeff Cody                 error_propagate(errp, local_err);
4915e971aa12SJeff Cody             } else {
4916b7cfc7d5SKevin Wolf                 bdrv_graph_rdlock_main_loop();
4917f30c66baSMax Reitz                 bdrv_refresh_filename(reopen_state->bs);
4918b7cfc7d5SKevin Wolf                 bdrv_graph_rdunlock_main_loop();
4919d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
4920e971aa12SJeff Cody                            reopen_state->bs->filename);
4921e971aa12SJeff Cody             }
4922e971aa12SJeff Cody             goto error;
4923e971aa12SJeff Cody         }
4924e971aa12SJeff Cody     } else {
4925e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
4926e971aa12SJeff Cody          * handler for each supported drv. */
49274026f1c4SKevin Wolf         bdrv_graph_rdlock_main_loop();
492881e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
492981e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
493081e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
49314026f1c4SKevin Wolf         bdrv_graph_rdunlock_main_loop();
4932e971aa12SJeff Cody         ret = -1;
4933e971aa12SJeff Cody         goto error;
4934e971aa12SJeff Cody     }
4935e971aa12SJeff Cody 
49369ad08c44SMax Reitz     drv_prepared = true;
49379ad08c44SMax Reitz 
4938bacd9b87SAlberto Garcia     /*
4939bacd9b87SAlberto Garcia      * We must provide the 'backing' option if the BDS has a backing
4940bacd9b87SAlberto Garcia      * file or if the image file has a backing file name as part of
4941bacd9b87SAlberto Garcia      * its metadata. Otherwise the 'backing' option can be omitted.
4942bacd9b87SAlberto Garcia      */
4943004915a9SKevin Wolf     bdrv_graph_rdlock_main_loop();
4944bacd9b87SAlberto Garcia     if (drv->supports_backing && reopen_state->backing_missing &&
49451d42f48cSMax Reitz         (reopen_state->bs->backing || reopen_state->bs->backing_file[0])) {
49468546632eSAlberto Garcia         error_setg(errp, "backing is missing for '%s'",
49478546632eSAlberto Garcia                    reopen_state->bs->node_name);
4948004915a9SKevin Wolf         bdrv_graph_rdunlock_main_loop();
49498546632eSAlberto Garcia         ret = -EINVAL;
49508546632eSAlberto Garcia         goto error;
49518546632eSAlberto Garcia     }
4952004915a9SKevin Wolf     bdrv_graph_rdunlock_main_loop();
49538546632eSAlberto Garcia 
4954cb828c31SAlberto Garcia     /*
4955cb828c31SAlberto Garcia      * Allow changing the 'backing' option. The new value can be
4956cb828c31SAlberto Garcia      * either a reference to an existing node (using its node name)
4957cb828c31SAlberto Garcia      * or NULL to simply detach the current backing file.
4958cb828c31SAlberto Garcia      */
4959ecd30d2dSAlberto Garcia     ret = bdrv_reopen_parse_file_or_backing(reopen_state, true,
4960ecd30d2dSAlberto Garcia                                             change_child_tran, errp);
4961cb828c31SAlberto Garcia     if (ret < 0) {
4962cb828c31SAlberto Garcia         goto error;
4963cb828c31SAlberto Garcia     }
4964cb828c31SAlberto Garcia     qdict_del(reopen_state->options, "backing");
4965cb828c31SAlberto Garcia 
4966ecd30d2dSAlberto Garcia     /* Allow changing the 'file' option. In this case NULL is not allowed */
4967ecd30d2dSAlberto Garcia     ret = bdrv_reopen_parse_file_or_backing(reopen_state, false,
4968ecd30d2dSAlberto Garcia                                             change_child_tran, errp);
4969ecd30d2dSAlberto Garcia     if (ret < 0) {
4970ecd30d2dSAlberto Garcia         goto error;
4971ecd30d2dSAlberto Garcia     }
4972ecd30d2dSAlberto Garcia     qdict_del(reopen_state->options, "file");
4973ecd30d2dSAlberto Garcia 
49744d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
49754d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
49764d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
49774d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
49784d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
49794d2cb092SKevin Wolf 
4980ce433d29SKevin Wolf         GRAPH_RDLOCK_GUARD_MAINLOOP();
4981ce433d29SKevin Wolf 
49824d2cb092SKevin Wolf         do {
498354fd1b0dSMax Reitz             QObject *new = entry->value;
498454fd1b0dSMax Reitz             QObject *old = qdict_get(reopen_state->bs->options, entry->key);
49854d2cb092SKevin Wolf 
4986db905283SAlberto Garcia             /* Allow child references (child_name=node_name) as long as they
4987db905283SAlberto Garcia              * point to the current child (i.e. everything stays the same). */
4988db905283SAlberto Garcia             if (qobject_type(new) == QTYPE_QSTRING) {
4989db905283SAlberto Garcia                 BdrvChild *child;
4990db905283SAlberto Garcia                 QLIST_FOREACH(child, &reopen_state->bs->children, next) {
4991db905283SAlberto Garcia                     if (!strcmp(child->name, entry->key)) {
4992db905283SAlberto Garcia                         break;
4993db905283SAlberto Garcia                     }
4994db905283SAlberto Garcia                 }
4995db905283SAlberto Garcia 
4996db905283SAlberto Garcia                 if (child) {
4997410f44f5SMarkus Armbruster                     if (!strcmp(child->bs->node_name,
4998410f44f5SMarkus Armbruster                                 qstring_get_str(qobject_to(QString, new)))) {
4999db905283SAlberto Garcia                         continue; /* Found child with this name, skip option */
5000db905283SAlberto Garcia                     }
5001db905283SAlberto Garcia                 }
5002db905283SAlberto Garcia             }
5003db905283SAlberto Garcia 
500454fd1b0dSMax Reitz             /*
500554fd1b0dSMax Reitz              * TODO: When using -drive to specify blockdev options, all values
500654fd1b0dSMax Reitz              * will be strings; however, when using -blockdev, blockdev-add or
500754fd1b0dSMax Reitz              * filenames using the json:{} pseudo-protocol, they will be
500854fd1b0dSMax Reitz              * correctly typed.
500954fd1b0dSMax Reitz              * In contrast, reopening options are (currently) always strings
501054fd1b0dSMax Reitz              * (because you can only specify them through qemu-io; all other
501154fd1b0dSMax Reitz              * callers do not specify any options).
501254fd1b0dSMax Reitz              * Therefore, when using anything other than -drive to create a BDS,
501354fd1b0dSMax Reitz              * this cannot detect non-string options as unchanged, because
501454fd1b0dSMax Reitz              * qobject_is_equal() always returns false for objects of different
501554fd1b0dSMax Reitz              * type.  In the future, this should be remedied by correctly typing
501654fd1b0dSMax Reitz              * all options.  For now, this is not too big of an issue because
501754fd1b0dSMax Reitz              * the user can simply omit options which cannot be changed anyway,
501854fd1b0dSMax Reitz              * so they will stay unchanged.
501954fd1b0dSMax Reitz              */
502054fd1b0dSMax Reitz             if (!qobject_is_equal(new, old)) {
50214d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
50224d2cb092SKevin Wolf                 ret = -EINVAL;
50234d2cb092SKevin Wolf                 goto error;
50244d2cb092SKevin Wolf             }
50254d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
50264d2cb092SKevin Wolf     }
50274d2cb092SKevin Wolf 
5028e971aa12SJeff Cody     ret = 0;
5029e971aa12SJeff Cody 
50304c8350feSAlberto Garcia     /* Restore the original reopen_state->options QDict */
50314c8350feSAlberto Garcia     qobject_unref(reopen_state->options);
50324c8350feSAlberto Garcia     reopen_state->options = qobject_ref(orig_reopen_opts);
50334c8350feSAlberto Garcia 
5034e971aa12SJeff Cody error:
50359ad08c44SMax Reitz     if (ret < 0 && drv_prepared) {
50369ad08c44SMax Reitz         /* drv->bdrv_reopen_prepare() has succeeded, so we need to
50379ad08c44SMax Reitz          * call drv->bdrv_reopen_abort() before signaling an error
50389ad08c44SMax Reitz          * (bdrv_reopen_multiple() will not call bdrv_reopen_abort()
50399ad08c44SMax Reitz          * when the respective bdrv_reopen_prepare() has failed) */
50409ad08c44SMax Reitz         if (drv->bdrv_reopen_abort) {
50419ad08c44SMax Reitz             drv->bdrv_reopen_abort(reopen_state);
50429ad08c44SMax Reitz         }
50439ad08c44SMax Reitz     }
5044ccf9dc07SKevin Wolf     qemu_opts_del(opts);
50454c8350feSAlberto Garcia     qobject_unref(orig_reopen_opts);
5046593b3071SAlberto Garcia     g_free(discard);
5047e971aa12SJeff Cody     return ret;
5048e971aa12SJeff Cody }
5049e971aa12SJeff Cody 
5050e971aa12SJeff Cody /*
5051e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
5052e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
5053e971aa12SJeff Cody  * the active BlockDriverState contents.
5054e971aa12SJeff Cody  */
5055ce433d29SKevin Wolf static void GRAPH_UNLOCKED bdrv_reopen_commit(BDRVReopenState *reopen_state)
5056e971aa12SJeff Cody {
5057e971aa12SJeff Cody     BlockDriver *drv;
505850bf65baSVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
505950196d7aSAlberto Garcia     BdrvChild *child;
5060e971aa12SJeff Cody 
5061e971aa12SJeff Cody     assert(reopen_state != NULL);
506250bf65baSVladimir Sementsov-Ogievskiy     bs = reopen_state->bs;
506350bf65baSVladimir Sementsov-Ogievskiy     drv = bs->drv;
5064e971aa12SJeff Cody     assert(drv != NULL);
5065da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5066e971aa12SJeff Cody 
5067e971aa12SJeff Cody     /* If there are any driver level actions to take */
5068e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
5069e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
5070e971aa12SJeff Cody     }
5071e971aa12SJeff Cody 
5072ce433d29SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
5073ce433d29SKevin Wolf 
5074e971aa12SJeff Cody     /* set BDS specific flags now */
5075cb3e7f08SMarc-André Lureau     qobject_unref(bs->explicit_options);
50764c8350feSAlberto Garcia     qobject_unref(bs->options);
5077ab5b5228SAlberto Garcia     qobject_ref(reopen_state->explicit_options);
5078ab5b5228SAlberto Garcia     qobject_ref(reopen_state->options);
5079145f598eSKevin Wolf 
508050bf65baSVladimir Sementsov-Ogievskiy     bs->explicit_options   = reopen_state->explicit_options;
50814c8350feSAlberto Garcia     bs->options            = reopen_state->options;
508250bf65baSVladimir Sementsov-Ogievskiy     bs->open_flags         = reopen_state->flags;
5083543770bdSAlberto Garcia     bs->detect_zeroes      = reopen_state->detect_zeroes;
5084355ef4acSKevin Wolf 
508550196d7aSAlberto Garcia     /* Remove child references from bs->options and bs->explicit_options.
508650196d7aSAlberto Garcia      * Child options were already removed in bdrv_reopen_queue_child() */
508750196d7aSAlberto Garcia     QLIST_FOREACH(child, &bs->children, next) {
508850196d7aSAlberto Garcia         qdict_del(bs->explicit_options, child->name);
508950196d7aSAlberto Garcia         qdict_del(bs->options, child->name);
509050196d7aSAlberto Garcia     }
50913d0e8743SVladimir Sementsov-Ogievskiy     /* backing is probably removed, so it's not handled by previous loop */
50923d0e8743SVladimir Sementsov-Ogievskiy     qdict_del(bs->explicit_options, "backing");
50933d0e8743SVladimir Sementsov-Ogievskiy     qdict_del(bs->options, "backing");
50943d0e8743SVladimir Sementsov-Ogievskiy 
50951e4c797cSVladimir Sementsov-Ogievskiy     bdrv_refresh_limits(bs, NULL, NULL);
5096439cc330SPaolo Bonzini     bdrv_refresh_total_sectors(bs, bs->total_sectors);
5097e971aa12SJeff Cody }
5098e971aa12SJeff Cody 
5099e971aa12SJeff Cody /*
5100e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
5101e971aa12SJeff Cody  * reopen_state
5102e971aa12SJeff Cody  */
5103ce433d29SKevin Wolf static void GRAPH_UNLOCKED bdrv_reopen_abort(BDRVReopenState *reopen_state)
5104e971aa12SJeff Cody {
5105e971aa12SJeff Cody     BlockDriver *drv;
5106e971aa12SJeff Cody 
5107e971aa12SJeff Cody     assert(reopen_state != NULL);
5108e971aa12SJeff Cody     drv = reopen_state->bs->drv;
5109e971aa12SJeff Cody     assert(drv != NULL);
5110da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5111e971aa12SJeff Cody 
5112e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
5113e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
5114e971aa12SJeff Cody     }
5115e971aa12SJeff Cody }
5116e971aa12SJeff Cody 
5117e971aa12SJeff Cody 
511864dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
5119fc01f7e7Sbellard {
512033384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
512150a3efb0SAlberto Garcia     BdrvChild *child, *next;
512233384421SMax Reitz 
5123f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
512430f55fb8SMax Reitz     assert(!bs->refcnt);
512599b7e775SAlberto Garcia 
5126fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
512758fda173SStefan Hajnoczi     bdrv_flush(bs);
512853ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
5129fc27291dSPaolo Bonzini 
51303cbc002cSPaolo Bonzini     if (bs->drv) {
51313c005293SVladimir Sementsov-Ogievskiy         if (bs->drv->bdrv_close) {
51327b99a266SMax Reitz             /* Must unfreeze all children, so bdrv_unref_child() works */
51339a7dedbcSKevin Wolf             bs->drv->bdrv_close(bs);
51343c005293SVladimir Sementsov-Ogievskiy         }
51359a4f4c31SKevin Wolf         bs->drv = NULL;
513650a3efb0SAlberto Garcia     }
51379a7dedbcSKevin Wolf 
51386bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
51396e93e7c4SKevin Wolf     QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
5140dd4118c7SAlberto Garcia         bdrv_unref_child(bs, child);
51416e93e7c4SKevin Wolf     }
51426e93e7c4SKevin Wolf 
51435bb04747SVladimir Sementsov-Ogievskiy     assert(!bs->backing);
51445bb04747SVladimir Sementsov-Ogievskiy     assert(!bs->file);
51456bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
5146004915a9SKevin Wolf 
51477267c094SAnthony Liguori     g_free(bs->opaque);
5148ea2384d3Sbellard     bs->opaque = NULL;
5149d73415a3SStefan Hajnoczi     qatomic_set(&bs->copy_on_read, 0);
5150a275fa42SPaolo Bonzini     bs->backing_file[0] = '\0';
5151a275fa42SPaolo Bonzini     bs->backing_format[0] = '\0';
51526405875cSPaolo Bonzini     bs->total_sectors = 0;
515354115412SEric Blake     bs->encrypted = false;
515454115412SEric Blake     bs->sg = false;
5155cb3e7f08SMarc-André Lureau     qobject_unref(bs->options);
5156cb3e7f08SMarc-André Lureau     qobject_unref(bs->explicit_options);
5157de9c0cecSKevin Wolf     bs->options = NULL;
5158998cbd6aSManos Pitsidianakis     bs->explicit_options = NULL;
5159cb3e7f08SMarc-André Lureau     qobject_unref(bs->full_open_options);
516091af7014SMax Reitz     bs->full_open_options = NULL;
51610bc329fbSHanna Reitz     g_free(bs->block_status_cache);
51620bc329fbSHanna Reitz     bs->block_status_cache = NULL;
516366f82ceeSKevin Wolf 
5164cca43ae1SVladimir Sementsov-Ogievskiy     bdrv_release_named_dirty_bitmaps(bs);
5165cca43ae1SVladimir Sementsov-Ogievskiy     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
5166cca43ae1SVladimir Sementsov-Ogievskiy 
516733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
516833384421SMax Reitz         g_free(ban);
516933384421SMax Reitz     }
517033384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
5171fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
51721a6d3bd2SGreg Kurz 
51731a6d3bd2SGreg Kurz     /*
51741a6d3bd2SGreg Kurz      * If we're still inside some bdrv_drain_all_begin()/end() sections, end
51751a6d3bd2SGreg Kurz      * them now since this BDS won't exist anymore when bdrv_drain_all_end()
51761a6d3bd2SGreg Kurz      * gets called.
51771a6d3bd2SGreg Kurz      */
51781a6d3bd2SGreg Kurz     if (bs->quiesce_counter) {
51791a6d3bd2SGreg Kurz         bdrv_drain_all_end_quiesce(bs);
51801a6d3bd2SGreg Kurz     }
5181b338082bSbellard }
5182b338082bSbellard 
51832bc93fedSMORITA Kazutaka void bdrv_close_all(void)
51842bc93fedSMORITA Kazutaka {
5185f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5186880eeec6SEmanuele Giuseppe Esposito     assert(job_next(NULL) == NULL);
51872bc93fedSMORITA Kazutaka 
5188ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
5189ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
5190ca9bd24cSMax Reitz     bdrv_drain_all();
5191ca9bd24cSMax Reitz 
5192ca9bd24cSMax Reitz     blk_remove_all_bs();
5193ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
5194ca9bd24cSMax Reitz 
5195a1a2af07SKevin Wolf     assert(QTAILQ_EMPTY(&all_bdrv_states));
51962bc93fedSMORITA Kazutaka }
51972bc93fedSMORITA Kazutaka 
51982f64e1fcSKevin Wolf static bool GRAPH_RDLOCK should_update_child(BdrvChild *c, BlockDriverState *to)
5199dd62f1caSKevin Wolf {
52002f30b7c3SVladimir Sementsov-Ogievskiy     GQueue *queue;
52012f30b7c3SVladimir Sementsov-Ogievskiy     GHashTable *found;
52022f30b7c3SVladimir Sementsov-Ogievskiy     bool ret;
5203dd62f1caSKevin Wolf 
5204bd86fb99SMax Reitz     if (c->klass->stay_at_node) {
5205d0ac0380SKevin Wolf         return false;
520626de9438SKevin Wolf     }
5207d0ac0380SKevin Wolf 
5208ec9f10feSMax Reitz     /* If the child @c belongs to the BDS @to, replacing the current
5209ec9f10feSMax Reitz      * c->bs by @to would mean to create a loop.
5210ec9f10feSMax Reitz      *
5211ec9f10feSMax Reitz      * Such a case occurs when appending a BDS to a backing chain.
5212ec9f10feSMax Reitz      * For instance, imagine the following chain:
5213ec9f10feSMax Reitz      *
5214ec9f10feSMax Reitz      *   guest device -> node A -> further backing chain...
5215ec9f10feSMax Reitz      *
5216ec9f10feSMax Reitz      * Now we create a new BDS B which we want to put on top of this
5217ec9f10feSMax Reitz      * chain, so we first attach A as its backing node:
5218ec9f10feSMax Reitz      *
5219ec9f10feSMax Reitz      *                   node B
5220ec9f10feSMax Reitz      *                     |
5221ec9f10feSMax Reitz      *                     v
5222ec9f10feSMax Reitz      *   guest device -> node A -> further backing chain...
5223ec9f10feSMax Reitz      *
5224ec9f10feSMax Reitz      * Finally we want to replace A by B.  When doing that, we want to
5225ec9f10feSMax Reitz      * replace all pointers to A by pointers to B -- except for the
5226ec9f10feSMax Reitz      * pointer from B because (1) that would create a loop, and (2)
5227ec9f10feSMax Reitz      * that pointer should simply stay intact:
5228ec9f10feSMax Reitz      *
5229ec9f10feSMax Reitz      *   guest device -> node B
5230ec9f10feSMax Reitz      *                     |
5231ec9f10feSMax Reitz      *                     v
5232ec9f10feSMax Reitz      *                   node A -> further backing chain...
5233ec9f10feSMax Reitz      *
5234ec9f10feSMax Reitz      * In general, when replacing a node A (c->bs) by a node B (@to),
5235ec9f10feSMax Reitz      * if A is a child of B, that means we cannot replace A by B there
5236ec9f10feSMax Reitz      * because that would create a loop.  Silently detaching A from B
5237ec9f10feSMax Reitz      * is also not really an option.  So overall just leaving A in
52382f30b7c3SVladimir Sementsov-Ogievskiy      * place there is the most sensible choice.
52392f30b7c3SVladimir Sementsov-Ogievskiy      *
52402f30b7c3SVladimir Sementsov-Ogievskiy      * We would also create a loop in any cases where @c is only
52412f30b7c3SVladimir Sementsov-Ogievskiy      * indirectly referenced by @to. Prevent this by returning false
52422f30b7c3SVladimir Sementsov-Ogievskiy      * if @c is found (by breadth-first search) anywhere in the whole
52432f30b7c3SVladimir Sementsov-Ogievskiy      * subtree of @to.
52442f30b7c3SVladimir Sementsov-Ogievskiy      */
52452f30b7c3SVladimir Sementsov-Ogievskiy 
52462f30b7c3SVladimir Sementsov-Ogievskiy     ret = true;
52472f30b7c3SVladimir Sementsov-Ogievskiy     found = g_hash_table_new(NULL, NULL);
52482f30b7c3SVladimir Sementsov-Ogievskiy     g_hash_table_add(found, to);
52492f30b7c3SVladimir Sementsov-Ogievskiy     queue = g_queue_new();
52502f30b7c3SVladimir Sementsov-Ogievskiy     g_queue_push_tail(queue, to);
52512f30b7c3SVladimir Sementsov-Ogievskiy 
52522f30b7c3SVladimir Sementsov-Ogievskiy     while (!g_queue_is_empty(queue)) {
52532f30b7c3SVladimir Sementsov-Ogievskiy         BlockDriverState *v = g_queue_pop_head(queue);
52542f30b7c3SVladimir Sementsov-Ogievskiy         BdrvChild *c2;
52552f30b7c3SVladimir Sementsov-Ogievskiy 
52562f30b7c3SVladimir Sementsov-Ogievskiy         QLIST_FOREACH(c2, &v->children, next) {
52572f30b7c3SVladimir Sementsov-Ogievskiy             if (c2 == c) {
52582f30b7c3SVladimir Sementsov-Ogievskiy                 ret = false;
52592f30b7c3SVladimir Sementsov-Ogievskiy                 break;
52602f30b7c3SVladimir Sementsov-Ogievskiy             }
52612f30b7c3SVladimir Sementsov-Ogievskiy 
52622f30b7c3SVladimir Sementsov-Ogievskiy             if (g_hash_table_contains(found, c2->bs)) {
52632f30b7c3SVladimir Sementsov-Ogievskiy                 continue;
52642f30b7c3SVladimir Sementsov-Ogievskiy             }
52652f30b7c3SVladimir Sementsov-Ogievskiy 
52662f30b7c3SVladimir Sementsov-Ogievskiy             g_queue_push_tail(queue, c2->bs);
52672f30b7c3SVladimir Sementsov-Ogievskiy             g_hash_table_add(found, c2->bs);
52689bd910e2SMax Reitz         }
52699bd910e2SMax Reitz     }
52709bd910e2SMax Reitz 
52712f30b7c3SVladimir Sementsov-Ogievskiy     g_queue_free(queue);
52722f30b7c3SVladimir Sementsov-Ogievskiy     g_hash_table_destroy(found);
52732f30b7c3SVladimir Sementsov-Ogievskiy 
52742f30b7c3SVladimir Sementsov-Ogievskiy     return ret;
5275d0ac0380SKevin Wolf }
5276d0ac0380SKevin Wolf 
527757f08941SVladimir Sementsov-Ogievskiy static void bdrv_remove_child_commit(void *opaque)
527846541ee5SVladimir Sementsov-Ogievskiy {
5279bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
52805bb04747SVladimir Sementsov-Ogievskiy     bdrv_child_free(opaque);
528146541ee5SVladimir Sementsov-Ogievskiy }
528246541ee5SVladimir Sementsov-Ogievskiy 
528357f08941SVladimir Sementsov-Ogievskiy static TransactionActionDrv bdrv_remove_child_drv = {
528457f08941SVladimir Sementsov-Ogievskiy     .commit = bdrv_remove_child_commit,
528546541ee5SVladimir Sementsov-Ogievskiy };
528646541ee5SVladimir Sementsov-Ogievskiy 
52872f64e1fcSKevin Wolf /*
52882f64e1fcSKevin Wolf  * Function doesn't update permissions, caller is responsible for this.
52892f64e1fcSKevin Wolf  *
52902f64e1fcSKevin Wolf  * @child->bs (if non-NULL) must be drained.
52915661a00dSKevin Wolf  *
52925661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
52935661a00dSKevin Wolf  * while holding a writer lock for the graph.
52942f64e1fcSKevin Wolf  */
52952f64e1fcSKevin Wolf static void GRAPH_WRLOCK bdrv_remove_child(BdrvChild *child, Transaction *tran)
529646541ee5SVladimir Sementsov-Ogievskiy {
529746541ee5SVladimir Sementsov-Ogievskiy     if (!child) {
529846541ee5SVladimir Sementsov-Ogievskiy         return;
529946541ee5SVladimir Sementsov-Ogievskiy     }
530046541ee5SVladimir Sementsov-Ogievskiy 
530146541ee5SVladimir Sementsov-Ogievskiy     if (child->bs) {
53022f64e1fcSKevin Wolf         assert(child->quiesced_parent);
5303a2c37a30SVladimir Sementsov-Ogievskiy         bdrv_replace_child_tran(child, NULL, tran);
530446541ee5SVladimir Sementsov-Ogievskiy     }
530546541ee5SVladimir Sementsov-Ogievskiy 
530657f08941SVladimir Sementsov-Ogievskiy     tran_add(tran, &bdrv_remove_child_drv, child);
530746541ee5SVladimir Sementsov-Ogievskiy }
530846541ee5SVladimir Sementsov-Ogievskiy 
53092f64e1fcSKevin Wolf /*
53102f64e1fcSKevin Wolf  * Both @from and @to (if non-NULL) must be drained. @to must be kept drained
53112f64e1fcSKevin Wolf  * until the transaction is completed.
53125661a00dSKevin Wolf  *
53135661a00dSKevin Wolf  * After calling this function, the transaction @tran may only be completed
53145661a00dSKevin Wolf  * while holding a writer lock for the graph.
53152f64e1fcSKevin Wolf  */
53162f64e1fcSKevin Wolf static int GRAPH_WRLOCK
53172f64e1fcSKevin Wolf bdrv_replace_node_noperm(BlockDriverState *from,
5318117caba9SVladimir Sementsov-Ogievskiy                          BlockDriverState *to,
5319117caba9SVladimir Sementsov-Ogievskiy                          bool auto_skip, Transaction *tran,
5320117caba9SVladimir Sementsov-Ogievskiy                          Error **errp)
5321117caba9SVladimir Sementsov-Ogievskiy {
5322117caba9SVladimir Sementsov-Ogievskiy     BdrvChild *c, *next;
5323117caba9SVladimir Sementsov-Ogievskiy 
5324bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
532582b54cf5SHanna Reitz 
53262f64e1fcSKevin Wolf     assert(from->quiesce_counter);
53272f64e1fcSKevin Wolf     assert(to->quiesce_counter);
532823987471SKevin Wolf 
5329117caba9SVladimir Sementsov-Ogievskiy     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
5330117caba9SVladimir Sementsov-Ogievskiy         assert(c->bs == from);
5331117caba9SVladimir Sementsov-Ogievskiy         if (!should_update_child(c, to)) {
5332117caba9SVladimir Sementsov-Ogievskiy             if (auto_skip) {
5333117caba9SVladimir Sementsov-Ogievskiy                 continue;
5334117caba9SVladimir Sementsov-Ogievskiy             }
5335117caba9SVladimir Sementsov-Ogievskiy             error_setg(errp, "Should not change '%s' link to '%s'",
5336117caba9SVladimir Sementsov-Ogievskiy                        c->name, from->node_name);
5337117caba9SVladimir Sementsov-Ogievskiy             return -EINVAL;
5338117caba9SVladimir Sementsov-Ogievskiy         }
5339117caba9SVladimir Sementsov-Ogievskiy         if (c->frozen) {
5340117caba9SVladimir Sementsov-Ogievskiy             error_setg(errp, "Cannot change '%s' link to '%s'",
5341117caba9SVladimir Sementsov-Ogievskiy                        c->name, from->node_name);
5342117caba9SVladimir Sementsov-Ogievskiy             return -EPERM;
5343117caba9SVladimir Sementsov-Ogievskiy         }
53440f0b1e29SVladimir Sementsov-Ogievskiy         bdrv_replace_child_tran(c, to, tran);
5345117caba9SVladimir Sementsov-Ogievskiy     }
5346117caba9SVladimir Sementsov-Ogievskiy 
5347117caba9SVladimir Sementsov-Ogievskiy     return 0;
5348117caba9SVladimir Sementsov-Ogievskiy }
5349117caba9SVladimir Sementsov-Ogievskiy 
5350313274bbSVladimir Sementsov-Ogievskiy /*
53515c0ef495SKevin Wolf  * Switch all parents of @from to point to @to instead. @from and @to must be in
53525c0ef495SKevin Wolf  * the same AioContext and both must be drained.
53535c0ef495SKevin Wolf  *
5354313274bbSVladimir Sementsov-Ogievskiy  * With auto_skip=true bdrv_replace_node_common skips updating from parents
5355313274bbSVladimir Sementsov-Ogievskiy  * if it creates a parent-child relation loop or if parent is block-job.
5356313274bbSVladimir Sementsov-Ogievskiy  *
5357313274bbSVladimir Sementsov-Ogievskiy  * With auto_skip=false the error is returned if from has a parent which should
5358313274bbSVladimir Sementsov-Ogievskiy  * not be updated.
53593108a15cSVladimir Sementsov-Ogievskiy  *
53603108a15cSVladimir Sementsov-Ogievskiy  * With @detach_subchain=true @to must be in a backing chain of @from. In this
53613108a15cSVladimir Sementsov-Ogievskiy  * case backing link of the cow-parent of @to is removed.
5362313274bbSVladimir Sementsov-Ogievskiy  */
53635c0ef495SKevin Wolf static int GRAPH_WRLOCK
53645c0ef495SKevin Wolf bdrv_replace_node_common(BlockDriverState *from, BlockDriverState *to,
53655c0ef495SKevin Wolf                          bool auto_skip, bool detach_subchain, Error **errp)
5366d0ac0380SKevin Wolf {
53673bb0e298SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
53683bb0e298SVladimir Sementsov-Ogievskiy     g_autoptr(GSList) refresh_list = NULL;
53692d369d6eSMiroslav Rezanina     BlockDriverState *to_cow_parent = NULL;
5370234ac1a9SKevin Wolf     int ret;
5371d0ac0380SKevin Wolf 
5372bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
537382b54cf5SHanna Reitz 
53745c0ef495SKevin Wolf     assert(from->quiesce_counter);
53755c0ef495SKevin Wolf     assert(to->quiesce_counter);
537630dd65f3SKevin Wolf     assert(bdrv_get_aio_context(from) == bdrv_get_aio_context(to));
5377f871abd6SKevin Wolf 
5378372b69f5SKevin Wolf     if (detach_subchain) {
5379372b69f5SKevin Wolf         assert(bdrv_chain_contains(from, to));
5380372b69f5SKevin Wolf         assert(from != to);
5381372b69f5SKevin Wolf         for (to_cow_parent = from;
5382372b69f5SKevin Wolf              bdrv_filter_or_cow_bs(to_cow_parent) != to;
5383372b69f5SKevin Wolf              to_cow_parent = bdrv_filter_or_cow_bs(to_cow_parent))
5384372b69f5SKevin Wolf         {
5385372b69f5SKevin Wolf             ;
5386372b69f5SKevin Wolf         }
5387372b69f5SKevin Wolf     }
5388372b69f5SKevin Wolf 
53893bb0e298SVladimir Sementsov-Ogievskiy     /*
53903bb0e298SVladimir Sementsov-Ogievskiy      * Do the replacement without permission update.
53913bb0e298SVladimir Sementsov-Ogievskiy      * Replacement may influence the permissions, we should calculate new
53923bb0e298SVladimir Sementsov-Ogievskiy      * permissions based on new graph. If we fail, we'll roll-back the
53933bb0e298SVladimir Sementsov-Ogievskiy      * replacement.
53943bb0e298SVladimir Sementsov-Ogievskiy      */
5395117caba9SVladimir Sementsov-Ogievskiy     ret = bdrv_replace_node_noperm(from, to, auto_skip, tran, errp);
5396117caba9SVladimir Sementsov-Ogievskiy     if (ret < 0) {
5397313274bbSVladimir Sementsov-Ogievskiy         goto out;
5398313274bbSVladimir Sementsov-Ogievskiy     }
5399234ac1a9SKevin Wolf 
54003108a15cSVladimir Sementsov-Ogievskiy     if (detach_subchain) {
54012f64e1fcSKevin Wolf         /* to_cow_parent is already drained because from is drained */
5402f38eaec4SVladimir Sementsov-Ogievskiy         bdrv_remove_child(bdrv_filter_or_cow_child(to_cow_parent), tran);
54033108a15cSVladimir Sementsov-Ogievskiy     }
54043108a15cSVladimir Sementsov-Ogievskiy 
5405fb0ff4d1SVladimir Sementsov-Ogievskiy     refresh_list = g_slist_prepend(refresh_list, to);
5406fb0ff4d1SVladimir Sementsov-Ogievskiy     refresh_list = g_slist_prepend(refresh_list, from);
54073bb0e298SVladimir Sementsov-Ogievskiy 
54083bb0e298SVladimir Sementsov-Ogievskiy     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5409234ac1a9SKevin Wolf     if (ret < 0) {
5410234ac1a9SKevin Wolf         goto out;
5411234ac1a9SKevin Wolf     }
5412234ac1a9SKevin Wolf 
5413a1e708fcSVladimir Sementsov-Ogievskiy     ret = 0;
5414a1e708fcSVladimir Sementsov-Ogievskiy 
5415234ac1a9SKevin Wolf out:
54163bb0e298SVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
54175c0ef495SKevin Wolf     return ret;
54185c0ef495SKevin Wolf }
54193bb0e298SVladimir Sementsov-Ogievskiy 
54205c0ef495SKevin Wolf int bdrv_replace_node(BlockDriverState *from, BlockDriverState *to,
54215c0ef495SKevin Wolf                       Error **errp)
54225c0ef495SKevin Wolf {
5423ccd6a379SKevin Wolf     return bdrv_replace_node_common(from, to, true, false, errp);
5424dd62f1caSKevin Wolf }
5425dd62f1caSKevin Wolf 
54263108a15cSVladimir Sementsov-Ogievskiy int bdrv_drop_filter(BlockDriverState *bs, Error **errp)
54273108a15cSVladimir Sementsov-Ogievskiy {
5428372b69f5SKevin Wolf     BlockDriverState *child_bs;
54295c0ef495SKevin Wolf     int ret;
5430f791bf7fSEmanuele Giuseppe Esposito 
5431372b69f5SKevin Wolf     GLOBAL_STATE_CODE();
54325c0ef495SKevin Wolf 
5433372b69f5SKevin Wolf     bdrv_graph_rdlock_main_loop();
5434372b69f5SKevin Wolf     child_bs = bdrv_filter_or_cow_bs(bs);
5435372b69f5SKevin Wolf     bdrv_graph_rdunlock_main_loop();
5436372b69f5SKevin Wolf 
54375c0ef495SKevin Wolf     bdrv_drained_begin(child_bs);
54386bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
54395c0ef495SKevin Wolf     ret = bdrv_replace_node_common(bs, child_bs, true, true, errp);
54406bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
54415c0ef495SKevin Wolf     bdrv_drained_end(child_bs);
54425c0ef495SKevin Wolf 
54435c0ef495SKevin Wolf     return ret;
5444313274bbSVladimir Sementsov-Ogievskiy }
5445313274bbSVladimir Sementsov-Ogievskiy 
54468802d1fdSJeff Cody /*
54478802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
54488802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
54498802d1fdSJeff Cody  *
54508802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
54518802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
54528802d1fdSJeff Cody  *
54532272edcfSVladimir Sementsov-Ogievskiy  * bs_new must not be attached to a BlockBackend and must not have backing
54542272edcfSVladimir Sementsov-Ogievskiy  * child.
5455f6801b83SJeff Cody  *
54568802d1fdSJeff Cody  * This function does not create any image files.
54578802d1fdSJeff Cody  */
5458a1e708fcSVladimir Sementsov-Ogievskiy int bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top,
5459b2c2832cSKevin Wolf                 Error **errp)
54608802d1fdSJeff Cody {
54612272edcfSVladimir Sementsov-Ogievskiy     int ret;
54625bb04747SVladimir Sementsov-Ogievskiy     BdrvChild *child;
54632272edcfSVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
54642272edcfSVladimir Sementsov-Ogievskiy 
5465f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5466f791bf7fSEmanuele Giuseppe Esposito 
5467004915a9SKevin Wolf     bdrv_graph_rdlock_main_loop();
54682272edcfSVladimir Sementsov-Ogievskiy     assert(!bs_new->backing);
5469004915a9SKevin Wolf     bdrv_graph_rdunlock_main_loop();
54702272edcfSVladimir Sementsov-Ogievskiy 
54717d4ca9d2SKevin Wolf     bdrv_drained_begin(bs_top);
54727d4ca9d2SKevin Wolf     bdrv_drained_begin(bs_new);
54737d4ca9d2SKevin Wolf 
54746bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
547560d90bf4SStefano Garzarella 
54765bb04747SVladimir Sementsov-Ogievskiy     child = bdrv_attach_child_noperm(bs_new, bs_top, "backing",
54772272edcfSVladimir Sementsov-Ogievskiy                                      &child_of_bds, bdrv_backing_role(bs_new),
54785bb04747SVladimir Sementsov-Ogievskiy                                      tran, errp);
54795bb04747SVladimir Sementsov-Ogievskiy     if (!child) {
54805bb04747SVladimir Sementsov-Ogievskiy         ret = -EINVAL;
54812272edcfSVladimir Sementsov-Ogievskiy         goto out;
5482b2c2832cSKevin Wolf     }
5483dd62f1caSKevin Wolf 
54842272edcfSVladimir Sementsov-Ogievskiy     ret = bdrv_replace_node_noperm(bs_top, bs_new, true, tran, errp);
5485a1e708fcSVladimir Sementsov-Ogievskiy     if (ret < 0) {
54862272edcfSVladimir Sementsov-Ogievskiy         goto out;
5487234ac1a9SKevin Wolf     }
5488dd62f1caSKevin Wolf 
5489f1316edbSVladimir Sementsov-Ogievskiy     ret = bdrv_refresh_perms(bs_new, tran, errp);
54902272edcfSVladimir Sementsov-Ogievskiy out:
54912272edcfSVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
54922272edcfSVladimir Sementsov-Ogievskiy 
54931e4c797cSVladimir Sementsov-Ogievskiy     bdrv_refresh_limits(bs_top, NULL, NULL);
54946bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
54952272edcfSVladimir Sementsov-Ogievskiy 
54962f64e1fcSKevin Wolf     bdrv_drained_end(bs_top);
54972f64e1fcSKevin Wolf     bdrv_drained_end(bs_new);
54982f64e1fcSKevin Wolf 
54992272edcfSVladimir Sementsov-Ogievskiy     return ret;
55008802d1fdSJeff Cody }
55018802d1fdSJeff Cody 
5502bd8f4c42SVladimir Sementsov-Ogievskiy /* Not for empty child */
5503bd8f4c42SVladimir Sementsov-Ogievskiy int bdrv_replace_child_bs(BdrvChild *child, BlockDriverState *new_bs,
5504bd8f4c42SVladimir Sementsov-Ogievskiy                           Error **errp)
5505bd8f4c42SVladimir Sementsov-Ogievskiy {
5506bd8f4c42SVladimir Sementsov-Ogievskiy     int ret;
5507bd8f4c42SVladimir Sementsov-Ogievskiy     Transaction *tran = tran_new();
5508bd8f4c42SVladimir Sementsov-Ogievskiy     g_autoptr(GSList) refresh_list = NULL;
5509bd8f4c42SVladimir Sementsov-Ogievskiy     BlockDriverState *old_bs = child->bs;
5510bd8f4c42SVladimir Sementsov-Ogievskiy 
5511f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5512f791bf7fSEmanuele Giuseppe Esposito 
5513bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_ref(old_bs);
5514bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_drained_begin(old_bs);
5515bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_drained_begin(new_bs);
55166bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
5517bd8f4c42SVladimir Sementsov-Ogievskiy 
55180f0b1e29SVladimir Sementsov-Ogievskiy     bdrv_replace_child_tran(child, new_bs, tran);
5519bd8f4c42SVladimir Sementsov-Ogievskiy 
5520fb0ff4d1SVladimir Sementsov-Ogievskiy     refresh_list = g_slist_prepend(refresh_list, old_bs);
5521fb0ff4d1SVladimir Sementsov-Ogievskiy     refresh_list = g_slist_prepend(refresh_list, new_bs);
5522bd8f4c42SVladimir Sementsov-Ogievskiy 
5523bd8f4c42SVladimir Sementsov-Ogievskiy     ret = bdrv_list_refresh_perms(refresh_list, NULL, tran, errp);
5524bd8f4c42SVladimir Sementsov-Ogievskiy 
5525bd8f4c42SVladimir Sementsov-Ogievskiy     tran_finalize(tran, ret);
5526bd8f4c42SVladimir Sementsov-Ogievskiy 
55276bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
5528bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_drained_end(old_bs);
5529bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_drained_end(new_bs);
5530bd8f4c42SVladimir Sementsov-Ogievskiy     bdrv_unref(old_bs);
5531bd8f4c42SVladimir Sementsov-Ogievskiy 
5532bd8f4c42SVladimir Sementsov-Ogievskiy     return ret;
5533bd8f4c42SVladimir Sementsov-Ogievskiy }
5534bd8f4c42SVladimir Sementsov-Ogievskiy 
55354f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
5536b338082bSbellard {
55373718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
55384f6fd349SFam Zheng     assert(!bs->refcnt);
5539f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
554018846deeSMarkus Armbruster 
55411b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
554263eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
554363eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
554463eaaae0SKevin Wolf     }
55452c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
55462c1d04e0SMax Reitz 
554730c321f9SAnton Kuchin     bdrv_close(bs);
554830c321f9SAnton Kuchin 
5549fa9185fcSStefan Hajnoczi     qemu_mutex_destroy(&bs->reqs_lock);
5550fa9185fcSStefan Hajnoczi 
55517267c094SAnthony Liguori     g_free(bs);
5552fc01f7e7Sbellard }
5553fc01f7e7Sbellard 
555496796faeSVladimir Sementsov-Ogievskiy 
555596796faeSVladimir Sementsov-Ogievskiy /*
555696796faeSVladimir Sementsov-Ogievskiy  * Replace @bs by newly created block node.
555796796faeSVladimir Sementsov-Ogievskiy  *
555896796faeSVladimir Sementsov-Ogievskiy  * @options is a QDict of options to pass to the block drivers, or NULL for an
555996796faeSVladimir Sementsov-Ogievskiy  * empty set of options. The reference to the QDict belongs to the block layer
556096796faeSVladimir Sementsov-Ogievskiy  * after the call (even on failure), so if the caller intends to reuse the
556196796faeSVladimir Sementsov-Ogievskiy  * dictionary, it needs to use qobject_ref() before calling bdrv_open.
55628823407cSKevin Wolf  *
556323c983c8SStefan Hajnoczi  * The caller must make sure that @bs stays in the same AioContext, i.e.
556423c983c8SStefan Hajnoczi  * @options must not refer to nodes in a different AioContext.
556596796faeSVladimir Sementsov-Ogievskiy  */
556696796faeSVladimir Sementsov-Ogievskiy BlockDriverState *bdrv_insert_node(BlockDriverState *bs, QDict *options,
55678872ef78SAndrey Shinkevich                                    int flags, Error **errp)
55688872ef78SAndrey Shinkevich {
5569f053b7e8SVladimir Sementsov-Ogievskiy     ERRP_GUARD();
5570f053b7e8SVladimir Sementsov-Ogievskiy     int ret;
55718823407cSKevin Wolf     AioContext *ctx = bdrv_get_aio_context(bs);
5572b11c8739SVladimir Sementsov-Ogievskiy     BlockDriverState *new_node_bs = NULL;
5573b11c8739SVladimir Sementsov-Ogievskiy     const char *drvname, *node_name;
5574b11c8739SVladimir Sementsov-Ogievskiy     BlockDriver *drv;
55758872ef78SAndrey Shinkevich 
5576b11c8739SVladimir Sementsov-Ogievskiy     drvname = qdict_get_try_str(options, "driver");
5577b11c8739SVladimir Sementsov-Ogievskiy     if (!drvname) {
5578b11c8739SVladimir Sementsov-Ogievskiy         error_setg(errp, "driver is not specified");
5579b11c8739SVladimir Sementsov-Ogievskiy         goto fail;
5580b11c8739SVladimir Sementsov-Ogievskiy     }
5581b11c8739SVladimir Sementsov-Ogievskiy 
5582b11c8739SVladimir Sementsov-Ogievskiy     drv = bdrv_find_format(drvname);
5583b11c8739SVladimir Sementsov-Ogievskiy     if (!drv) {
5584b11c8739SVladimir Sementsov-Ogievskiy         error_setg(errp, "Unknown driver: '%s'", drvname);
5585b11c8739SVladimir Sementsov-Ogievskiy         goto fail;
5586b11c8739SVladimir Sementsov-Ogievskiy     }
5587b11c8739SVladimir Sementsov-Ogievskiy 
5588b11c8739SVladimir Sementsov-Ogievskiy     node_name = qdict_get_try_str(options, "node-name");
5589b11c8739SVladimir Sementsov-Ogievskiy 
5590f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5591f791bf7fSEmanuele Giuseppe Esposito 
5592b11c8739SVladimir Sementsov-Ogievskiy     new_node_bs = bdrv_new_open_driver_opts(drv, node_name, options, flags,
5593b11c8739SVladimir Sementsov-Ogievskiy                                             errp);
55948823407cSKevin Wolf     assert(bdrv_get_aio_context(bs) == ctx);
55958823407cSKevin Wolf 
5596b11c8739SVladimir Sementsov-Ogievskiy     options = NULL; /* bdrv_new_open_driver() eats options */
5597b11c8739SVladimir Sementsov-Ogievskiy     if (!new_node_bs) {
55988872ef78SAndrey Shinkevich         error_prepend(errp, "Could not create node: ");
5599b11c8739SVladimir Sementsov-Ogievskiy         goto fail;
56008872ef78SAndrey Shinkevich     }
56018872ef78SAndrey Shinkevich 
5602ccd6a379SKevin Wolf     /*
5603ccd6a379SKevin Wolf      * Make sure that @bs doesn't go away until we have successfully attached
5604ccd6a379SKevin Wolf      * all of its parents to @new_node_bs and undrained it again.
5605ccd6a379SKevin Wolf      */
5606ccd6a379SKevin Wolf     bdrv_ref(bs);
56078872ef78SAndrey Shinkevich     bdrv_drained_begin(bs);
5608ccd6a379SKevin Wolf     bdrv_drained_begin(new_node_bs);
56096bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
5610f053b7e8SVladimir Sementsov-Ogievskiy     ret = bdrv_replace_node(bs, new_node_bs, errp);
56116bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
5612ccd6a379SKevin Wolf     bdrv_drained_end(new_node_bs);
56138872ef78SAndrey Shinkevich     bdrv_drained_end(bs);
5614ccd6a379SKevin Wolf     bdrv_unref(bs);
56158872ef78SAndrey Shinkevich 
5616f053b7e8SVladimir Sementsov-Ogievskiy     if (ret < 0) {
5617f053b7e8SVladimir Sementsov-Ogievskiy         error_prepend(errp, "Could not replace node: ");
5618b11c8739SVladimir Sementsov-Ogievskiy         goto fail;
56198872ef78SAndrey Shinkevich     }
56208872ef78SAndrey Shinkevich 
56218872ef78SAndrey Shinkevich     return new_node_bs;
5622b11c8739SVladimir Sementsov-Ogievskiy 
5623b11c8739SVladimir Sementsov-Ogievskiy fail:
5624b11c8739SVladimir Sementsov-Ogievskiy     qobject_unref(options);
5625b11c8739SVladimir Sementsov-Ogievskiy     bdrv_unref(new_node_bs);
5626b11c8739SVladimir Sementsov-Ogievskiy     return NULL;
56278872ef78SAndrey Shinkevich }
56288872ef78SAndrey Shinkevich 
5629e97fc193Saliguori /*
5630e97fc193Saliguori  * Run consistency checks on an image
5631e97fc193Saliguori  *
5632e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
5633a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
5634e076f338SKevin Wolf  * check are stored in res.
5635e97fc193Saliguori  */
563621c2283eSVladimir Sementsov-Ogievskiy int coroutine_fn bdrv_co_check(BlockDriverState *bs,
56372fd61638SPaolo Bonzini                                BdrvCheckResult *res, BdrvCheckMode fix)
5638e97fc193Saliguori {
56391581a70dSEmanuele Giuseppe Esposito     IO_CODE();
56401b3ff9feSKevin Wolf     assert_bdrv_graph_readable();
5641908bcd54SMax Reitz     if (bs->drv == NULL) {
5642908bcd54SMax Reitz         return -ENOMEDIUM;
5643908bcd54SMax Reitz     }
56442fd61638SPaolo Bonzini     if (bs->drv->bdrv_co_check == NULL) {
5645e97fc193Saliguori         return -ENOTSUP;
5646e97fc193Saliguori     }
5647e97fc193Saliguori 
5648e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
56492fd61638SPaolo Bonzini     return bs->drv->bdrv_co_check(bs, res, fix);
56502fd61638SPaolo Bonzini }
56512fd61638SPaolo Bonzini 
5652756e6736SKevin Wolf /*
5653756e6736SKevin Wolf  * Return values:
5654756e6736SKevin Wolf  * 0        - success
5655756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
5656756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
5657756e6736SKevin Wolf  *            image file header
5658756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
5659756e6736SKevin Wolf  */
5660e2dd2737SKevin Wolf int coroutine_fn
5661e2dd2737SKevin Wolf bdrv_co_change_backing_file(BlockDriverState *bs, const char *backing_file,
5662497a30dbSEric Blake                             const char *backing_fmt, bool require)
5663756e6736SKevin Wolf {
5664756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
5665469ef350SPaolo Bonzini     int ret;
5666756e6736SKevin Wolf 
5667e2dd2737SKevin Wolf     IO_CODE();
5668f791bf7fSEmanuele Giuseppe Esposito 
5669d470ad42SMax Reitz     if (!drv) {
5670d470ad42SMax Reitz         return -ENOMEDIUM;
5671d470ad42SMax Reitz     }
5672d470ad42SMax Reitz 
56735f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
56745f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
56755f377794SPaolo Bonzini         return -EINVAL;
56765f377794SPaolo Bonzini     }
56775f377794SPaolo Bonzini 
5678497a30dbSEric Blake     if (require && backing_file && !backing_fmt) {
5679497a30dbSEric Blake         return -EINVAL;
5680e54ee1b3SEric Blake     }
5681e54ee1b3SEric Blake 
5682e2dd2737SKevin Wolf     if (drv->bdrv_co_change_backing_file != NULL) {
5683e2dd2737SKevin Wolf         ret = drv->bdrv_co_change_backing_file(bs, backing_file, backing_fmt);
5684756e6736SKevin Wolf     } else {
5685469ef350SPaolo Bonzini         ret = -ENOTSUP;
5686756e6736SKevin Wolf     }
5687469ef350SPaolo Bonzini 
5688469ef350SPaolo Bonzini     if (ret == 0) {
5689469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
5690469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
5691998c2019SMax Reitz         pstrcpy(bs->auto_backing_file, sizeof(bs->auto_backing_file),
5692998c2019SMax Reitz                 backing_file ?: "");
5693469ef350SPaolo Bonzini     }
5694469ef350SPaolo Bonzini     return ret;
5695756e6736SKevin Wolf }
5696756e6736SKevin Wolf 
56976ebdcee2SJeff Cody /*
5698dcf3f9b2SMax Reitz  * Finds the first non-filter node above bs in the chain between
5699dcf3f9b2SMax Reitz  * active and bs.  The returned node is either an immediate parent of
5700dcf3f9b2SMax Reitz  * bs, or there are only filter nodes between the two.
57016ebdcee2SJeff Cody  *
57026ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
57036ebdcee2SJeff Cody  * or if active == bs.
57044caf0fcdSJeff Cody  *
57054caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
57066ebdcee2SJeff Cody  */
57076ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
57086ebdcee2SJeff Cody                                     BlockDriverState *bs)
57096ebdcee2SJeff Cody {
5710f791bf7fSEmanuele Giuseppe Esposito 
5711f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5712f791bf7fSEmanuele Giuseppe Esposito 
5713dcf3f9b2SMax Reitz     bs = bdrv_skip_filters(bs);
5714dcf3f9b2SMax Reitz     active = bdrv_skip_filters(active);
5715dcf3f9b2SMax Reitz 
5716dcf3f9b2SMax Reitz     while (active) {
5717dcf3f9b2SMax Reitz         BlockDriverState *next = bdrv_backing_chain_next(active);
5718dcf3f9b2SMax Reitz         if (bs == next) {
5719dcf3f9b2SMax Reitz             return active;
5720dcf3f9b2SMax Reitz         }
5721dcf3f9b2SMax Reitz         active = next;
57226ebdcee2SJeff Cody     }
57236ebdcee2SJeff Cody 
5724dcf3f9b2SMax Reitz     return NULL;
57256ebdcee2SJeff Cody }
57266ebdcee2SJeff Cody 
57274caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
57284caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
57294caf0fcdSJeff Cody {
5730f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5731f791bf7fSEmanuele Giuseppe Esposito 
57324caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
57336ebdcee2SJeff Cody }
57346ebdcee2SJeff Cody 
57356ebdcee2SJeff Cody /*
57367b99a266SMax Reitz  * Return true if at least one of the COW (backing) and filter links
57377b99a266SMax Reitz  * between @bs and @base is frozen. @errp is set if that's the case.
57380f0998f6SAlberto Garcia  * @base must be reachable from @bs, or NULL.
57392cad1ebeSAlberto Garcia  */
57409275fc72SKevin Wolf static bool GRAPH_RDLOCK
57419275fc72SKevin Wolf bdrv_is_backing_chain_frozen(BlockDriverState *bs, BlockDriverState *base,
57422cad1ebeSAlberto Garcia                              Error **errp)
57432cad1ebeSAlberto Garcia {
57442cad1ebeSAlberto Garcia     BlockDriverState *i;
57457b99a266SMax Reitz     BdrvChild *child;
57462cad1ebeSAlberto Garcia 
5747f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5748f791bf7fSEmanuele Giuseppe Esposito 
57497b99a266SMax Reitz     for (i = bs; i != base; i = child_bs(child)) {
57507b99a266SMax Reitz         child = bdrv_filter_or_cow_child(i);
57517b99a266SMax Reitz 
57527b99a266SMax Reitz         if (child && child->frozen) {
57532cad1ebeSAlberto Garcia             error_setg(errp, "Cannot change '%s' link from '%s' to '%s'",
57547b99a266SMax Reitz                        child->name, i->node_name, child->bs->node_name);
57552cad1ebeSAlberto Garcia             return true;
57562cad1ebeSAlberto Garcia         }
57572cad1ebeSAlberto Garcia     }
57582cad1ebeSAlberto Garcia 
57592cad1ebeSAlberto Garcia     return false;
57602cad1ebeSAlberto Garcia }
57612cad1ebeSAlberto Garcia 
57622cad1ebeSAlberto Garcia /*
57637b99a266SMax Reitz  * Freeze all COW (backing) and filter links between @bs and @base.
57642cad1ebeSAlberto Garcia  * If any of the links is already frozen the operation is aborted and
57652cad1ebeSAlberto Garcia  * none of the links are modified.
57660f0998f6SAlberto Garcia  * @base must be reachable from @bs, or NULL.
57672cad1ebeSAlberto Garcia  * Returns 0 on success. On failure returns < 0 and sets @errp.
57682cad1ebeSAlberto Garcia  */
57692cad1ebeSAlberto Garcia int bdrv_freeze_backing_chain(BlockDriverState *bs, BlockDriverState *base,
57702cad1ebeSAlberto Garcia                               Error **errp)
57712cad1ebeSAlberto Garcia {
57722cad1ebeSAlberto Garcia     BlockDriverState *i;
57737b99a266SMax Reitz     BdrvChild *child;
57742cad1ebeSAlberto Garcia 
5775f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5776f791bf7fSEmanuele Giuseppe Esposito 
57772cad1ebeSAlberto Garcia     if (bdrv_is_backing_chain_frozen(bs, base, errp)) {
57782cad1ebeSAlberto Garcia         return -EPERM;
57792cad1ebeSAlberto Garcia     }
57802cad1ebeSAlberto Garcia 
57817b99a266SMax Reitz     for (i = bs; i != base; i = child_bs(child)) {
57827b99a266SMax Reitz         child = bdrv_filter_or_cow_child(i);
57837b99a266SMax Reitz         if (child && child->bs->never_freeze) {
5784e5182c1cSMax Reitz             error_setg(errp, "Cannot freeze '%s' link to '%s'",
57857b99a266SMax Reitz                        child->name, child->bs->node_name);
5786e5182c1cSMax Reitz             return -EPERM;
5787e5182c1cSMax Reitz         }
5788e5182c1cSMax Reitz     }
5789e5182c1cSMax Reitz 
57907b99a266SMax Reitz     for (i = bs; i != base; i = child_bs(child)) {
57917b99a266SMax Reitz         child = bdrv_filter_or_cow_child(i);
57927b99a266SMax Reitz         if (child) {
57937b99a266SMax Reitz             child->frozen = true;
57942cad1ebeSAlberto Garcia         }
57950f0998f6SAlberto Garcia     }
57962cad1ebeSAlberto Garcia 
57972cad1ebeSAlberto Garcia     return 0;
57982cad1ebeSAlberto Garcia }
57992cad1ebeSAlberto Garcia 
58002cad1ebeSAlberto Garcia /*
58017b99a266SMax Reitz  * Unfreeze all COW (backing) and filter links between @bs and @base.
58027b99a266SMax Reitz  * The caller must ensure that all links are frozen before using this
58037b99a266SMax Reitz  * function.
58040f0998f6SAlberto Garcia  * @base must be reachable from @bs, or NULL.
58052cad1ebeSAlberto Garcia  */
58062cad1ebeSAlberto Garcia void bdrv_unfreeze_backing_chain(BlockDriverState *bs, BlockDriverState *base)
58072cad1ebeSAlberto Garcia {
58082cad1ebeSAlberto Garcia     BlockDriverState *i;
58097b99a266SMax Reitz     BdrvChild *child;
58102cad1ebeSAlberto Garcia 
5811f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5812f791bf7fSEmanuele Giuseppe Esposito 
58137b99a266SMax Reitz     for (i = bs; i != base; i = child_bs(child)) {
58147b99a266SMax Reitz         child = bdrv_filter_or_cow_child(i);
58157b99a266SMax Reitz         if (child) {
58167b99a266SMax Reitz             assert(child->frozen);
58177b99a266SMax Reitz             child->frozen = false;
58182cad1ebeSAlberto Garcia         }
58192cad1ebeSAlberto Garcia     }
58200f0998f6SAlberto Garcia }
58212cad1ebeSAlberto Garcia 
58222cad1ebeSAlberto Garcia /*
58236ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
58246ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
58256ebdcee2SJeff Cody  *
58266ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
58276ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
58286ebdcee2SJeff Cody  *
58296ebdcee2SJeff Cody  * E.g., this will convert the following chain:
58306ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
58316ebdcee2SJeff Cody  *
58326ebdcee2SJeff Cody  * to
58336ebdcee2SJeff Cody  *
58346ebdcee2SJeff Cody  * bottom <- base <- active
58356ebdcee2SJeff Cody  *
58366ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
58376ebdcee2SJeff Cody  *
58386ebdcee2SJeff Cody  * base <- intermediate <- top <- active
58396ebdcee2SJeff Cody  *
58406ebdcee2SJeff Cody  * to
58416ebdcee2SJeff Cody  *
58426ebdcee2SJeff Cody  * base <- active
58436ebdcee2SJeff Cody  *
584454e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
584554e26900SJeff Cody  * overlay image metadata.
584654e26900SJeff Cody  *
58476ebdcee2SJeff Cody  * Error conditions:
58486ebdcee2SJeff Cody  *  if active == top, that is considered an error
58496ebdcee2SJeff Cody  *
58506ebdcee2SJeff Cody  */
5851bde70715SKevin Wolf int bdrv_drop_intermediate(BlockDriverState *top, BlockDriverState *base,
58524b028cbeSPeter Krempa                            const char *backing_file_str,
58534b028cbeSPeter Krempa                            bool backing_mask_protocol)
58546ebdcee2SJeff Cody {
58556bd858b3SAlberto Garcia     BlockDriverState *explicit_top = top;
58566bd858b3SAlberto Garcia     bool update_inherits_from;
5857d669ed6aSVladimir Sementsov-Ogievskiy     BdrvChild *c;
585812fa4af6SKevin Wolf     Error *local_err = NULL;
58596ebdcee2SJeff Cody     int ret = -EIO;
5860d669ed6aSVladimir Sementsov-Ogievskiy     g_autoptr(GSList) updated_children = NULL;
5861d669ed6aSVladimir Sementsov-Ogievskiy     GSList *p;
58626ebdcee2SJeff Cody 
5863f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
5864f791bf7fSEmanuele Giuseppe Esposito 
58656858eba0SKevin Wolf     bdrv_ref(top);
5866631086deSKevin Wolf     bdrv_drained_begin(base);
58676bc30f19SStefan Hajnoczi     bdrv_graph_wrlock();
58686858eba0SKevin Wolf 
58696ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
58705c0ef495SKevin Wolf         goto exit_wrlock;
58716ebdcee2SJeff Cody     }
58726ebdcee2SJeff Cody 
58735db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
58745db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
58755c0ef495SKevin Wolf         goto exit_wrlock;
58766ebdcee2SJeff Cody     }
58776ebdcee2SJeff Cody 
58786bd858b3SAlberto Garcia     /* If 'base' recursively inherits from 'top' then we should set
58796bd858b3SAlberto Garcia      * base->inherits_from to top->inherits_from after 'top' and all
58806bd858b3SAlberto Garcia      * other intermediate nodes have been dropped.
58816bd858b3SAlberto Garcia      * If 'top' is an implicit node (e.g. "commit_top") we should skip
58826bd858b3SAlberto Garcia      * it because no one inherits from it. We use explicit_top for that. */
5883dcf3f9b2SMax Reitz     explicit_top = bdrv_skip_implicit_filters(explicit_top);
58846bd858b3SAlberto Garcia     update_inherits_from = bdrv_inherits_from_recursive(base, explicit_top);
58856bd858b3SAlberto Garcia 
58866ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
5887f30c66baSMax Reitz     if (!backing_file_str) {
5888f30c66baSMax Reitz         bdrv_refresh_filename(base);
5889f30c66baSMax Reitz         backing_file_str = base->filename;
5890f30c66baSMax Reitz     }
589112fa4af6SKevin Wolf 
5892d669ed6aSVladimir Sementsov-Ogievskiy     QLIST_FOREACH(c, &top->parents, next_parent) {
5893d669ed6aSVladimir Sementsov-Ogievskiy         updated_children = g_slist_prepend(updated_children, c);
5894d669ed6aSVladimir Sementsov-Ogievskiy     }
5895d669ed6aSVladimir Sementsov-Ogievskiy 
58963108a15cSVladimir Sementsov-Ogievskiy     /*
58973108a15cSVladimir Sementsov-Ogievskiy      * It seems correct to pass detach_subchain=true here, but it triggers
58983108a15cSVladimir Sementsov-Ogievskiy      * one more yet not fixed bug, when due to nested aio_poll loop we switch to
58993108a15cSVladimir Sementsov-Ogievskiy      * another drained section, which modify the graph (for example, removing
59003108a15cSVladimir Sementsov-Ogievskiy      * the child, which we keep in updated_children list). So, it's a TODO.
59013108a15cSVladimir Sementsov-Ogievskiy      *
59023108a15cSVladimir Sementsov-Ogievskiy      * Note, bug triggered if pass detach_subchain=true here and run
59033108a15cSVladimir Sementsov-Ogievskiy      * test-bdrv-drain. test_drop_intermediate_poll() test-case will crash.
59043108a15cSVladimir Sementsov-Ogievskiy      * That's a FIXME.
59053108a15cSVladimir Sementsov-Ogievskiy      */
59063108a15cSVladimir Sementsov-Ogievskiy     bdrv_replace_node_common(top, base, false, false, &local_err);
59076bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
59085c0ef495SKevin Wolf 
5909d669ed6aSVladimir Sementsov-Ogievskiy     if (local_err) {
591012fa4af6SKevin Wolf         error_report_err(local_err);
591112fa4af6SKevin Wolf         goto exit;
591212fa4af6SKevin Wolf     }
591361f09ceaSKevin Wolf 
5914d669ed6aSVladimir Sementsov-Ogievskiy     for (p = updated_children; p; p = p->next) {
5915d669ed6aSVladimir Sementsov-Ogievskiy         c = p->data;
5916d669ed6aSVladimir Sementsov-Ogievskiy 
5917bd86fb99SMax Reitz         if (c->klass->update_filename) {
5918bd86fb99SMax Reitz             ret = c->klass->update_filename(c, base, backing_file_str,
59194b028cbeSPeter Krempa                                             backing_mask_protocol,
592061f09ceaSKevin Wolf                                             &local_err);
592161f09ceaSKevin Wolf             if (ret < 0) {
5922d669ed6aSVladimir Sementsov-Ogievskiy                 /*
5923d669ed6aSVladimir Sementsov-Ogievskiy                  * TODO: Actually, we want to rollback all previous iterations
5924d669ed6aSVladimir Sementsov-Ogievskiy                  * of this loop, and (which is almost impossible) previous
5925d669ed6aSVladimir Sementsov-Ogievskiy                  * bdrv_replace_node()...
5926d669ed6aSVladimir Sementsov-Ogievskiy                  *
5927d669ed6aSVladimir Sementsov-Ogievskiy                  * Note, that c->klass->update_filename may lead to permission
5928d669ed6aSVladimir Sementsov-Ogievskiy                  * update, so it's a bad idea to call it inside permission
5929d669ed6aSVladimir Sementsov-Ogievskiy                  * update transaction of bdrv_replace_node.
5930d669ed6aSVladimir Sementsov-Ogievskiy                  */
593161f09ceaSKevin Wolf                 error_report_err(local_err);
593261f09ceaSKevin Wolf                 goto exit;
593361f09ceaSKevin Wolf             }
593461f09ceaSKevin Wolf         }
593561f09ceaSKevin Wolf     }
59366ebdcee2SJeff Cody 
59376bd858b3SAlberto Garcia     if (update_inherits_from) {
59386bd858b3SAlberto Garcia         base->inherits_from = explicit_top->inherits_from;
59396bd858b3SAlberto Garcia     }
59406bd858b3SAlberto Garcia 
59416ebdcee2SJeff Cody     ret = 0;
59425c0ef495SKevin Wolf     goto exit;
59435c0ef495SKevin Wolf 
59445c0ef495SKevin Wolf exit_wrlock:
59456bc30f19SStefan Hajnoczi     bdrv_graph_wrunlock();
59466ebdcee2SJeff Cody exit:
5947631086deSKevin Wolf     bdrv_drained_end(base);
59486858eba0SKevin Wolf     bdrv_unref(top);
59496ebdcee2SJeff Cody     return ret;
59506ebdcee2SJeff Cody }
59516ebdcee2SJeff Cody 
595283f64091Sbellard /**
595382618d7bSEmanuele Giuseppe Esposito  * Implementation of BlockDriver.bdrv_co_get_allocated_file_size() that
5954081e4650SMax Reitz  * sums the size of all data-bearing children.  (This excludes backing
5955081e4650SMax Reitz  * children.)
5956081e4650SMax Reitz  */
5957de335638SEmanuele Giuseppe Esposito static int64_t coroutine_fn GRAPH_RDLOCK
5958de335638SEmanuele Giuseppe Esposito bdrv_sum_allocated_file_size(BlockDriverState *bs)
5959081e4650SMax Reitz {
5960081e4650SMax Reitz     BdrvChild *child;
5961081e4650SMax Reitz     int64_t child_size, sum = 0;
5962081e4650SMax Reitz 
5963081e4650SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
5964081e4650SMax Reitz         if (child->role & (BDRV_CHILD_DATA | BDRV_CHILD_METADATA |
5965081e4650SMax Reitz                            BDRV_CHILD_FILTERED))
5966081e4650SMax Reitz         {
596782618d7bSEmanuele Giuseppe Esposito             child_size = bdrv_co_get_allocated_file_size(child->bs);
5968081e4650SMax Reitz             if (child_size < 0) {
5969081e4650SMax Reitz                 return child_size;
5970081e4650SMax Reitz             }
5971081e4650SMax Reitz             sum += child_size;
5972081e4650SMax Reitz         }
5973081e4650SMax Reitz     }
5974081e4650SMax Reitz 
5975081e4650SMax Reitz     return sum;
5976081e4650SMax Reitz }
5977081e4650SMax Reitz 
5978081e4650SMax Reitz /**
59794a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
59804a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
59814a1d5e1fSFam Zheng  */
598282618d7bSEmanuele Giuseppe Esposito int64_t coroutine_fn bdrv_co_get_allocated_file_size(BlockDriverState *bs)
59834a1d5e1fSFam Zheng {
59844a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
5985384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
5986de335638SEmanuele Giuseppe Esposito     assert_bdrv_graph_readable();
5987384a48fbSEmanuele Giuseppe Esposito 
59884a1d5e1fSFam Zheng     if (!drv) {
59894a1d5e1fSFam Zheng         return -ENOMEDIUM;
59904a1d5e1fSFam Zheng     }
599182618d7bSEmanuele Giuseppe Esposito     if (drv->bdrv_co_get_allocated_file_size) {
599282618d7bSEmanuele Giuseppe Esposito         return drv->bdrv_co_get_allocated_file_size(bs);
59934a1d5e1fSFam Zheng     }
5994081e4650SMax Reitz 
599541770f6eSPaolo Bonzini     if (drv->protocol_name) {
5996081e4650SMax Reitz         /*
5997081e4650SMax Reitz          * Protocol drivers default to -ENOTSUP (most of their data is
5998081e4650SMax Reitz          * not stored in any of their children (if they even have any),
5999081e4650SMax Reitz          * so there is no generic way to figure it out).
6000081e4650SMax Reitz          */
60014a1d5e1fSFam Zheng         return -ENOTSUP;
6002081e4650SMax Reitz     } else if (drv->is_filter) {
6003081e4650SMax Reitz         /* Filter drivers default to the size of their filtered child */
600482618d7bSEmanuele Giuseppe Esposito         return bdrv_co_get_allocated_file_size(bdrv_filter_bs(bs));
6005081e4650SMax Reitz     } else {
6006081e4650SMax Reitz         /* Other drivers default to summing their children's sizes */
6007081e4650SMax Reitz         return bdrv_sum_allocated_file_size(bs);
6008081e4650SMax Reitz     }
60094a1d5e1fSFam Zheng }
60104a1d5e1fSFam Zheng 
601190880ff1SStefan Hajnoczi /*
601290880ff1SStefan Hajnoczi  * bdrv_measure:
601390880ff1SStefan Hajnoczi  * @drv: Format driver
601490880ff1SStefan Hajnoczi  * @opts: Creation options for new image
601590880ff1SStefan Hajnoczi  * @in_bs: Existing image containing data for new image (may be NULL)
601690880ff1SStefan Hajnoczi  * @errp: Error object
601790880ff1SStefan Hajnoczi  * Returns: A #BlockMeasureInfo (free using qapi_free_BlockMeasureInfo())
601890880ff1SStefan Hajnoczi  *          or NULL on error
601990880ff1SStefan Hajnoczi  *
602090880ff1SStefan Hajnoczi  * Calculate file size required to create a new image.
602190880ff1SStefan Hajnoczi  *
602290880ff1SStefan Hajnoczi  * If @in_bs is given then space for allocated clusters and zero clusters
602390880ff1SStefan Hajnoczi  * from that image are included in the calculation.  If @opts contains a
602490880ff1SStefan Hajnoczi  * backing file that is shared by @in_bs then backing clusters may be omitted
602590880ff1SStefan Hajnoczi  * from the calculation.
602690880ff1SStefan Hajnoczi  *
602790880ff1SStefan Hajnoczi  * If @in_bs is NULL then the calculation includes no allocated clusters
602890880ff1SStefan Hajnoczi  * unless a preallocation option is given in @opts.
602990880ff1SStefan Hajnoczi  *
603090880ff1SStefan Hajnoczi  * Note that @in_bs may use a different BlockDriver from @drv.
603190880ff1SStefan Hajnoczi  *
603290880ff1SStefan Hajnoczi  * If an error occurs the @errp pointer is set.
603390880ff1SStefan Hajnoczi  */
603490880ff1SStefan Hajnoczi BlockMeasureInfo *bdrv_measure(BlockDriver *drv, QemuOpts *opts,
603590880ff1SStefan Hajnoczi                                BlockDriverState *in_bs, Error **errp)
603690880ff1SStefan Hajnoczi {
6037384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
603890880ff1SStefan Hajnoczi     if (!drv->bdrv_measure) {
603990880ff1SStefan Hajnoczi         error_setg(errp, "Block driver '%s' does not support size measurement",
604090880ff1SStefan Hajnoczi                    drv->format_name);
604190880ff1SStefan Hajnoczi         return NULL;
604290880ff1SStefan Hajnoczi     }
604390880ff1SStefan Hajnoczi 
604490880ff1SStefan Hajnoczi     return drv->bdrv_measure(opts, in_bs, errp);
604590880ff1SStefan Hajnoczi }
604690880ff1SStefan Hajnoczi 
60474a1d5e1fSFam Zheng /**
604865a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
604983f64091Sbellard  */
6050c86422c5SEmanuele Giuseppe Esposito int64_t coroutine_fn bdrv_co_nb_sectors(BlockDriverState *bs)
605183f64091Sbellard {
605283f64091Sbellard     BlockDriver *drv = bs->drv;
6053384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
60548ab8140aSKevin Wolf     assert_bdrv_graph_readable();
605565a9bb25SMarkus Armbruster 
605683f64091Sbellard     if (!drv)
605719cb3738Sbellard         return -ENOMEDIUM;
605851762288SStefan Hajnoczi 
6059160a29e2SPaolo Bonzini     if (bs->bl.has_variable_length) {
6060c86422c5SEmanuele Giuseppe Esposito         int ret = bdrv_co_refresh_total_sectors(bs, bs->total_sectors);
6061b94a2610SKevin Wolf         if (ret < 0) {
6062b94a2610SKevin Wolf             return ret;
6063fc01f7e7Sbellard         }
606446a4e4e6SStefan Hajnoczi     }
606565a9bb25SMarkus Armbruster     return bs->total_sectors;
606665a9bb25SMarkus Armbruster }
606765a9bb25SMarkus Armbruster 
606881f730d4SPaolo Bonzini /*
606981f730d4SPaolo Bonzini  * This wrapper is written by hand because this function is in the hot I/O path,
607081f730d4SPaolo Bonzini  * via blk_get_geometry.
607181f730d4SPaolo Bonzini  */
607281f730d4SPaolo Bonzini int64_t coroutine_mixed_fn bdrv_nb_sectors(BlockDriverState *bs)
607381f730d4SPaolo Bonzini {
607481f730d4SPaolo Bonzini     BlockDriver *drv = bs->drv;
607581f730d4SPaolo Bonzini     IO_CODE();
607681f730d4SPaolo Bonzini 
607781f730d4SPaolo Bonzini     if (!drv)
607881f730d4SPaolo Bonzini         return -ENOMEDIUM;
607981f730d4SPaolo Bonzini 
608081f730d4SPaolo Bonzini     if (bs->bl.has_variable_length) {
608181f730d4SPaolo Bonzini         int ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
608281f730d4SPaolo Bonzini         if (ret < 0) {
608381f730d4SPaolo Bonzini             return ret;
608481f730d4SPaolo Bonzini         }
608581f730d4SPaolo Bonzini     }
608681f730d4SPaolo Bonzini 
608781f730d4SPaolo Bonzini     return bs->total_sectors;
608881f730d4SPaolo Bonzini }
608981f730d4SPaolo Bonzini 
609065a9bb25SMarkus Armbruster /**
609165a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
609265a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
609365a9bb25SMarkus Armbruster  */
6094c86422c5SEmanuele Giuseppe Esposito int64_t coroutine_fn bdrv_co_getlength(BlockDriverState *bs)
609565a9bb25SMarkus Armbruster {
6096c86422c5SEmanuele Giuseppe Esposito     int64_t ret;
6097384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
60988ab8140aSKevin Wolf     assert_bdrv_graph_readable();
609965a9bb25SMarkus Armbruster 
6100c86422c5SEmanuele Giuseppe Esposito     ret = bdrv_co_nb_sectors(bs);
6101122860baSEric Blake     if (ret < 0) {
6102122860baSEric Blake         return ret;
6103122860baSEric Blake     }
6104122860baSEric Blake     if (ret > INT64_MAX / BDRV_SECTOR_SIZE) {
6105122860baSEric Blake         return -EFBIG;
6106122860baSEric Blake     }
6107122860baSEric Blake     return ret * BDRV_SECTOR_SIZE;
610846a4e4e6SStefan Hajnoczi }
6109fc01f7e7Sbellard 
611054115412SEric Blake bool bdrv_is_sg(BlockDriverState *bs)
6111985a03b0Sths {
6112384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6113985a03b0Sths     return bs->sg;
6114985a03b0Sths }
6115985a03b0Sths 
6116ae23f786SMax Reitz /**
6117ae23f786SMax Reitz  * Return whether the given node supports compressed writes.
6118ae23f786SMax Reitz  */
6119ae23f786SMax Reitz bool bdrv_supports_compressed_writes(BlockDriverState *bs)
6120ae23f786SMax Reitz {
6121ae23f786SMax Reitz     BlockDriverState *filtered;
6122384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6123ae23f786SMax Reitz 
6124ae23f786SMax Reitz     if (!bs->drv || !block_driver_can_compress(bs->drv)) {
6125ae23f786SMax Reitz         return false;
6126ae23f786SMax Reitz     }
6127ae23f786SMax Reitz 
6128ae23f786SMax Reitz     filtered = bdrv_filter_bs(bs);
6129ae23f786SMax Reitz     if (filtered) {
6130ae23f786SMax Reitz         /*
6131ae23f786SMax Reitz          * Filters can only forward compressed writes, so we have to
6132ae23f786SMax Reitz          * check the child.
6133ae23f786SMax Reitz          */
6134ae23f786SMax Reitz         return bdrv_supports_compressed_writes(filtered);
6135ae23f786SMax Reitz     }
6136ae23f786SMax Reitz 
6137ae23f786SMax Reitz     return true;
6138ae23f786SMax Reitz }
6139ae23f786SMax Reitz 
6140f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
6141ea2384d3Sbellard {
6142384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6143f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
6144ea2384d3Sbellard }
6145ea2384d3Sbellard 
6146ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
6147ada42401SStefan Hajnoczi {
6148ceff5bd7SMax Reitz     return strcmp(*(char *const *)a, *(char *const *)b);
6149ada42401SStefan Hajnoczi }
6150ada42401SStefan Hajnoczi 
6151ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
61529ac404c5SAndrey Shinkevich                          void *opaque, bool read_only)
6153ea2384d3Sbellard {
6154ea2384d3Sbellard     BlockDriver *drv;
6155e855e4fbSJeff Cody     int count = 0;
6156ada42401SStefan Hajnoczi     int i;
6157e855e4fbSJeff Cody     const char **formats = NULL;
6158ea2384d3Sbellard 
6159f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6160f791bf7fSEmanuele Giuseppe Esposito 
61618a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
6162e855e4fbSJeff Cody         if (drv->format_name) {
6163e855e4fbSJeff Cody             bool found = false;
61649ac404c5SAndrey Shinkevich 
61659ac404c5SAndrey Shinkevich             if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, read_only)) {
61669ac404c5SAndrey Shinkevich                 continue;
61679ac404c5SAndrey Shinkevich             }
61689ac404c5SAndrey Shinkevich 
6169fb2575f9SMarkus Armbruster             i = count;
6170e855e4fbSJeff Cody             while (formats && i && !found) {
6171e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
6172e855e4fbSJeff Cody             }
6173e855e4fbSJeff Cody 
6174e855e4fbSJeff Cody             if (!found) {
61755839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
6176e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
6177ea2384d3Sbellard             }
6178ea2384d3Sbellard         }
6179e855e4fbSJeff Cody     }
6180ada42401SStefan Hajnoczi 
6181eb0df69fSMax Reitz     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
6182eb0df69fSMax Reitz         const char *format_name = block_driver_modules[i].format_name;
6183eb0df69fSMax Reitz 
6184eb0df69fSMax Reitz         if (format_name) {
6185eb0df69fSMax Reitz             bool found = false;
6186eb0df69fSMax Reitz             int j = count;
6187eb0df69fSMax Reitz 
61889ac404c5SAndrey Shinkevich             if (use_bdrv_whitelist &&
61899ac404c5SAndrey Shinkevich                 !bdrv_format_is_whitelisted(format_name, read_only)) {
61909ac404c5SAndrey Shinkevich                 continue;
61919ac404c5SAndrey Shinkevich             }
61929ac404c5SAndrey Shinkevich 
6193eb0df69fSMax Reitz             while (formats && j && !found) {
6194eb0df69fSMax Reitz                 found = !strcmp(formats[--j], format_name);
6195eb0df69fSMax Reitz             }
6196eb0df69fSMax Reitz 
6197eb0df69fSMax Reitz             if (!found) {
6198eb0df69fSMax Reitz                 formats = g_renew(const char *, formats, count + 1);
6199eb0df69fSMax Reitz                 formats[count++] = format_name;
6200eb0df69fSMax Reitz             }
6201eb0df69fSMax Reitz         }
6202eb0df69fSMax Reitz     }
6203eb0df69fSMax Reitz 
6204ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
6205ada42401SStefan Hajnoczi 
6206ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
6207ada42401SStefan Hajnoczi         it(opaque, formats[i]);
6208ada42401SStefan Hajnoczi     }
6209ada42401SStefan Hajnoczi 
6210e855e4fbSJeff Cody     g_free(formats);
6211e855e4fbSJeff Cody }
6212ea2384d3Sbellard 
6213dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
6214dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
6215dc364f4cSBenoît Canet {
6216dc364f4cSBenoît Canet     BlockDriverState *bs;
6217dc364f4cSBenoît Canet 
6218dc364f4cSBenoît Canet     assert(node_name);
6219f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6220dc364f4cSBenoît Canet 
6221dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6222dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
6223dc364f4cSBenoît Canet             return bs;
6224dc364f4cSBenoît Canet         }
6225dc364f4cSBenoît Canet     }
6226dc364f4cSBenoît Canet     return NULL;
6227dc364f4cSBenoît Canet }
6228dc364f4cSBenoît Canet 
6229c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
6230facda544SPeter Krempa BlockDeviceInfoList *bdrv_named_nodes_list(bool flat,
6231facda544SPeter Krempa                                            Error **errp)
6232c13163fbSBenoît Canet {
62339812e712SEric Blake     BlockDeviceInfoList *list;
6234c13163fbSBenoît Canet     BlockDriverState *bs;
6235c13163fbSBenoît Canet 
6236f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6237b7cfc7d5SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6238f791bf7fSEmanuele Giuseppe Esposito 
6239c13163fbSBenoît Canet     list = NULL;
6240c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6241facda544SPeter Krempa         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, flat, errp);
6242d5a8ee60SAlberto Garcia         if (!info) {
6243d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
6244d5a8ee60SAlberto Garcia             return NULL;
6245d5a8ee60SAlberto Garcia         }
62469812e712SEric Blake         QAPI_LIST_PREPEND(list, info);
6247c13163fbSBenoît Canet     }
6248c13163fbSBenoît Canet 
6249c13163fbSBenoît Canet     return list;
6250c13163fbSBenoît Canet }
6251c13163fbSBenoît Canet 
62525d3b4e99SVladimir Sementsov-Ogievskiy typedef struct XDbgBlockGraphConstructor {
62535d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraph *graph;
62545d3b4e99SVladimir Sementsov-Ogievskiy     GHashTable *graph_nodes;
62555d3b4e99SVladimir Sementsov-Ogievskiy } XDbgBlockGraphConstructor;
62565d3b4e99SVladimir Sementsov-Ogievskiy 
62575d3b4e99SVladimir Sementsov-Ogievskiy static XDbgBlockGraphConstructor *xdbg_graph_new(void)
62585d3b4e99SVladimir Sementsov-Ogievskiy {
62595d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraphConstructor *gr = g_new(XDbgBlockGraphConstructor, 1);
62605d3b4e99SVladimir Sementsov-Ogievskiy 
62615d3b4e99SVladimir Sementsov-Ogievskiy     gr->graph = g_new0(XDbgBlockGraph, 1);
62625d3b4e99SVladimir Sementsov-Ogievskiy     gr->graph_nodes = g_hash_table_new(NULL, NULL);
62635d3b4e99SVladimir Sementsov-Ogievskiy 
62645d3b4e99SVladimir Sementsov-Ogievskiy     return gr;
62655d3b4e99SVladimir Sementsov-Ogievskiy }
62665d3b4e99SVladimir Sementsov-Ogievskiy 
62675d3b4e99SVladimir Sementsov-Ogievskiy static XDbgBlockGraph *xdbg_graph_finalize(XDbgBlockGraphConstructor *gr)
62685d3b4e99SVladimir Sementsov-Ogievskiy {
62695d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraph *graph = gr->graph;
62705d3b4e99SVladimir Sementsov-Ogievskiy 
62715d3b4e99SVladimir Sementsov-Ogievskiy     g_hash_table_destroy(gr->graph_nodes);
62725d3b4e99SVladimir Sementsov-Ogievskiy     g_free(gr);
62735d3b4e99SVladimir Sementsov-Ogievskiy 
62745d3b4e99SVladimir Sementsov-Ogievskiy     return graph;
62755d3b4e99SVladimir Sementsov-Ogievskiy }
62765d3b4e99SVladimir Sementsov-Ogievskiy 
62775d3b4e99SVladimir Sementsov-Ogievskiy static uintptr_t xdbg_graph_node_num(XDbgBlockGraphConstructor *gr, void *node)
62785d3b4e99SVladimir Sementsov-Ogievskiy {
62795d3b4e99SVladimir Sementsov-Ogievskiy     uintptr_t ret = (uintptr_t)g_hash_table_lookup(gr->graph_nodes, node);
62805d3b4e99SVladimir Sementsov-Ogievskiy 
62815d3b4e99SVladimir Sementsov-Ogievskiy     if (ret != 0) {
62825d3b4e99SVladimir Sementsov-Ogievskiy         return ret;
62835d3b4e99SVladimir Sementsov-Ogievskiy     }
62845d3b4e99SVladimir Sementsov-Ogievskiy 
62855d3b4e99SVladimir Sementsov-Ogievskiy     /*
62865d3b4e99SVladimir Sementsov-Ogievskiy      * Start counting from 1, not 0, because 0 interferes with not-found (NULL)
62875d3b4e99SVladimir Sementsov-Ogievskiy      * answer of g_hash_table_lookup.
62885d3b4e99SVladimir Sementsov-Ogievskiy      */
62895d3b4e99SVladimir Sementsov-Ogievskiy     ret = g_hash_table_size(gr->graph_nodes) + 1;
62905d3b4e99SVladimir Sementsov-Ogievskiy     g_hash_table_insert(gr->graph_nodes, node, (void *)ret);
62915d3b4e99SVladimir Sementsov-Ogievskiy 
62925d3b4e99SVladimir Sementsov-Ogievskiy     return ret;
62935d3b4e99SVladimir Sementsov-Ogievskiy }
62945d3b4e99SVladimir Sementsov-Ogievskiy 
62955d3b4e99SVladimir Sementsov-Ogievskiy static void xdbg_graph_add_node(XDbgBlockGraphConstructor *gr, void *node,
62965d3b4e99SVladimir Sementsov-Ogievskiy                                 XDbgBlockGraphNodeType type, const char *name)
62975d3b4e99SVladimir Sementsov-Ogievskiy {
62985d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraphNode *n;
62995d3b4e99SVladimir Sementsov-Ogievskiy 
63005d3b4e99SVladimir Sementsov-Ogievskiy     n = g_new0(XDbgBlockGraphNode, 1);
63015d3b4e99SVladimir Sementsov-Ogievskiy 
63025d3b4e99SVladimir Sementsov-Ogievskiy     n->id = xdbg_graph_node_num(gr, node);
63035d3b4e99SVladimir Sementsov-Ogievskiy     n->type = type;
63045d3b4e99SVladimir Sementsov-Ogievskiy     n->name = g_strdup(name);
63055d3b4e99SVladimir Sementsov-Ogievskiy 
63069812e712SEric Blake     QAPI_LIST_PREPEND(gr->graph->nodes, n);
63075d3b4e99SVladimir Sementsov-Ogievskiy }
63085d3b4e99SVladimir Sementsov-Ogievskiy 
63095d3b4e99SVladimir Sementsov-Ogievskiy static void xdbg_graph_add_edge(XDbgBlockGraphConstructor *gr, void *parent,
63105d3b4e99SVladimir Sementsov-Ogievskiy                                 const BdrvChild *child)
63115d3b4e99SVladimir Sementsov-Ogievskiy {
6312cdb1cec8SMax Reitz     BlockPermission qapi_perm;
63135d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraphEdge *edge;
6314862fded9SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
63155d3b4e99SVladimir Sementsov-Ogievskiy 
63165d3b4e99SVladimir Sementsov-Ogievskiy     edge = g_new0(XDbgBlockGraphEdge, 1);
63175d3b4e99SVladimir Sementsov-Ogievskiy 
63185d3b4e99SVladimir Sementsov-Ogievskiy     edge->parent = xdbg_graph_node_num(gr, parent);
63195d3b4e99SVladimir Sementsov-Ogievskiy     edge->child = xdbg_graph_node_num(gr, child->bs);
63205d3b4e99SVladimir Sementsov-Ogievskiy     edge->name = g_strdup(child->name);
63215d3b4e99SVladimir Sementsov-Ogievskiy 
6322cdb1cec8SMax Reitz     for (qapi_perm = 0; qapi_perm < BLOCK_PERMISSION__MAX; qapi_perm++) {
6323cdb1cec8SMax Reitz         uint64_t flag = bdrv_qapi_perm_to_blk_perm(qapi_perm);
6324cdb1cec8SMax Reitz 
6325cdb1cec8SMax Reitz         if (flag & child->perm) {
63269812e712SEric Blake             QAPI_LIST_PREPEND(edge->perm, qapi_perm);
63275d3b4e99SVladimir Sementsov-Ogievskiy         }
6328cdb1cec8SMax Reitz         if (flag & child->shared_perm) {
63299812e712SEric Blake             QAPI_LIST_PREPEND(edge->shared_perm, qapi_perm);
63305d3b4e99SVladimir Sementsov-Ogievskiy         }
63315d3b4e99SVladimir Sementsov-Ogievskiy     }
63325d3b4e99SVladimir Sementsov-Ogievskiy 
63339812e712SEric Blake     QAPI_LIST_PREPEND(gr->graph->edges, edge);
63345d3b4e99SVladimir Sementsov-Ogievskiy }
63355d3b4e99SVladimir Sementsov-Ogievskiy 
63365d3b4e99SVladimir Sementsov-Ogievskiy 
63375d3b4e99SVladimir Sementsov-Ogievskiy XDbgBlockGraph *bdrv_get_xdbg_block_graph(Error **errp)
63385d3b4e99SVladimir Sementsov-Ogievskiy {
63395d3b4e99SVladimir Sementsov-Ogievskiy     BlockBackend *blk;
63405d3b4e99SVladimir Sementsov-Ogievskiy     BlockJob *job;
63415d3b4e99SVladimir Sementsov-Ogievskiy     BlockDriverState *bs;
63425d3b4e99SVladimir Sementsov-Ogievskiy     BdrvChild *child;
63435d3b4e99SVladimir Sementsov-Ogievskiy     XDbgBlockGraphConstructor *gr = xdbg_graph_new();
63445d3b4e99SVladimir Sementsov-Ogievskiy 
6345f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6346f791bf7fSEmanuele Giuseppe Esposito 
63475d3b4e99SVladimir Sementsov-Ogievskiy     for (blk = blk_all_next(NULL); blk; blk = blk_all_next(blk)) {
63485d3b4e99SVladimir Sementsov-Ogievskiy         char *allocated_name = NULL;
63495d3b4e99SVladimir Sementsov-Ogievskiy         const char *name = blk_name(blk);
63505d3b4e99SVladimir Sementsov-Ogievskiy 
63515d3b4e99SVladimir Sementsov-Ogievskiy         if (!*name) {
63525d3b4e99SVladimir Sementsov-Ogievskiy             name = allocated_name = blk_get_attached_dev_id(blk);
63535d3b4e99SVladimir Sementsov-Ogievskiy         }
6354*bcd63b55SMarkus Armbruster         xdbg_graph_add_node(gr, blk, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_BACKEND,
63555d3b4e99SVladimir Sementsov-Ogievskiy                            name);
63565d3b4e99SVladimir Sementsov-Ogievskiy         g_free(allocated_name);
63575d3b4e99SVladimir Sementsov-Ogievskiy         if (blk_root(blk)) {
63585d3b4e99SVladimir Sementsov-Ogievskiy             xdbg_graph_add_edge(gr, blk, blk_root(blk));
63595d3b4e99SVladimir Sementsov-Ogievskiy         }
63605d3b4e99SVladimir Sementsov-Ogievskiy     }
63615d3b4e99SVladimir Sementsov-Ogievskiy 
6362880eeec6SEmanuele Giuseppe Esposito     WITH_JOB_LOCK_GUARD() {
6363880eeec6SEmanuele Giuseppe Esposito         for (job = block_job_next_locked(NULL); job;
6364880eeec6SEmanuele Giuseppe Esposito              job = block_job_next_locked(job)) {
63655d3b4e99SVladimir Sementsov-Ogievskiy             GSList *el;
63665d3b4e99SVladimir Sementsov-Ogievskiy 
6367*bcd63b55SMarkus Armbruster             xdbg_graph_add_node(gr, job, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_JOB,
63685d3b4e99SVladimir Sementsov-Ogievskiy                                 job->job.id);
63695d3b4e99SVladimir Sementsov-Ogievskiy             for (el = job->nodes; el; el = el->next) {
63705d3b4e99SVladimir Sementsov-Ogievskiy                 xdbg_graph_add_edge(gr, job, (BdrvChild *)el->data);
63715d3b4e99SVladimir Sementsov-Ogievskiy             }
63725d3b4e99SVladimir Sementsov-Ogievskiy         }
6373880eeec6SEmanuele Giuseppe Esposito     }
63745d3b4e99SVladimir Sementsov-Ogievskiy 
63755d3b4e99SVladimir Sementsov-Ogievskiy     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
6376*bcd63b55SMarkus Armbruster         xdbg_graph_add_node(gr, bs, XDBG_BLOCK_GRAPH_NODE_TYPE_BLOCK_DRIVER,
63775d3b4e99SVladimir Sementsov-Ogievskiy                            bs->node_name);
63785d3b4e99SVladimir Sementsov-Ogievskiy         QLIST_FOREACH(child, &bs->children, next) {
63795d3b4e99SVladimir Sementsov-Ogievskiy             xdbg_graph_add_edge(gr, bs, child);
63805d3b4e99SVladimir Sementsov-Ogievskiy         }
63815d3b4e99SVladimir Sementsov-Ogievskiy     }
63825d3b4e99SVladimir Sementsov-Ogievskiy 
63835d3b4e99SVladimir Sementsov-Ogievskiy     return xdbg_graph_finalize(gr);
63845d3b4e99SVladimir Sementsov-Ogievskiy }
63855d3b4e99SVladimir Sementsov-Ogievskiy 
638612d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
638712d3ba82SBenoît Canet                                  const char *node_name,
638812d3ba82SBenoît Canet                                  Error **errp)
638912d3ba82SBenoît Canet {
63907f06d47eSMarkus Armbruster     BlockBackend *blk;
63917f06d47eSMarkus Armbruster     BlockDriverState *bs;
639212d3ba82SBenoît Canet 
6393f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6394f791bf7fSEmanuele Giuseppe Esposito 
639512d3ba82SBenoît Canet     if (device) {
63967f06d47eSMarkus Armbruster         blk = blk_by_name(device);
639712d3ba82SBenoît Canet 
63987f06d47eSMarkus Armbruster         if (blk) {
63999f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
64009f4ed6fbSAlberto Garcia             if (!bs) {
64015433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
64025433c24fSMax Reitz             }
64035433c24fSMax Reitz 
64049f4ed6fbSAlberto Garcia             return bs;
640512d3ba82SBenoît Canet         }
6406dd67fa50SBenoît Canet     }
640712d3ba82SBenoît Canet 
6408dd67fa50SBenoît Canet     if (node_name) {
640912d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
641012d3ba82SBenoît Canet 
6411dd67fa50SBenoît Canet         if (bs) {
6412dd67fa50SBenoît Canet             return bs;
6413dd67fa50SBenoît Canet         }
641412d3ba82SBenoît Canet     }
641512d3ba82SBenoît Canet 
6416785ec4b1SConnor Kuehl     error_setg(errp, "Cannot find device=\'%s\' nor node-name=\'%s\'",
6417dd67fa50SBenoît Canet                      device ? device : "",
6418dd67fa50SBenoît Canet                      node_name ? node_name : "");
6419dd67fa50SBenoît Canet     return NULL;
642012d3ba82SBenoît Canet }
642112d3ba82SBenoît Canet 
64225a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
64235a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
64245a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
64255a6684d2SJeff Cody {
6426f791bf7fSEmanuele Giuseppe Esposito 
6427f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6428f791bf7fSEmanuele Giuseppe Esposito 
64295a6684d2SJeff Cody     while (top && top != base) {
6430dcf3f9b2SMax Reitz         top = bdrv_filter_or_cow_bs(top);
64315a6684d2SJeff Cody     }
64325a6684d2SJeff Cody 
64335a6684d2SJeff Cody     return top != NULL;
64345a6684d2SJeff Cody }
64355a6684d2SJeff Cody 
643604df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
643704df765aSFam Zheng {
6438f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
643904df765aSFam Zheng     if (!bs) {
644004df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
644104df765aSFam Zheng     }
644204df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
644304df765aSFam Zheng }
644404df765aSFam Zheng 
64450f12264eSKevin Wolf BlockDriverState *bdrv_next_all_states(BlockDriverState *bs)
64460f12264eSKevin Wolf {
6447f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
64480f12264eSKevin Wolf     if (!bs) {
64490f12264eSKevin Wolf         return QTAILQ_FIRST(&all_bdrv_states);
64500f12264eSKevin Wolf     }
64510f12264eSKevin Wolf     return QTAILQ_NEXT(bs, bs_list);
64520f12264eSKevin Wolf }
64530f12264eSKevin Wolf 
645420a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
645520a9e77dSFam Zheng {
6456384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
645720a9e77dSFam Zheng     return bs->node_name;
645820a9e77dSFam Zheng }
645920a9e77dSFam Zheng 
64601f0c461bSKevin Wolf const char *bdrv_get_parent_name(const BlockDriverState *bs)
64614c265bf9SKevin Wolf {
64624c265bf9SKevin Wolf     BdrvChild *c;
64634c265bf9SKevin Wolf     const char *name;
6464967d7905SEmanuele Giuseppe Esposito     IO_CODE();
64654c265bf9SKevin Wolf 
64664c265bf9SKevin Wolf     /* If multiple parents have a name, just pick the first one. */
64674c265bf9SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
6468bd86fb99SMax Reitz         if (c->klass->get_name) {
6469bd86fb99SMax Reitz             name = c->klass->get_name(c);
64704c265bf9SKevin Wolf             if (name && *name) {
64714c265bf9SKevin Wolf                 return name;
64724c265bf9SKevin Wolf             }
64734c265bf9SKevin Wolf         }
64744c265bf9SKevin Wolf     }
64754c265bf9SKevin Wolf 
64764c265bf9SKevin Wolf     return NULL;
64774c265bf9SKevin Wolf }
64784c265bf9SKevin Wolf 
64797f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
6480bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
6481ea2384d3Sbellard {
6482384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
64834c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: "";
6484ea2384d3Sbellard }
6485ea2384d3Sbellard 
64869b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
64879b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
64889b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
64899b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
64909b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
64919b2aa84fSAlberto Garcia {
6492384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
64934c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: bs->node_name;
64949b2aa84fSAlberto Garcia }
64959b2aa84fSAlberto Garcia 
6496c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
6497c8433287SMarkus Armbruster {
649815aee7acSHanna Reitz     IO_CODE();
6499c8433287SMarkus Armbruster     return bs->open_flags;
6500c8433287SMarkus Armbruster }
6501c8433287SMarkus Armbruster 
65023ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
65033ac21627SPeter Lieven {
6504f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
65053ac21627SPeter Lieven     return 1;
65063ac21627SPeter Lieven }
65073ac21627SPeter Lieven 
650806717986SKevin Wolf int coroutine_mixed_fn bdrv_has_zero_init(BlockDriverState *bs)
6509f2feebbdSKevin Wolf {
651093393e69SMax Reitz     BlockDriverState *filtered;
6511f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
651293393e69SMax Reitz 
6513d470ad42SMax Reitz     if (!bs->drv) {
6514d470ad42SMax Reitz         return 0;
6515d470ad42SMax Reitz     }
6516f2feebbdSKevin Wolf 
651711212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
651811212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
651934778172SMax Reitz     if (bdrv_cow_child(bs)) {
652011212d8fSPaolo Bonzini         return 0;
652111212d8fSPaolo Bonzini     }
6522336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
6523336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
6524f2feebbdSKevin Wolf     }
652593393e69SMax Reitz 
652693393e69SMax Reitz     filtered = bdrv_filter_bs(bs);
652793393e69SMax Reitz     if (filtered) {
652893393e69SMax Reitz         return bdrv_has_zero_init(filtered);
65295a612c00SManos Pitsidianakis     }
6530f2feebbdSKevin Wolf 
65313ac21627SPeter Lieven     /* safe default */
65323ac21627SPeter Lieven     return 0;
6533f2feebbdSKevin Wolf }
6534f2feebbdSKevin Wolf 
65354ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
65364ce78691SPeter Lieven {
6537384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
65382f0342efSDenis V. Lunev     if (!(bs->open_flags & BDRV_O_UNMAP)) {
65394ce78691SPeter Lieven         return false;
65404ce78691SPeter Lieven     }
65414ce78691SPeter Lieven 
6542e24d813bSEric Blake     return bs->supported_zero_flags & BDRV_REQ_MAY_UNMAP;
65434ce78691SPeter Lieven }
65444ce78691SPeter Lieven 
654583f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
654683f64091Sbellard                                char *filename, int filename_size)
654783f64091Sbellard {
6548384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
654983f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
655083f64091Sbellard }
655183f64091Sbellard 
65523d47eb0aSEmanuele Giuseppe Esposito int coroutine_fn bdrv_co_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
6553faea38e7Sbellard {
65548b117001SVladimir Sementsov-Ogievskiy     int ret;
6555faea38e7Sbellard     BlockDriver *drv = bs->drv;
6556384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6557a00e70c0SEmanuele Giuseppe Esposito     assert_bdrv_graph_readable();
6558a00e70c0SEmanuele Giuseppe Esposito 
65595a612c00SManos Pitsidianakis     /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
65605a612c00SManos Pitsidianakis     if (!drv) {
656119cb3738Sbellard         return -ENOMEDIUM;
65625a612c00SManos Pitsidianakis     }
65633d47eb0aSEmanuele Giuseppe Esposito     if (!drv->bdrv_co_get_info) {
656493393e69SMax Reitz         BlockDriverState *filtered = bdrv_filter_bs(bs);
656593393e69SMax Reitz         if (filtered) {
65663d47eb0aSEmanuele Giuseppe Esposito             return bdrv_co_get_info(filtered, bdi);
65675a612c00SManos Pitsidianakis         }
6568faea38e7Sbellard         return -ENOTSUP;
65695a612c00SManos Pitsidianakis     }
6570faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
65713d47eb0aSEmanuele Giuseppe Esposito     ret = drv->bdrv_co_get_info(bs, bdi);
6572c54483b6SAndrey Drobyshev     if (bdi->subcluster_size == 0) {
6573c54483b6SAndrey Drobyshev         /*
6574c54483b6SAndrey Drobyshev          * If the driver left this unset, subclusters are not supported.
6575c54483b6SAndrey Drobyshev          * Then it is safe to treat each cluster as having only one subcluster.
6576c54483b6SAndrey Drobyshev          */
6577c54483b6SAndrey Drobyshev         bdi->subcluster_size = bdi->cluster_size;
6578c54483b6SAndrey Drobyshev     }
65798b117001SVladimir Sementsov-Ogievskiy     if (ret < 0) {
65808b117001SVladimir Sementsov-Ogievskiy         return ret;
65818b117001SVladimir Sementsov-Ogievskiy     }
65828b117001SVladimir Sementsov-Ogievskiy 
65838b117001SVladimir Sementsov-Ogievskiy     if (bdi->cluster_size > BDRV_MAX_ALIGNMENT) {
65848b117001SVladimir Sementsov-Ogievskiy         return -EINVAL;
65858b117001SVladimir Sementsov-Ogievskiy     }
65868b117001SVladimir Sementsov-Ogievskiy 
65878b117001SVladimir Sementsov-Ogievskiy     return 0;
6588faea38e7Sbellard }
6589faea38e7Sbellard 
65901bf6e9caSAndrey Shinkevich ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs,
65911bf6e9caSAndrey Shinkevich                                           Error **errp)
6592eae041feSMax Reitz {
6593eae041feSMax Reitz     BlockDriver *drv = bs->drv;
6594384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6595eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
65961bf6e9caSAndrey Shinkevich         return drv->bdrv_get_specific_info(bs, errp);
6597eae041feSMax Reitz     }
6598eae041feSMax Reitz     return NULL;
6599eae041feSMax Reitz }
6600eae041feSMax Reitz 
6601d9245599SAnton Nefedov BlockStatsSpecific *bdrv_get_specific_stats(BlockDriverState *bs)
6602d9245599SAnton Nefedov {
6603d9245599SAnton Nefedov     BlockDriver *drv = bs->drv;
6604384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6605d9245599SAnton Nefedov     if (!drv || !drv->bdrv_get_specific_stats) {
6606d9245599SAnton Nefedov         return NULL;
6607d9245599SAnton Nefedov     }
6608d9245599SAnton Nefedov     return drv->bdrv_get_specific_stats(bs);
6609d9245599SAnton Nefedov }
6610d9245599SAnton Nefedov 
6611c834dc05SEmanuele Giuseppe Esposito void coroutine_fn bdrv_co_debug_event(BlockDriverState *bs, BlkdebugEvent event)
66128b9b0cc2SKevin Wolf {
6613384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
6614cb2bfaa4SEmanuele Giuseppe Esposito     assert_bdrv_graph_readable();
6615cb2bfaa4SEmanuele Giuseppe Esposito 
6616c834dc05SEmanuele Giuseppe Esposito     if (!bs || !bs->drv || !bs->drv->bdrv_co_debug_event) {
66178b9b0cc2SKevin Wolf         return;
66188b9b0cc2SKevin Wolf     }
66198b9b0cc2SKevin Wolf 
6620c834dc05SEmanuele Giuseppe Esposito     bs->drv->bdrv_co_debug_event(bs, event);
662141c695c7SKevin Wolf }
66228b9b0cc2SKevin Wolf 
6623c0fc5123SKevin Wolf static BlockDriverState * GRAPH_RDLOCK
6624c0fc5123SKevin Wolf bdrv_find_debug_node(BlockDriverState *bs)
662541c695c7SKevin Wolf {
6626bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
662741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
6628f706a92fSMax Reitz         bs = bdrv_primary_bs(bs);
662941c695c7SKevin Wolf     }
663041c695c7SKevin Wolf 
663141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
6632d10529a2SVladimir Sementsov-Ogievskiy         assert(bs->drv->bdrv_debug_remove_breakpoint);
6633d10529a2SVladimir Sementsov-Ogievskiy         return bs;
6634d10529a2SVladimir Sementsov-Ogievskiy     }
6635d10529a2SVladimir Sementsov-Ogievskiy 
6636d10529a2SVladimir Sementsov-Ogievskiy     return NULL;
6637d10529a2SVladimir Sementsov-Ogievskiy }
6638d10529a2SVladimir Sementsov-Ogievskiy 
6639d10529a2SVladimir Sementsov-Ogievskiy int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
6640d10529a2SVladimir Sementsov-Ogievskiy                           const char *tag)
6641d10529a2SVladimir Sementsov-Ogievskiy {
6642f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6643c0fc5123SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6644c0fc5123SKevin Wolf 
6645d10529a2SVladimir Sementsov-Ogievskiy     bs = bdrv_find_debug_node(bs);
6646d10529a2SVladimir Sementsov-Ogievskiy     if (bs) {
664741c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
664841c695c7SKevin Wolf     }
664941c695c7SKevin Wolf 
665041c695c7SKevin Wolf     return -ENOTSUP;
665141c695c7SKevin Wolf }
665241c695c7SKevin Wolf 
66534cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
66544cc70e93SFam Zheng {
6655f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6656c0fc5123SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6657c0fc5123SKevin Wolf 
6658d10529a2SVladimir Sementsov-Ogievskiy     bs = bdrv_find_debug_node(bs);
6659d10529a2SVladimir Sementsov-Ogievskiy     if (bs) {
66604cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
66614cc70e93SFam Zheng     }
66624cc70e93SFam Zheng 
66634cc70e93SFam Zheng     return -ENOTSUP;
66644cc70e93SFam Zheng }
66654cc70e93SFam Zheng 
666641c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
666741c695c7SKevin Wolf {
6668f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6669c0fc5123SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6670c0fc5123SKevin Wolf 
6671938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
6672f706a92fSMax Reitz         bs = bdrv_primary_bs(bs);
667341c695c7SKevin Wolf     }
667441c695c7SKevin Wolf 
667541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
667641c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
667741c695c7SKevin Wolf     }
667841c695c7SKevin Wolf 
667941c695c7SKevin Wolf     return -ENOTSUP;
668041c695c7SKevin Wolf }
668141c695c7SKevin Wolf 
668241c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
668341c695c7SKevin Wolf {
6684f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6685c0fc5123SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6686c0fc5123SKevin Wolf 
668741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
6688f706a92fSMax Reitz         bs = bdrv_primary_bs(bs);
668941c695c7SKevin Wolf     }
669041c695c7SKevin Wolf 
669141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
669241c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
669341c695c7SKevin Wolf     }
669441c695c7SKevin Wolf 
669541c695c7SKevin Wolf     return false;
66968b9b0cc2SKevin Wolf }
66978b9b0cc2SKevin Wolf 
6698b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
6699b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
6700b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
6701b1b1d783SJeff Cody  * the CWD rather than the chain. */
6702e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
6703e8a6bb9cSMarcelo Tosatti         const char *backing_file)
6704e8a6bb9cSMarcelo Tosatti {
6705b1b1d783SJeff Cody     char *filename_full = NULL;
6706b1b1d783SJeff Cody     char *backing_file_full = NULL;
6707b1b1d783SJeff Cody     char *filename_tmp = NULL;
6708b1b1d783SJeff Cody     int is_protocol = 0;
67090b877d09SMax Reitz     bool filenames_refreshed = false;
6710b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
6711b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
6712dcf3f9b2SMax Reitz     BlockDriverState *bs_below;
6713b1b1d783SJeff Cody 
6714f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6715b7cfc7d5SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6716f791bf7fSEmanuele Giuseppe Esposito 
6717b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
6718e8a6bb9cSMarcelo Tosatti         return NULL;
6719e8a6bb9cSMarcelo Tosatti     }
6720e8a6bb9cSMarcelo Tosatti 
6721b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
6722b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
6723b1b1d783SJeff Cody 
6724b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
6725b1b1d783SJeff Cody 
6726dcf3f9b2SMax Reitz     /*
6727dcf3f9b2SMax Reitz      * Being largely a legacy function, skip any filters here
6728dcf3f9b2SMax Reitz      * (because filters do not have normal filenames, so they cannot
6729dcf3f9b2SMax Reitz      * match anyway; and allowing json:{} filenames is a bit out of
6730dcf3f9b2SMax Reitz      * scope).
6731dcf3f9b2SMax Reitz      */
6732dcf3f9b2SMax Reitz     for (curr_bs = bdrv_skip_filters(bs);
6733dcf3f9b2SMax Reitz          bdrv_cow_child(curr_bs) != NULL;
6734dcf3f9b2SMax Reitz          curr_bs = bs_below)
6735dcf3f9b2SMax Reitz     {
6736dcf3f9b2SMax Reitz         bs_below = bdrv_backing_chain_next(curr_bs);
6737b1b1d783SJeff Cody 
67380b877d09SMax Reitz         if (bdrv_backing_overridden(curr_bs)) {
67390b877d09SMax Reitz             /*
67400b877d09SMax Reitz              * If the backing file was overridden, we can only compare
67410b877d09SMax Reitz              * directly against the backing node's filename.
67420b877d09SMax Reitz              */
67430b877d09SMax Reitz 
67440b877d09SMax Reitz             if (!filenames_refreshed) {
67450b877d09SMax Reitz                 /*
67460b877d09SMax Reitz                  * This will automatically refresh all of the
67470b877d09SMax Reitz                  * filenames in the rest of the backing chain, so we
67480b877d09SMax Reitz                  * only need to do this once.
67490b877d09SMax Reitz                  */
67500b877d09SMax Reitz                 bdrv_refresh_filename(bs_below);
67510b877d09SMax Reitz                 filenames_refreshed = true;
67520b877d09SMax Reitz             }
67530b877d09SMax Reitz 
67540b877d09SMax Reitz             if (strcmp(backing_file, bs_below->filename) == 0) {
67550b877d09SMax Reitz                 retval = bs_below;
67560b877d09SMax Reitz                 break;
67570b877d09SMax Reitz             }
67580b877d09SMax Reitz         } else if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
67590b877d09SMax Reitz             /*
67600b877d09SMax Reitz              * If either of the filename paths is actually a protocol, then
67610b877d09SMax Reitz              * compare unmodified paths; otherwise make paths relative.
67620b877d09SMax Reitz              */
67636b6833c1SMax Reitz             char *backing_file_full_ret;
67646b6833c1SMax Reitz 
6765b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
6766dcf3f9b2SMax Reitz                 retval = bs_below;
6767b1b1d783SJeff Cody                 break;
6768b1b1d783SJeff Cody             }
6769418661e0SJeff Cody             /* Also check against the full backing filename for the image */
67706b6833c1SMax Reitz             backing_file_full_ret = bdrv_get_full_backing_filename(curr_bs,
67716b6833c1SMax Reitz                                                                    NULL);
67726b6833c1SMax Reitz             if (backing_file_full_ret) {
67736b6833c1SMax Reitz                 bool equal = strcmp(backing_file, backing_file_full_ret) == 0;
67746b6833c1SMax Reitz                 g_free(backing_file_full_ret);
67756b6833c1SMax Reitz                 if (equal) {
6776dcf3f9b2SMax Reitz                     retval = bs_below;
6777418661e0SJeff Cody                     break;
6778418661e0SJeff Cody                 }
6779418661e0SJeff Cody             }
6780e8a6bb9cSMarcelo Tosatti         } else {
6781b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
6782b1b1d783SJeff Cody              * image's filename path */
67832d9158ceSMax Reitz             filename_tmp = bdrv_make_absolute_filename(curr_bs, backing_file,
67842d9158ceSMax Reitz                                                        NULL);
67852d9158ceSMax Reitz             /* We are going to compare canonicalized absolute pathnames */
67862d9158ceSMax Reitz             if (!filename_tmp || !realpath(filename_tmp, filename_full)) {
67872d9158ceSMax Reitz                 g_free(filename_tmp);
6788b1b1d783SJeff Cody                 continue;
6789b1b1d783SJeff Cody             }
67902d9158ceSMax Reitz             g_free(filename_tmp);
6791b1b1d783SJeff Cody 
6792b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
6793b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
67942d9158ceSMax Reitz             filename_tmp = bdrv_get_full_backing_filename(curr_bs, NULL);
67952d9158ceSMax Reitz             if (!filename_tmp || !realpath(filename_tmp, backing_file_full)) {
67962d9158ceSMax Reitz                 g_free(filename_tmp);
6797b1b1d783SJeff Cody                 continue;
6798b1b1d783SJeff Cody             }
67992d9158ceSMax Reitz             g_free(filename_tmp);
6800b1b1d783SJeff Cody 
6801b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
6802dcf3f9b2SMax Reitz                 retval = bs_below;
6803b1b1d783SJeff Cody                 break;
6804b1b1d783SJeff Cody             }
6805e8a6bb9cSMarcelo Tosatti         }
6806e8a6bb9cSMarcelo Tosatti     }
6807e8a6bb9cSMarcelo Tosatti 
6808b1b1d783SJeff Cody     g_free(filename_full);
6809b1b1d783SJeff Cody     g_free(backing_file_full);
6810b1b1d783SJeff Cody     return retval;
6811e8a6bb9cSMarcelo Tosatti }
6812e8a6bb9cSMarcelo Tosatti 
6813ea2384d3Sbellard void bdrv_init(void)
6814ea2384d3Sbellard {
6815e5f05f8cSKevin Wolf #ifdef CONFIG_BDRV_WHITELIST_TOOLS
6816e5f05f8cSKevin Wolf     use_bdrv_whitelist = 1;
6817e5f05f8cSKevin Wolf #endif
68185efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
6819ea2384d3Sbellard }
6820ce1a14dcSpbrook 
6821eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
6822eb852011SMarkus Armbruster {
6823eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
6824eb852011SMarkus Armbruster     bdrv_init();
6825eb852011SMarkus Armbruster }
6826eb852011SMarkus Armbruster 
6827a94750d9SEmanuele Giuseppe Esposito int bdrv_activate(BlockDriverState *bs, Error **errp)
6828a94750d9SEmanuele Giuseppe Esposito {
68294417ab7aSKevin Wolf     BdrvChild *child, *parent;
68305a8a30dbSKevin Wolf     Error *local_err = NULL;
68315a8a30dbSKevin Wolf     int ret;
68329c98f145SVladimir Sementsov-Ogievskiy     BdrvDirtyBitmap *bm;
68335a8a30dbSKevin Wolf 
6834f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
68353804e3cfSKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6836f791bf7fSEmanuele Giuseppe Esposito 
68373456a8d1SKevin Wolf     if (!bs->drv)  {
68385416645fSVladimir Sementsov-Ogievskiy         return -ENOMEDIUM;
68390f15423cSAnthony Liguori     }
68403456a8d1SKevin Wolf 
684116e977d5SVladimir Sementsov-Ogievskiy     QLIST_FOREACH(child, &bs->children, next) {
684211d0c9b3SEmanuele Giuseppe Esposito         bdrv_activate(child->bs, &local_err);
68435a8a30dbSKevin Wolf         if (local_err) {
68445a8a30dbSKevin Wolf             error_propagate(errp, local_err);
68455416645fSVladimir Sementsov-Ogievskiy             return -EINVAL;
68463456a8d1SKevin Wolf         }
68470d1c5c91SFam Zheng     }
68480d1c5c91SFam Zheng 
6849dafe0960SKevin Wolf     /*
6850dafe0960SKevin Wolf      * Update permissions, they may differ for inactive nodes.
6851dafe0960SKevin Wolf      *
6852dafe0960SKevin Wolf      * Note that the required permissions of inactive images are always a
6853dafe0960SKevin Wolf      * subset of the permissions required after activating the image. This
6854dafe0960SKevin Wolf      * allows us to just get the permissions upfront without restricting
685511d0c9b3SEmanuele Giuseppe Esposito      * bdrv_co_invalidate_cache().
6856dafe0960SKevin Wolf      *
6857dafe0960SKevin Wolf      * It also means that in error cases, we don't have to try and revert to
6858dafe0960SKevin Wolf      * the old permissions (which is an operation that could fail, too). We can
6859dafe0960SKevin Wolf      * just keep the extended permissions for the next time that an activation
6860dafe0960SKevin Wolf      * of the image is tried.
6861dafe0960SKevin Wolf      */
68627bb4941aSKevin Wolf     if (bs->open_flags & BDRV_O_INACTIVE) {
686316e977d5SVladimir Sementsov-Ogievskiy         bs->open_flags &= ~BDRV_O_INACTIVE;
6864f1316edbSVladimir Sementsov-Ogievskiy         ret = bdrv_refresh_perms(bs, NULL, errp);
6865dafe0960SKevin Wolf         if (ret < 0) {
6866dafe0960SKevin Wolf             bs->open_flags |= BDRV_O_INACTIVE;
68675416645fSVladimir Sementsov-Ogievskiy             return ret;
6868dafe0960SKevin Wolf         }
6869dafe0960SKevin Wolf 
687011d0c9b3SEmanuele Giuseppe Esposito         ret = bdrv_invalidate_cache(bs, errp);
687111d0c9b3SEmanuele Giuseppe Esposito         if (ret < 0) {
68720d1c5c91SFam Zheng             bs->open_flags |= BDRV_O_INACTIVE;
687311d0c9b3SEmanuele Giuseppe Esposito             return ret;
68740d1c5c91SFam Zheng         }
68753456a8d1SKevin Wolf 
6876ef9041a7SVladimir Sementsov-Ogievskiy         FOR_EACH_DIRTY_BITMAP(bs, bm) {
6877c4e4b0faSJohn Snow             bdrv_dirty_bitmap_skip_store(bm, false);
68789c98f145SVladimir Sementsov-Ogievskiy         }
68799c98f145SVladimir Sementsov-Ogievskiy 
6880c057960cSEmanuele Giuseppe Esposito         ret = bdrv_refresh_total_sectors(bs, bs->total_sectors);
68815a8a30dbSKevin Wolf         if (ret < 0) {
688204c01a5cSKevin Wolf             bs->open_flags |= BDRV_O_INACTIVE;
68835a8a30dbSKevin Wolf             error_setg_errno(errp, -ret, "Could not refresh total sector count");
68845416645fSVladimir Sementsov-Ogievskiy             return ret;
68855a8a30dbSKevin Wolf         }
68867bb4941aSKevin Wolf     }
68874417ab7aSKevin Wolf 
68884417ab7aSKevin Wolf     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6889bd86fb99SMax Reitz         if (parent->klass->activate) {
6890bd86fb99SMax Reitz             parent->klass->activate(parent, &local_err);
68914417ab7aSKevin Wolf             if (local_err) {
689278fc3b3aSKevin Wolf                 bs->open_flags |= BDRV_O_INACTIVE;
68934417ab7aSKevin Wolf                 error_propagate(errp, local_err);
68945416645fSVladimir Sementsov-Ogievskiy                 return -EINVAL;
68954417ab7aSKevin Wolf             }
68964417ab7aSKevin Wolf         }
68974417ab7aSKevin Wolf     }
68985416645fSVladimir Sementsov-Ogievskiy 
68995416645fSVladimir Sementsov-Ogievskiy     return 0;
69000f15423cSAnthony Liguori }
69010f15423cSAnthony Liguori 
690211d0c9b3SEmanuele Giuseppe Esposito int coroutine_fn bdrv_co_invalidate_cache(BlockDriverState *bs, Error **errp)
690311d0c9b3SEmanuele Giuseppe Esposito {
690411d0c9b3SEmanuele Giuseppe Esposito     Error *local_err = NULL;
69051581a70dSEmanuele Giuseppe Esposito     IO_CODE();
690611d0c9b3SEmanuele Giuseppe Esposito 
690711d0c9b3SEmanuele Giuseppe Esposito     assert(!(bs->open_flags & BDRV_O_INACTIVE));
69081b3ff9feSKevin Wolf     assert_bdrv_graph_readable();
690911d0c9b3SEmanuele Giuseppe Esposito 
691011d0c9b3SEmanuele Giuseppe Esposito     if (bs->drv->bdrv_co_invalidate_cache) {
691111d0c9b3SEmanuele Giuseppe Esposito         bs->drv->bdrv_co_invalidate_cache(bs, &local_err);
691211d0c9b3SEmanuele Giuseppe Esposito         if (local_err) {
691311d0c9b3SEmanuele Giuseppe Esposito             error_propagate(errp, local_err);
691411d0c9b3SEmanuele Giuseppe Esposito             return -EINVAL;
691511d0c9b3SEmanuele Giuseppe Esposito         }
691611d0c9b3SEmanuele Giuseppe Esposito     }
691711d0c9b3SEmanuele Giuseppe Esposito 
691811d0c9b3SEmanuele Giuseppe Esposito     return 0;
691911d0c9b3SEmanuele Giuseppe Esposito }
692011d0c9b3SEmanuele Giuseppe Esposito 
69213b717194SEmanuele Giuseppe Esposito void bdrv_activate_all(Error **errp)
69220f15423cSAnthony Liguori {
69237c8eece4SKevin Wolf     BlockDriverState *bs;
692488be7b4bSKevin Wolf     BdrvNextIterator it;
69250f15423cSAnthony Liguori 
6926f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
69272b3912f1SKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
6928f791bf7fSEmanuele Giuseppe Esposito 
692988be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
69305416645fSVladimir Sementsov-Ogievskiy         int ret;
6931ed78cda3SStefan Hajnoczi 
6932a94750d9SEmanuele Giuseppe Esposito         ret = bdrv_activate(bs, errp);
69335416645fSVladimir Sementsov-Ogievskiy         if (ret < 0) {
69345e003f17SMax Reitz             bdrv_next_cleanup(&it);
69355a8a30dbSKevin Wolf             return;
69365a8a30dbSKevin Wolf         }
69370f15423cSAnthony Liguori     }
69380f15423cSAnthony Liguori }
69390f15423cSAnthony Liguori 
69400e6bad1fSKevin Wolf static bool GRAPH_RDLOCK
69410e6bad1fSKevin Wolf bdrv_has_bds_parent(BlockDriverState *bs, bool only_active)
69429e37271fSKevin Wolf {
69439e37271fSKevin Wolf     BdrvChild *parent;
6944bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
69459e37271fSKevin Wolf 
69469e37271fSKevin Wolf     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6947bd86fb99SMax Reitz         if (parent->klass->parent_is_bds) {
69489e37271fSKevin Wolf             BlockDriverState *parent_bs = parent->opaque;
69499e37271fSKevin Wolf             if (!only_active || !(parent_bs->open_flags & BDRV_O_INACTIVE)) {
69509e37271fSKevin Wolf                 return true;
69519e37271fSKevin Wolf             }
69529e37271fSKevin Wolf         }
69539e37271fSKevin Wolf     }
69549e37271fSKevin Wolf 
69559e37271fSKevin Wolf     return false;
69569e37271fSKevin Wolf }
69579e37271fSKevin Wolf 
69580e6bad1fSKevin Wolf static int GRAPH_RDLOCK bdrv_inactivate_recurse(BlockDriverState *bs)
695976b1c7feSKevin Wolf {
6960cfa1a572SKevin Wolf     BdrvChild *child, *parent;
696176b1c7feSKevin Wolf     int ret;
6962a13de40aSVladimir Sementsov-Ogievskiy     uint64_t cumulative_perms, cumulative_shared_perms;
696376b1c7feSKevin Wolf 
6964da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
6965da359909SEmanuele Giuseppe Esposito 
6966d470ad42SMax Reitz     if (!bs->drv) {
6967d470ad42SMax Reitz         return -ENOMEDIUM;
6968d470ad42SMax Reitz     }
6969d470ad42SMax Reitz 
69709e37271fSKevin Wolf     /* Make sure that we don't inactivate a child before its parent.
69719e37271fSKevin Wolf      * It will be covered by recursion from the yet active parent. */
69729e37271fSKevin Wolf     if (bdrv_has_bds_parent(bs, true)) {
69739e37271fSKevin Wolf         return 0;
69749e37271fSKevin Wolf     }
69759e37271fSKevin Wolf 
69769e37271fSKevin Wolf     assert(!(bs->open_flags & BDRV_O_INACTIVE));
69779e37271fSKevin Wolf 
69789e37271fSKevin Wolf     /* Inactivate this node */
69799e37271fSKevin Wolf     if (bs->drv->bdrv_inactivate) {
698076b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
698176b1c7feSKevin Wolf         if (ret < 0) {
698276b1c7feSKevin Wolf             return ret;
698376b1c7feSKevin Wolf         }
698476b1c7feSKevin Wolf     }
698576b1c7feSKevin Wolf 
6986cfa1a572SKevin Wolf     QLIST_FOREACH(parent, &bs->parents, next_parent) {
6987bd86fb99SMax Reitz         if (parent->klass->inactivate) {
6988bd86fb99SMax Reitz             ret = parent->klass->inactivate(parent);
6989cfa1a572SKevin Wolf             if (ret < 0) {
6990cfa1a572SKevin Wolf                 return ret;
6991cfa1a572SKevin Wolf             }
6992cfa1a572SKevin Wolf         }
6993cfa1a572SKevin Wolf     }
69949c5e6594SKevin Wolf 
6995a13de40aSVladimir Sementsov-Ogievskiy     bdrv_get_cumulative_perm(bs, &cumulative_perms,
6996a13de40aSVladimir Sementsov-Ogievskiy                              &cumulative_shared_perms);
6997a13de40aSVladimir Sementsov-Ogievskiy     if (cumulative_perms & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
6998a13de40aSVladimir Sementsov-Ogievskiy         /* Our inactive parents still need write access. Inactivation failed. */
6999a13de40aSVladimir Sementsov-Ogievskiy         return -EPERM;
7000a13de40aSVladimir Sementsov-Ogievskiy     }
7001a13de40aSVladimir Sementsov-Ogievskiy 
70027d5b5261SStefan Hajnoczi     bs->open_flags |= BDRV_O_INACTIVE;
70037d5b5261SStefan Hajnoczi 
7004bb87e4d1SVladimir Sementsov-Ogievskiy     /*
7005bb87e4d1SVladimir Sementsov-Ogievskiy      * Update permissions, they may differ for inactive nodes.
7006bb87e4d1SVladimir Sementsov-Ogievskiy      * We only tried to loosen restrictions, so errors are not fatal, ignore
7007bb87e4d1SVladimir Sementsov-Ogievskiy      * them.
7008bb87e4d1SVladimir Sementsov-Ogievskiy      */
7009f1316edbSVladimir Sementsov-Ogievskiy     bdrv_refresh_perms(bs, NULL, NULL);
70109e37271fSKevin Wolf 
70119e37271fSKevin Wolf     /* Recursively inactivate children */
701238701b6aSKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
70139e37271fSKevin Wolf         ret = bdrv_inactivate_recurse(child->bs);
701438701b6aSKevin Wolf         if (ret < 0) {
701538701b6aSKevin Wolf             return ret;
701638701b6aSKevin Wolf         }
701738701b6aSKevin Wolf     }
701838701b6aSKevin Wolf 
701976b1c7feSKevin Wolf     return 0;
702076b1c7feSKevin Wolf }
702176b1c7feSKevin Wolf 
702276b1c7feSKevin Wolf int bdrv_inactivate_all(void)
702376b1c7feSKevin Wolf {
702479720af6SMax Reitz     BlockDriverState *bs = NULL;
702588be7b4bSKevin Wolf     BdrvNextIterator it;
7026aad0b7a0SFam Zheng     int ret = 0;
702776b1c7feSKevin Wolf 
7028f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
70290e6bad1fSKevin Wolf     GRAPH_RDLOCK_GUARD_MAINLOOP();
7030f791bf7fSEmanuele Giuseppe Esposito 
703188be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
70329e37271fSKevin Wolf         /* Nodes with BDS parents are covered by recursion from the last
70339e37271fSKevin Wolf          * parent that gets inactivated. Don't inactivate them a second
70349e37271fSKevin Wolf          * time if that has already happened. */
70359e37271fSKevin Wolf         if (bdrv_has_bds_parent(bs, false)) {
70369e37271fSKevin Wolf             continue;
70379e37271fSKevin Wolf         }
70389e37271fSKevin Wolf         ret = bdrv_inactivate_recurse(bs);
703976b1c7feSKevin Wolf         if (ret < 0) {
70405e003f17SMax Reitz             bdrv_next_cleanup(&it);
7041b49f4755SStefan Hajnoczi             break;
7042aad0b7a0SFam Zheng         }
704376b1c7feSKevin Wolf     }
704476b1c7feSKevin Wolf 
7045aad0b7a0SFam Zheng     return ret;
704676b1c7feSKevin Wolf }
704776b1c7feSKevin Wolf 
7048f9f05dc5SKevin Wolf /**************************************************************/
704919cb3738Sbellard /* removable device support */
705019cb3738Sbellard 
705119cb3738Sbellard /**
705219cb3738Sbellard  * Return TRUE if the media is present
705319cb3738Sbellard  */
70541e97be91SEmanuele Giuseppe Esposito bool coroutine_fn bdrv_co_is_inserted(BlockDriverState *bs)
705519cb3738Sbellard {
705619cb3738Sbellard     BlockDriver *drv = bs->drv;
705728d7a789SMax Reitz     BdrvChild *child;
7058384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
7059c73ff92cSEmanuele Giuseppe Esposito     assert_bdrv_graph_readable();
7060a1aff5bfSMarkus Armbruster 
7061e031f750SMax Reitz     if (!drv) {
7062e031f750SMax Reitz         return false;
7063e031f750SMax Reitz     }
70641e97be91SEmanuele Giuseppe Esposito     if (drv->bdrv_co_is_inserted) {
70651e97be91SEmanuele Giuseppe Esposito         return drv->bdrv_co_is_inserted(bs);
706619cb3738Sbellard     }
706728d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
70681e97be91SEmanuele Giuseppe Esposito         if (!bdrv_co_is_inserted(child->bs)) {
706928d7a789SMax Reitz             return false;
707028d7a789SMax Reitz         }
707128d7a789SMax Reitz     }
707228d7a789SMax Reitz     return true;
707328d7a789SMax Reitz }
707419cb3738Sbellard 
707519cb3738Sbellard /**
707619cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
707719cb3738Sbellard  */
70782531b390SEmanuele Giuseppe Esposito void coroutine_fn bdrv_co_eject(BlockDriverState *bs, bool eject_flag)
707919cb3738Sbellard {
708019cb3738Sbellard     BlockDriver *drv = bs->drv;
7081384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
708279a292e5SKevin Wolf     assert_bdrv_graph_readable();
708319cb3738Sbellard 
70842531b390SEmanuele Giuseppe Esposito     if (drv && drv->bdrv_co_eject) {
70852531b390SEmanuele Giuseppe Esposito         drv->bdrv_co_eject(bs, eject_flag);
708619cb3738Sbellard     }
708719cb3738Sbellard }
708819cb3738Sbellard 
708919cb3738Sbellard /**
709019cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
709119cb3738Sbellard  * to eject it manually).
709219cb3738Sbellard  */
70932c75261cSEmanuele Giuseppe Esposito void coroutine_fn bdrv_co_lock_medium(BlockDriverState *bs, bool locked)
709419cb3738Sbellard {
709519cb3738Sbellard     BlockDriver *drv = bs->drv;
7096384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
709779a292e5SKevin Wolf     assert_bdrv_graph_readable();
7098025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
7099b8c6d095SStefan Hajnoczi 
71002c75261cSEmanuele Giuseppe Esposito     if (drv && drv->bdrv_co_lock_medium) {
71012c75261cSEmanuele Giuseppe Esposito         drv->bdrv_co_lock_medium(bs, locked);
710219cb3738Sbellard     }
710319cb3738Sbellard }
7104985a03b0Sths 
71059fcb0251SFam Zheng /* Get a reference to bs */
71069fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
71079fcb0251SFam Zheng {
7108f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
71099fcb0251SFam Zheng     bs->refcnt++;
71109fcb0251SFam Zheng }
71119fcb0251SFam Zheng 
71129fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
71139fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
71149fcb0251SFam Zheng  * deleted. */
71159fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
71169fcb0251SFam Zheng {
7117f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
71189a4d5ca6SJeff Cody     if (!bs) {
71199a4d5ca6SJeff Cody         return;
71209a4d5ca6SJeff Cody     }
71219fcb0251SFam Zheng     assert(bs->refcnt > 0);
71229fcb0251SFam Zheng     if (--bs->refcnt == 0) {
71239fcb0251SFam Zheng         bdrv_delete(bs);
71249fcb0251SFam Zheng     }
71259fcb0251SFam Zheng }
71269fcb0251SFam Zheng 
71276bc0bcc8SKevin Wolf static void bdrv_schedule_unref_bh(void *opaque)
71286bc0bcc8SKevin Wolf {
71296bc0bcc8SKevin Wolf     BlockDriverState *bs = opaque;
71306bc0bcc8SKevin Wolf 
71316bc0bcc8SKevin Wolf     bdrv_unref(bs);
71326bc0bcc8SKevin Wolf }
71336bc0bcc8SKevin Wolf 
7134ac2ae233SKevin Wolf /*
7135ac2ae233SKevin Wolf  * Release a BlockDriverState reference while holding the graph write lock.
7136ac2ae233SKevin Wolf  *
7137ac2ae233SKevin Wolf  * Calling bdrv_unref() directly is forbidden while holding the graph lock
7138ac2ae233SKevin Wolf  * because bdrv_close() both involves polling and taking the graph lock
7139ac2ae233SKevin Wolf  * internally. bdrv_schedule_unref() instead delays decreasing the refcount and
7140ac2ae233SKevin Wolf  * possibly closing @bs until the graph lock is released.
7141ac2ae233SKevin Wolf  */
7142ac2ae233SKevin Wolf void bdrv_schedule_unref(BlockDriverState *bs)
7143ac2ae233SKevin Wolf {
7144ac2ae233SKevin Wolf     if (!bs) {
7145ac2ae233SKevin Wolf         return;
7146ac2ae233SKevin Wolf     }
71476bc0bcc8SKevin Wolf     aio_bh_schedule_oneshot(qemu_get_aio_context(), bdrv_schedule_unref_bh, bs);
7148ac2ae233SKevin Wolf }
7149ac2ae233SKevin Wolf 
7150fbe40ff7SFam Zheng struct BdrvOpBlocker {
7151fbe40ff7SFam Zheng     Error *reason;
7152fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
7153fbe40ff7SFam Zheng };
7154fbe40ff7SFam Zheng 
7155fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
7156fbe40ff7SFam Zheng {
7157fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
7158f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
71590bb79c97SKevin Wolf 
7160fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7161fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
7162fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
71634b576648SMarkus Armbruster         error_propagate_prepend(errp, error_copy(blocker->reason),
71644b576648SMarkus Armbruster                                 "Node '%s' is busy: ",
7165e43bfd9cSMarkus Armbruster                                 bdrv_get_device_or_node_name(bs));
7166fbe40ff7SFam Zheng         return true;
7167fbe40ff7SFam Zheng     }
7168fbe40ff7SFam Zheng     return false;
7169fbe40ff7SFam Zheng }
7170fbe40ff7SFam Zheng 
7171fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
7172fbe40ff7SFam Zheng {
7173fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
7174f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7175fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7176fbe40ff7SFam Zheng 
71775839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
7178fbe40ff7SFam Zheng     blocker->reason = reason;
7179fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
7180fbe40ff7SFam Zheng }
7181fbe40ff7SFam Zheng 
7182fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
7183fbe40ff7SFam Zheng {
7184fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
7185f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7186fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
7187fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
7188fbe40ff7SFam Zheng         if (blocker->reason == reason) {
7189fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
7190fbe40ff7SFam Zheng             g_free(blocker);
7191fbe40ff7SFam Zheng         }
7192fbe40ff7SFam Zheng     }
7193fbe40ff7SFam Zheng }
7194fbe40ff7SFam Zheng 
7195fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
7196fbe40ff7SFam Zheng {
7197fbe40ff7SFam Zheng     int i;
7198f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7199fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7200fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
7201fbe40ff7SFam Zheng     }
7202fbe40ff7SFam Zheng }
7203fbe40ff7SFam Zheng 
7204fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
7205fbe40ff7SFam Zheng {
7206fbe40ff7SFam Zheng     int i;
7207f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7208fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7209fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
7210fbe40ff7SFam Zheng     }
7211fbe40ff7SFam Zheng }
7212fbe40ff7SFam Zheng 
7213fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
7214fbe40ff7SFam Zheng {
7215fbe40ff7SFam Zheng     int i;
7216f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7217fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
7218fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
7219fbe40ff7SFam Zheng             return false;
7220fbe40ff7SFam Zheng         }
7221fbe40ff7SFam Zheng     }
7222fbe40ff7SFam Zheng     return true;
7223fbe40ff7SFam Zheng }
7224fbe40ff7SFam Zheng 
7225e1355055SKevin Wolf /*
7226e1355055SKevin Wolf  * Must not be called while holding the lock of an AioContext other than the
7227e1355055SKevin Wolf  * current one.
7228e1355055SKevin Wolf  */
7229d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
7230f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
72319217283dSFam Zheng                      char *options, uint64_t img_size, int flags, bool quiet,
72329217283dSFam Zheng                      Error **errp)
7233f88e1a42SJes Sorensen {
723483d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
723583d0521aSChunyan Liu     QemuOpts *opts = NULL;
723683d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
723783d0521aSChunyan Liu     int64_t size;
7238f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
7239cc84d90fSMax Reitz     Error *local_err = NULL;
7240f88e1a42SJes Sorensen     int ret = 0;
7241f88e1a42SJes Sorensen 
7242f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7243f791bf7fSEmanuele Giuseppe Esposito 
7244f88e1a42SJes Sorensen     /* Find driver and parse its options */
7245f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
7246f88e1a42SJes Sorensen     if (!drv) {
724771c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
7248d92ada22SLuiz Capitulino         return;
7249f88e1a42SJes Sorensen     }
7250f88e1a42SJes Sorensen 
7251b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
7252f88e1a42SJes Sorensen     if (!proto_drv) {
7253d92ada22SLuiz Capitulino         return;
7254f88e1a42SJes Sorensen     }
7255f88e1a42SJes Sorensen 
7256c6149724SMax Reitz     if (!drv->create_opts) {
7257c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
7258c6149724SMax Reitz                    drv->format_name);
7259c6149724SMax Reitz         return;
7260c6149724SMax Reitz     }
7261c6149724SMax Reitz 
72625a5e7f8cSMaxim Levitsky     if (!proto_drv->create_opts) {
72635a5e7f8cSMaxim Levitsky         error_setg(errp, "Protocol driver '%s' does not support image creation",
72645a5e7f8cSMaxim Levitsky                    proto_drv->format_name);
72655a5e7f8cSMaxim Levitsky         return;
72665a5e7f8cSMaxim Levitsky     }
72675a5e7f8cSMaxim Levitsky 
7268f6dc1c31SKevin Wolf     /* Create parameter list */
7269c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
7270c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
7271f88e1a42SJes Sorensen 
727283d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
7273f88e1a42SJes Sorensen 
7274f88e1a42SJes Sorensen     /* Parse -o options */
7275f88e1a42SJes Sorensen     if (options) {
7276a5f9b9dfSMarkus Armbruster         if (!qemu_opts_do_parse(opts, options, NULL, errp)) {
7277f88e1a42SJes Sorensen             goto out;
7278f88e1a42SJes Sorensen         }
7279f88e1a42SJes Sorensen     }
7280f88e1a42SJes Sorensen 
7281f6dc1c31SKevin Wolf     if (!qemu_opt_get(opts, BLOCK_OPT_SIZE)) {
7282f6dc1c31SKevin Wolf         qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
7283f6dc1c31SKevin Wolf     } else if (img_size != UINT64_C(-1)) {
7284f6dc1c31SKevin Wolf         error_setg(errp, "The image size must be specified only once");
7285f6dc1c31SKevin Wolf         goto out;
7286f6dc1c31SKevin Wolf     }
7287f6dc1c31SKevin Wolf 
7288f88e1a42SJes Sorensen     if (base_filename) {
7289235e59cfSMarkus Armbruster         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename,
72903882578bSMarkus Armbruster                           NULL)) {
729171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
729271c79813SLuiz Capitulino                        fmt);
7293f88e1a42SJes Sorensen             goto out;
7294f88e1a42SJes Sorensen         }
7295f88e1a42SJes Sorensen     }
7296f88e1a42SJes Sorensen 
7297f88e1a42SJes Sorensen     if (base_fmt) {
72983882578bSMarkus Armbruster         if (!qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, NULL)) {
729971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
730071c79813SLuiz Capitulino                              "format '%s'", fmt);
7301f88e1a42SJes Sorensen             goto out;
7302f88e1a42SJes Sorensen         }
7303f88e1a42SJes Sorensen     }
7304f88e1a42SJes Sorensen 
730583d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
730683d0521aSChunyan Liu     if (backing_file) {
730783d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
730871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
730971c79813SLuiz Capitulino                              "same filename as the backing file");
7310792da93aSJes Sorensen             goto out;
7311792da93aSJes Sorensen         }
7312975a7bd2SConnor Kuehl         if (backing_file[0] == '\0') {
7313975a7bd2SConnor Kuehl             error_setg(errp, "Expected backing file name, got empty string");
7314975a7bd2SConnor Kuehl             goto out;
7315975a7bd2SConnor Kuehl         }
7316792da93aSJes Sorensen     }
7317792da93aSJes Sorensen 
731883d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
7319f88e1a42SJes Sorensen 
73206e6e55f5SJohn Snow     /* The size for the image must always be specified, unless we have a backing
73216e6e55f5SJohn Snow      * file and we have not been forbidden from opening it. */
7322a8b42a1cSEric Blake     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, img_size);
73236e6e55f5SJohn Snow     if (backing_file && !(flags & BDRV_O_NO_BACKING)) {
732466f6b814SMax Reitz         BlockDriverState *bs;
7325645ae7d8SMax Reitz         char *full_backing;
732663090dacSPaolo Bonzini         int back_flags;
7327e6641719SMax Reitz         QDict *backing_options = NULL;
732863090dacSPaolo Bonzini 
7329645ae7d8SMax Reitz         full_backing =
733029168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
733129168018SMax Reitz                                                          &local_err);
733229168018SMax Reitz         if (local_err) {
733329168018SMax Reitz             goto out;
733429168018SMax Reitz         }
7335645ae7d8SMax Reitz         assert(full_backing);
733629168018SMax Reitz 
7337d5b23994SMax Reitz         /*
7338d5b23994SMax Reitz          * No need to do I/O here, which allows us to open encrypted
7339d5b23994SMax Reitz          * backing images without needing the secret
7340d5b23994SMax Reitz          */
734161de4c68SKevin Wolf         back_flags = flags;
7342bfd18d1eSKevin Wolf         back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
7343d5b23994SMax Reitz         back_flags |= BDRV_O_NO_IO;
7344f88e1a42SJes Sorensen 
7345e6641719SMax Reitz         backing_options = qdict_new();
7346cc954f01SFam Zheng         if (backing_fmt) {
734746f5ac20SEric Blake             qdict_put_str(backing_options, "driver", backing_fmt);
7348e6641719SMax Reitz         }
7349cc954f01SFam Zheng         qdict_put_bool(backing_options, BDRV_OPT_FORCE_SHARE, true);
7350e6641719SMax Reitz 
73515b363937SMax Reitz         bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
73525b363937SMax Reitz                        &local_err);
735329168018SMax Reitz         g_free(full_backing);
7354add8200dSEric Blake         if (!bs) {
7355add8200dSEric Blake             error_append_hint(&local_err, "Could not open backing image.\n");
7356f88e1a42SJes Sorensen             goto out;
73576e6e55f5SJohn Snow         } else {
7358d9f059aaSEric Blake             if (!backing_fmt) {
7359497a30dbSEric Blake                 error_setg(&local_err,
7360497a30dbSEric Blake                            "Backing file specified without backing format");
7361fbdffb08SMichael Tokarev                 error_append_hint(&local_err, "Detected format of %s.\n",
7362d9f059aaSEric Blake                                   bs->drv->format_name);
7363497a30dbSEric Blake                 goto out;
7364d9f059aaSEric Blake             }
73656e6e55f5SJohn Snow             if (size == -1) {
73666e6e55f5SJohn Snow                 /* Opened BS, have no size */
736752bf1e72SMarkus Armbruster                 size = bdrv_getlength(bs);
736852bf1e72SMarkus Armbruster                 if (size < 0) {
736952bf1e72SMarkus Armbruster                     error_setg_errno(errp, -size, "Could not get size of '%s'",
737052bf1e72SMarkus Armbruster                                      backing_file);
737152bf1e72SMarkus Armbruster                     bdrv_unref(bs);
737252bf1e72SMarkus Armbruster                     goto out;
737352bf1e72SMarkus Armbruster                 }
737439101f25SMarkus Armbruster                 qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
73756e6e55f5SJohn Snow             }
737666f6b814SMax Reitz             bdrv_unref(bs);
73776e6e55f5SJohn Snow         }
7378d9f059aaSEric Blake         /* (backing_file && !(flags & BDRV_O_NO_BACKING)) */
7379d9f059aaSEric Blake     } else if (backing_file && !backing_fmt) {
7380497a30dbSEric Blake         error_setg(&local_err,
7381497a30dbSEric Blake                    "Backing file specified without backing format");
7382497a30dbSEric Blake         goto out;
7383d9f059aaSEric Blake     }
73846e6e55f5SJohn Snow 
738535286daeSHyman Huang     /* Parameter 'size' is not needed for detached LUKS header */
738635286daeSHyman Huang     if (size == -1 &&
738735286daeSHyman Huang         !(!strcmp(fmt, "luks") &&
738835286daeSHyman Huang           qemu_opt_get_bool(opts, "detached-header", false))) {
738971c79813SLuiz Capitulino         error_setg(errp, "Image creation needs a size parameter");
7390f88e1a42SJes Sorensen         goto out;
7391f88e1a42SJes Sorensen     }
7392f88e1a42SJes Sorensen 
7393f382d43aSMiroslav Rezanina     if (!quiet) {
7394f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
739543c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
7396f88e1a42SJes Sorensen         puts("");
73974e2f4418SEric Blake         fflush(stdout);
7398f382d43aSMiroslav Rezanina     }
739983d0521aSChunyan Liu 
7400c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
740183d0521aSChunyan Liu 
7402cc84d90fSMax Reitz     if (ret == -EFBIG) {
7403cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
7404cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
7405cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
7406f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
740783d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
7408f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
7409f3f4d2c0SKevin Wolf         }
7410cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
7411cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
7412cc84d90fSMax Reitz         error_free(local_err);
7413cc84d90fSMax Reitz         local_err = NULL;
7414f88e1a42SJes Sorensen     }
7415f88e1a42SJes Sorensen 
7416f88e1a42SJes Sorensen out:
741783d0521aSChunyan Liu     qemu_opts_del(opts);
741883d0521aSChunyan Liu     qemu_opts_free(create_opts);
7419cc84d90fSMax Reitz     error_propagate(errp, local_err);
7420cc84d90fSMax Reitz }
742185d126f3SStefan Hajnoczi 
742285d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
742385d126f3SStefan Hajnoczi {
7424384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
742533f2a757SStefan Hajnoczi     return bs ? bs->aio_context : qemu_get_aio_context();
7426dcd04228SStefan Hajnoczi }
7427dcd04228SStefan Hajnoczi 
7428e336fd4cSKevin Wolf AioContext *coroutine_fn bdrv_co_enter(BlockDriverState *bs)
7429e336fd4cSKevin Wolf {
7430e336fd4cSKevin Wolf     Coroutine *self = qemu_coroutine_self();
7431e336fd4cSKevin Wolf     AioContext *old_ctx = qemu_coroutine_get_aio_context(self);
7432e336fd4cSKevin Wolf     AioContext *new_ctx;
7433384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
7434e336fd4cSKevin Wolf 
7435e336fd4cSKevin Wolf     /*
7436e336fd4cSKevin Wolf      * Increase bs->in_flight to ensure that this operation is completed before
7437e336fd4cSKevin Wolf      * moving the node to a different AioContext. Read new_ctx only afterwards.
7438e336fd4cSKevin Wolf      */
7439e336fd4cSKevin Wolf     bdrv_inc_in_flight(bs);
7440e336fd4cSKevin Wolf 
7441e336fd4cSKevin Wolf     new_ctx = bdrv_get_aio_context(bs);
7442e336fd4cSKevin Wolf     aio_co_reschedule_self(new_ctx);
7443e336fd4cSKevin Wolf     return old_ctx;
7444e336fd4cSKevin Wolf }
7445e336fd4cSKevin Wolf 
7446e336fd4cSKevin Wolf void coroutine_fn bdrv_co_leave(BlockDriverState *bs, AioContext *old_ctx)
7447e336fd4cSKevin Wolf {
7448384a48fbSEmanuele Giuseppe Esposito     IO_CODE();
7449e336fd4cSKevin Wolf     aio_co_reschedule_self(old_ctx);
7450e336fd4cSKevin Wolf     bdrv_dec_in_flight(bs);
7451e336fd4cSKevin Wolf }
7452e336fd4cSKevin Wolf 
7453e8a095daSStefan Hajnoczi static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
7454e8a095daSStefan Hajnoczi {
7455bdb73476SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7456e8a095daSStefan Hajnoczi     QLIST_REMOVE(ban, list);
7457e8a095daSStefan Hajnoczi     g_free(ban);
7458e8a095daSStefan Hajnoczi }
7459e8a095daSStefan Hajnoczi 
7460a3a683c3SKevin Wolf static void bdrv_detach_aio_context(BlockDriverState *bs)
7461dcd04228SStefan Hajnoczi {
7462e8a095daSStefan Hajnoczi     BdrvAioNotifier *baf, *baf_tmp;
746333384421SMax Reitz 
7464e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
7465da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7466e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
7467e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
7468e8a095daSStefan Hajnoczi         if (baf->deleted) {
7469e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(baf);
7470e8a095daSStefan Hajnoczi         } else {
747133384421SMax Reitz             baf->detach_aio_context(baf->opaque);
747233384421SMax Reitz         }
7473e8a095daSStefan Hajnoczi     }
7474e8a095daSStefan Hajnoczi     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
7475e8a095daSStefan Hajnoczi      * remove remaining aio notifiers if we aren't called again.
7476e8a095daSStefan Hajnoczi      */
7477e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
747833384421SMax Reitz 
74791bffe1aeSKevin Wolf     if (bs->drv && bs->drv->bdrv_detach_aio_context) {
7480dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
7481dcd04228SStefan Hajnoczi     }
7482dcd04228SStefan Hajnoczi 
7483dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
7484dcd04228SStefan Hajnoczi }
7485dcd04228SStefan Hajnoczi 
7486a3a683c3SKevin Wolf static void bdrv_attach_aio_context(BlockDriverState *bs,
7487dcd04228SStefan Hajnoczi                                     AioContext *new_context)
7488dcd04228SStefan Hajnoczi {
7489e8a095daSStefan Hajnoczi     BdrvAioNotifier *ban, *ban_tmp;
7490da359909SEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
749133384421SMax Reitz 
7492dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
7493dcd04228SStefan Hajnoczi 
74941bffe1aeSKevin Wolf     if (bs->drv && bs->drv->bdrv_attach_aio_context) {
7495dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
7496dcd04228SStefan Hajnoczi     }
749733384421SMax Reitz 
7498e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
7499e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
7500e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
7501e8a095daSStefan Hajnoczi         if (ban->deleted) {
7502e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(ban);
7503e8a095daSStefan Hajnoczi         } else {
750433384421SMax Reitz             ban->attached_aio_context(new_context, ban->opaque);
750533384421SMax Reitz         }
7506dcd04228SStefan Hajnoczi     }
7507e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
7508e8a095daSStefan Hajnoczi }
7509dcd04228SStefan Hajnoczi 
75107e8c182fSEmanuele Giuseppe Esposito typedef struct BdrvStateSetAioContext {
75117e8c182fSEmanuele Giuseppe Esposito     AioContext *new_ctx;
75127e8c182fSEmanuele Giuseppe Esposito     BlockDriverState *bs;
75137e8c182fSEmanuele Giuseppe Esposito } BdrvStateSetAioContext;
75147e8c182fSEmanuele Giuseppe Esposito 
75157e8c182fSEmanuele Giuseppe Esposito static bool bdrv_parent_change_aio_context(BdrvChild *c, AioContext *ctx,
7516e08cc001SEmanuele Giuseppe Esposito                                            GHashTable *visited,
7517e08cc001SEmanuele Giuseppe Esposito                                            Transaction *tran,
75187e8c182fSEmanuele Giuseppe Esposito                                            Error **errp)
75197e8c182fSEmanuele Giuseppe Esposito {
75207e8c182fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7521e08cc001SEmanuele Giuseppe Esposito     if (g_hash_table_contains(visited, c)) {
75227e8c182fSEmanuele Giuseppe Esposito         return true;
75237e8c182fSEmanuele Giuseppe Esposito     }
7524e08cc001SEmanuele Giuseppe Esposito     g_hash_table_add(visited, c);
75257e8c182fSEmanuele Giuseppe Esposito 
75267e8c182fSEmanuele Giuseppe Esposito     /*
75277e8c182fSEmanuele Giuseppe Esposito      * A BdrvChildClass that doesn't handle AioContext changes cannot
75287e8c182fSEmanuele Giuseppe Esposito      * tolerate any AioContext changes
75297e8c182fSEmanuele Giuseppe Esposito      */
75307e8c182fSEmanuele Giuseppe Esposito     if (!c->klass->change_aio_ctx) {
75317e8c182fSEmanuele Giuseppe Esposito         char *user = bdrv_child_user_desc(c);
75327e8c182fSEmanuele Giuseppe Esposito         error_setg(errp, "Changing iothreads is not supported by %s", user);
75337e8c182fSEmanuele Giuseppe Esposito         g_free(user);
75347e8c182fSEmanuele Giuseppe Esposito         return false;
75357e8c182fSEmanuele Giuseppe Esposito     }
75367e8c182fSEmanuele Giuseppe Esposito     if (!c->klass->change_aio_ctx(c, ctx, visited, tran, errp)) {
75377e8c182fSEmanuele Giuseppe Esposito         assert(!errp || *errp);
75387e8c182fSEmanuele Giuseppe Esposito         return false;
75397e8c182fSEmanuele Giuseppe Esposito     }
75407e8c182fSEmanuele Giuseppe Esposito     return true;
75417e8c182fSEmanuele Giuseppe Esposito }
75427e8c182fSEmanuele Giuseppe Esposito 
75437e8c182fSEmanuele Giuseppe Esposito bool bdrv_child_change_aio_context(BdrvChild *c, AioContext *ctx,
7544e08cc001SEmanuele Giuseppe Esposito                                    GHashTable *visited, Transaction *tran,
75457e8c182fSEmanuele Giuseppe Esposito                                    Error **errp)
75467e8c182fSEmanuele Giuseppe Esposito {
75477e8c182fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7548e08cc001SEmanuele Giuseppe Esposito     if (g_hash_table_contains(visited, c)) {
75497e8c182fSEmanuele Giuseppe Esposito         return true;
75507e8c182fSEmanuele Giuseppe Esposito     }
7551e08cc001SEmanuele Giuseppe Esposito     g_hash_table_add(visited, c);
75527e8c182fSEmanuele Giuseppe Esposito     return bdrv_change_aio_context(c->bs, ctx, visited, tran, errp);
75537e8c182fSEmanuele Giuseppe Esposito }
75547e8c182fSEmanuele Giuseppe Esposito 
75557e8c182fSEmanuele Giuseppe Esposito static void bdrv_set_aio_context_clean(void *opaque)
75567e8c182fSEmanuele Giuseppe Esposito {
75577e8c182fSEmanuele Giuseppe Esposito     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
75587e8c182fSEmanuele Giuseppe Esposito     BlockDriverState *bs = (BlockDriverState *) state->bs;
75597e8c182fSEmanuele Giuseppe Esposito 
75607e8c182fSEmanuele Giuseppe Esposito     /* Paired with bdrv_drained_begin in bdrv_change_aio_context() */
75617e8c182fSEmanuele Giuseppe Esposito     bdrv_drained_end(bs);
75627e8c182fSEmanuele Giuseppe Esposito 
75637e8c182fSEmanuele Giuseppe Esposito     g_free(state);
75647e8c182fSEmanuele Giuseppe Esposito }
75657e8c182fSEmanuele Giuseppe Esposito 
75667e8c182fSEmanuele Giuseppe Esposito static void bdrv_set_aio_context_commit(void *opaque)
75677e8c182fSEmanuele Giuseppe Esposito {
75687e8c182fSEmanuele Giuseppe Esposito     BdrvStateSetAioContext *state = (BdrvStateSetAioContext *) opaque;
75697e8c182fSEmanuele Giuseppe Esposito     BlockDriverState *bs = (BlockDriverState *) state->bs;
75707e8c182fSEmanuele Giuseppe Esposito     AioContext *new_context = state->new_ctx;
75717e8c182fSEmanuele Giuseppe Esposito 
75727e8c182fSEmanuele Giuseppe Esposito     bdrv_detach_aio_context(bs);
75737e8c182fSEmanuele Giuseppe Esposito     bdrv_attach_aio_context(bs, new_context);
75747e8c182fSEmanuele Giuseppe Esposito }
75757e8c182fSEmanuele Giuseppe Esposito 
75767e8c182fSEmanuele Giuseppe Esposito static TransactionActionDrv set_aio_context = {
75777e8c182fSEmanuele Giuseppe Esposito     .commit = bdrv_set_aio_context_commit,
75787e8c182fSEmanuele Giuseppe Esposito     .clean = bdrv_set_aio_context_clean,
75797e8c182fSEmanuele Giuseppe Esposito };
75807e8c182fSEmanuele Giuseppe Esposito 
758142a65f02SKevin Wolf /*
758242a65f02SKevin Wolf  * Changes the AioContext used for fd handlers, timers, and BHs by this
758342a65f02SKevin Wolf  * BlockDriverState and all its children and parents.
758442a65f02SKevin Wolf  *
758543eaaaefSMax Reitz  * Must be called from the main AioContext.
758643eaaaefSMax Reitz  *
75877e8c182fSEmanuele Giuseppe Esposito  * @visited will accumulate all visited BdrvChild objects. The caller is
758842a65f02SKevin Wolf  * responsible for freeing the list afterwards.
758942a65f02SKevin Wolf  */
75907e8c182fSEmanuele Giuseppe Esposito static bool bdrv_change_aio_context(BlockDriverState *bs, AioContext *ctx,
7591e08cc001SEmanuele Giuseppe Esposito                                     GHashTable *visited, Transaction *tran,
75927e8c182fSEmanuele Giuseppe Esposito                                     Error **errp)
75935d231849SKevin Wolf {
75945d231849SKevin Wolf     BdrvChild *c;
75957e8c182fSEmanuele Giuseppe Esposito     BdrvStateSetAioContext *state;
75967e8c182fSEmanuele Giuseppe Esposito 
75977e8c182fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
75985d231849SKevin Wolf 
75995d231849SKevin Wolf     if (bdrv_get_aio_context(bs) == ctx) {
76005d231849SKevin Wolf         return true;
76015d231849SKevin Wolf     }
76025d231849SKevin Wolf 
76037f831d29SKevin Wolf     bdrv_graph_rdlock_main_loop();
76045d231849SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
76057e8c182fSEmanuele Giuseppe Esposito         if (!bdrv_parent_change_aio_context(c, ctx, visited, tran, errp)) {
76067f831d29SKevin Wolf             bdrv_graph_rdunlock_main_loop();
76075d231849SKevin Wolf             return false;
76085d231849SKevin Wolf         }
76095d231849SKevin Wolf     }
76107e8c182fSEmanuele Giuseppe Esposito 
76115d231849SKevin Wolf     QLIST_FOREACH(c, &bs->children, next) {
76127e8c182fSEmanuele Giuseppe Esposito         if (!bdrv_child_change_aio_context(c, ctx, visited, tran, errp)) {
76137f831d29SKevin Wolf             bdrv_graph_rdunlock_main_loop();
76145d231849SKevin Wolf             return false;
76155d231849SKevin Wolf         }
76165d231849SKevin Wolf     }
76177f831d29SKevin Wolf     bdrv_graph_rdunlock_main_loop();
76185d231849SKevin Wolf 
76197e8c182fSEmanuele Giuseppe Esposito     state = g_new(BdrvStateSetAioContext, 1);
76207e8c182fSEmanuele Giuseppe Esposito     *state = (BdrvStateSetAioContext) {
76217e8c182fSEmanuele Giuseppe Esposito         .new_ctx = ctx,
76227e8c182fSEmanuele Giuseppe Esposito         .bs = bs,
76237e8c182fSEmanuele Giuseppe Esposito     };
76247e8c182fSEmanuele Giuseppe Esposito 
76257e8c182fSEmanuele Giuseppe Esposito     /* Paired with bdrv_drained_end in bdrv_set_aio_context_clean() */
76267e8c182fSEmanuele Giuseppe Esposito     bdrv_drained_begin(bs);
76277e8c182fSEmanuele Giuseppe Esposito 
76287e8c182fSEmanuele Giuseppe Esposito     tran_add(tran, &set_aio_context, state);
76297e8c182fSEmanuele Giuseppe Esposito 
76305d231849SKevin Wolf     return true;
76315d231849SKevin Wolf }
76325d231849SKevin Wolf 
76337e8c182fSEmanuele Giuseppe Esposito /*
76347e8c182fSEmanuele Giuseppe Esposito  * Change bs's and recursively all of its parents' and children's AioContext
76357e8c182fSEmanuele Giuseppe Esposito  * to the given new context, returning an error if that isn't possible.
76367e8c182fSEmanuele Giuseppe Esposito  *
76377e8c182fSEmanuele Giuseppe Esposito  * If ignore_child is not NULL, that child (and its subgraph) will not
76387e8c182fSEmanuele Giuseppe Esposito  * be touched.
76397e8c182fSEmanuele Giuseppe Esposito  */
7640a41cfda1SEmanuele Giuseppe Esposito int bdrv_try_change_aio_context(BlockDriverState *bs, AioContext *ctx,
76415d231849SKevin Wolf                                 BdrvChild *ignore_child, Error **errp)
76425d231849SKevin Wolf {
76437e8c182fSEmanuele Giuseppe Esposito     Transaction *tran;
7644e08cc001SEmanuele Giuseppe Esposito     GHashTable *visited;
76457e8c182fSEmanuele Giuseppe Esposito     int ret;
7646f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7647f791bf7fSEmanuele Giuseppe Esposito 
76487e8c182fSEmanuele Giuseppe Esposito     /*
76497e8c182fSEmanuele Giuseppe Esposito      * Recursion phase: go through all nodes of the graph.
76507e8c182fSEmanuele Giuseppe Esposito      * Take care of checking that all nodes support changing AioContext
76513202d8e4SMichael Tokarev      * and drain them, building a linear list of callbacks to run if everything
76527e8c182fSEmanuele Giuseppe Esposito      * is successful (the transaction itself).
76537e8c182fSEmanuele Giuseppe Esposito      */
76547e8c182fSEmanuele Giuseppe Esposito     tran = tran_new();
7655e08cc001SEmanuele Giuseppe Esposito     visited = g_hash_table_new(NULL, NULL);
7656e08cc001SEmanuele Giuseppe Esposito     if (ignore_child) {
7657e08cc001SEmanuele Giuseppe Esposito         g_hash_table_add(visited, ignore_child);
7658e08cc001SEmanuele Giuseppe Esposito     }
7659e08cc001SEmanuele Giuseppe Esposito     ret = bdrv_change_aio_context(bs, ctx, visited, tran, errp);
7660e08cc001SEmanuele Giuseppe Esposito     g_hash_table_destroy(visited);
76617e8c182fSEmanuele Giuseppe Esposito 
76627e8c182fSEmanuele Giuseppe Esposito     /*
76637e8c182fSEmanuele Giuseppe Esposito      * Linear phase: go through all callbacks collected in the transaction.
766423c983c8SStefan Hajnoczi      * Run all callbacks collected in the recursion to switch every node's
766523c983c8SStefan Hajnoczi      * AioContext (transaction commit), or undo all changes done in the
76667e8c182fSEmanuele Giuseppe Esposito      * recursion (transaction abort).
76677e8c182fSEmanuele Giuseppe Esposito      */
76685d231849SKevin Wolf 
76695d231849SKevin Wolf     if (!ret) {
76707e8c182fSEmanuele Giuseppe Esposito         /* Just run clean() callbacks. No AioContext changed. */
76717e8c182fSEmanuele Giuseppe Esposito         tran_abort(tran);
76725d231849SKevin Wolf         return -EPERM;
76735d231849SKevin Wolf     }
76745d231849SKevin Wolf 
76757e8c182fSEmanuele Giuseppe Esposito     tran_commit(tran);
76767e8c182fSEmanuele Giuseppe Esposito     return 0;
76775d231849SKevin Wolf }
76785d231849SKevin Wolf 
767933384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
768033384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
768133384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
768233384421SMax Reitz {
768333384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
768433384421SMax Reitz     *ban = (BdrvAioNotifier){
768533384421SMax Reitz         .attached_aio_context = attached_aio_context,
768633384421SMax Reitz         .detach_aio_context   = detach_aio_context,
768733384421SMax Reitz         .opaque               = opaque
768833384421SMax Reitz     };
7689f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
769033384421SMax Reitz 
769133384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
769233384421SMax Reitz }
769333384421SMax Reitz 
769433384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
769533384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
769633384421SMax Reitz                                                                    void *),
769733384421SMax Reitz                                       void (*detach_aio_context)(void *),
769833384421SMax Reitz                                       void *opaque)
769933384421SMax Reitz {
770033384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
7701f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
770233384421SMax Reitz 
770333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
770433384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
770533384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
7706e8a095daSStefan Hajnoczi             ban->opaque               == opaque               &&
7707e8a095daSStefan Hajnoczi             ban->deleted              == false)
770833384421SMax Reitz         {
7709e8a095daSStefan Hajnoczi             if (bs->walking_aio_notifiers) {
7710e8a095daSStefan Hajnoczi                 ban->deleted = true;
7711e8a095daSStefan Hajnoczi             } else {
7712e8a095daSStefan Hajnoczi                 bdrv_do_remove_aio_context_notifier(ban);
7713e8a095daSStefan Hajnoczi             }
771433384421SMax Reitz             return;
771533384421SMax Reitz         }
771633384421SMax Reitz     }
771733384421SMax Reitz 
771833384421SMax Reitz     abort();
771933384421SMax Reitz }
772033384421SMax Reitz 
772177485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
7722d1402b50SMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque,
7723a3579bfaSMaxim Levitsky                        bool force,
7724d1402b50SMax Reitz                        Error **errp)
77256f176b48SMax Reitz {
7726f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7727d470ad42SMax Reitz     if (!bs->drv) {
7728d1402b50SMax Reitz         error_setg(errp, "Node is ejected");
7729d470ad42SMax Reitz         return -ENOMEDIUM;
7730d470ad42SMax Reitz     }
7731c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
7732d1402b50SMax Reitz         error_setg(errp, "Block driver '%s' does not support option amendment",
7733d1402b50SMax Reitz                    bs->drv->format_name);
77346f176b48SMax Reitz         return -ENOTSUP;
77356f176b48SMax Reitz     }
7736a3579bfaSMaxim Levitsky     return bs->drv->bdrv_amend_options(bs, opts, status_cb,
7737a3579bfaSMaxim Levitsky                                        cb_opaque, force, errp);
77386f176b48SMax Reitz }
7739f6186f49SBenoît Canet 
77405d69b5abSMax Reitz /*
77415d69b5abSMax Reitz  * This function checks whether the given @to_replace is allowed to be
77425d69b5abSMax Reitz  * replaced by a node that always shows the same data as @bs.  This is
77435d69b5abSMax Reitz  * used for example to verify whether the mirror job can replace
77445d69b5abSMax Reitz  * @to_replace by the target mirrored from @bs.
77455d69b5abSMax Reitz  * To be replaceable, @bs and @to_replace may either be guaranteed to
77465d69b5abSMax Reitz  * always show the same data (because they are only connected through
77475d69b5abSMax Reitz  * filters), or some driver may allow replacing one of its children
77485d69b5abSMax Reitz  * because it can guarantee that this child's data is not visible at
77495d69b5abSMax Reitz  * all (for example, for dissenting quorum children that have no other
77505d69b5abSMax Reitz  * parents).
77515d69b5abSMax Reitz  */
77525d69b5abSMax Reitz bool bdrv_recurse_can_replace(BlockDriverState *bs,
77535d69b5abSMax Reitz                               BlockDriverState *to_replace)
77545d69b5abSMax Reitz {
775593393e69SMax Reitz     BlockDriverState *filtered;
775693393e69SMax Reitz 
7757b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7758b4ad82aaSEmanuele Giuseppe Esposito 
77595d69b5abSMax Reitz     if (!bs || !bs->drv) {
77605d69b5abSMax Reitz         return false;
77615d69b5abSMax Reitz     }
77625d69b5abSMax Reitz 
77635d69b5abSMax Reitz     if (bs == to_replace) {
77645d69b5abSMax Reitz         return true;
77655d69b5abSMax Reitz     }
77665d69b5abSMax Reitz 
77675d69b5abSMax Reitz     /* See what the driver can do */
77685d69b5abSMax Reitz     if (bs->drv->bdrv_recurse_can_replace) {
77695d69b5abSMax Reitz         return bs->drv->bdrv_recurse_can_replace(bs, to_replace);
77705d69b5abSMax Reitz     }
77715d69b5abSMax Reitz 
77725d69b5abSMax Reitz     /* For filters without an own implementation, we can recurse on our own */
777393393e69SMax Reitz     filtered = bdrv_filter_bs(bs);
777493393e69SMax Reitz     if (filtered) {
777593393e69SMax Reitz         return bdrv_recurse_can_replace(filtered, to_replace);
77765d69b5abSMax Reitz     }
77775d69b5abSMax Reitz 
77785d69b5abSMax Reitz     /* Safe default */
77795d69b5abSMax Reitz     return false;
77805d69b5abSMax Reitz }
77815d69b5abSMax Reitz 
7782810803a8SMax Reitz /*
7783810803a8SMax Reitz  * Check whether the given @node_name can be replaced by a node that
7784810803a8SMax Reitz  * has the same data as @parent_bs.  If so, return @node_name's BDS;
7785810803a8SMax Reitz  * NULL otherwise.
7786810803a8SMax Reitz  *
7787810803a8SMax Reitz  * @node_name must be a (recursive) *child of @parent_bs (or this
7788810803a8SMax Reitz  * function will return NULL).
7789810803a8SMax Reitz  *
7790810803a8SMax Reitz  * The result (whether the node can be replaced or not) is only valid
7791810803a8SMax Reitz  * for as long as no graph or permission changes occur.
7792810803a8SMax Reitz  */
7793e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
7794e12f3784SWen Congyang                                         const char *node_name, Error **errp)
779509158f00SBenoît Canet {
779609158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
77975a7e7a0bSStefan Hajnoczi 
7798f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7799f791bf7fSEmanuele Giuseppe Esposito 
780009158f00SBenoît Canet     if (!to_replace_bs) {
7801785ec4b1SConnor Kuehl         error_setg(errp, "Failed to find node with node-name='%s'", node_name);
780209158f00SBenoît Canet         return NULL;
780309158f00SBenoît Canet     }
780409158f00SBenoît Canet 
780509158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
7806b49f4755SStefan Hajnoczi         return NULL;
780709158f00SBenoît Canet     }
780809158f00SBenoît Canet 
780909158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
781009158f00SBenoît Canet      * most non filter in order to prevent data corruption.
781109158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
781209158f00SBenoît Canet      * blocked by the backing blockers.
781309158f00SBenoît Canet      */
7814810803a8SMax Reitz     if (!bdrv_recurse_can_replace(parent_bs, to_replace_bs)) {
7815810803a8SMax Reitz         error_setg(errp, "Cannot replace '%s' by a node mirrored from '%s', "
7816810803a8SMax Reitz                    "because it cannot be guaranteed that doing so would not "
7817810803a8SMax Reitz                    "lead to an abrupt change of visible data",
7818810803a8SMax Reitz                    node_name, parent_bs->node_name);
7819b49f4755SStefan Hajnoczi         return NULL;
782009158f00SBenoît Canet     }
782109158f00SBenoît Canet 
782209158f00SBenoît Canet     return to_replace_bs;
782309158f00SBenoît Canet }
7824448ad91dSMing Lei 
782597e2f021SMax Reitz /**
782697e2f021SMax Reitz  * Iterates through the list of runtime option keys that are said to
782797e2f021SMax Reitz  * be "strong" for a BDS.  An option is called "strong" if it changes
782897e2f021SMax Reitz  * a BDS's data.  For example, the null block driver's "size" and
782997e2f021SMax Reitz  * "read-zeroes" options are strong, but its "latency-ns" option is
783097e2f021SMax Reitz  * not.
783197e2f021SMax Reitz  *
783297e2f021SMax Reitz  * If a key returned by this function ends with a dot, all options
783397e2f021SMax Reitz  * starting with that prefix are strong.
783497e2f021SMax Reitz  */
783597e2f021SMax Reitz static const char *const *strong_options(BlockDriverState *bs,
783697e2f021SMax Reitz                                          const char *const *curopt)
783797e2f021SMax Reitz {
783897e2f021SMax Reitz     static const char *const global_options[] = {
783997e2f021SMax Reitz         "driver", "filename", NULL
784097e2f021SMax Reitz     };
784197e2f021SMax Reitz 
784297e2f021SMax Reitz     if (!curopt) {
784397e2f021SMax Reitz         return &global_options[0];
784497e2f021SMax Reitz     }
784597e2f021SMax Reitz 
784697e2f021SMax Reitz     curopt++;
784797e2f021SMax Reitz     if (curopt == &global_options[ARRAY_SIZE(global_options) - 1] && bs->drv) {
784897e2f021SMax Reitz         curopt = bs->drv->strong_runtime_opts;
784997e2f021SMax Reitz     }
785097e2f021SMax Reitz 
785197e2f021SMax Reitz     return (curopt && *curopt) ? curopt : NULL;
785297e2f021SMax Reitz }
785397e2f021SMax Reitz 
785497e2f021SMax Reitz /**
785597e2f021SMax Reitz  * Copies all strong runtime options from bs->options to the given
785697e2f021SMax Reitz  * QDict.  The set of strong option keys is determined by invoking
785797e2f021SMax Reitz  * strong_options().
785897e2f021SMax Reitz  *
785997e2f021SMax Reitz  * Returns true iff any strong option was present in bs->options (and
786097e2f021SMax Reitz  * thus copied to the target QDict) with the exception of "filename"
786197e2f021SMax Reitz  * and "driver".  The caller is expected to use this value to decide
786297e2f021SMax Reitz  * whether the existence of strong options prevents the generation of
786397e2f021SMax Reitz  * a plain filename.
786497e2f021SMax Reitz  */
786597e2f021SMax Reitz static bool append_strong_runtime_options(QDict *d, BlockDriverState *bs)
786697e2f021SMax Reitz {
786797e2f021SMax Reitz     bool found_any = false;
786897e2f021SMax Reitz     const char *const *option_name = NULL;
786997e2f021SMax Reitz 
787097e2f021SMax Reitz     if (!bs->drv) {
787197e2f021SMax Reitz         return false;
787297e2f021SMax Reitz     }
787397e2f021SMax Reitz 
787497e2f021SMax Reitz     while ((option_name = strong_options(bs, option_name))) {
787597e2f021SMax Reitz         bool option_given = false;
787697e2f021SMax Reitz 
787797e2f021SMax Reitz         assert(strlen(*option_name) > 0);
787897e2f021SMax Reitz         if ((*option_name)[strlen(*option_name) - 1] != '.') {
787997e2f021SMax Reitz             QObject *entry = qdict_get(bs->options, *option_name);
788097e2f021SMax Reitz             if (!entry) {
788197e2f021SMax Reitz                 continue;
788297e2f021SMax Reitz             }
788397e2f021SMax Reitz 
788497e2f021SMax Reitz             qdict_put_obj(d, *option_name, qobject_ref(entry));
788597e2f021SMax Reitz             option_given = true;
788697e2f021SMax Reitz         } else {
788797e2f021SMax Reitz             const QDictEntry *entry;
788897e2f021SMax Reitz             for (entry = qdict_first(bs->options); entry;
788997e2f021SMax Reitz                  entry = qdict_next(bs->options, entry))
789097e2f021SMax Reitz             {
789197e2f021SMax Reitz                 if (strstart(qdict_entry_key(entry), *option_name, NULL)) {
789297e2f021SMax Reitz                     qdict_put_obj(d, qdict_entry_key(entry),
789397e2f021SMax Reitz                                   qobject_ref(qdict_entry_value(entry)));
789497e2f021SMax Reitz                     option_given = true;
789597e2f021SMax Reitz                 }
789697e2f021SMax Reitz             }
789797e2f021SMax Reitz         }
789897e2f021SMax Reitz 
789997e2f021SMax Reitz         /* While "driver" and "filename" need to be included in a JSON filename,
790097e2f021SMax Reitz          * their existence does not prohibit generation of a plain filename. */
790197e2f021SMax Reitz         if (!found_any && option_given &&
790297e2f021SMax Reitz             strcmp(*option_name, "driver") && strcmp(*option_name, "filename"))
790397e2f021SMax Reitz         {
790497e2f021SMax Reitz             found_any = true;
790597e2f021SMax Reitz         }
790697e2f021SMax Reitz     }
790797e2f021SMax Reitz 
790862a01a27SMax Reitz     if (!qdict_haskey(d, "driver")) {
790962a01a27SMax Reitz         /* Drivers created with bdrv_new_open_driver() may not have a
791062a01a27SMax Reitz          * @driver option.  Add it here. */
791162a01a27SMax Reitz         qdict_put_str(d, "driver", bs->drv->format_name);
791262a01a27SMax Reitz     }
791362a01a27SMax Reitz 
791497e2f021SMax Reitz     return found_any;
791597e2f021SMax Reitz }
791697e2f021SMax Reitz 
791790993623SMax Reitz /* Note: This function may return false positives; it may return true
791890993623SMax Reitz  * even if opening the backing file specified by bs's image header
791990993623SMax Reitz  * would result in exactly bs->backing. */
7920004915a9SKevin Wolf static bool GRAPH_RDLOCK bdrv_backing_overridden(BlockDriverState *bs)
792190993623SMax Reitz {
7922b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
792390993623SMax Reitz     if (bs->backing) {
792490993623SMax Reitz         return strcmp(bs->auto_backing_file,
792590993623SMax Reitz                       bs->backing->bs->filename);
792690993623SMax Reitz     } else {
792790993623SMax Reitz         /* No backing BDS, so if the image header reports any backing
792890993623SMax Reitz          * file, it must have been suppressed */
792990993623SMax Reitz         return bs->auto_backing_file[0] != '\0';
793090993623SMax Reitz     }
793190993623SMax Reitz }
793290993623SMax Reitz 
793391af7014SMax Reitz /* Updates the following BDS fields:
793491af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
793591af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
793691af7014SMax Reitz  *                    other options; so reading and writing must return the same
793791af7014SMax Reitz  *                    results, but caching etc. may be different)
793891af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
793991af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
794091af7014SMax Reitz  *                       equalling the given one
794191af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
794291af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
794391af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
794491af7014SMax Reitz  */
794591af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
794691af7014SMax Reitz {
794791af7014SMax Reitz     BlockDriver *drv = bs->drv;
7948e24518e3SMax Reitz     BdrvChild *child;
794952f72d6fSMax Reitz     BlockDriverState *primary_child_bs;
795091af7014SMax Reitz     QDict *opts;
795190993623SMax Reitz     bool backing_overridden;
7952998b3a1eSMax Reitz     bool generate_json_filename; /* Whether our default implementation should
7953998b3a1eSMax Reitz                                     fill exact_filename (false) or not (true) */
795491af7014SMax Reitz 
7955f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
7956f791bf7fSEmanuele Giuseppe Esposito 
795791af7014SMax Reitz     if (!drv) {
795891af7014SMax Reitz         return;
795991af7014SMax Reitz     }
796091af7014SMax Reitz 
7961e24518e3SMax Reitz     /* This BDS's file name may depend on any of its children's file names, so
7962e24518e3SMax Reitz      * refresh those first */
7963e24518e3SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
7964e24518e3SMax Reitz         bdrv_refresh_filename(child->bs);
796591af7014SMax Reitz     }
796691af7014SMax Reitz 
7967bb808d5fSMax Reitz     if (bs->implicit) {
7968bb808d5fSMax Reitz         /* For implicit nodes, just copy everything from the single child */
7969bb808d5fSMax Reitz         child = QLIST_FIRST(&bs->children);
7970bb808d5fSMax Reitz         assert(QLIST_NEXT(child, next) == NULL);
7971bb808d5fSMax Reitz 
7972bb808d5fSMax Reitz         pstrcpy(bs->exact_filename, sizeof(bs->exact_filename),
7973bb808d5fSMax Reitz                 child->bs->exact_filename);
7974bb808d5fSMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), child->bs->filename);
7975bb808d5fSMax Reitz 
7976cb895614SPan Nengyuan         qobject_unref(bs->full_open_options);
7977bb808d5fSMax Reitz         bs->full_open_options = qobject_ref(child->bs->full_open_options);
7978bb808d5fSMax Reitz 
7979bb808d5fSMax Reitz         return;
7980bb808d5fSMax Reitz     }
7981bb808d5fSMax Reitz 
798290993623SMax Reitz     backing_overridden = bdrv_backing_overridden(bs);
798390993623SMax Reitz 
798490993623SMax Reitz     if (bs->open_flags & BDRV_O_NO_IO) {
798590993623SMax Reitz         /* Without I/O, the backing file does not change anything.
798690993623SMax Reitz          * Therefore, in such a case (primarily qemu-img), we can
798790993623SMax Reitz          * pretend the backing file has not been overridden even if
798890993623SMax Reitz          * it technically has been. */
798990993623SMax Reitz         backing_overridden = false;
799090993623SMax Reitz     }
799190993623SMax Reitz 
799297e2f021SMax Reitz     /* Gather the options QDict */
799397e2f021SMax Reitz     opts = qdict_new();
7994998b3a1eSMax Reitz     generate_json_filename = append_strong_runtime_options(opts, bs);
7995998b3a1eSMax Reitz     generate_json_filename |= backing_overridden;
799697e2f021SMax Reitz 
799797e2f021SMax Reitz     if (drv->bdrv_gather_child_options) {
799897e2f021SMax Reitz         /* Some block drivers may not want to present all of their children's
799997e2f021SMax Reitz          * options, or name them differently from BdrvChild.name */
800097e2f021SMax Reitz         drv->bdrv_gather_child_options(bs, opts, backing_overridden);
800197e2f021SMax Reitz     } else {
800297e2f021SMax Reitz         QLIST_FOREACH(child, &bs->children, next) {
800325191e5fSMax Reitz             if (child == bs->backing && !backing_overridden) {
800497e2f021SMax Reitz                 /* We can skip the backing BDS if it has not been overridden */
800597e2f021SMax Reitz                 continue;
800697e2f021SMax Reitz             }
800797e2f021SMax Reitz 
800897e2f021SMax Reitz             qdict_put(opts, child->name,
800997e2f021SMax Reitz                       qobject_ref(child->bs->full_open_options));
801097e2f021SMax Reitz         }
801197e2f021SMax Reitz 
801297e2f021SMax Reitz         if (backing_overridden && !bs->backing) {
801397e2f021SMax Reitz             /* Force no backing file */
801497e2f021SMax Reitz             qdict_put_null(opts, "backing");
801597e2f021SMax Reitz         }
801697e2f021SMax Reitz     }
801797e2f021SMax Reitz 
801897e2f021SMax Reitz     qobject_unref(bs->full_open_options);
801997e2f021SMax Reitz     bs->full_open_options = opts;
802097e2f021SMax Reitz 
802152f72d6fSMax Reitz     primary_child_bs = bdrv_primary_bs(bs);
802252f72d6fSMax Reitz 
8023998b3a1eSMax Reitz     if (drv->bdrv_refresh_filename) {
8024998b3a1eSMax Reitz         /* Obsolete information is of no use here, so drop the old file name
8025998b3a1eSMax Reitz          * information before refreshing it */
8026998b3a1eSMax Reitz         bs->exact_filename[0] = '\0';
8027998b3a1eSMax Reitz 
8028998b3a1eSMax Reitz         drv->bdrv_refresh_filename(bs);
802952f72d6fSMax Reitz     } else if (primary_child_bs) {
803052f72d6fSMax Reitz         /*
803152f72d6fSMax Reitz          * Try to reconstruct valid information from the underlying
803252f72d6fSMax Reitz          * file -- this only works for format nodes (filter nodes
803352f72d6fSMax Reitz          * cannot be probed and as such must be selected by the user
803452f72d6fSMax Reitz          * either through an options dict, or through a special
803552f72d6fSMax Reitz          * filename which the filter driver must construct in its
803652f72d6fSMax Reitz          * .bdrv_refresh_filename() implementation).
803752f72d6fSMax Reitz          */
8038998b3a1eSMax Reitz 
8039998b3a1eSMax Reitz         bs->exact_filename[0] = '\0';
8040998b3a1eSMax Reitz 
8041fb695c74SMax Reitz         /*
8042fb695c74SMax Reitz          * We can use the underlying file's filename if:
8043fb695c74SMax Reitz          * - it has a filename,
804452f72d6fSMax Reitz          * - the current BDS is not a filter,
8045fb695c74SMax Reitz          * - the file is a protocol BDS, and
8046fb695c74SMax Reitz          * - opening that file (as this BDS's format) will automatically create
8047fb695c74SMax Reitz          *   the BDS tree we have right now, that is:
8048fb695c74SMax Reitz          *   - the user did not significantly change this BDS's behavior with
8049fb695c74SMax Reitz          *     some explicit (strong) options
8050fb695c74SMax Reitz          *   - no non-file child of this BDS has been overridden by the user
8051fb695c74SMax Reitz          *   Both of these conditions are represented by generate_json_filename.
8052fb695c74SMax Reitz          */
805352f72d6fSMax Reitz         if (primary_child_bs->exact_filename[0] &&
805441770f6eSPaolo Bonzini             primary_child_bs->drv->protocol_name &&
805552f72d6fSMax Reitz             !drv->is_filter && !generate_json_filename)
8056fb695c74SMax Reitz         {
805752f72d6fSMax Reitz             strcpy(bs->exact_filename, primary_child_bs->exact_filename);
8058998b3a1eSMax Reitz         }
8059998b3a1eSMax Reitz     }
8060998b3a1eSMax Reitz 
806191af7014SMax Reitz     if (bs->exact_filename[0]) {
806291af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
806397e2f021SMax Reitz     } else {
8064eab3a467SMarkus Armbruster         GString *json = qobject_to_json(QOBJECT(bs->full_open_options));
80655c86bdf1SEric Blake         if (snprintf(bs->filename, sizeof(bs->filename), "json:%s",
8066eab3a467SMarkus Armbruster                      json->str) >= sizeof(bs->filename)) {
80675c86bdf1SEric Blake             /* Give user a hint if we truncated things. */
80685c86bdf1SEric Blake             strcpy(bs->filename + sizeof(bs->filename) - 4, "...");
80695c86bdf1SEric Blake         }
8070eab3a467SMarkus Armbruster         g_string_free(json, true);
807191af7014SMax Reitz     }
807291af7014SMax Reitz }
8073e06018adSWen Congyang 
80741e89d0f9SMax Reitz char *bdrv_dirname(BlockDriverState *bs, Error **errp)
80751e89d0f9SMax Reitz {
80761e89d0f9SMax Reitz     BlockDriver *drv = bs->drv;
807752f72d6fSMax Reitz     BlockDriverState *child_bs;
80781e89d0f9SMax Reitz 
8079f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
8080f791bf7fSEmanuele Giuseppe Esposito 
80811e89d0f9SMax Reitz     if (!drv) {
80821e89d0f9SMax Reitz         error_setg(errp, "Node '%s' is ejected", bs->node_name);
80831e89d0f9SMax Reitz         return NULL;
80841e89d0f9SMax Reitz     }
80851e89d0f9SMax Reitz 
80861e89d0f9SMax Reitz     if (drv->bdrv_dirname) {
80871e89d0f9SMax Reitz         return drv->bdrv_dirname(bs, errp);
80881e89d0f9SMax Reitz     }
80891e89d0f9SMax Reitz 
809052f72d6fSMax Reitz     child_bs = bdrv_primary_bs(bs);
809152f72d6fSMax Reitz     if (child_bs) {
809252f72d6fSMax Reitz         return bdrv_dirname(child_bs, errp);
80931e89d0f9SMax Reitz     }
80941e89d0f9SMax Reitz 
80951e89d0f9SMax Reitz     bdrv_refresh_filename(bs);
80961e89d0f9SMax Reitz     if (bs->exact_filename[0] != '\0') {
80971e89d0f9SMax Reitz         return path_combine(bs->exact_filename, "");
80981e89d0f9SMax Reitz     }
80991e89d0f9SMax Reitz 
81001e89d0f9SMax Reitz     error_setg(errp, "Cannot generate a base directory for %s nodes",
81011e89d0f9SMax Reitz                drv->format_name);
81021e89d0f9SMax Reitz     return NULL;
81031e89d0f9SMax Reitz }
81041e89d0f9SMax Reitz 
8105e06018adSWen Congyang /*
8106e06018adSWen Congyang  * Hot add/remove a BDS's child. So the user can take a child offline when
8107e06018adSWen Congyang  * it is broken and take a new child online
8108e06018adSWen Congyang  */
8109e06018adSWen Congyang void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
8110e06018adSWen Congyang                     Error **errp)
8111e06018adSWen Congyang {
8112f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
8113e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
8114e06018adSWen Congyang         error_setg(errp, "The node %s does not support adding a child",
8115e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
8116e06018adSWen Congyang         return;
8117e06018adSWen Congyang     }
8118e06018adSWen Congyang 
8119774c726cSSam Li     /*
8120774c726cSSam Li      * Non-zoned block drivers do not follow zoned storage constraints
8121774c726cSSam Li      * (i.e. sequential writes to zones). Refuse mixing zoned and non-zoned
8122774c726cSSam Li      * drivers in a graph.
8123774c726cSSam Li      */
8124774c726cSSam Li     if (!parent_bs->drv->supports_zoned_children &&
8125774c726cSSam Li         child_bs->bl.zoned == BLK_Z_HM) {
8126774c726cSSam Li         /*
8127774c726cSSam Li          * The host-aware model allows zoned storage constraints and random
8128774c726cSSam Li          * write. Allow mixing host-aware and non-zoned drivers. Using
8129774c726cSSam Li          * host-aware device as a regular device.
8130774c726cSSam Li          */
8131774c726cSSam Li         error_setg(errp, "Cannot add a %s child to a %s parent",
8132774c726cSSam Li                    child_bs->bl.zoned == BLK_Z_HM ? "zoned" : "non-zoned",
8133774c726cSSam Li                    parent_bs->drv->supports_zoned_children ?
8134774c726cSSam Li                    "support zoned children" : "not support zoned children");
8135774c726cSSam Li         return;
8136774c726cSSam Li     }
8137774c726cSSam Li 
8138e06018adSWen Congyang     if (!QLIST_EMPTY(&child_bs->parents)) {
8139e06018adSWen Congyang         error_setg(errp, "The node %s already has a parent",
8140e06018adSWen Congyang                    child_bs->node_name);
8141e06018adSWen Congyang         return;
8142e06018adSWen Congyang     }
8143e06018adSWen Congyang 
8144e06018adSWen Congyang     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
8145e06018adSWen Congyang }
8146e06018adSWen Congyang 
8147e06018adSWen Congyang void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
8148e06018adSWen Congyang {
8149e06018adSWen Congyang     BdrvChild *tmp;
8150e06018adSWen Congyang 
8151f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
8152e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
8153e06018adSWen Congyang         error_setg(errp, "The node %s does not support removing a child",
8154e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
8155e06018adSWen Congyang         return;
8156e06018adSWen Congyang     }
8157e06018adSWen Congyang 
8158e06018adSWen Congyang     QLIST_FOREACH(tmp, &parent_bs->children, next) {
8159e06018adSWen Congyang         if (tmp == child) {
8160e06018adSWen Congyang             break;
8161e06018adSWen Congyang         }
8162e06018adSWen Congyang     }
8163e06018adSWen Congyang 
8164e06018adSWen Congyang     if (!tmp) {
8165e06018adSWen Congyang         error_setg(errp, "The node %s does not have a child named %s",
8166e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs),
8167e06018adSWen Congyang                    bdrv_get_device_or_node_name(child->bs));
8168e06018adSWen Congyang         return;
8169e06018adSWen Congyang     }
8170e06018adSWen Congyang 
8171e06018adSWen Congyang     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
8172e06018adSWen Congyang }
81736f7a3b53SMax Reitz 
81746f7a3b53SMax Reitz int bdrv_make_empty(BdrvChild *c, Error **errp)
81756f7a3b53SMax Reitz {
81766f7a3b53SMax Reitz     BlockDriver *drv = c->bs->drv;
81776f7a3b53SMax Reitz     int ret;
81786f7a3b53SMax Reitz 
8179f791bf7fSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
81806f7a3b53SMax Reitz     assert(c->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED));
81816f7a3b53SMax Reitz 
81826f7a3b53SMax Reitz     if (!drv->bdrv_make_empty) {
81836f7a3b53SMax Reitz         error_setg(errp, "%s does not support emptying nodes",
81846f7a3b53SMax Reitz                    drv->format_name);
81856f7a3b53SMax Reitz         return -ENOTSUP;
81866f7a3b53SMax Reitz     }
81876f7a3b53SMax Reitz 
81886f7a3b53SMax Reitz     ret = drv->bdrv_make_empty(c->bs);
81896f7a3b53SMax Reitz     if (ret < 0) {
81906f7a3b53SMax Reitz         error_setg_errno(errp, -ret, "Failed to empty %s",
81916f7a3b53SMax Reitz                          c->bs->filename);
81926f7a3b53SMax Reitz         return ret;
81936f7a3b53SMax Reitz     }
81946f7a3b53SMax Reitz 
81956f7a3b53SMax Reitz     return 0;
81966f7a3b53SMax Reitz }
81979a6fc887SMax Reitz 
81989a6fc887SMax Reitz /*
81999a6fc887SMax Reitz  * Return the child that @bs acts as an overlay for, and from which data may be
82009a6fc887SMax Reitz  * copied in COW or COR operations.  Usually this is the backing file.
82019a6fc887SMax Reitz  */
82029a6fc887SMax Reitz BdrvChild *bdrv_cow_child(BlockDriverState *bs)
82039a6fc887SMax Reitz {
8204967d7905SEmanuele Giuseppe Esposito     IO_CODE();
8205967d7905SEmanuele Giuseppe Esposito 
82069a6fc887SMax Reitz     if (!bs || !bs->drv) {
82079a6fc887SMax Reitz         return NULL;
82089a6fc887SMax Reitz     }
82099a6fc887SMax Reitz 
82109a6fc887SMax Reitz     if (bs->drv->is_filter) {
82119a6fc887SMax Reitz         return NULL;
82129a6fc887SMax Reitz     }
82139a6fc887SMax Reitz 
82149a6fc887SMax Reitz     if (!bs->backing) {
82159a6fc887SMax Reitz         return NULL;
82169a6fc887SMax Reitz     }
82179a6fc887SMax Reitz 
82189a6fc887SMax Reitz     assert(bs->backing->role & BDRV_CHILD_COW);
82199a6fc887SMax Reitz     return bs->backing;
82209a6fc887SMax Reitz }
82219a6fc887SMax Reitz 
82229a6fc887SMax Reitz /*
82239a6fc887SMax Reitz  * If @bs acts as a filter for exactly one of its children, return
82249a6fc887SMax Reitz  * that child.
82259a6fc887SMax Reitz  */
82269a6fc887SMax Reitz BdrvChild *bdrv_filter_child(BlockDriverState *bs)
82279a6fc887SMax Reitz {
82289a6fc887SMax Reitz     BdrvChild *c;
8229967d7905SEmanuele Giuseppe Esposito     IO_CODE();
82309a6fc887SMax Reitz 
82319a6fc887SMax Reitz     if (!bs || !bs->drv) {
82329a6fc887SMax Reitz         return NULL;
82339a6fc887SMax Reitz     }
82349a6fc887SMax Reitz 
82359a6fc887SMax Reitz     if (!bs->drv->is_filter) {
82369a6fc887SMax Reitz         return NULL;
82379a6fc887SMax Reitz     }
82389a6fc887SMax Reitz 
82399a6fc887SMax Reitz     /* Only one of @backing or @file may be used */
82409a6fc887SMax Reitz     assert(!(bs->backing && bs->file));
82419a6fc887SMax Reitz 
82429a6fc887SMax Reitz     c = bs->backing ?: bs->file;
82439a6fc887SMax Reitz     if (!c) {
82449a6fc887SMax Reitz         return NULL;
82459a6fc887SMax Reitz     }
82469a6fc887SMax Reitz 
82479a6fc887SMax Reitz     assert(c->role & BDRV_CHILD_FILTERED);
82489a6fc887SMax Reitz     return c;
82499a6fc887SMax Reitz }
82509a6fc887SMax Reitz 
82519a6fc887SMax Reitz /*
82529a6fc887SMax Reitz  * Return either the result of bdrv_cow_child() or bdrv_filter_child(),
82539a6fc887SMax Reitz  * whichever is non-NULL.
82549a6fc887SMax Reitz  *
82559a6fc887SMax Reitz  * Return NULL if both are NULL.
82569a6fc887SMax Reitz  */
82579a6fc887SMax Reitz BdrvChild *bdrv_filter_or_cow_child(BlockDriverState *bs)
82589a6fc887SMax Reitz {
82599a6fc887SMax Reitz     BdrvChild *cow_child = bdrv_cow_child(bs);
82609a6fc887SMax Reitz     BdrvChild *filter_child = bdrv_filter_child(bs);
8261967d7905SEmanuele Giuseppe Esposito     IO_CODE();
82629a6fc887SMax Reitz 
82639a6fc887SMax Reitz     /* Filter nodes cannot have COW backing files */
82649a6fc887SMax Reitz     assert(!(cow_child && filter_child));
82659a6fc887SMax Reitz 
82669a6fc887SMax Reitz     return cow_child ?: filter_child;
82679a6fc887SMax Reitz }
82689a6fc887SMax Reitz 
82699a6fc887SMax Reitz /*
82709a6fc887SMax Reitz  * Return the primary child of this node: For filters, that is the
82719a6fc887SMax Reitz  * filtered child.  For other nodes, that is usually the child storing
82729a6fc887SMax Reitz  * metadata.
82739a6fc887SMax Reitz  * (A generally more helpful description is that this is (usually) the
82749a6fc887SMax Reitz  * child that has the same filename as @bs.)
82759a6fc887SMax Reitz  *
82769a6fc887SMax Reitz  * Drivers do not necessarily have a primary child; for example quorum
82779a6fc887SMax Reitz  * does not.
82789a6fc887SMax Reitz  */
82799a6fc887SMax Reitz BdrvChild *bdrv_primary_child(BlockDriverState *bs)
82809a6fc887SMax Reitz {
82819a6fc887SMax Reitz     BdrvChild *c, *found = NULL;
8282967d7905SEmanuele Giuseppe Esposito     IO_CODE();
82839a6fc887SMax Reitz 
82849a6fc887SMax Reitz     QLIST_FOREACH(c, &bs->children, next) {
82859a6fc887SMax Reitz         if (c->role & BDRV_CHILD_PRIMARY) {
82869a6fc887SMax Reitz             assert(!found);
82879a6fc887SMax Reitz             found = c;
82889a6fc887SMax Reitz         }
82899a6fc887SMax Reitz     }
82909a6fc887SMax Reitz 
82919a6fc887SMax Reitz     return found;
82929a6fc887SMax Reitz }
8293d38d7eb8SMax Reitz 
8294ec82cc41SKevin Wolf static BlockDriverState * GRAPH_RDLOCK
8295ec82cc41SKevin Wolf bdrv_do_skip_filters(BlockDriverState *bs, bool stop_on_explicit_filter)
8296d38d7eb8SMax Reitz {
8297d38d7eb8SMax Reitz     BdrvChild *c;
8298d38d7eb8SMax Reitz 
8299d38d7eb8SMax Reitz     if (!bs) {
8300d38d7eb8SMax Reitz         return NULL;
8301d38d7eb8SMax Reitz     }
8302d38d7eb8SMax Reitz 
8303d38d7eb8SMax Reitz     while (!(stop_on_explicit_filter && !bs->implicit)) {
8304d38d7eb8SMax Reitz         c = bdrv_filter_child(bs);
8305d38d7eb8SMax Reitz         if (!c) {
8306d38d7eb8SMax Reitz             /*
8307d38d7eb8SMax Reitz              * A filter that is embedded in a working block graph must
8308d38d7eb8SMax Reitz              * have a child.  Assert this here so this function does
8309d38d7eb8SMax Reitz              * not return a filter node that is not expected by the
8310d38d7eb8SMax Reitz              * caller.
8311d38d7eb8SMax Reitz              */
8312d38d7eb8SMax Reitz             assert(!bs->drv || !bs->drv->is_filter);
8313d38d7eb8SMax Reitz             break;
8314d38d7eb8SMax Reitz         }
8315d38d7eb8SMax Reitz         bs = c->bs;
8316d38d7eb8SMax Reitz     }
8317d38d7eb8SMax Reitz     /*
8318d38d7eb8SMax Reitz      * Note that this treats nodes with bs->drv == NULL as not being
8319d38d7eb8SMax Reitz      * filters (bs->drv == NULL should be replaced by something else
8320d38d7eb8SMax Reitz      * anyway).
8321d38d7eb8SMax Reitz      * The advantage of this behavior is that this function will thus
8322d38d7eb8SMax Reitz      * always return a non-NULL value (given a non-NULL @bs).
8323d38d7eb8SMax Reitz      */
8324d38d7eb8SMax Reitz 
8325d38d7eb8SMax Reitz     return bs;
8326d38d7eb8SMax Reitz }
8327d38d7eb8SMax Reitz 
8328d38d7eb8SMax Reitz /*
8329d38d7eb8SMax Reitz  * Return the first BDS that has not been added implicitly or that
8330d38d7eb8SMax Reitz  * does not have a filtered child down the chain starting from @bs
8331d38d7eb8SMax Reitz  * (including @bs itself).
8332d38d7eb8SMax Reitz  */
8333d38d7eb8SMax Reitz BlockDriverState *bdrv_skip_implicit_filters(BlockDriverState *bs)
8334d38d7eb8SMax Reitz {
8335b4ad82aaSEmanuele Giuseppe Esposito     GLOBAL_STATE_CODE();
8336d38d7eb8SMax Reitz     return bdrv_do_skip_filters(bs, true);
8337d38d7eb8SMax Reitz }
8338d38d7eb8SMax Reitz 
8339d38d7eb8SMax Reitz /*
8340d38d7eb8SMax Reitz  * Return the first BDS that does not have a filtered child down the
8341d38d7eb8SMax Reitz  * chain starting from @bs (including @bs itself).
8342d38d7eb8SMax Reitz  */
8343d38d7eb8SMax Reitz BlockDriverState *bdrv_skip_filters(BlockDriverState *bs)
8344d38d7eb8SMax Reitz {
8345967d7905SEmanuele Giuseppe Esposito     IO_CODE();
8346d38d7eb8SMax Reitz     return bdrv_do_skip_filters(bs, false);
8347d38d7eb8SMax Reitz }
8348d38d7eb8SMax Reitz 
8349d38d7eb8SMax Reitz /*
8350d38d7eb8SMax Reitz  * For a backing chain, return the first non-filter backing image of
8351d38d7eb8SMax Reitz  * the first non-filter image.
8352d38d7eb8SMax Reitz  */
8353d38d7eb8SMax Reitz BlockDriverState *bdrv_backing_chain_next(BlockDriverState *bs)
8354d38d7eb8SMax Reitz {
8355967d7905SEmanuele Giuseppe Esposito     IO_CODE();
8356d38d7eb8SMax Reitz     return bdrv_skip_filters(bdrv_cow_bs(bdrv_skip_filters(bs)));
8357d38d7eb8SMax Reitz }
83580bc329fbSHanna Reitz 
83590bc329fbSHanna Reitz /**
83600bc329fbSHanna Reitz  * Check whether [offset, offset + bytes) overlaps with the cached
83610bc329fbSHanna Reitz  * block-status data region.
83620bc329fbSHanna Reitz  *
83630bc329fbSHanna Reitz  * If so, and @pnum is not NULL, set *pnum to `bsc.data_end - offset`,
83640bc329fbSHanna Reitz  * which is what bdrv_bsc_is_data()'s interface needs.
83650bc329fbSHanna Reitz  * Otherwise, *pnum is not touched.
83660bc329fbSHanna Reitz  */
83670bc329fbSHanna Reitz static bool bdrv_bsc_range_overlaps_locked(BlockDriverState *bs,
83680bc329fbSHanna Reitz                                            int64_t offset, int64_t bytes,
83690bc329fbSHanna Reitz                                            int64_t *pnum)
83700bc329fbSHanna Reitz {
83710bc329fbSHanna Reitz     BdrvBlockStatusCache *bsc = qatomic_rcu_read(&bs->block_status_cache);
83720bc329fbSHanna Reitz     bool overlaps;
83730bc329fbSHanna Reitz 
83740bc329fbSHanna Reitz     overlaps =
83750bc329fbSHanna Reitz         qatomic_read(&bsc->valid) &&
83760bc329fbSHanna Reitz         ranges_overlap(offset, bytes, bsc->data_start,
83770bc329fbSHanna Reitz                        bsc->data_end - bsc->data_start);
83780bc329fbSHanna Reitz 
83790bc329fbSHanna Reitz     if (overlaps && pnum) {
83800bc329fbSHanna Reitz         *pnum = bsc->data_end - offset;
83810bc329fbSHanna Reitz     }
83820bc329fbSHanna Reitz 
83830bc329fbSHanna Reitz     return overlaps;
83840bc329fbSHanna Reitz }
83850bc329fbSHanna Reitz 
83860bc329fbSHanna Reitz /**
83870bc329fbSHanna Reitz  * See block_int.h for this function's documentation.
83880bc329fbSHanna Reitz  */
83890bc329fbSHanna Reitz bool bdrv_bsc_is_data(BlockDriverState *bs, int64_t offset, int64_t *pnum)
83900bc329fbSHanna Reitz {
8391967d7905SEmanuele Giuseppe Esposito     IO_CODE();
83920bc329fbSHanna Reitz     RCU_READ_LOCK_GUARD();
83930bc329fbSHanna Reitz     return bdrv_bsc_range_overlaps_locked(bs, offset, 1, pnum);
83940bc329fbSHanna Reitz }
83950bc329fbSHanna Reitz 
83960bc329fbSHanna Reitz /**
83970bc329fbSHanna Reitz  * See block_int.h for this function's documentation.
83980bc329fbSHanna Reitz  */
83990bc329fbSHanna Reitz void bdrv_bsc_invalidate_range(BlockDriverState *bs,
84000bc329fbSHanna Reitz                                int64_t offset, int64_t bytes)
84010bc329fbSHanna Reitz {
8402967d7905SEmanuele Giuseppe Esposito     IO_CODE();
84030bc329fbSHanna Reitz     RCU_READ_LOCK_GUARD();
84040bc329fbSHanna Reitz 
84050bc329fbSHanna Reitz     if (bdrv_bsc_range_overlaps_locked(bs, offset, bytes, NULL)) {
84060bc329fbSHanna Reitz         qatomic_set(&bs->block_status_cache->valid, false);
84070bc329fbSHanna Reitz     }
84080bc329fbSHanna Reitz }
84090bc329fbSHanna Reitz 
84100bc329fbSHanna Reitz /**
84110bc329fbSHanna Reitz  * See block_int.h for this function's documentation.
84120bc329fbSHanna Reitz  */
84130bc329fbSHanna Reitz void bdrv_bsc_fill(BlockDriverState *bs, int64_t offset, int64_t bytes)
84140bc329fbSHanna Reitz {
84150bc329fbSHanna Reitz     BdrvBlockStatusCache *new_bsc = g_new(BdrvBlockStatusCache, 1);
84160bc329fbSHanna Reitz     BdrvBlockStatusCache *old_bsc;
8417967d7905SEmanuele Giuseppe Esposito     IO_CODE();
84180bc329fbSHanna Reitz 
84190bc329fbSHanna Reitz     *new_bsc = (BdrvBlockStatusCache) {
84200bc329fbSHanna Reitz         .valid = true,
84210bc329fbSHanna Reitz         .data_start = offset,
84220bc329fbSHanna Reitz         .data_end = offset + bytes,
84230bc329fbSHanna Reitz     };
84240bc329fbSHanna Reitz 
84250bc329fbSHanna Reitz     QEMU_LOCK_GUARD(&bs->bsc_modify_lock);
84260bc329fbSHanna Reitz 
84270bc329fbSHanna Reitz     old_bsc = qatomic_rcu_read(&bs->block_status_cache);
84280bc329fbSHanna Reitz     qatomic_rcu_set(&bs->block_status_cache, new_bsc);
84290bc329fbSHanna Reitz     if (old_bsc) {
84300bc329fbSHanna Reitz         g_free_rcu(old_bsc, rcu);
84310bc329fbSHanna Reitz     }
84320bc329fbSHanna Reitz }
8433