xref: /openbmc/qemu/block.c (revision ca6b6e1e68ac44b2e8895da10dd1c80dc03d08b7)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
24d38ea87aSPeter Maydell #include "qemu/osdep.h"
250ab8ed18SDaniel P. Berrange #include "block/trace.h"
26737e150eSPaolo Bonzini #include "block/block_int.h"
27737e150eSPaolo Bonzini #include "block/blockjob.h"
28cd7fca95SKevin Wolf #include "block/nbd.h"
29d49b6836SMarkus Armbruster #include "qemu/error-report.h"
3088d88798SMarc Mari #include "module_block.h"
311de7afc9SPaolo Bonzini #include "qemu/module.h"
32cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
3391a097e7SKevin Wolf #include "qapi/qmp/qbool.h"
347b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
35bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
369c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
371de7afc9SPaolo Bonzini #include "qemu/notify.h"
3810817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
39c13163fbSBenoît Canet #include "block/qapi.h"
40b2023818SLuiz Capitulino #include "qmp-commands.h"
411de7afc9SPaolo Bonzini #include "qemu/timer.h"
42a5ee7bd4SWenchao Xia #include "qapi-event.h"
43f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
44f348b6d1SVeronia Bahaa #include "qemu/id.h"
45692e01a2SKevin Wolf #include "qapi/util.h"
46fc01f7e7Sbellard 
4771e72a19SJuan Quintela #ifdef CONFIG_BSD
487674e7bfSbellard #include <sys/ioctl.h>
4972cf2d4fSBlue Swirl #include <sys/queue.h>
50c5e97233Sblueswir1 #ifndef __DragonFly__
517674e7bfSbellard #include <sys/disk.h>
527674e7bfSbellard #endif
53c5e97233Sblueswir1 #endif
547674e7bfSbellard 
5549dc768dSaliguori #ifdef _WIN32
5649dc768dSaliguori #include <windows.h>
5749dc768dSaliguori #endif
5849dc768dSaliguori 
591c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
601c9805a3SStefan Hajnoczi 
61dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
62dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
63dc364f4cSBenoît Canet 
642c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
652c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
662c1d04e0SMax Reitz 
678a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
688a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
69ea2384d3Sbellard 
705b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
715b363937SMax Reitz                                            const char *reference,
725b363937SMax Reitz                                            QDict *options, int flags,
73f3930ed0SKevin Wolf                                            BlockDriverState *parent,
745b363937SMax Reitz                                            const BdrvChildRole *child_role,
755b363937SMax Reitz                                            Error **errp);
76f3930ed0SKevin Wolf 
77eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
78eb852011SMarkus Armbruster static int use_bdrv_whitelist;
79eb852011SMarkus Armbruster 
809e0b22f4SStefan Hajnoczi #ifdef _WIN32
819e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
829e0b22f4SStefan Hajnoczi {
839e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
849e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
859e0b22f4SStefan Hajnoczi             filename[1] == ':');
869e0b22f4SStefan Hajnoczi }
879e0b22f4SStefan Hajnoczi 
889e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
899e0b22f4SStefan Hajnoczi {
909e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
919e0b22f4SStefan Hajnoczi         filename[2] == '\0')
929e0b22f4SStefan Hajnoczi         return 1;
939e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
949e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
959e0b22f4SStefan Hajnoczi         return 1;
969e0b22f4SStefan Hajnoczi     return 0;
979e0b22f4SStefan Hajnoczi }
989e0b22f4SStefan Hajnoczi #endif
999e0b22f4SStefan Hajnoczi 
100339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
101339064d5SKevin Wolf {
102339064d5SKevin Wolf     if (!bs || !bs->drv) {
103459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
104459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
105339064d5SKevin Wolf     }
106339064d5SKevin Wolf 
107339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
108339064d5SKevin Wolf }
109339064d5SKevin Wolf 
1104196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1114196d2f0SDenis V. Lunev {
1124196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
113459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
114459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1154196d2f0SDenis V. Lunev     }
1164196d2f0SDenis V. Lunev 
1174196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1184196d2f0SDenis V. Lunev }
1194196d2f0SDenis V. Lunev 
1209e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1215c98415bSMax Reitz int path_has_protocol(const char *path)
1229e0b22f4SStefan Hajnoczi {
123947995c0SPaolo Bonzini     const char *p;
124947995c0SPaolo Bonzini 
1259e0b22f4SStefan Hajnoczi #ifdef _WIN32
1269e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1279e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1289e0b22f4SStefan Hajnoczi         return 0;
1299e0b22f4SStefan Hajnoczi     }
130947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
131947995c0SPaolo Bonzini #else
132947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1339e0b22f4SStefan Hajnoczi #endif
1349e0b22f4SStefan Hajnoczi 
135947995c0SPaolo Bonzini     return *p == ':';
1369e0b22f4SStefan Hajnoczi }
1379e0b22f4SStefan Hajnoczi 
13883f64091Sbellard int path_is_absolute(const char *path)
13983f64091Sbellard {
14021664424Sbellard #ifdef _WIN32
14121664424Sbellard     /* specific case for names like: "\\.\d:" */
142f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
14321664424Sbellard         return 1;
144f53f4da9SPaolo Bonzini     }
145f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1463b9f94e1Sbellard #else
147f53f4da9SPaolo Bonzini     return (*path == '/');
1483b9f94e1Sbellard #endif
14983f64091Sbellard }
15083f64091Sbellard 
15183f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
15283f64091Sbellard    path to it by considering it is relative to base_path. URL are
15383f64091Sbellard    supported. */
15483f64091Sbellard void path_combine(char *dest, int dest_size,
15583f64091Sbellard                   const char *base_path,
15683f64091Sbellard                   const char *filename)
15783f64091Sbellard {
15883f64091Sbellard     const char *p, *p1;
15983f64091Sbellard     int len;
16083f64091Sbellard 
16183f64091Sbellard     if (dest_size <= 0)
16283f64091Sbellard         return;
16383f64091Sbellard     if (path_is_absolute(filename)) {
16483f64091Sbellard         pstrcpy(dest, dest_size, filename);
16583f64091Sbellard     } else {
16683f64091Sbellard         p = strchr(base_path, ':');
16783f64091Sbellard         if (p)
16883f64091Sbellard             p++;
16983f64091Sbellard         else
17083f64091Sbellard             p = base_path;
1713b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1723b9f94e1Sbellard #ifdef _WIN32
1733b9f94e1Sbellard         {
1743b9f94e1Sbellard             const char *p2;
1753b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1763b9f94e1Sbellard             if (!p1 || p2 > p1)
1773b9f94e1Sbellard                 p1 = p2;
1783b9f94e1Sbellard         }
1793b9f94e1Sbellard #endif
18083f64091Sbellard         if (p1)
18183f64091Sbellard             p1++;
18283f64091Sbellard         else
18383f64091Sbellard             p1 = base_path;
18483f64091Sbellard         if (p1 > p)
18583f64091Sbellard             p = p1;
18683f64091Sbellard         len = p - base_path;
18783f64091Sbellard         if (len > dest_size - 1)
18883f64091Sbellard             len = dest_size - 1;
18983f64091Sbellard         memcpy(dest, base_path, len);
19083f64091Sbellard         dest[len] = '\0';
19183f64091Sbellard         pstrcat(dest, dest_size, filename);
19283f64091Sbellard     }
19383f64091Sbellard }
19483f64091Sbellard 
1950a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
1960a82855aSMax Reitz                                                   const char *backing,
1979f07429eSMax Reitz                                                   char *dest, size_t sz,
1989f07429eSMax Reitz                                                   Error **errp)
1990a82855aSMax Reitz {
2009f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2019f07429eSMax Reitz         path_is_absolute(backing))
2029f07429eSMax Reitz     {
2030a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2049f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2059f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2069f07429eSMax Reitz                    backed);
2070a82855aSMax Reitz     } else {
2080a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2090a82855aSMax Reitz     }
2100a82855aSMax Reitz }
2110a82855aSMax Reitz 
2129f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2139f07429eSMax Reitz                                     Error **errp)
214dc5a1371SPaolo Bonzini {
2159f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2169f07429eSMax Reitz 
2179f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2189f07429eSMax Reitz                                                  dest, sz, errp);
219dc5a1371SPaolo Bonzini }
220dc5a1371SPaolo Bonzini 
2210eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2220eb7217eSStefan Hajnoczi {
2238a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
224ea2384d3Sbellard }
225b338082bSbellard 
226e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
227e4e9986bSMarkus Armbruster {
228e4e9986bSMarkus Armbruster     BlockDriverState *bs;
229e4e9986bSMarkus Armbruster     int i;
230e4e9986bSMarkus Armbruster 
2315839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
232e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
233fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
234fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
235fbe40ff7SFam Zheng     }
236d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
2379fcb0251SFam Zheng     bs->refcnt = 1;
238dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
239d7d512f6SPaolo Bonzini 
2403ff2f67aSEvgeny Yakovlev     qemu_co_queue_init(&bs->flush_queue);
2413ff2f67aSEvgeny Yakovlev 
2422c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
2432c1d04e0SMax Reitz 
244b338082bSbellard     return bs;
245b338082bSbellard }
246b338082bSbellard 
24788d88798SMarc Mari static BlockDriver *bdrv_do_find_format(const char *format_name)
248ea2384d3Sbellard {
249ea2384d3Sbellard     BlockDriver *drv1;
25088d88798SMarc Mari 
2518a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2528a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
253ea2384d3Sbellard             return drv1;
254ea2384d3Sbellard         }
2558a22f02aSStefan Hajnoczi     }
25688d88798SMarc Mari 
257ea2384d3Sbellard     return NULL;
258ea2384d3Sbellard }
259ea2384d3Sbellard 
26088d88798SMarc Mari BlockDriver *bdrv_find_format(const char *format_name)
26188d88798SMarc Mari {
26288d88798SMarc Mari     BlockDriver *drv1;
26388d88798SMarc Mari     int i;
26488d88798SMarc Mari 
26588d88798SMarc Mari     drv1 = bdrv_do_find_format(format_name);
26688d88798SMarc Mari     if (drv1) {
26788d88798SMarc Mari         return drv1;
26888d88798SMarc Mari     }
26988d88798SMarc Mari 
27088d88798SMarc Mari     /* The driver isn't registered, maybe we need to load a module */
27188d88798SMarc Mari     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
27288d88798SMarc Mari         if (!strcmp(block_driver_modules[i].format_name, format_name)) {
27388d88798SMarc Mari             block_module_load_one(block_driver_modules[i].library_name);
27488d88798SMarc Mari             break;
27588d88798SMarc Mari         }
27688d88798SMarc Mari     }
27788d88798SMarc Mari 
27888d88798SMarc Mari     return bdrv_do_find_format(format_name);
27988d88798SMarc Mari }
28088d88798SMarc Mari 
281b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
282eb852011SMarkus Armbruster {
283b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
284b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
285b64ec4e4SFam Zheng     };
286b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
287b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
288eb852011SMarkus Armbruster     };
289eb852011SMarkus Armbruster     const char **p;
290eb852011SMarkus Armbruster 
291b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
292eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
293b64ec4e4SFam Zheng     }
294eb852011SMarkus Armbruster 
295b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
296eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
297eb852011SMarkus Armbruster             return 1;
298eb852011SMarkus Armbruster         }
299eb852011SMarkus Armbruster     }
300b64ec4e4SFam Zheng     if (read_only) {
301b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
302b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
303b64ec4e4SFam Zheng                 return 1;
304b64ec4e4SFam Zheng             }
305b64ec4e4SFam Zheng         }
306b64ec4e4SFam Zheng     }
307eb852011SMarkus Armbruster     return 0;
308eb852011SMarkus Armbruster }
309eb852011SMarkus Armbruster 
310e6ff69bfSDaniel P. Berrange bool bdrv_uses_whitelist(void)
311e6ff69bfSDaniel P. Berrange {
312e6ff69bfSDaniel P. Berrange     return use_bdrv_whitelist;
313e6ff69bfSDaniel P. Berrange }
314e6ff69bfSDaniel P. Berrange 
3155b7e1542SZhi Yong Wu typedef struct CreateCo {
3165b7e1542SZhi Yong Wu     BlockDriver *drv;
3175b7e1542SZhi Yong Wu     char *filename;
31883d0521aSChunyan Liu     QemuOpts *opts;
3195b7e1542SZhi Yong Wu     int ret;
320cc84d90fSMax Reitz     Error *err;
3215b7e1542SZhi Yong Wu } CreateCo;
3225b7e1542SZhi Yong Wu 
3235b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3245b7e1542SZhi Yong Wu {
325cc84d90fSMax Reitz     Error *local_err = NULL;
326cc84d90fSMax Reitz     int ret;
327cc84d90fSMax Reitz 
3285b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3295b7e1542SZhi Yong Wu     assert(cco->drv);
3305b7e1542SZhi Yong Wu 
331c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
332cc84d90fSMax Reitz     error_propagate(&cco->err, local_err);
333cc84d90fSMax Reitz     cco->ret = ret;
3345b7e1542SZhi Yong Wu }
3355b7e1542SZhi Yong Wu 
3360e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
33783d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
338ea2384d3Sbellard {
3395b7e1542SZhi Yong Wu     int ret;
3400e7e1989SKevin Wolf 
3415b7e1542SZhi Yong Wu     Coroutine *co;
3425b7e1542SZhi Yong Wu     CreateCo cco = {
3435b7e1542SZhi Yong Wu         .drv = drv,
3445b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
34583d0521aSChunyan Liu         .opts = opts,
3465b7e1542SZhi Yong Wu         .ret = NOT_DONE,
347cc84d90fSMax Reitz         .err = NULL,
3485b7e1542SZhi Yong Wu     };
3495b7e1542SZhi Yong Wu 
350c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
351cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35280168bffSLuiz Capitulino         ret = -ENOTSUP;
35380168bffSLuiz Capitulino         goto out;
3545b7e1542SZhi Yong Wu     }
3555b7e1542SZhi Yong Wu 
3565b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3575b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3585b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3595b7e1542SZhi Yong Wu     } else {
3600b8b8753SPaolo Bonzini         co = qemu_coroutine_create(bdrv_create_co_entry, &cco);
3610b8b8753SPaolo Bonzini         qemu_coroutine_enter(co);
3625b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
363b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3645b7e1542SZhi Yong Wu         }
3655b7e1542SZhi Yong Wu     }
3665b7e1542SZhi Yong Wu 
3675b7e1542SZhi Yong Wu     ret = cco.ret;
368cc84d90fSMax Reitz     if (ret < 0) {
36984d18f06SMarkus Armbruster         if (cco.err) {
370cc84d90fSMax Reitz             error_propagate(errp, cco.err);
371cc84d90fSMax Reitz         } else {
372cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
373cc84d90fSMax Reitz         }
374cc84d90fSMax Reitz     }
3755b7e1542SZhi Yong Wu 
37680168bffSLuiz Capitulino out:
37780168bffSLuiz Capitulino     g_free(cco.filename);
3785b7e1542SZhi Yong Wu     return ret;
379ea2384d3Sbellard }
380ea2384d3Sbellard 
381c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38284a12e66SChristoph Hellwig {
38384a12e66SChristoph Hellwig     BlockDriver *drv;
384cc84d90fSMax Reitz     Error *local_err = NULL;
385cc84d90fSMax Reitz     int ret;
38684a12e66SChristoph Hellwig 
387b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
38884a12e66SChristoph Hellwig     if (drv == NULL) {
38916905d71SStefan Hajnoczi         return -ENOENT;
39084a12e66SChristoph Hellwig     }
39184a12e66SChristoph Hellwig 
392c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
393cc84d90fSMax Reitz     error_propagate(errp, local_err);
394cc84d90fSMax Reitz     return ret;
39584a12e66SChristoph Hellwig }
39684a12e66SChristoph Hellwig 
397892b7de8SEkaterina Tumanova /**
398892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
399892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
400892b7de8SEkaterina Tumanova  * On failure return -errno.
401892b7de8SEkaterina Tumanova  * @bs must not be empty.
402892b7de8SEkaterina Tumanova  */
403892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
404892b7de8SEkaterina Tumanova {
405892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
406892b7de8SEkaterina Tumanova 
407892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
408892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
409892b7de8SEkaterina Tumanova     }
410892b7de8SEkaterina Tumanova 
411892b7de8SEkaterina Tumanova     return -ENOTSUP;
412892b7de8SEkaterina Tumanova }
413892b7de8SEkaterina Tumanova 
414892b7de8SEkaterina Tumanova /**
415892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
416892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
417892b7de8SEkaterina Tumanova  * On failure return -errno.
418892b7de8SEkaterina Tumanova  * @bs must not be empty.
419892b7de8SEkaterina Tumanova  */
420892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
421892b7de8SEkaterina Tumanova {
422892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
423892b7de8SEkaterina Tumanova 
424892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
425892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
426892b7de8SEkaterina Tumanova     }
427892b7de8SEkaterina Tumanova 
428892b7de8SEkaterina Tumanova     return -ENOTSUP;
429892b7de8SEkaterina Tumanova }
430892b7de8SEkaterina Tumanova 
431eba25057SJim Meyering /*
432eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
433eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
434eba25057SJim Meyering  */
435eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
436eba25057SJim Meyering {
437d5249393Sbellard #ifdef _WIN32
4383b9f94e1Sbellard     char temp_dir[MAX_PATH];
439eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
440eba25057SJim Meyering        have length MAX_PATH or greater.  */
441eba25057SJim Meyering     assert(size >= MAX_PATH);
442eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
443eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
444eba25057SJim Meyering             ? 0 : -GetLastError());
445d5249393Sbellard #else
446ea2384d3Sbellard     int fd;
4477ccfb2ebSblueswir1     const char *tmpdir;
4480badc1eeSaurel32     tmpdir = getenv("TMPDIR");
44969bef793SAmit Shah     if (!tmpdir) {
45069bef793SAmit Shah         tmpdir = "/var/tmp";
45169bef793SAmit Shah     }
452eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
453eba25057SJim Meyering         return -EOVERFLOW;
454ea2384d3Sbellard     }
455eba25057SJim Meyering     fd = mkstemp(filename);
456fe235a06SDunrong Huang     if (fd < 0) {
457fe235a06SDunrong Huang         return -errno;
458fe235a06SDunrong Huang     }
459fe235a06SDunrong Huang     if (close(fd) != 0) {
460fe235a06SDunrong Huang         unlink(filename);
461eba25057SJim Meyering         return -errno;
462eba25057SJim Meyering     }
463eba25057SJim Meyering     return 0;
464d5249393Sbellard #endif
465eba25057SJim Meyering }
466ea2384d3Sbellard 
467f3a5d3f8SChristoph Hellwig /*
468f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
469f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
470f3a5d3f8SChristoph Hellwig  */
471f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
472f3a5d3f8SChristoph Hellwig {
473508c7cb3SChristoph Hellwig     int score_max = 0, score;
474508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
475f3a5d3f8SChristoph Hellwig 
4768a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
477508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
478508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
479508c7cb3SChristoph Hellwig             if (score > score_max) {
480508c7cb3SChristoph Hellwig                 score_max = score;
481508c7cb3SChristoph Hellwig                 drv = d;
482f3a5d3f8SChristoph Hellwig             }
483508c7cb3SChristoph Hellwig         }
484f3a5d3f8SChristoph Hellwig     }
485f3a5d3f8SChristoph Hellwig 
486508c7cb3SChristoph Hellwig     return drv;
487f3a5d3f8SChristoph Hellwig }
488f3a5d3f8SChristoph Hellwig 
48988d88798SMarc Mari static BlockDriver *bdrv_do_find_protocol(const char *protocol)
49088d88798SMarc Mari {
49188d88798SMarc Mari     BlockDriver *drv1;
49288d88798SMarc Mari 
49388d88798SMarc Mari     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
49488d88798SMarc Mari         if (drv1->protocol_name && !strcmp(drv1->protocol_name, protocol)) {
49588d88798SMarc Mari             return drv1;
49688d88798SMarc Mari         }
49788d88798SMarc Mari     }
49888d88798SMarc Mari 
49988d88798SMarc Mari     return NULL;
50088d88798SMarc Mari }
50188d88798SMarc Mari 
50298289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
503b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
504b65a5e12SMax Reitz                                 Error **errp)
50584a12e66SChristoph Hellwig {
50684a12e66SChristoph Hellwig     BlockDriver *drv1;
50784a12e66SChristoph Hellwig     char protocol[128];
50884a12e66SChristoph Hellwig     int len;
50984a12e66SChristoph Hellwig     const char *p;
51088d88798SMarc Mari     int i;
51184a12e66SChristoph Hellwig 
51266f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
51366f82ceeSKevin Wolf 
51439508e7aSChristoph Hellwig     /*
51539508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
51639508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
51739508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
51839508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
51939508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
52039508e7aSChristoph Hellwig      */
52184a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
52239508e7aSChristoph Hellwig     if (drv1) {
52384a12e66SChristoph Hellwig         return drv1;
52484a12e66SChristoph Hellwig     }
52539508e7aSChristoph Hellwig 
52698289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
527ef810437SMax Reitz         return &bdrv_file;
52839508e7aSChristoph Hellwig     }
52998289620SKevin Wolf 
5309e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5319e0b22f4SStefan Hajnoczi     assert(p != NULL);
53284a12e66SChristoph Hellwig     len = p - filename;
53384a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
53484a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
53584a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
53684a12e66SChristoph Hellwig     protocol[len] = '\0';
53788d88798SMarc Mari 
53888d88798SMarc Mari     drv1 = bdrv_do_find_protocol(protocol);
53988d88798SMarc Mari     if (drv1) {
54084a12e66SChristoph Hellwig         return drv1;
54184a12e66SChristoph Hellwig     }
54288d88798SMarc Mari 
54388d88798SMarc Mari     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); ++i) {
54488d88798SMarc Mari         if (block_driver_modules[i].protocol_name &&
54588d88798SMarc Mari             !strcmp(block_driver_modules[i].protocol_name, protocol)) {
54688d88798SMarc Mari             block_module_load_one(block_driver_modules[i].library_name);
54788d88798SMarc Mari             break;
54888d88798SMarc Mari         }
54984a12e66SChristoph Hellwig     }
550b65a5e12SMax Reitz 
55188d88798SMarc Mari     drv1 = bdrv_do_find_protocol(protocol);
55288d88798SMarc Mari     if (!drv1) {
553b65a5e12SMax Reitz         error_setg(errp, "Unknown protocol '%s'", protocol);
55488d88798SMarc Mari     }
55588d88798SMarc Mari     return drv1;
55684a12e66SChristoph Hellwig }
55784a12e66SChristoph Hellwig 
558c6684249SMarkus Armbruster /*
559c6684249SMarkus Armbruster  * Guess image format by probing its contents.
560c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
561c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
562c6684249SMarkus Armbruster  *
563c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5647cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5657cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
566c6684249SMarkus Armbruster  * @filename    is its filename.
567c6684249SMarkus Armbruster  *
568c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
569c6684249SMarkus Armbruster  * probing score.
570c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
571c6684249SMarkus Armbruster  */
57238f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
573c6684249SMarkus Armbruster                             const char *filename)
574c6684249SMarkus Armbruster {
575c6684249SMarkus Armbruster     int score_max = 0, score;
576c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
577c6684249SMarkus Armbruster 
578c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
579c6684249SMarkus Armbruster         if (d->bdrv_probe) {
580c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
581c6684249SMarkus Armbruster             if (score > score_max) {
582c6684249SMarkus Armbruster                 score_max = score;
583c6684249SMarkus Armbruster                 drv = d;
584c6684249SMarkus Armbruster             }
585c6684249SMarkus Armbruster         }
586c6684249SMarkus Armbruster     }
587c6684249SMarkus Armbruster 
588c6684249SMarkus Armbruster     return drv;
589c6684249SMarkus Armbruster }
590c6684249SMarkus Armbruster 
591cf2ab8fcSKevin Wolf static int find_image_format(BdrvChild *file, const char *filename,
59234b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
593ea2384d3Sbellard {
594cf2ab8fcSKevin Wolf     BlockDriverState *bs = file->bs;
595c6684249SMarkus Armbruster     BlockDriver *drv;
5967cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
597f500a6d3SKevin Wolf     int ret = 0;
598f8ea0b00SNicholas Bellinger 
59908a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
600b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
601ef810437SMax Reitz         *pdrv = &bdrv_raw;
602c98ac35dSStefan Weil         return ret;
6031a396859SNicholas A. Bellinger     }
604f8ea0b00SNicholas Bellinger 
605cf2ab8fcSKevin Wolf     ret = bdrv_pread(file, 0, buf, sizeof(buf));
606ea2384d3Sbellard     if (ret < 0) {
60734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
60834b5d2c6SMax Reitz                          "format");
609c98ac35dSStefan Weil         *pdrv = NULL;
610c98ac35dSStefan Weil         return ret;
611ea2384d3Sbellard     }
612ea2384d3Sbellard 
613c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
614c98ac35dSStefan Weil     if (!drv) {
61534b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
61634b5d2c6SMax Reitz                    "driver found");
617c98ac35dSStefan Weil         ret = -ENOENT;
618c98ac35dSStefan Weil     }
619c98ac35dSStefan Weil     *pdrv = drv;
620c98ac35dSStefan Weil     return ret;
621ea2384d3Sbellard }
622ea2384d3Sbellard 
62351762288SStefan Hajnoczi /**
62451762288SStefan Hajnoczi  * Set the current 'total_sectors' value
62565a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
62651762288SStefan Hajnoczi  */
62751762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
62851762288SStefan Hajnoczi {
62951762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
63051762288SStefan Hajnoczi 
631396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
632b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
633396759adSNicholas Bellinger         return 0;
634396759adSNicholas Bellinger 
63551762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
63651762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
63751762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
63851762288SStefan Hajnoczi         if (length < 0) {
63951762288SStefan Hajnoczi             return length;
64051762288SStefan Hajnoczi         }
6417e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
64251762288SStefan Hajnoczi     }
64351762288SStefan Hajnoczi 
64451762288SStefan Hajnoczi     bs->total_sectors = hint;
64551762288SStefan Hajnoczi     return 0;
64651762288SStefan Hajnoczi }
64751762288SStefan Hajnoczi 
648c3993cdcSStefan Hajnoczi /**
649cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
650cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
651cddff5baSKevin Wolf  */
652cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
653cddff5baSKevin Wolf                               QDict *old_options)
654cddff5baSKevin Wolf {
655cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
656cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
657cddff5baSKevin Wolf     } else {
658cddff5baSKevin Wolf         qdict_join(options, old_options, false);
659cddff5baSKevin Wolf     }
660cddff5baSKevin Wolf }
661cddff5baSKevin Wolf 
662cddff5baSKevin Wolf /**
6639e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6649e8f1835SPaolo Bonzini  *
6659e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6669e8f1835SPaolo Bonzini  */
6679e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6689e8f1835SPaolo Bonzini {
6699e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6709e8f1835SPaolo Bonzini 
6719e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6729e8f1835SPaolo Bonzini         /* do nothing */
6739e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6749e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6759e8f1835SPaolo Bonzini     } else {
6769e8f1835SPaolo Bonzini         return -1;
6779e8f1835SPaolo Bonzini     }
6789e8f1835SPaolo Bonzini 
6799e8f1835SPaolo Bonzini     return 0;
6809e8f1835SPaolo Bonzini }
6819e8f1835SPaolo Bonzini 
6829e8f1835SPaolo Bonzini /**
683c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
684c3993cdcSStefan Hajnoczi  *
685c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
686c3993cdcSStefan Hajnoczi  */
68753e8ae01SKevin Wolf int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
688c3993cdcSStefan Hajnoczi {
689c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
690c3993cdcSStefan Hajnoczi 
691c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
69253e8ae01SKevin Wolf         *writethrough = false;
69353e8ae01SKevin Wolf         *flags |= BDRV_O_NOCACHE;
69492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
69553e8ae01SKevin Wolf         *writethrough = true;
69692196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
697c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
69853e8ae01SKevin Wolf         *writethrough = false;
699c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
70053e8ae01SKevin Wolf         *writethrough = false;
701c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
702c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
70353e8ae01SKevin Wolf         *writethrough = true;
704c3993cdcSStefan Hajnoczi     } else {
705c3993cdcSStefan Hajnoczi         return -1;
706c3993cdcSStefan Hajnoczi     }
707c3993cdcSStefan Hajnoczi 
708c3993cdcSStefan Hajnoczi     return 0;
709c3993cdcSStefan Hajnoczi }
710c3993cdcSStefan Hajnoczi 
71120018e12SKevin Wolf static void bdrv_child_cb_drained_begin(BdrvChild *child)
71220018e12SKevin Wolf {
71320018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
71420018e12SKevin Wolf     bdrv_drained_begin(bs);
71520018e12SKevin Wolf }
71620018e12SKevin Wolf 
71720018e12SKevin Wolf static void bdrv_child_cb_drained_end(BdrvChild *child)
71820018e12SKevin Wolf {
71920018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
72020018e12SKevin Wolf     bdrv_drained_end(bs);
72120018e12SKevin Wolf }
72220018e12SKevin Wolf 
7230b50cc88SKevin Wolf /*
72473176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
72573176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
72673176beeSKevin Wolf  * flags like a backing file)
727b1e6fc08SKevin Wolf  */
72873176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
72973176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
730b1e6fc08SKevin Wolf {
73173176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
73273176beeSKevin Wolf 
73373176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
73473176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
73573176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
73641869044SKevin Wolf 
737f87a0e29SAlberto Garcia     /* Copy the read-only option from the parent */
738f87a0e29SAlberto Garcia     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
739f87a0e29SAlberto Garcia 
74041869044SKevin Wolf     /* aio=native doesn't work for cache.direct=off, so disable it for the
74141869044SKevin Wolf      * temporary snapshot */
74241869044SKevin Wolf     *child_flags &= ~BDRV_O_NATIVE_AIO;
743b1e6fc08SKevin Wolf }
744b1e6fc08SKevin Wolf 
745b1e6fc08SKevin Wolf /*
7468e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
7478e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
7480b50cc88SKevin Wolf  */
7498e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
7508e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
7510b50cc88SKevin Wolf {
7528e2160e2SKevin Wolf     int flags = parent_flags;
7538e2160e2SKevin Wolf 
7540b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7550b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7560b50cc88SKevin Wolf 
75791a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
75891a097e7SKevin Wolf      * the parent. */
75991a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
76091a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
76191a097e7SKevin Wolf 
762f87a0e29SAlberto Garcia     /* Inherit the read-only option from the parent if it's not set */
763f87a0e29SAlberto Garcia     qdict_copy_default(child_options, parent_options, BDRV_OPT_READ_ONLY);
764f87a0e29SAlberto Garcia 
7650b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
76691a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
76791a097e7SKevin Wolf      * corresponding parent options. */
768818584a4SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_DISCARD, "unmap");
7690b50cc88SKevin Wolf 
7700b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
771abb06c5aSDaniel P. Berrange     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
772abb06c5aSDaniel P. Berrange                BDRV_O_NO_IO);
7730b50cc88SKevin Wolf 
7748e2160e2SKevin Wolf     *child_flags = flags;
7750b50cc88SKevin Wolf }
7760b50cc88SKevin Wolf 
777f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7788e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
77920018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
78020018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
781f3930ed0SKevin Wolf };
782f3930ed0SKevin Wolf 
783f3930ed0SKevin Wolf /*
7848e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7858e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7868e2160e2SKevin Wolf  * flags for the parent BDS
787f3930ed0SKevin Wolf  */
7888e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7898e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
790f3930ed0SKevin Wolf {
7918e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7928e2160e2SKevin Wolf                                parent_flags, parent_options);
7938e2160e2SKevin Wolf 
794abb06c5aSDaniel P. Berrange     *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
795f3930ed0SKevin Wolf }
796f3930ed0SKevin Wolf 
797f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7988e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
79920018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
80020018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
801f3930ed0SKevin Wolf };
802f3930ed0SKevin Wolf 
803317fc44eSKevin Wolf /*
8048e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
8058e2160e2SKevin Wolf  * given options and flags for the parent BDS
806317fc44eSKevin Wolf  */
8078e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
8088e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
809317fc44eSKevin Wolf {
8108e2160e2SKevin Wolf     int flags = parent_flags;
8118e2160e2SKevin Wolf 
812b8816a43SKevin Wolf     /* The cache mode is inherited unmodified for backing files; except WCE,
813b8816a43SKevin Wolf      * which is only applied on the top level (BlockBackend) */
81491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
81591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
81691a097e7SKevin Wolf 
817317fc44eSKevin Wolf     /* backing files always opened read-only */
818f87a0e29SAlberto Garcia     qdict_set_default_str(child_options, BDRV_OPT_READ_ONLY, "on");
819f87a0e29SAlberto Garcia     flags &= ~BDRV_O_COPY_ON_READ;
820317fc44eSKevin Wolf 
821317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
8228bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
823317fc44eSKevin Wolf 
8248e2160e2SKevin Wolf     *child_flags = flags;
825317fc44eSKevin Wolf }
826317fc44eSKevin Wolf 
827f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
8288e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
82920018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
83020018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
831f3930ed0SKevin Wolf };
832f3930ed0SKevin Wolf 
8337b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
8347b272452SKevin Wolf {
83561de4c68SKevin Wolf     int open_flags = flags;
8367b272452SKevin Wolf 
8377b272452SKevin Wolf     /*
8387b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
8397b272452SKevin Wolf      * image.
8407b272452SKevin Wolf      */
84120cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
8427b272452SKevin Wolf 
8437b272452SKevin Wolf     /*
8447b272452SKevin Wolf      * Snapshots should be writable.
8457b272452SKevin Wolf      */
8468bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
8477b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
8487b272452SKevin Wolf     }
8497b272452SKevin Wolf 
8507b272452SKevin Wolf     return open_flags;
8517b272452SKevin Wolf }
8527b272452SKevin Wolf 
85391a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
85491a097e7SKevin Wolf {
85591a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
85691a097e7SKevin Wolf 
85791a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
85891a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
85991a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
86091a097e7SKevin Wolf     }
86191a097e7SKevin Wolf 
86291a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
86391a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
86491a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
86591a097e7SKevin Wolf     }
866f87a0e29SAlberto Garcia 
867f87a0e29SAlberto Garcia     *flags &= ~BDRV_O_RDWR;
868f87a0e29SAlberto Garcia 
869f87a0e29SAlberto Garcia     assert(qemu_opt_find(opts, BDRV_OPT_READ_ONLY));
870f87a0e29SAlberto Garcia     if (!qemu_opt_get_bool(opts, BDRV_OPT_READ_ONLY, false)) {
871f87a0e29SAlberto Garcia         *flags |= BDRV_O_RDWR;
872f87a0e29SAlberto Garcia     }
873f87a0e29SAlberto Garcia 
87491a097e7SKevin Wolf }
87591a097e7SKevin Wolf 
87691a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
87791a097e7SKevin Wolf {
87891a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
87991a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
88091a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
88191a097e7SKevin Wolf     }
88291a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
88391a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
88491a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
88591a097e7SKevin Wolf     }
886f87a0e29SAlberto Garcia     if (!qdict_haskey(options, BDRV_OPT_READ_ONLY)) {
887f87a0e29SAlberto Garcia         qdict_put(options, BDRV_OPT_READ_ONLY,
888f87a0e29SAlberto Garcia                   qbool_from_bool(!(flags & BDRV_O_RDWR)));
889f87a0e29SAlberto Garcia     }
89091a097e7SKevin Wolf }
89191a097e7SKevin Wolf 
892636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8936913c0c2SBenoît Canet                                   const char *node_name,
8946913c0c2SBenoît Canet                                   Error **errp)
8956913c0c2SBenoît Canet {
89615489c76SJeff Cody     char *gen_node_name = NULL;
8976913c0c2SBenoît Canet 
89815489c76SJeff Cody     if (!node_name) {
89915489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
90015489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
90115489c76SJeff Cody         /*
90215489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
90315489c76SJeff Cody          * generated (generated names use characters not available to the user)
90415489c76SJeff Cody          */
9059aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
906636ea370SKevin Wolf         return;
9076913c0c2SBenoît Canet     }
9086913c0c2SBenoît Canet 
9090c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
9107f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
9110c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
9120c5e94eeSBenoît Canet                    node_name);
91315489c76SJeff Cody         goto out;
9140c5e94eeSBenoît Canet     }
9150c5e94eeSBenoît Canet 
9166913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
9176913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
9186913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
91915489c76SJeff Cody         goto out;
9206913c0c2SBenoît Canet     }
9216913c0c2SBenoît Canet 
9226913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
9236913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
9246913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
92515489c76SJeff Cody out:
92615489c76SJeff Cody     g_free(gen_node_name);
9276913c0c2SBenoît Canet }
9286913c0c2SBenoît Canet 
929c5f3014bSKevin Wolf QemuOptsList bdrv_runtime_opts = {
93018edf289SKevin Wolf     .name = "bdrv_common",
93118edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
93218edf289SKevin Wolf     .desc = {
93318edf289SKevin Wolf         {
93418edf289SKevin Wolf             .name = "node-name",
93518edf289SKevin Wolf             .type = QEMU_OPT_STRING,
93618edf289SKevin Wolf             .help = "Node name of the block device node",
93718edf289SKevin Wolf         },
93862392ebbSKevin Wolf         {
93962392ebbSKevin Wolf             .name = "driver",
94062392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
94162392ebbSKevin Wolf             .help = "Block driver to use for the node",
94262392ebbSKevin Wolf         },
94391a097e7SKevin Wolf         {
94491a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
94591a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
94691a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
94791a097e7SKevin Wolf         },
94891a097e7SKevin Wolf         {
94991a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
95091a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
95191a097e7SKevin Wolf             .help = "Ignore flush requests",
95291a097e7SKevin Wolf         },
953f87a0e29SAlberto Garcia         {
954f87a0e29SAlberto Garcia             .name = BDRV_OPT_READ_ONLY,
955f87a0e29SAlberto Garcia             .type = QEMU_OPT_BOOL,
956f87a0e29SAlberto Garcia             .help = "Node is opened in read-only mode",
957f87a0e29SAlberto Garcia         },
958692e01a2SKevin Wolf         {
959692e01a2SKevin Wolf             .name = "detect-zeroes",
960692e01a2SKevin Wolf             .type = QEMU_OPT_STRING,
961692e01a2SKevin Wolf             .help = "try to optimize zero writes (off, on, unmap)",
962692e01a2SKevin Wolf         },
963818584a4SKevin Wolf         {
964818584a4SKevin Wolf             .name = "discard",
965818584a4SKevin Wolf             .type = QEMU_OPT_STRING,
966818584a4SKevin Wolf             .help = "discard operation (ignore/off, unmap/on)",
967818584a4SKevin Wolf         },
96818edf289SKevin Wolf         { /* end of list */ }
96918edf289SKevin Wolf     },
97018edf289SKevin Wolf };
97118edf289SKevin Wolf 
972b6ce07aaSKevin Wolf /*
97357915332SKevin Wolf  * Common part for opening disk images and files
974b6ad491aSKevin Wolf  *
975b6ad491aSKevin Wolf  * Removes all processed options from *options.
97657915332SKevin Wolf  */
9779a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
97882dc8b41SKevin Wolf                             QDict *options, Error **errp)
97957915332SKevin Wolf {
98057915332SKevin Wolf     int ret, open_flags;
981035fccdfSKevin Wolf     const char *filename;
98262392ebbSKevin Wolf     const char *driver_name = NULL;
9836913c0c2SBenoît Canet     const char *node_name = NULL;
984818584a4SKevin Wolf     const char *discard;
985692e01a2SKevin Wolf     const char *detect_zeroes;
98618edf289SKevin Wolf     QemuOpts *opts;
98762392ebbSKevin Wolf     BlockDriver *drv;
98834b5d2c6SMax Reitz     Error *local_err = NULL;
98957915332SKevin Wolf 
9906405875cSPaolo Bonzini     assert(bs->file == NULL);
991707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
99257915332SKevin Wolf 
99362392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
99462392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
99562392ebbSKevin Wolf     if (local_err) {
99662392ebbSKevin Wolf         error_propagate(errp, local_err);
99762392ebbSKevin Wolf         ret = -EINVAL;
99862392ebbSKevin Wolf         goto fail_opts;
99962392ebbSKevin Wolf     }
100062392ebbSKevin Wolf 
10019b7e8691SAlberto Garcia     update_flags_from_options(&bs->open_flags, opts);
10029b7e8691SAlberto Garcia 
100362392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
100462392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
100562392ebbSKevin Wolf     assert(drv != NULL);
100662392ebbSKevin Wolf 
100745673671SKevin Wolf     if (file != NULL) {
10089a4f4c31SKevin Wolf         filename = file->bs->filename;
100945673671SKevin Wolf     } else {
101045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
101145673671SKevin Wolf     }
101245673671SKevin Wolf 
1013765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
1014765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
1015765003dbSKevin Wolf                    drv->format_name);
101618edf289SKevin Wolf         ret = -EINVAL;
101718edf289SKevin Wolf         goto fail_opts;
101818edf289SKevin Wolf     }
101918edf289SKevin Wolf 
102082dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
102182dc8b41SKevin Wolf                            drv->format_name);
102262392ebbSKevin Wolf 
102318edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
1024636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
10250fb6395cSMarkus Armbruster     if (local_err) {
1026636ea370SKevin Wolf         error_propagate(errp, local_err);
102718edf289SKevin Wolf         ret = -EINVAL;
102818edf289SKevin Wolf         goto fail_opts;
10295d186eb0SKevin Wolf     }
10305d186eb0SKevin Wolf 
103182dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
1032b64ec4e4SFam Zheng 
1033b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
10348f94a6e4SKevin Wolf         error_setg(errp,
10358f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
10368f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
10378f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
10388f94a6e4SKevin Wolf                    drv->format_name);
103918edf289SKevin Wolf         ret = -ENOTSUP;
104018edf289SKevin Wolf         goto fail_opts;
1041b64ec4e4SFam Zheng     }
104257915332SKevin Wolf 
104353fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
104482dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
10450ebd24e0SKevin Wolf         if (!bs->read_only) {
104653fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
10470ebd24e0SKevin Wolf         } else {
10480ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
104918edf289SKevin Wolf             ret = -EINVAL;
105018edf289SKevin Wolf             goto fail_opts;
10510ebd24e0SKevin Wolf         }
105253fec9d3SStefan Hajnoczi     }
105353fec9d3SStefan Hajnoczi 
1054818584a4SKevin Wolf     discard = qemu_opt_get(opts, "discard");
1055818584a4SKevin Wolf     if (discard != NULL) {
1056818584a4SKevin Wolf         if (bdrv_parse_discard_flags(discard, &bs->open_flags) != 0) {
1057818584a4SKevin Wolf             error_setg(errp, "Invalid discard option");
1058818584a4SKevin Wolf             ret = -EINVAL;
1059818584a4SKevin Wolf             goto fail_opts;
1060818584a4SKevin Wolf         }
1061818584a4SKevin Wolf     }
1062818584a4SKevin Wolf 
1063692e01a2SKevin Wolf     detect_zeroes = qemu_opt_get(opts, "detect-zeroes");
1064692e01a2SKevin Wolf     if (detect_zeroes) {
1065692e01a2SKevin Wolf         BlockdevDetectZeroesOptions value =
1066692e01a2SKevin Wolf             qapi_enum_parse(BlockdevDetectZeroesOptions_lookup,
1067692e01a2SKevin Wolf                             detect_zeroes,
1068692e01a2SKevin Wolf                             BLOCKDEV_DETECT_ZEROES_OPTIONS__MAX,
1069692e01a2SKevin Wolf                             BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF,
1070692e01a2SKevin Wolf                             &local_err);
1071692e01a2SKevin Wolf         if (local_err) {
1072692e01a2SKevin Wolf             error_propagate(errp, local_err);
1073692e01a2SKevin Wolf             ret = -EINVAL;
1074692e01a2SKevin Wolf             goto fail_opts;
1075692e01a2SKevin Wolf         }
1076692e01a2SKevin Wolf 
1077692e01a2SKevin Wolf         if (value == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP &&
1078692e01a2SKevin Wolf             !(bs->open_flags & BDRV_O_UNMAP))
1079692e01a2SKevin Wolf         {
1080692e01a2SKevin Wolf             error_setg(errp, "setting detect-zeroes to unmap is not allowed "
1081692e01a2SKevin Wolf                              "without setting discard operation to unmap");
1082692e01a2SKevin Wolf             ret = -EINVAL;
1083692e01a2SKevin Wolf             goto fail_opts;
1084692e01a2SKevin Wolf         }
1085692e01a2SKevin Wolf 
1086692e01a2SKevin Wolf         bs->detect_zeroes = value;
1087692e01a2SKevin Wolf     }
1088692e01a2SKevin Wolf 
1089c2ad1b0cSKevin Wolf     if (filename != NULL) {
109057915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
1091c2ad1b0cSKevin Wolf     } else {
1092c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
1093c2ad1b0cSKevin Wolf     }
109491af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
109557915332SKevin Wolf 
109657915332SKevin Wolf     bs->drv = drv;
10977267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
109857915332SKevin Wolf 
109966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
110082dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
110166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
11025d186eb0SKevin Wolf         assert(file == NULL);
1103030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
110434b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1105f500a6d3SKevin Wolf     } else {
11062af5ef70SKevin Wolf         if (file == NULL) {
110734b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
110834b5d2c6SMax Reitz                        "protocol level", drv->format_name);
11092af5ef70SKevin Wolf             ret = -EINVAL;
11102af5ef70SKevin Wolf             goto free_and_fail;
11112af5ef70SKevin Wolf         }
1112f500a6d3SKevin Wolf         bs->file = file;
111334b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
111466f82ceeSKevin Wolf     }
111566f82ceeSKevin Wolf 
111657915332SKevin Wolf     if (ret < 0) {
111784d18f06SMarkus Armbruster         if (local_err) {
111834b5d2c6SMax Reitz             error_propagate(errp, local_err);
11192fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
11202fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
112134b5d2c6SMax Reitz         } else {
112234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
112334b5d2c6SMax Reitz         }
112457915332SKevin Wolf         goto free_and_fail;
112557915332SKevin Wolf     }
112657915332SKevin Wolf 
112751762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
112851762288SStefan Hajnoczi     if (ret < 0) {
112934b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
113051762288SStefan Hajnoczi         goto free_and_fail;
113157915332SKevin Wolf     }
113251762288SStefan Hajnoczi 
11333baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
11343baca891SKevin Wolf     if (local_err) {
11353baca891SKevin Wolf         error_propagate(errp, local_err);
11363baca891SKevin Wolf         ret = -EINVAL;
11373baca891SKevin Wolf         goto free_and_fail;
11383baca891SKevin Wolf     }
11393baca891SKevin Wolf 
1140c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
11414196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1142a5b8dd2cSEric Blake     assert(is_power_of_2(bs->bl.request_alignment));
114318edf289SKevin Wolf 
114418edf289SKevin Wolf     qemu_opts_del(opts);
114557915332SKevin Wolf     return 0;
114657915332SKevin Wolf 
114757915332SKevin Wolf free_and_fail:
114866f82ceeSKevin Wolf     bs->file = NULL;
11497267c094SAnthony Liguori     g_free(bs->opaque);
115057915332SKevin Wolf     bs->opaque = NULL;
115157915332SKevin Wolf     bs->drv = NULL;
115218edf289SKevin Wolf fail_opts:
115318edf289SKevin Wolf     qemu_opts_del(opts);
115457915332SKevin Wolf     return ret;
115557915332SKevin Wolf }
115657915332SKevin Wolf 
11575e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
11585e5c4f63SKevin Wolf {
11595e5c4f63SKevin Wolf     QObject *options_obj;
11605e5c4f63SKevin Wolf     QDict *options;
11615e5c4f63SKevin Wolf     int ret;
11625e5c4f63SKevin Wolf 
11635e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
11645e5c4f63SKevin Wolf     assert(ret);
11655e5c4f63SKevin Wolf 
11665e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
11675e5c4f63SKevin Wolf     if (!options_obj) {
11685e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
11695e5c4f63SKevin Wolf         return NULL;
11705e5c4f63SKevin Wolf     }
11715e5c4f63SKevin Wolf 
1172*ca6b6e1eSMarkus Armbruster     options = qobject_to_qdict(options_obj);
1173*ca6b6e1eSMarkus Armbruster     if (!options) {
11745e5c4f63SKevin Wolf         qobject_decref(options_obj);
11755e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
11765e5c4f63SKevin Wolf         return NULL;
11775e5c4f63SKevin Wolf     }
11785e5c4f63SKevin Wolf 
11795e5c4f63SKevin Wolf     qdict_flatten(options);
11805e5c4f63SKevin Wolf 
11815e5c4f63SKevin Wolf     return options;
11825e5c4f63SKevin Wolf }
11835e5c4f63SKevin Wolf 
1184de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1185de3b53f0SKevin Wolf                                 Error **errp)
1186de3b53f0SKevin Wolf {
1187de3b53f0SKevin Wolf     QDict *json_options;
1188de3b53f0SKevin Wolf     Error *local_err = NULL;
1189de3b53f0SKevin Wolf 
1190de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1191de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1192de3b53f0SKevin Wolf         return;
1193de3b53f0SKevin Wolf     }
1194de3b53f0SKevin Wolf 
1195de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1196de3b53f0SKevin Wolf     if (local_err) {
1197de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1198de3b53f0SKevin Wolf         return;
1199de3b53f0SKevin Wolf     }
1200de3b53f0SKevin Wolf 
1201de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1202de3b53f0SKevin Wolf      * specified directly */
1203de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1204de3b53f0SKevin Wolf     QDECREF(json_options);
1205de3b53f0SKevin Wolf     *pfilename = NULL;
1206de3b53f0SKevin Wolf }
1207de3b53f0SKevin Wolf 
120857915332SKevin Wolf /*
1209f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1210f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
121153a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
121253a29513SMax Reitz  * block driver has been specified explicitly.
1213f54120ffSKevin Wolf  */
1214de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1215053e1578SMax Reitz                              int *flags, Error **errp)
1216f54120ffSKevin Wolf {
1217f54120ffSKevin Wolf     const char *drvname;
121853a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1219f54120ffSKevin Wolf     bool parse_filename = false;
1220053e1578SMax Reitz     BlockDriver *drv = NULL;
1221f54120ffSKevin Wolf     Error *local_err = NULL;
1222f54120ffSKevin Wolf 
122353a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1224053e1578SMax Reitz     if (drvname) {
1225053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1226053e1578SMax Reitz         if (!drv) {
1227053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1228053e1578SMax Reitz             return -ENOENT;
1229053e1578SMax Reitz         }
123053a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
123153a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1232053e1578SMax Reitz         protocol = drv->bdrv_file_open;
123353a29513SMax Reitz     }
123453a29513SMax Reitz 
123553a29513SMax Reitz     if (protocol) {
123653a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
123753a29513SMax Reitz     } else {
123853a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
123953a29513SMax Reitz     }
124053a29513SMax Reitz 
124191a097e7SKevin Wolf     /* Translate cache options from flags into options */
124291a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
124391a097e7SKevin Wolf 
1244f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
124517b005f1SKevin Wolf     if (protocol && filename) {
1246f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1247f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1248f54120ffSKevin Wolf             parse_filename = true;
1249f54120ffSKevin Wolf         } else {
1250f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1251f54120ffSKevin Wolf                              "the same time");
1252f54120ffSKevin Wolf             return -EINVAL;
1253f54120ffSKevin Wolf         }
1254f54120ffSKevin Wolf     }
1255f54120ffSKevin Wolf 
1256f54120ffSKevin Wolf     /* Find the right block driver */
1257f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1258f54120ffSKevin Wolf 
125917b005f1SKevin Wolf     if (!drvname && protocol) {
1260f54120ffSKevin Wolf         if (filename) {
1261b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1262f54120ffSKevin Wolf             if (!drv) {
1263f54120ffSKevin Wolf                 return -EINVAL;
1264f54120ffSKevin Wolf             }
1265f54120ffSKevin Wolf 
1266f54120ffSKevin Wolf             drvname = drv->format_name;
1267f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1268f54120ffSKevin Wolf         } else {
1269f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1270f54120ffSKevin Wolf             return -EINVAL;
1271f54120ffSKevin Wolf         }
127217b005f1SKevin Wolf     }
127317b005f1SKevin Wolf 
127417b005f1SKevin Wolf     assert(drv || !protocol);
1275f54120ffSKevin Wolf 
1276f54120ffSKevin Wolf     /* Driver-specific filename parsing */
127717b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1278f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1279f54120ffSKevin Wolf         if (local_err) {
1280f54120ffSKevin Wolf             error_propagate(errp, local_err);
1281f54120ffSKevin Wolf             return -EINVAL;
1282f54120ffSKevin Wolf         }
1283f54120ffSKevin Wolf 
1284f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1285f54120ffSKevin Wolf             qdict_del(*options, "filename");
1286f54120ffSKevin Wolf         }
1287f54120ffSKevin Wolf     }
1288f54120ffSKevin Wolf 
1289f54120ffSKevin Wolf     return 0;
1290f54120ffSKevin Wolf }
1291f54120ffSKevin Wolf 
1292e9740bc6SKevin Wolf static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
1293e9740bc6SKevin Wolf {
1294e9740bc6SKevin Wolf     BlockDriverState *old_bs = child->bs;
1295e9740bc6SKevin Wolf 
1296e9740bc6SKevin Wolf     if (old_bs) {
129736fe1331SKevin Wolf         if (old_bs->quiesce_counter && child->role->drained_end) {
129836fe1331SKevin Wolf             child->role->drained_end(child);
1299e9740bc6SKevin Wolf         }
130036fe1331SKevin Wolf         QLIST_REMOVE(child, next_parent);
1301e9740bc6SKevin Wolf     }
1302e9740bc6SKevin Wolf 
1303e9740bc6SKevin Wolf     child->bs = new_bs;
130436fe1331SKevin Wolf 
130536fe1331SKevin Wolf     if (new_bs) {
130636fe1331SKevin Wolf         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
130736fe1331SKevin Wolf         if (new_bs->quiesce_counter && child->role->drained_begin) {
130836fe1331SKevin Wolf             child->role->drained_begin(child);
130936fe1331SKevin Wolf         }
131036fe1331SKevin Wolf     }
1311e9740bc6SKevin Wolf }
1312e9740bc6SKevin Wolf 
1313f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1314260fecf1SKevin Wolf                                   const char *child_name,
131536fe1331SKevin Wolf                                   const BdrvChildRole *child_role,
131636fe1331SKevin Wolf                                   void *opaque)
1317df581792SKevin Wolf {
1318df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1319df581792SKevin Wolf     *child = (BdrvChild) {
1320e9740bc6SKevin Wolf         .bs     = NULL,
1321260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1322df581792SKevin Wolf         .role   = child_role,
132336fe1331SKevin Wolf         .opaque = opaque,
1324df581792SKevin Wolf     };
1325df581792SKevin Wolf 
1326e9740bc6SKevin Wolf     bdrv_replace_child(child, child_bs);
1327b4b059f6SKevin Wolf 
1328b4b059f6SKevin Wolf     return child;
1329df581792SKevin Wolf }
1330df581792SKevin Wolf 
133198292c61SWen Congyang BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1332f21d96d0SKevin Wolf                              BlockDriverState *child_bs,
1333f21d96d0SKevin Wolf                              const char *child_name,
1334f21d96d0SKevin Wolf                              const BdrvChildRole *child_role)
1335f21d96d0SKevin Wolf {
133636fe1331SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role,
133720018e12SKevin Wolf                                               parent_bs);
1338f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1339f21d96d0SKevin Wolf     return child;
1340f21d96d0SKevin Wolf }
1341f21d96d0SKevin Wolf 
13423f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
134333a60407SKevin Wolf {
1344f21d96d0SKevin Wolf     if (child->next.le_prev) {
134533a60407SKevin Wolf         QLIST_REMOVE(child, next);
1346f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1347f21d96d0SKevin Wolf     }
1348e9740bc6SKevin Wolf 
1349e9740bc6SKevin Wolf     bdrv_replace_child(child, NULL);
1350e9740bc6SKevin Wolf 
1351260fecf1SKevin Wolf     g_free(child->name);
135233a60407SKevin Wolf     g_free(child);
135333a60407SKevin Wolf }
135433a60407SKevin Wolf 
1355f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
135633a60407SKevin Wolf {
1357779020cbSKevin Wolf     BlockDriverState *child_bs;
1358779020cbSKevin Wolf 
1359f21d96d0SKevin Wolf     child_bs = child->bs;
1360f21d96d0SKevin Wolf     bdrv_detach_child(child);
1361f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1362f21d96d0SKevin Wolf }
1363f21d96d0SKevin Wolf 
1364f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1365f21d96d0SKevin Wolf {
1366779020cbSKevin Wolf     if (child == NULL) {
1367779020cbSKevin Wolf         return;
1368779020cbSKevin Wolf     }
136933a60407SKevin Wolf 
137033a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
137133a60407SKevin Wolf         child->bs->inherits_from = NULL;
137233a60407SKevin Wolf     }
137333a60407SKevin Wolf 
1374f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
137533a60407SKevin Wolf }
137633a60407SKevin Wolf 
13775c8cab48SKevin Wolf 
13785c8cab48SKevin Wolf static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
13795c8cab48SKevin Wolf {
13805c8cab48SKevin Wolf     BdrvChild *c;
13815c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
13825c8cab48SKevin Wolf         if (c->role->change_media) {
13835c8cab48SKevin Wolf             c->role->change_media(c, load);
13845c8cab48SKevin Wolf         }
13855c8cab48SKevin Wolf     }
13865c8cab48SKevin Wolf }
13875c8cab48SKevin Wolf 
13885c8cab48SKevin Wolf static void bdrv_parent_cb_resize(BlockDriverState *bs)
13895c8cab48SKevin Wolf {
13905c8cab48SKevin Wolf     BdrvChild *c;
13915c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
13925c8cab48SKevin Wolf         if (c->role->resize) {
13935c8cab48SKevin Wolf             c->role->resize(c);
13945c8cab48SKevin Wolf         }
13955c8cab48SKevin Wolf     }
13965c8cab48SKevin Wolf }
13975c8cab48SKevin Wolf 
13985db15a57SKevin Wolf /*
13995db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
14005db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
14015db15a57SKevin Wolf  */
14028d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
14038d24cce1SFam Zheng {
14045db15a57SKevin Wolf     if (backing_hd) {
14055db15a57SKevin Wolf         bdrv_ref(backing_hd);
14065db15a57SKevin Wolf     }
14078d24cce1SFam Zheng 
1408760e0063SKevin Wolf     if (bs->backing) {
1409826b6ca0SFam Zheng         assert(bs->backing_blocker);
1410760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
14115db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1412826b6ca0SFam Zheng     } else if (backing_hd) {
1413826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
141481e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
141581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1416826b6ca0SFam Zheng     }
1417826b6ca0SFam Zheng 
14188d24cce1SFam Zheng     if (!backing_hd) {
1419826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1420826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1421760e0063SKevin Wolf         bs->backing = NULL;
14228d24cce1SFam Zheng         goto out;
14238d24cce1SFam Zheng     }
1424260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
14258d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
14268d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
14278d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
14288d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1429826b6ca0SFam Zheng 
1430760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
143161b49e48SAlberto Garcia     /* Otherwise we won't be able to commit or stream */
1432760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1433826b6ca0SFam Zheng                     bs->backing_blocker);
143461b49e48SAlberto Garcia     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_STREAM,
143561b49e48SAlberto Garcia                     bs->backing_blocker);
1436e9d6456eSWen Congyang     /*
1437e9d6456eSWen Congyang      * We do backup in 3 ways:
1438e9d6456eSWen Congyang      * 1. drive backup
1439e9d6456eSWen Congyang      *    The target bs is new opened, and the source is top BDS
1440e9d6456eSWen Congyang      * 2. blockdev backup
1441e9d6456eSWen Congyang      *    Both the source and the target are top BDSes.
1442e9d6456eSWen Congyang      * 3. internal backup(used for block replication)
1443e9d6456eSWen Congyang      *    Both the source and the target are backing file
1444e9d6456eSWen Congyang      *
1445e9d6456eSWen Congyang      * In case 1 and 2, neither the source nor the target is the backing file.
1446e9d6456eSWen Congyang      * In case 3, we will block the top BDS, so there is only one block job
1447e9d6456eSWen Congyang      * for the top BDS and its backing chain.
1448e9d6456eSWen Congyang      */
1449e9d6456eSWen Congyang     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_SOURCE,
1450e9d6456eSWen Congyang                     bs->backing_blocker);
1451e9d6456eSWen Congyang     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_BACKUP_TARGET,
1452e9d6456eSWen Congyang                     bs->backing_blocker);
14538d24cce1SFam Zheng out:
14543baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
14558d24cce1SFam Zheng }
14568d24cce1SFam Zheng 
145731ca6d07SKevin Wolf /*
145831ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
145931ca6d07SKevin Wolf  *
1460d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1461d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1462d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1463d9b7b057SKevin Wolf  * BlockdevRef.
1464d9b7b057SKevin Wolf  *
1465d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
146631ca6d07SKevin Wolf  */
1467d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1468d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
14699156df12SPaolo Bonzini {
14701ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1471d9b7b057SKevin Wolf     char *bdref_key_dot;
1472d9b7b057SKevin Wolf     const char *reference = NULL;
1473317fc44eSKevin Wolf     int ret = 0;
14748d24cce1SFam Zheng     BlockDriverState *backing_hd;
1475d9b7b057SKevin Wolf     QDict *options;
1476d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
147734b5d2c6SMax Reitz     Error *local_err = NULL;
14789156df12SPaolo Bonzini 
1479760e0063SKevin Wolf     if (bs->backing != NULL) {
14801ba4b6a5SBenoît Canet         goto free_exit;
14819156df12SPaolo Bonzini     }
14829156df12SPaolo Bonzini 
148331ca6d07SKevin Wolf     /* NULL means an empty set of options */
1484d9b7b057SKevin Wolf     if (parent_options == NULL) {
1485d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1486d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
148731ca6d07SKevin Wolf     }
148831ca6d07SKevin Wolf 
14899156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1490d9b7b057SKevin Wolf 
1491d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1492d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1493d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1494d9b7b057SKevin Wolf 
1495d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1496d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
14971cb6f506SKevin Wolf         backing_filename[0] = '\0';
14981cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
149931ca6d07SKevin Wolf         QDECREF(options);
15001ba4b6a5SBenoît Canet         goto free_exit;
1501dbecebddSFam Zheng     } else {
15029f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
15039f07429eSMax Reitz                                        &local_err);
15049f07429eSMax Reitz         if (local_err) {
15059f07429eSMax Reitz             ret = -EINVAL;
15069f07429eSMax Reitz             error_propagate(errp, local_err);
15079f07429eSMax Reitz             QDECREF(options);
15089f07429eSMax Reitz             goto free_exit;
15099f07429eSMax Reitz         }
15109156df12SPaolo Bonzini     }
15119156df12SPaolo Bonzini 
15128ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
15138ee79e70SKevin Wolf         ret = -EINVAL;
15148ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
15158ee79e70SKevin Wolf         QDECREF(options);
15168ee79e70SKevin Wolf         goto free_exit;
15178ee79e70SKevin Wolf     }
15188ee79e70SKevin Wolf 
1519c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1520c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
15219156df12SPaolo Bonzini     }
15229156df12SPaolo Bonzini 
15235b363937SMax Reitz     backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
1524d9b7b057SKevin Wolf                                    reference, options, 0, bs, &child_backing,
1525e43bfd9cSMarkus Armbruster                                    errp);
15265b363937SMax Reitz     if (!backing_hd) {
15279156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1528e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
15295b363937SMax Reitz         ret = -EINVAL;
15301ba4b6a5SBenoît Canet         goto free_exit;
15319156df12SPaolo Bonzini     }
1532df581792SKevin Wolf 
15335db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
15345db15a57SKevin Wolf      * backing_hd reference now */
15358d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
15365db15a57SKevin Wolf     bdrv_unref(backing_hd);
1537d80ac658SPeter Feiner 
1538d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1539d9b7b057SKevin Wolf 
15401ba4b6a5SBenoît Canet free_exit:
15411ba4b6a5SBenoît Canet     g_free(backing_filename);
1542d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
15431ba4b6a5SBenoît Canet     return ret;
15449156df12SPaolo Bonzini }
15459156df12SPaolo Bonzini 
1546b6ce07aaSKevin Wolf /*
1547da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1548da557aacSMax Reitz  * device's options.
1549da557aacSMax Reitz  *
1550da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1551b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1552da557aacSMax Reitz  *
1553da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1554da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1555da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1556da557aacSMax Reitz  * BlockdevRef.
1557da557aacSMax Reitz  *
1558da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1559da557aacSMax Reitz  */
1560b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1561f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1562b4b059f6SKevin Wolf                            BlockDriverState* parent,
1563b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1564f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1565da557aacSMax Reitz {
1566b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1567b4b059f6SKevin Wolf     BlockDriverState *bs;
1568da557aacSMax Reitz     QDict *image_options;
1569da557aacSMax Reitz     char *bdref_key_dot;
1570da557aacSMax Reitz     const char *reference;
1571da557aacSMax Reitz 
1572df581792SKevin Wolf     assert(child_role != NULL);
1573f67503e5SMax Reitz 
1574da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1575da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1576da557aacSMax Reitz     g_free(bdref_key_dot);
1577da557aacSMax Reitz 
1578da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1579da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1580b4b059f6SKevin Wolf         if (!allow_none) {
1581da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1582da557aacSMax Reitz                        bdref_key);
1583da557aacSMax Reitz         }
1584b20e61e0SMarkus Armbruster         QDECREF(image_options);
1585da557aacSMax Reitz         goto done;
1586da557aacSMax Reitz     }
1587da557aacSMax Reitz 
15885b363937SMax Reitz     bs = bdrv_open_inherit(filename, reference, image_options, 0,
1589ce343771SMax Reitz                            parent, child_role, errp);
15905b363937SMax Reitz     if (!bs) {
1591df581792SKevin Wolf         goto done;
1592df581792SKevin Wolf     }
1593df581792SKevin Wolf 
1594260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1595da557aacSMax Reitz 
1596da557aacSMax Reitz done:
1597da557aacSMax Reitz     qdict_del(options, bdref_key);
1598b4b059f6SKevin Wolf     return c;
1599b4b059f6SKevin Wolf }
1600b4b059f6SKevin Wolf 
160166836189SMax Reitz static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
160266836189SMax Reitz                                                    int flags,
160366836189SMax Reitz                                                    QDict *snapshot_options,
160466836189SMax Reitz                                                    Error **errp)
1605b998875dSKevin Wolf {
1606b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
16071ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1608b998875dSKevin Wolf     int64_t total_size;
160983d0521aSChunyan Liu     QemuOpts *opts = NULL;
1610b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1611b998875dSKevin Wolf     int ret;
1612b998875dSKevin Wolf 
1613b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1614b998875dSKevin Wolf        instead of opening 'filename' directly */
1615b998875dSKevin Wolf 
1616b998875dSKevin Wolf     /* Get the required size from the image */
1617f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1618f187743aSKevin Wolf     if (total_size < 0) {
1619f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
16201ba4b6a5SBenoît Canet         goto out;
1621f187743aSKevin Wolf     }
1622b998875dSKevin Wolf 
1623b998875dSKevin Wolf     /* Create the temporary image */
16241ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1625b998875dSKevin Wolf     if (ret < 0) {
1626b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
16271ba4b6a5SBenoît Canet         goto out;
1628b998875dSKevin Wolf     }
1629b998875dSKevin Wolf 
1630ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1631c282e1fdSChunyan Liu                             &error_abort);
163239101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1633e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
163483d0521aSChunyan Liu     qemu_opts_del(opts);
1635b998875dSKevin Wolf     if (ret < 0) {
1636e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1637e43bfd9cSMarkus Armbruster                       tmp_filename);
16381ba4b6a5SBenoît Canet         goto out;
1639b998875dSKevin Wolf     }
1640b998875dSKevin Wolf 
164173176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1642b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1643b998875dSKevin Wolf               qstring_from_str("file"));
1644b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1645b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1646e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1647e6641719SMax Reitz               qstring_from_str("qcow2"));
1648b998875dSKevin Wolf 
16495b363937SMax Reitz     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
165073176beeSKevin Wolf     snapshot_options = NULL;
16515b363937SMax Reitz     if (!bs_snapshot) {
16525b363937SMax Reitz         ret = -EINVAL;
16531ba4b6a5SBenoît Canet         goto out;
1654b998875dSKevin Wolf     }
1655b998875dSKevin Wolf 
165666836189SMax Reitz     /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
165766836189SMax Reitz      * call bdrv_unref() on it), so in order to be able to return one, we have
165866836189SMax Reitz      * to increase bs_snapshot's refcount here */
165966836189SMax Reitz     bdrv_ref(bs_snapshot);
1660b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
16611ba4b6a5SBenoît Canet 
166266836189SMax Reitz     g_free(tmp_filename);
166366836189SMax Reitz     return bs_snapshot;
166466836189SMax Reitz 
16651ba4b6a5SBenoît Canet out:
166673176beeSKevin Wolf     QDECREF(snapshot_options);
16671ba4b6a5SBenoît Canet     g_free(tmp_filename);
166866836189SMax Reitz     return NULL;
1669b998875dSKevin Wolf }
1670b998875dSKevin Wolf 
1671da557aacSMax Reitz /*
1672b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1673de9c0cecSKevin Wolf  *
1674de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1675de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1676de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1677de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1678f67503e5SMax Reitz  *
1679f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1680f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1681ddf5636dSMax Reitz  *
1682ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1683ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1684ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1685b6ce07aaSKevin Wolf  */
16865b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
16875b363937SMax Reitz                                            const char *reference,
16885b363937SMax Reitz                                            QDict *options, int flags,
1689f3930ed0SKevin Wolf                                            BlockDriverState *parent,
16905b363937SMax Reitz                                            const BdrvChildRole *child_role,
16915b363937SMax Reitz                                            Error **errp)
1692ea2384d3Sbellard {
1693b6ce07aaSKevin Wolf     int ret;
16949a4f4c31SKevin Wolf     BdrvChild *file = NULL;
16959a4f4c31SKevin Wolf     BlockDriverState *bs;
1696ce343771SMax Reitz     BlockDriver *drv = NULL;
169774fe54f2SKevin Wolf     const char *drvname;
16983e8c2e57SAlberto Garcia     const char *backing;
169934b5d2c6SMax Reitz     Error *local_err = NULL;
170073176beeSKevin Wolf     QDict *snapshot_options = NULL;
1701b1e6fc08SKevin Wolf     int snapshot_flags = 0;
170233e3963eSbellard 
1703f3930ed0SKevin Wolf     assert(!child_role || !flags);
1704f3930ed0SKevin Wolf     assert(!child_role == !parent);
1705f67503e5SMax Reitz 
1706ddf5636dSMax Reitz     if (reference) {
1707ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1708ddf5636dSMax Reitz         QDECREF(options);
1709ddf5636dSMax Reitz 
1710ddf5636dSMax Reitz         if (filename || options_non_empty) {
1711ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1712ddf5636dSMax Reitz                        "additional options or a new filename");
17135b363937SMax Reitz             return NULL;
1714ddf5636dSMax Reitz         }
1715ddf5636dSMax Reitz 
1716ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1717ddf5636dSMax Reitz         if (!bs) {
17185b363937SMax Reitz             return NULL;
1719ddf5636dSMax Reitz         }
172076b22320SKevin Wolf 
1721ddf5636dSMax Reitz         bdrv_ref(bs);
17225b363937SMax Reitz         return bs;
1723ddf5636dSMax Reitz     }
1724ddf5636dSMax Reitz 
1725e4e9986bSMarkus Armbruster     bs = bdrv_new();
1726f67503e5SMax Reitz 
1727de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1728de9c0cecSKevin Wolf     if (options == NULL) {
1729de9c0cecSKevin Wolf         options = qdict_new();
1730de9c0cecSKevin Wolf     }
1731de9c0cecSKevin Wolf 
1732145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1733de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1734de3b53f0SKevin Wolf     if (local_err) {
1735de3b53f0SKevin Wolf         goto fail;
1736de3b53f0SKevin Wolf     }
1737de3b53f0SKevin Wolf 
1738145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1739145f598eSKevin Wolf 
1740f3930ed0SKevin Wolf     if (child_role) {
1741bddcec37SKevin Wolf         bs->inherits_from = parent;
17428e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
17438e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1744f3930ed0SKevin Wolf     }
1745f3930ed0SKevin Wolf 
1746de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1747462f5bcfSKevin Wolf     if (local_err) {
1748462f5bcfSKevin Wolf         goto fail;
1749462f5bcfSKevin Wolf     }
1750462f5bcfSKevin Wolf 
1751f87a0e29SAlberto Garcia     /* Set the BDRV_O_RDWR and BDRV_O_ALLOW_RDWR flags.
1752f87a0e29SAlberto Garcia      * FIXME: we're parsing the QDict to avoid having to create a
1753f87a0e29SAlberto Garcia      * QemuOpts just for this, but neither option is optimal. */
1754f87a0e29SAlberto Garcia     if (g_strcmp0(qdict_get_try_str(options, BDRV_OPT_READ_ONLY), "on") &&
1755f87a0e29SAlberto Garcia         !qdict_get_try_bool(options, BDRV_OPT_READ_ONLY, false)) {
1756f87a0e29SAlberto Garcia         flags |= (BDRV_O_RDWR | BDRV_O_ALLOW_RDWR);
1757f87a0e29SAlberto Garcia     } else {
1758f87a0e29SAlberto Garcia         flags &= ~BDRV_O_RDWR;
175914499ea5SAlberto Garcia     }
176014499ea5SAlberto Garcia 
176114499ea5SAlberto Garcia     if (flags & BDRV_O_SNAPSHOT) {
176214499ea5SAlberto Garcia         snapshot_options = qdict_new();
176314499ea5SAlberto Garcia         bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
176414499ea5SAlberto Garcia                                    flags, options);
1765f87a0e29SAlberto Garcia         /* Let bdrv_backing_options() override "read-only" */
1766f87a0e29SAlberto Garcia         qdict_del(options, BDRV_OPT_READ_ONLY);
176714499ea5SAlberto Garcia         bdrv_backing_options(&flags, options, flags, options);
176814499ea5SAlberto Garcia     }
176914499ea5SAlberto Garcia 
177062392ebbSKevin Wolf     bs->open_flags = flags;
177162392ebbSKevin Wolf     bs->options = options;
177262392ebbSKevin Wolf     options = qdict_clone_shallow(options);
177362392ebbSKevin Wolf 
177476c591b0SKevin Wolf     /* Find the right image format driver */
177576c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
177676c591b0SKevin Wolf     if (drvname) {
177776c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
177876c591b0SKevin Wolf         if (!drv) {
177976c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
178076c591b0SKevin Wolf             goto fail;
178176c591b0SKevin Wolf         }
178276c591b0SKevin Wolf     }
178376c591b0SKevin Wolf 
178476c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
178576c591b0SKevin Wolf 
17863e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
17873e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
17883e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
17893e8c2e57SAlberto Garcia         qdict_del(options, "backing");
17903e8c2e57SAlberto Garcia     }
17913e8c2e57SAlberto Garcia 
1792f500a6d3SKevin Wolf     /* Open image file without format layer */
1793f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
17949a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
17951fdd6933SKevin Wolf                                &child_file, true, &local_err);
17961fdd6933SKevin Wolf         if (local_err) {
17978bfea15dSKevin Wolf             goto fail;
1798f500a6d3SKevin Wolf         }
1799f4788adcSKevin Wolf     }
1800f500a6d3SKevin Wolf 
180176c591b0SKevin Wolf     /* Image format probing */
180238f3ef57SKevin Wolf     bs->probed = !drv;
180376c591b0SKevin Wolf     if (!drv && file) {
1804cf2ab8fcSKevin Wolf         ret = find_image_format(file, filename, &drv, &local_err);
180517b005f1SKevin Wolf         if (ret < 0) {
180617b005f1SKevin Wolf             goto fail;
180717b005f1SKevin Wolf         }
180862392ebbSKevin Wolf         /*
180962392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
181062392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
181162392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
181262392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
181362392ebbSKevin Wolf          *
181462392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
181562392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
181662392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
181762392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
181862392ebbSKevin Wolf          */
181962392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
182062392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
182176c591b0SKevin Wolf     } else if (!drv) {
18222a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
18238bfea15dSKevin Wolf         goto fail;
18242a05cbe4SMax Reitz     }
1825f500a6d3SKevin Wolf 
182653a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
182753a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
182853a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
182953a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
183053a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
183153a29513SMax Reitz 
1832b6ce07aaSKevin Wolf     /* Open the image */
183382dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1834b6ce07aaSKevin Wolf     if (ret < 0) {
18358bfea15dSKevin Wolf         goto fail;
18366987307cSChristoph Hellwig     }
18376987307cSChristoph Hellwig 
18382a05cbe4SMax Reitz     if (file && (bs->file != file)) {
18399a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1840f500a6d3SKevin Wolf         file = NULL;
1841f500a6d3SKevin Wolf     }
1842f500a6d3SKevin Wolf 
1843b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
18449156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1845d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1846b6ce07aaSKevin Wolf         if (ret < 0) {
1847b6ad491aSKevin Wolf             goto close_and_fail;
1848b6ce07aaSKevin Wolf         }
1849b6ce07aaSKevin Wolf     }
1850b6ce07aaSKevin Wolf 
185191af7014SMax Reitz     bdrv_refresh_filename(bs);
185291af7014SMax Reitz 
1853b6ad491aSKevin Wolf     /* Check if any unknown options were used */
18547ad2757fSPaolo Bonzini     if (qdict_size(options) != 0) {
1855b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
18565acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
18575acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
18585acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
18595acd9d81SMax Reitz         } else {
1860d0e46a55SMax Reitz             error_setg(errp,
1861d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1862d0e46a55SMax Reitz                        drv->format_name, entry->key);
18635acd9d81SMax Reitz         }
1864b6ad491aSKevin Wolf 
1865b6ad491aSKevin Wolf         goto close_and_fail;
1866b6ad491aSKevin Wolf     }
1867b6ad491aSKevin Wolf 
1868b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
18695c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
1870c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1871c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1872c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1873c3adb58fSMarkus Armbruster         error_setg(errp,
1874c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1875c3adb58fSMarkus Armbruster         goto close_and_fail;
1876b6ce07aaSKevin Wolf     }
1877b6ce07aaSKevin Wolf 
1878c3adb58fSMarkus Armbruster     QDECREF(options);
1879dd62f1caSKevin Wolf 
1880dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1881dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1882dd62f1caSKevin Wolf     if (snapshot_flags) {
188366836189SMax Reitz         BlockDriverState *snapshot_bs;
188466836189SMax Reitz         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
188566836189SMax Reitz                                                 snapshot_options, &local_err);
188673176beeSKevin Wolf         snapshot_options = NULL;
1887dd62f1caSKevin Wolf         if (local_err) {
1888dd62f1caSKevin Wolf             goto close_and_fail;
1889dd62f1caSKevin Wolf         }
189066836189SMax Reitz         /* We are not going to return bs but the overlay on top of it
189166836189SMax Reitz          * (snapshot_bs); thus, we have to drop the strong reference to bs
18925b363937SMax Reitz          * (which we obtained by calling bdrv_new()). bs will not be deleted,
18935b363937SMax Reitz          * though, because the overlay still has a reference to it. */
189466836189SMax Reitz         bdrv_unref(bs);
189566836189SMax Reitz         bs = snapshot_bs;
189666836189SMax Reitz     }
189766836189SMax Reitz 
18985b363937SMax Reitz     return bs;
1899b6ce07aaSKevin Wolf 
19008bfea15dSKevin Wolf fail:
1901f500a6d3SKevin Wolf     if (file != NULL) {
19029a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1903f500a6d3SKevin Wolf     }
190473176beeSKevin Wolf     QDECREF(snapshot_options);
1905145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1906de9c0cecSKevin Wolf     QDECREF(bs->options);
1907b6ad491aSKevin Wolf     QDECREF(options);
1908de9c0cecSKevin Wolf     bs->options = NULL;
1909f67503e5SMax Reitz     bdrv_unref(bs);
191034b5d2c6SMax Reitz     error_propagate(errp, local_err);
19115b363937SMax Reitz     return NULL;
1912de9c0cecSKevin Wolf 
1913b6ad491aSKevin Wolf close_and_fail:
1914f67503e5SMax Reitz     bdrv_unref(bs);
191573176beeSKevin Wolf     QDECREF(snapshot_options);
1916b6ad491aSKevin Wolf     QDECREF(options);
191734b5d2c6SMax Reitz     error_propagate(errp, local_err);
19185b363937SMax Reitz     return NULL;
1919b6ce07aaSKevin Wolf }
1920b6ce07aaSKevin Wolf 
19215b363937SMax Reitz BlockDriverState *bdrv_open(const char *filename, const char *reference,
19225b363937SMax Reitz                             QDict *options, int flags, Error **errp)
1923f3930ed0SKevin Wolf {
19245b363937SMax Reitz     return bdrv_open_inherit(filename, reference, options, flags, NULL,
1925ce343771SMax Reitz                              NULL, errp);
1926f3930ed0SKevin Wolf }
1927f3930ed0SKevin Wolf 
1928e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1929e971aa12SJeff Cody      bool prepared;
1930e971aa12SJeff Cody      BDRVReopenState state;
1931e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1932e971aa12SJeff Cody } BlockReopenQueueEntry;
1933e971aa12SJeff Cody 
1934e971aa12SJeff Cody /*
1935e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1936e971aa12SJeff Cody  * reopen of multiple devices.
1937e971aa12SJeff Cody  *
1938e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1939e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1940e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1941e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1942e971aa12SJeff Cody  * atomic 'set'.
1943e971aa12SJeff Cody  *
1944e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1945e971aa12SJeff Cody  *
19464d2cb092SKevin Wolf  * options contains the changed options for the associated bs
19474d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
19484d2cb092SKevin Wolf  *
1949e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1950e971aa12SJeff Cody  *
1951e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1952e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1953e971aa12SJeff Cody  *
1954e971aa12SJeff Cody  */
195528518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
19564d2cb092SKevin Wolf                                                  BlockDriverState *bs,
195728518102SKevin Wolf                                                  QDict *options,
195828518102SKevin Wolf                                                  int flags,
195928518102SKevin Wolf                                                  const BdrvChildRole *role,
196028518102SKevin Wolf                                                  QDict *parent_options,
196128518102SKevin Wolf                                                  int parent_flags)
1962e971aa12SJeff Cody {
1963e971aa12SJeff Cody     assert(bs != NULL);
1964e971aa12SJeff Cody 
1965e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
196667251a31SKevin Wolf     BdrvChild *child;
1967145f598eSKevin Wolf     QDict *old_options, *explicit_options;
196867251a31SKevin Wolf 
1969e971aa12SJeff Cody     if (bs_queue == NULL) {
1970e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1971e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1972e971aa12SJeff Cody     }
1973e971aa12SJeff Cody 
19744d2cb092SKevin Wolf     if (!options) {
19754d2cb092SKevin Wolf         options = qdict_new();
19764d2cb092SKevin Wolf     }
19774d2cb092SKevin Wolf 
19785b7ba05fSAlberto Garcia     /* Check if this BlockDriverState is already in the queue */
19795b7ba05fSAlberto Garcia     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
19805b7ba05fSAlberto Garcia         if (bs == bs_entry->state.bs) {
19815b7ba05fSAlberto Garcia             break;
19825b7ba05fSAlberto Garcia         }
19835b7ba05fSAlberto Garcia     }
19845b7ba05fSAlberto Garcia 
198528518102SKevin Wolf     /*
198628518102SKevin Wolf      * Precedence of options:
198728518102SKevin Wolf      * 1. Explicitly passed in options (highest)
198891a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1989145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
19908e2160e2SKevin Wolf      * 4. Inherited from parent node
199128518102SKevin Wolf      * 5. Retained from effective options of bs
199228518102SKevin Wolf      */
199328518102SKevin Wolf 
199491a097e7SKevin Wolf     if (!parent_options) {
199591a097e7SKevin Wolf         /*
199691a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
199791a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
199891a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
199991a097e7SKevin Wolf          * not considered.
200091a097e7SKevin Wolf          */
200191a097e7SKevin Wolf         update_options_from_flags(options, flags);
200291a097e7SKevin Wolf     }
200391a097e7SKevin Wolf 
2004145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
20055b7ba05fSAlberto Garcia     if (bs_entry) {
20065b7ba05fSAlberto Garcia         old_options = qdict_clone_shallow(bs_entry->state.explicit_options);
20075b7ba05fSAlberto Garcia     } else {
2008145f598eSKevin Wolf         old_options = qdict_clone_shallow(bs->explicit_options);
20095b7ba05fSAlberto Garcia     }
2010145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
2011145f598eSKevin Wolf     QDECREF(old_options);
2012145f598eSKevin Wolf 
2013145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
2014145f598eSKevin Wolf 
201528518102SKevin Wolf     /* Inherit from parent node */
201628518102SKevin Wolf     if (parent_options) {
201728518102SKevin Wolf         assert(!flags);
20188e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
201928518102SKevin Wolf     }
202028518102SKevin Wolf 
202128518102SKevin Wolf     /* Old values are used for options that aren't set yet */
20224d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
2023cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
20244d2cb092SKevin Wolf     QDECREF(old_options);
20254d2cb092SKevin Wolf 
2026f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
2027f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
2028f1f25a2eSKevin Wolf 
202967251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
20304c9dfe5dSKevin Wolf         QDict *new_child_options;
20314c9dfe5dSKevin Wolf         char *child_key_dot;
203267251a31SKevin Wolf 
20334c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
20344c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
20354c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
203667251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
203767251a31SKevin Wolf             continue;
203867251a31SKevin Wolf         }
203967251a31SKevin Wolf 
20404c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
20414c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
20424c9dfe5dSKevin Wolf         g_free(child_key_dot);
20434c9dfe5dSKevin Wolf 
204428518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
204528518102SKevin Wolf                                 child->role, options, flags);
2046e971aa12SJeff Cody     }
2047e971aa12SJeff Cody 
20485b7ba05fSAlberto Garcia     if (!bs_entry) {
2049e971aa12SJeff Cody         bs_entry = g_new0(BlockReopenQueueEntry, 1);
2050e971aa12SJeff Cody         QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
20515b7ba05fSAlberto Garcia     } else {
20525b7ba05fSAlberto Garcia         QDECREF(bs_entry->state.options);
20535b7ba05fSAlberto Garcia         QDECREF(bs_entry->state.explicit_options);
20545b7ba05fSAlberto Garcia     }
2055e971aa12SJeff Cody 
2056e971aa12SJeff Cody     bs_entry->state.bs = bs;
20574d2cb092SKevin Wolf     bs_entry->state.options = options;
2058145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
2059e971aa12SJeff Cody     bs_entry->state.flags = flags;
2060e971aa12SJeff Cody 
2061e971aa12SJeff Cody     return bs_queue;
2062e971aa12SJeff Cody }
2063e971aa12SJeff Cody 
206428518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
206528518102SKevin Wolf                                     BlockDriverState *bs,
206628518102SKevin Wolf                                     QDict *options, int flags)
206728518102SKevin Wolf {
206828518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
206928518102SKevin Wolf                                    NULL, NULL, 0);
207028518102SKevin Wolf }
207128518102SKevin Wolf 
2072e971aa12SJeff Cody /*
2073e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
2074e971aa12SJeff Cody  *
2075e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
2076e971aa12SJeff Cody  * via bdrv_reopen_queue().
2077e971aa12SJeff Cody  *
2078e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
2079e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
2080e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
2081e971aa12SJeff Cody  * data cleaned up.
2082e971aa12SJeff Cody  *
2083e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
2084e971aa12SJeff Cody  * to all devices.
2085e971aa12SJeff Cody  *
2086e971aa12SJeff Cody  */
2087720150f3SPaolo Bonzini int bdrv_reopen_multiple(AioContext *ctx, BlockReopenQueue *bs_queue, Error **errp)
2088e971aa12SJeff Cody {
2089e971aa12SJeff Cody     int ret = -1;
2090e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
2091e971aa12SJeff Cody     Error *local_err = NULL;
2092e971aa12SJeff Cody 
2093e971aa12SJeff Cody     assert(bs_queue != NULL);
2094e971aa12SJeff Cody 
2095c9d1a561SPaolo Bonzini     aio_context_release(ctx);
209640840e41SAlberto Garcia     bdrv_drain_all_begin();
2097c9d1a561SPaolo Bonzini     aio_context_acquire(ctx);
2098e971aa12SJeff Cody 
2099e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2100e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
2101e971aa12SJeff Cody             error_propagate(errp, local_err);
2102e971aa12SJeff Cody             goto cleanup;
2103e971aa12SJeff Cody         }
2104e971aa12SJeff Cody         bs_entry->prepared = true;
2105e971aa12SJeff Cody     }
2106e971aa12SJeff Cody 
2107e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
2108e971aa12SJeff Cody      * changes
2109e971aa12SJeff Cody      */
2110e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
2111e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
2112e971aa12SJeff Cody     }
2113e971aa12SJeff Cody 
2114e971aa12SJeff Cody     ret = 0;
2115e971aa12SJeff Cody 
2116e971aa12SJeff Cody cleanup:
2117e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
2118e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
2119e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
2120145f598eSKevin Wolf         } else if (ret) {
2121145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
2122e971aa12SJeff Cody         }
21234d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
2124e971aa12SJeff Cody         g_free(bs_entry);
2125e971aa12SJeff Cody     }
2126e971aa12SJeff Cody     g_free(bs_queue);
212740840e41SAlberto Garcia 
212840840e41SAlberto Garcia     bdrv_drain_all_end();
212940840e41SAlberto Garcia 
2130e971aa12SJeff Cody     return ret;
2131e971aa12SJeff Cody }
2132e971aa12SJeff Cody 
2133e971aa12SJeff Cody 
2134e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
2135e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
2136e971aa12SJeff Cody {
2137e971aa12SJeff Cody     int ret = -1;
2138e971aa12SJeff Cody     Error *local_err = NULL;
21394d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
2140e971aa12SJeff Cody 
2141720150f3SPaolo Bonzini     ret = bdrv_reopen_multiple(bdrv_get_aio_context(bs), queue, &local_err);
2142e971aa12SJeff Cody     if (local_err != NULL) {
2143e971aa12SJeff Cody         error_propagate(errp, local_err);
2144e971aa12SJeff Cody     }
2145e971aa12SJeff Cody     return ret;
2146e971aa12SJeff Cody }
2147e971aa12SJeff Cody 
2148e971aa12SJeff Cody 
2149e971aa12SJeff Cody /*
2150e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
2151e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
2152e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
2153e971aa12SJeff Cody  *
2154e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
2155e971aa12SJeff Cody  * flags are the new open flags
2156e971aa12SJeff Cody  * queue is the reopen queue
2157e971aa12SJeff Cody  *
2158e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
2159e971aa12SJeff Cody  * as well.
2160e971aa12SJeff Cody  *
2161e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
2162e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
2163e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
2164e971aa12SJeff Cody  *
2165e971aa12SJeff Cody  */
2166e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2167e971aa12SJeff Cody                         Error **errp)
2168e971aa12SJeff Cody {
2169e971aa12SJeff Cody     int ret = -1;
2170e971aa12SJeff Cody     Error *local_err = NULL;
2171e971aa12SJeff Cody     BlockDriver *drv;
2172ccf9dc07SKevin Wolf     QemuOpts *opts;
2173ccf9dc07SKevin Wolf     const char *value;
2174e971aa12SJeff Cody 
2175e971aa12SJeff Cody     assert(reopen_state != NULL);
2176e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
2177e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2178e971aa12SJeff Cody 
2179ccf9dc07SKevin Wolf     /* Process generic block layer options */
2180ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2181ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2182ccf9dc07SKevin Wolf     if (local_err) {
2183ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2184ccf9dc07SKevin Wolf         ret = -EINVAL;
2185ccf9dc07SKevin Wolf         goto error;
2186ccf9dc07SKevin Wolf     }
2187ccf9dc07SKevin Wolf 
218891a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
218991a097e7SKevin Wolf 
2190ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2191ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2192ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2193ccf9dc07SKevin Wolf     if (value) {
2194ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2195ccf9dc07SKevin Wolf     }
2196ccf9dc07SKevin Wolf 
2197ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2198ccf9dc07SKevin Wolf     if (value) {
2199ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2200ccf9dc07SKevin Wolf     }
2201ccf9dc07SKevin Wolf 
2202e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2203e971aa12SJeff Cody      * to r/w */
2204e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2205e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
220681e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
220781e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2208e971aa12SJeff Cody         goto error;
2209e971aa12SJeff Cody     }
2210e971aa12SJeff Cody 
2211e971aa12SJeff Cody 
2212e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2213e971aa12SJeff Cody     if (ret) {
2214455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2215e971aa12SJeff Cody         goto error;
2216e971aa12SJeff Cody     }
2217e971aa12SJeff Cody 
2218e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2219e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2220e971aa12SJeff Cody         if (ret) {
2221e971aa12SJeff Cody             if (local_err != NULL) {
2222e971aa12SJeff Cody                 error_propagate(errp, local_err);
2223e971aa12SJeff Cody             } else {
2224d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2225e971aa12SJeff Cody                            reopen_state->bs->filename);
2226e971aa12SJeff Cody             }
2227e971aa12SJeff Cody             goto error;
2228e971aa12SJeff Cody         }
2229e971aa12SJeff Cody     } else {
2230e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2231e971aa12SJeff Cody          * handler for each supported drv. */
223281e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
223381e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
223481e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2235e971aa12SJeff Cody         ret = -1;
2236e971aa12SJeff Cody         goto error;
2237e971aa12SJeff Cody     }
2238e971aa12SJeff Cody 
22394d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
22404d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
22414d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
22424d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
22434d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
22444d2cb092SKevin Wolf 
22454d2cb092SKevin Wolf         do {
22464d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
22474d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
22484d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
22494d2cb092SKevin Wolf                                                 entry->key);
22504d2cb092SKevin Wolf 
22514d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
22524d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
22534d2cb092SKevin Wolf                 ret = -EINVAL;
22544d2cb092SKevin Wolf                 goto error;
22554d2cb092SKevin Wolf             }
22564d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
22574d2cb092SKevin Wolf     }
22584d2cb092SKevin Wolf 
2259e971aa12SJeff Cody     ret = 0;
2260e971aa12SJeff Cody 
2261e971aa12SJeff Cody error:
2262ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2263e971aa12SJeff Cody     return ret;
2264e971aa12SJeff Cody }
2265e971aa12SJeff Cody 
2266e971aa12SJeff Cody /*
2267e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2268e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2269e971aa12SJeff Cody  * the active BlockDriverState contents.
2270e971aa12SJeff Cody  */
2271e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2272e971aa12SJeff Cody {
2273e971aa12SJeff Cody     BlockDriver *drv;
2274e971aa12SJeff Cody 
2275e971aa12SJeff Cody     assert(reopen_state != NULL);
2276e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2277e971aa12SJeff Cody     assert(drv != NULL);
2278e971aa12SJeff Cody 
2279e971aa12SJeff Cody     /* If there are any driver level actions to take */
2280e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2281e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2282e971aa12SJeff Cody     }
2283e971aa12SJeff Cody 
2284e971aa12SJeff Cody     /* set BDS specific flags now */
2285145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2286145f598eSKevin Wolf 
2287145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2288e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2289e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2290355ef4acSKevin Wolf 
22913baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2292e971aa12SJeff Cody }
2293e971aa12SJeff Cody 
2294e971aa12SJeff Cody /*
2295e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2296e971aa12SJeff Cody  * reopen_state
2297e971aa12SJeff Cody  */
2298e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2299e971aa12SJeff Cody {
2300e971aa12SJeff Cody     BlockDriver *drv;
2301e971aa12SJeff Cody 
2302e971aa12SJeff Cody     assert(reopen_state != NULL);
2303e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2304e971aa12SJeff Cody     assert(drv != NULL);
2305e971aa12SJeff Cody 
2306e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2307e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2308e971aa12SJeff Cody     }
2309145f598eSKevin Wolf 
2310145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2311e971aa12SJeff Cody }
2312e971aa12SJeff Cody 
2313e971aa12SJeff Cody 
231464dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2315fc01f7e7Sbellard {
231633384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
231733384421SMax Reitz 
2318ca9bd24cSMax Reitz     assert(!bs->job);
231930f55fb8SMax Reitz     assert(!bs->refcnt);
232099b7e775SAlberto Garcia 
2321fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
232258fda173SStefan Hajnoczi     bdrv_flush(bs);
232353ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2324fc27291dSPaolo Bonzini 
2325c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2326c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2327c5acdc9aSMax Reitz 
23283cbc002cSPaolo Bonzini     if (bs->drv) {
23296e93e7c4SKevin Wolf         BdrvChild *child, *next;
23306e93e7c4SKevin Wolf 
23319a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
23329a4f4c31SKevin Wolf         bs->drv = NULL;
23339a7dedbcSKevin Wolf 
23349a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
23359a7dedbcSKevin Wolf 
23369a4f4c31SKevin Wolf         if (bs->file != NULL) {
23379a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
23389a4f4c31SKevin Wolf             bs->file = NULL;
23399a4f4c31SKevin Wolf         }
23409a4f4c31SKevin Wolf 
23416e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
234233a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
234333a60407SKevin Wolf              * bdrv_unref_child() here */
2344bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2345bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2346bddcec37SKevin Wolf             }
234733a60407SKevin Wolf             bdrv_detach_child(child);
23486e93e7c4SKevin Wolf         }
23496e93e7c4SKevin Wolf 
23507267c094SAnthony Liguori         g_free(bs->opaque);
2351ea2384d3Sbellard         bs->opaque = NULL;
235253fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2353a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2354a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
23556405875cSPaolo Bonzini         bs->total_sectors = 0;
235654115412SEric Blake         bs->encrypted = false;
235754115412SEric Blake         bs->valid_key = false;
235854115412SEric Blake         bs->sg = false;
2359de9c0cecSKevin Wolf         QDECREF(bs->options);
2360145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2361de9c0cecSKevin Wolf         bs->options = NULL;
236291af7014SMax Reitz         QDECREF(bs->full_open_options);
236391af7014SMax Reitz         bs->full_open_options = NULL;
23649ca11154SPavel Hrdina     }
236566f82ceeSKevin Wolf 
236633384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
236733384421SMax Reitz         g_free(ban);
236833384421SMax Reitz     }
236933384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2370fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2371b338082bSbellard }
2372b338082bSbellard 
23732bc93fedSMORITA Kazutaka void bdrv_close_all(void)
23742bc93fedSMORITA Kazutaka {
2375a1a2af07SKevin Wolf     block_job_cancel_sync_all();
2376cd7fca95SKevin Wolf     nbd_export_close_all();
23772bc93fedSMORITA Kazutaka 
2378ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2379ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2380ca9bd24cSMax Reitz     bdrv_drain_all();
2381ca9bd24cSMax Reitz 
2382ca9bd24cSMax Reitz     blk_remove_all_bs();
2383ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2384ca9bd24cSMax Reitz 
2385a1a2af07SKevin Wolf     assert(QTAILQ_EMPTY(&all_bdrv_states));
23862bc93fedSMORITA Kazutaka }
23872bc93fedSMORITA Kazutaka 
2388dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2389dd62f1caSKevin Wolf                                        BlockDriverState *to)
2390dd62f1caSKevin Wolf {
23919bd910e2SMax Reitz     BdrvChild *c, *next, *to_c;
2392dd62f1caSKevin Wolf 
2393dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
23949bd910e2SMax Reitz         if (c->role == &child_backing) {
23959bd910e2SMax Reitz             /* @from is generally not allowed to be a backing file, except for
23969bd910e2SMax Reitz              * when @to is the overlay. In that case, @from may not be replaced
23979bd910e2SMax Reitz              * by @to as @to's backing node. */
23989bd910e2SMax Reitz             QLIST_FOREACH(to_c, &to->children, next) {
23999bd910e2SMax Reitz                 if (to_c == c) {
24009bd910e2SMax Reitz                     break;
24019bd910e2SMax Reitz                 }
24029bd910e2SMax Reitz             }
24039bd910e2SMax Reitz             if (to_c) {
24049bd910e2SMax Reitz                 continue;
24059bd910e2SMax Reitz             }
24069bd910e2SMax Reitz         }
24079bd910e2SMax Reitz 
2408dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2409dd62f1caSKevin Wolf         bdrv_ref(to);
2410e9740bc6SKevin Wolf         bdrv_replace_child(c, to);
2411dd62f1caSKevin Wolf         bdrv_unref(from);
2412dd62f1caSKevin Wolf     }
2413dd62f1caSKevin Wolf }
2414dd62f1caSKevin Wolf 
24158802d1fdSJeff Cody /*
24168802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
24178802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
24188802d1fdSJeff Cody  *
24198802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
24208802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
24218802d1fdSJeff Cody  *
2422bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2423f6801b83SJeff Cody  *
24248802d1fdSJeff Cody  * This function does not create any image files.
2425dd62f1caSKevin Wolf  *
2426dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2427dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2428dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2429dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
24308802d1fdSJeff Cody  */
24318802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
24328802d1fdSJeff Cody {
2433dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2434dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
24358802d1fdSJeff Cody 
2436dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2437dd62f1caSKevin Wolf 
243827ccdd52SKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2439dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2440dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2441dd62f1caSKevin Wolf 
2442dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2443dd62f1caSKevin Wolf      * additional reference any more. */
2444dd62f1caSKevin Wolf     bdrv_unref(bs_new);
24458802d1fdSJeff Cody }
24468802d1fdSJeff Cody 
24473f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
24483f09bfbcSKevin Wolf {
24493f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
24503f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
24513f09bfbcSKevin Wolf 
24523f09bfbcSKevin Wolf     bdrv_ref(old);
24533f09bfbcSKevin Wolf 
24543f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
24553f09bfbcSKevin Wolf 
24563f09bfbcSKevin Wolf     bdrv_unref(old);
24573f09bfbcSKevin Wolf }
24583f09bfbcSKevin Wolf 
24594f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2460b338082bSbellard {
24613e914655SPaolo Bonzini     assert(!bs->job);
24623718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
24634f6fd349SFam Zheng     assert(!bs->refcnt);
246418846deeSMarkus Armbruster 
2465e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2466e1b5c52eSStefan Hajnoczi 
24671b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
246863eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
246963eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
247063eaaae0SKevin Wolf     }
24712c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
24722c1d04e0SMax Reitz 
24737267c094SAnthony Liguori     g_free(bs);
2474fc01f7e7Sbellard }
2475fc01f7e7Sbellard 
2476e97fc193Saliguori /*
2477e97fc193Saliguori  * Run consistency checks on an image
2478e97fc193Saliguori  *
2479e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2480a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2481e076f338SKevin Wolf  * check are stored in res.
2482e97fc193Saliguori  */
24834534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2484e97fc193Saliguori {
2485908bcd54SMax Reitz     if (bs->drv == NULL) {
2486908bcd54SMax Reitz         return -ENOMEDIUM;
2487908bcd54SMax Reitz     }
2488e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2489e97fc193Saliguori         return -ENOTSUP;
2490e97fc193Saliguori     }
2491e97fc193Saliguori 
2492e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
24934534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2494e97fc193Saliguori }
2495e97fc193Saliguori 
2496756e6736SKevin Wolf /*
2497756e6736SKevin Wolf  * Return values:
2498756e6736SKevin Wolf  * 0        - success
2499756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2500756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2501756e6736SKevin Wolf  *            image file header
2502756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2503756e6736SKevin Wolf  */
2504756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2505756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2506756e6736SKevin Wolf {
2507756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2508469ef350SPaolo Bonzini     int ret;
2509756e6736SKevin Wolf 
25105f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25115f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25125f377794SPaolo Bonzini         return -EINVAL;
25135f377794SPaolo Bonzini     }
25145f377794SPaolo Bonzini 
2515756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2516469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2517756e6736SKevin Wolf     } else {
2518469ef350SPaolo Bonzini         ret = -ENOTSUP;
2519756e6736SKevin Wolf     }
2520469ef350SPaolo Bonzini 
2521469ef350SPaolo Bonzini     if (ret == 0) {
2522469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2523469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2524469ef350SPaolo Bonzini     }
2525469ef350SPaolo Bonzini     return ret;
2526756e6736SKevin Wolf }
2527756e6736SKevin Wolf 
25286ebdcee2SJeff Cody /*
25296ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25306ebdcee2SJeff Cody  *
25316ebdcee2SJeff Cody  * active is the current topmost image.
25326ebdcee2SJeff Cody  *
25336ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25346ebdcee2SJeff Cody  * or if active == bs.
25354caf0fcdSJeff Cody  *
25364caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25376ebdcee2SJeff Cody  */
25386ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25396ebdcee2SJeff Cody                                     BlockDriverState *bs)
25406ebdcee2SJeff Cody {
2541760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2542760e0063SKevin Wolf         active = backing_bs(active);
25436ebdcee2SJeff Cody     }
25446ebdcee2SJeff Cody 
25454caf0fcdSJeff Cody     return active;
25466ebdcee2SJeff Cody }
25476ebdcee2SJeff Cody 
25484caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25494caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25504caf0fcdSJeff Cody {
25514caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25526ebdcee2SJeff Cody }
25536ebdcee2SJeff Cody 
25546ebdcee2SJeff Cody /*
25556ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25566ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25576ebdcee2SJeff Cody  *
25586ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25596ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25606ebdcee2SJeff Cody  *
25616ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25626ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25636ebdcee2SJeff Cody  *
25646ebdcee2SJeff Cody  * to
25656ebdcee2SJeff Cody  *
25666ebdcee2SJeff Cody  * bottom <- base <- active
25676ebdcee2SJeff Cody  *
25686ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25696ebdcee2SJeff Cody  *
25706ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25716ebdcee2SJeff Cody  *
25726ebdcee2SJeff Cody  * to
25736ebdcee2SJeff Cody  *
25746ebdcee2SJeff Cody  * base <- active
25756ebdcee2SJeff Cody  *
257654e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
257754e26900SJeff Cody  * overlay image metadata.
257854e26900SJeff Cody  *
25796ebdcee2SJeff Cody  * Error conditions:
25806ebdcee2SJeff Cody  *  if active == top, that is considered an error
25816ebdcee2SJeff Cody  *
25826ebdcee2SJeff Cody  */
25836ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
258454e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
25856ebdcee2SJeff Cody {
25866ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25876ebdcee2SJeff Cody     int ret = -EIO;
25886ebdcee2SJeff Cody 
25896ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25906ebdcee2SJeff Cody         goto exit;
25916ebdcee2SJeff Cody     }
25926ebdcee2SJeff Cody 
25936ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25946ebdcee2SJeff Cody 
25956ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25966ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25976ebdcee2SJeff Cody         goto exit;
25986ebdcee2SJeff Cody     }
25996ebdcee2SJeff Cody 
2600760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
26016ebdcee2SJeff Cody      * to do, no intermediate images */
2602760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
26036ebdcee2SJeff Cody         ret = 0;
26046ebdcee2SJeff Cody         goto exit;
26056ebdcee2SJeff Cody     }
26066ebdcee2SJeff Cody 
26075db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
26085db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
26096ebdcee2SJeff Cody         goto exit;
26106ebdcee2SJeff Cody     }
26116ebdcee2SJeff Cody 
26126ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26135db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
261454e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26155db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
26166ebdcee2SJeff Cody     if (ret) {
26176ebdcee2SJeff Cody         goto exit;
26186ebdcee2SJeff Cody     }
26195db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
26206ebdcee2SJeff Cody 
26216ebdcee2SJeff Cody     ret = 0;
26226ebdcee2SJeff Cody exit:
26236ebdcee2SJeff Cody     return ret;
26246ebdcee2SJeff Cody }
26256ebdcee2SJeff Cody 
262683f64091Sbellard /**
262783f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
262883f64091Sbellard  */
262983f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
263083f64091Sbellard {
263183f64091Sbellard     BlockDriver *drv = bs->drv;
263251762288SStefan Hajnoczi     int ret;
263383f64091Sbellard     if (!drv)
263419cb3738Sbellard         return -ENOMEDIUM;
263583f64091Sbellard     if (!drv->bdrv_truncate)
263683f64091Sbellard         return -ENOTSUP;
263759f2689dSNaphtali Sprei     if (bs->read_only)
263859f2689dSNaphtali Sprei         return -EACCES;
26399c75e168SJeff Cody 
264051762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
264151762288SStefan Hajnoczi     if (ret == 0) {
264251762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2643ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
26445c8cab48SKevin Wolf         bdrv_parent_cb_resize(bs);
26453ff2f67aSEvgeny Yakovlev         ++bs->write_gen;
264651762288SStefan Hajnoczi     }
264751762288SStefan Hajnoczi     return ret;
264883f64091Sbellard }
264983f64091Sbellard 
265083f64091Sbellard /**
26514a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26524a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26534a1d5e1fSFam Zheng  */
26544a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26554a1d5e1fSFam Zheng {
26564a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26574a1d5e1fSFam Zheng     if (!drv) {
26584a1d5e1fSFam Zheng         return -ENOMEDIUM;
26594a1d5e1fSFam Zheng     }
26604a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26614a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26624a1d5e1fSFam Zheng     }
26634a1d5e1fSFam Zheng     if (bs->file) {
26649a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26654a1d5e1fSFam Zheng     }
26664a1d5e1fSFam Zheng     return -ENOTSUP;
26674a1d5e1fSFam Zheng }
26684a1d5e1fSFam Zheng 
26694a1d5e1fSFam Zheng /**
267065a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
267183f64091Sbellard  */
267265a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
267383f64091Sbellard {
267483f64091Sbellard     BlockDriver *drv = bs->drv;
267565a9bb25SMarkus Armbruster 
267683f64091Sbellard     if (!drv)
267719cb3738Sbellard         return -ENOMEDIUM;
267851762288SStefan Hajnoczi 
2679b94a2610SKevin Wolf     if (drv->has_variable_length) {
2680b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2681b94a2610SKevin Wolf         if (ret < 0) {
2682b94a2610SKevin Wolf             return ret;
2683fc01f7e7Sbellard         }
268446a4e4e6SStefan Hajnoczi     }
268565a9bb25SMarkus Armbruster     return bs->total_sectors;
268665a9bb25SMarkus Armbruster }
268765a9bb25SMarkus Armbruster 
268865a9bb25SMarkus Armbruster /**
268965a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
269065a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
269165a9bb25SMarkus Armbruster  */
269265a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
269365a9bb25SMarkus Armbruster {
269465a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
269565a9bb25SMarkus Armbruster 
26964a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
269765a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
269846a4e4e6SStefan Hajnoczi }
2699fc01f7e7Sbellard 
270019cb3738Sbellard /* return 0 as number of sectors if no device present or error */
270196b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2702fc01f7e7Sbellard {
270365a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
270465a9bb25SMarkus Armbruster 
270565a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2706fc01f7e7Sbellard }
2707cf98951bSbellard 
270854115412SEric Blake bool bdrv_is_read_only(BlockDriverState *bs)
2709b338082bSbellard {
2710b338082bSbellard     return bs->read_only;
2711b338082bSbellard }
2712b338082bSbellard 
271354115412SEric Blake bool bdrv_is_sg(BlockDriverState *bs)
2714985a03b0Sths {
2715985a03b0Sths     return bs->sg;
2716985a03b0Sths }
2717985a03b0Sths 
271854115412SEric Blake bool bdrv_is_encrypted(BlockDriverState *bs)
2719ea2384d3Sbellard {
2720760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
272154115412SEric Blake         return true;
2722760e0063SKevin Wolf     }
2723ea2384d3Sbellard     return bs->encrypted;
2724ea2384d3Sbellard }
2725ea2384d3Sbellard 
272654115412SEric Blake bool bdrv_key_required(BlockDriverState *bs)
2727c0f4ce77Saliguori {
2728760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2729c0f4ce77Saliguori 
2730760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
273154115412SEric Blake         return true;
2732760e0063SKevin Wolf     }
2733c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2734c0f4ce77Saliguori }
2735c0f4ce77Saliguori 
2736ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2737ea2384d3Sbellard {
2738ea2384d3Sbellard     int ret;
2739760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2740760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2741ea2384d3Sbellard         if (ret < 0)
2742ea2384d3Sbellard             return ret;
2743ea2384d3Sbellard         if (!bs->encrypted)
2744ea2384d3Sbellard             return 0;
2745ea2384d3Sbellard     }
2746fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2747fd04a2aeSShahar Havivi         return -EINVAL;
2748fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2749fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2750fd04a2aeSShahar Havivi     }
2751c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2752bb5fc20fSaliguori     if (ret < 0) {
275354115412SEric Blake         bs->valid_key = false;
2754bb5fc20fSaliguori     } else if (!bs->valid_key) {
2755bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
275654115412SEric Blake         bs->valid_key = true;
27575c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
2758bb5fc20fSaliguori     }
2759c0f4ce77Saliguori     return ret;
2760ea2384d3Sbellard }
2761ea2384d3Sbellard 
27624d2855a3SMarkus Armbruster /*
27634d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
27644d2855a3SMarkus Armbruster  * If @key is non-null:
27654d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
27664d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
27674d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
27684d2855a3SMarkus Armbruster  * If @key is null:
27694d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
27704d2855a3SMarkus Armbruster  *     Else do nothing.
27714d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
27724d2855a3SMarkus Armbruster  */
27734d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
27744d2855a3SMarkus Armbruster {
27754d2855a3SMarkus Armbruster     if (key) {
27764d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
277781e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
277881e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
27794d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2780c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
27814d2855a3SMarkus Armbruster         }
27824d2855a3SMarkus Armbruster     } else {
27834d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2784b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2785b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
278681e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
27874d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
27884d2855a3SMarkus Armbruster         }
27894d2855a3SMarkus Armbruster     }
27904d2855a3SMarkus Armbruster }
27914d2855a3SMarkus Armbruster 
2792f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2793ea2384d3Sbellard {
2794f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2795ea2384d3Sbellard }
2796ea2384d3Sbellard 
2797ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2798ada42401SStefan Hajnoczi {
2799ceff5bd7SMax Reitz     return strcmp(*(char *const *)a, *(char *const *)b);
2800ada42401SStefan Hajnoczi }
2801ada42401SStefan Hajnoczi 
2802ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2803ea2384d3Sbellard                          void *opaque)
2804ea2384d3Sbellard {
2805ea2384d3Sbellard     BlockDriver *drv;
2806e855e4fbSJeff Cody     int count = 0;
2807ada42401SStefan Hajnoczi     int i;
2808e855e4fbSJeff Cody     const char **formats = NULL;
2809ea2384d3Sbellard 
28108a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2811e855e4fbSJeff Cody         if (drv->format_name) {
2812e855e4fbSJeff Cody             bool found = false;
2813e855e4fbSJeff Cody             int i = count;
2814e855e4fbSJeff Cody             while (formats && i && !found) {
2815e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2816e855e4fbSJeff Cody             }
2817e855e4fbSJeff Cody 
2818e855e4fbSJeff Cody             if (!found) {
28195839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2820e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2821ea2384d3Sbellard             }
2822ea2384d3Sbellard         }
2823e855e4fbSJeff Cody     }
2824ada42401SStefan Hajnoczi 
2825eb0df69fSMax Reitz     for (i = 0; i < (int)ARRAY_SIZE(block_driver_modules); i++) {
2826eb0df69fSMax Reitz         const char *format_name = block_driver_modules[i].format_name;
2827eb0df69fSMax Reitz 
2828eb0df69fSMax Reitz         if (format_name) {
2829eb0df69fSMax Reitz             bool found = false;
2830eb0df69fSMax Reitz             int j = count;
2831eb0df69fSMax Reitz 
2832eb0df69fSMax Reitz             while (formats && j && !found) {
2833eb0df69fSMax Reitz                 found = !strcmp(formats[--j], format_name);
2834eb0df69fSMax Reitz             }
2835eb0df69fSMax Reitz 
2836eb0df69fSMax Reitz             if (!found) {
2837eb0df69fSMax Reitz                 formats = g_renew(const char *, formats, count + 1);
2838eb0df69fSMax Reitz                 formats[count++] = format_name;
2839eb0df69fSMax Reitz             }
2840eb0df69fSMax Reitz         }
2841eb0df69fSMax Reitz     }
2842eb0df69fSMax Reitz 
2843ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2844ada42401SStefan Hajnoczi 
2845ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2846ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2847ada42401SStefan Hajnoczi     }
2848ada42401SStefan Hajnoczi 
2849e855e4fbSJeff Cody     g_free(formats);
2850e855e4fbSJeff Cody }
2851ea2384d3Sbellard 
2852dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2853dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2854dc364f4cSBenoît Canet {
2855dc364f4cSBenoît Canet     BlockDriverState *bs;
2856dc364f4cSBenoît Canet 
2857dc364f4cSBenoît Canet     assert(node_name);
2858dc364f4cSBenoît Canet 
2859dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2860dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2861dc364f4cSBenoît Canet             return bs;
2862dc364f4cSBenoît Canet         }
2863dc364f4cSBenoît Canet     }
2864dc364f4cSBenoît Canet     return NULL;
2865dc364f4cSBenoît Canet }
2866dc364f4cSBenoît Canet 
2867c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2868d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2869c13163fbSBenoît Canet {
2870c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2871c13163fbSBenoît Canet     BlockDriverState *bs;
2872c13163fbSBenoît Canet 
2873c13163fbSBenoît Canet     list = NULL;
2874c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2875c83f9fbaSKevin Wolf         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
2876d5a8ee60SAlberto Garcia         if (!info) {
2877d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2878d5a8ee60SAlberto Garcia             return NULL;
2879d5a8ee60SAlberto Garcia         }
2880c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2881d5a8ee60SAlberto Garcia         entry->value = info;
2882c13163fbSBenoît Canet         entry->next = list;
2883c13163fbSBenoît Canet         list = entry;
2884c13163fbSBenoît Canet     }
2885c13163fbSBenoît Canet 
2886c13163fbSBenoît Canet     return list;
2887c13163fbSBenoît Canet }
2888c13163fbSBenoît Canet 
288912d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
289012d3ba82SBenoît Canet                                  const char *node_name,
289112d3ba82SBenoît Canet                                  Error **errp)
289212d3ba82SBenoît Canet {
28937f06d47eSMarkus Armbruster     BlockBackend *blk;
28947f06d47eSMarkus Armbruster     BlockDriverState *bs;
289512d3ba82SBenoît Canet 
289612d3ba82SBenoît Canet     if (device) {
28977f06d47eSMarkus Armbruster         blk = blk_by_name(device);
289812d3ba82SBenoît Canet 
28997f06d47eSMarkus Armbruster         if (blk) {
29009f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
29019f4ed6fbSAlberto Garcia             if (!bs) {
29025433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
29035433c24fSMax Reitz             }
29045433c24fSMax Reitz 
29059f4ed6fbSAlberto Garcia             return bs;
290612d3ba82SBenoît Canet         }
2907dd67fa50SBenoît Canet     }
290812d3ba82SBenoît Canet 
2909dd67fa50SBenoît Canet     if (node_name) {
291012d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
291112d3ba82SBenoît Canet 
2912dd67fa50SBenoît Canet         if (bs) {
2913dd67fa50SBenoît Canet             return bs;
2914dd67fa50SBenoît Canet         }
291512d3ba82SBenoît Canet     }
291612d3ba82SBenoît Canet 
2917dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2918dd67fa50SBenoît Canet                      device ? device : "",
2919dd67fa50SBenoît Canet                      node_name ? node_name : "");
2920dd67fa50SBenoît Canet     return NULL;
292112d3ba82SBenoît Canet }
292212d3ba82SBenoît Canet 
29235a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
29245a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
29255a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
29265a6684d2SJeff Cody {
29275a6684d2SJeff Cody     while (top && top != base) {
2928760e0063SKevin Wolf         top = backing_bs(top);
29295a6684d2SJeff Cody     }
29305a6684d2SJeff Cody 
29315a6684d2SJeff Cody     return top != NULL;
29325a6684d2SJeff Cody }
29335a6684d2SJeff Cody 
293404df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
293504df765aSFam Zheng {
293604df765aSFam Zheng     if (!bs) {
293704df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
293804df765aSFam Zheng     }
293904df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
294004df765aSFam Zheng }
294104df765aSFam Zheng 
294220a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
294320a9e77dSFam Zheng {
294420a9e77dSFam Zheng     return bs->node_name;
294520a9e77dSFam Zheng }
294620a9e77dSFam Zheng 
29471f0c461bSKevin Wolf const char *bdrv_get_parent_name(const BlockDriverState *bs)
29484c265bf9SKevin Wolf {
29494c265bf9SKevin Wolf     BdrvChild *c;
29504c265bf9SKevin Wolf     const char *name;
29514c265bf9SKevin Wolf 
29524c265bf9SKevin Wolf     /* If multiple parents have a name, just pick the first one. */
29534c265bf9SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
29544c265bf9SKevin Wolf         if (c->role->get_name) {
29554c265bf9SKevin Wolf             name = c->role->get_name(c);
29564c265bf9SKevin Wolf             if (name && *name) {
29574c265bf9SKevin Wolf                 return name;
29584c265bf9SKevin Wolf             }
29594c265bf9SKevin Wolf         }
29604c265bf9SKevin Wolf     }
29614c265bf9SKevin Wolf 
29624c265bf9SKevin Wolf     return NULL;
29634c265bf9SKevin Wolf }
29644c265bf9SKevin Wolf 
29657f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2966bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2967ea2384d3Sbellard {
29684c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: "";
2969ea2384d3Sbellard }
2970ea2384d3Sbellard 
29719b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29729b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29739b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29749b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29759b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29769b2aa84fSAlberto Garcia {
29774c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: bs->node_name;
29789b2aa84fSAlberto Garcia }
29799b2aa84fSAlberto Garcia 
2980c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2981c8433287SMarkus Armbruster {
2982c8433287SMarkus Armbruster     return bs->open_flags;
2983c8433287SMarkus Armbruster }
2984c8433287SMarkus Armbruster 
29853ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
29863ac21627SPeter Lieven {
29873ac21627SPeter Lieven     return 1;
29883ac21627SPeter Lieven }
29893ac21627SPeter Lieven 
2990f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2991f2feebbdSKevin Wolf {
2992f2feebbdSKevin Wolf     assert(bs->drv);
2993f2feebbdSKevin Wolf 
299411212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
299511212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2996760e0063SKevin Wolf     if (bs->backing) {
299711212d8fSPaolo Bonzini         return 0;
299811212d8fSPaolo Bonzini     }
2999336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3000336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3001f2feebbdSKevin Wolf     }
3002f2feebbdSKevin Wolf 
30033ac21627SPeter Lieven     /* safe default */
30043ac21627SPeter Lieven     return 0;
3005f2feebbdSKevin Wolf }
3006f2feebbdSKevin Wolf 
30074ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
30084ce78691SPeter Lieven {
30094ce78691SPeter Lieven     BlockDriverInfo bdi;
30104ce78691SPeter Lieven 
3011760e0063SKevin Wolf     if (bs->backing) {
30124ce78691SPeter Lieven         return false;
30134ce78691SPeter Lieven     }
30144ce78691SPeter Lieven 
30154ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30164ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
30174ce78691SPeter Lieven     }
30184ce78691SPeter Lieven 
30194ce78691SPeter Lieven     return false;
30204ce78691SPeter Lieven }
30214ce78691SPeter Lieven 
30224ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
30234ce78691SPeter Lieven {
30244ce78691SPeter Lieven     BlockDriverInfo bdi;
30254ce78691SPeter Lieven 
30262f0342efSDenis V. Lunev     if (!(bs->open_flags & BDRV_O_UNMAP)) {
30274ce78691SPeter Lieven         return false;
30284ce78691SPeter Lieven     }
30294ce78691SPeter Lieven 
30304ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30314ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
30324ce78691SPeter Lieven     }
30334ce78691SPeter Lieven 
30344ce78691SPeter Lieven     return false;
30354ce78691SPeter Lieven }
30364ce78691SPeter Lieven 
3037045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3038045df330Saliguori {
3039760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
3040045df330Saliguori         return bs->backing_file;
3041045df330Saliguori     else if (bs->encrypted)
3042045df330Saliguori         return bs->filename;
3043045df330Saliguori     else
3044045df330Saliguori         return NULL;
3045045df330Saliguori }
3046045df330Saliguori 
304783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
304883f64091Sbellard                                char *filename, int filename_size)
304983f64091Sbellard {
305083f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
305183f64091Sbellard }
305283f64091Sbellard 
3053faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3054faea38e7Sbellard {
3055faea38e7Sbellard     BlockDriver *drv = bs->drv;
3056faea38e7Sbellard     if (!drv)
305719cb3738Sbellard         return -ENOMEDIUM;
3058faea38e7Sbellard     if (!drv->bdrv_get_info)
3059faea38e7Sbellard         return -ENOTSUP;
3060faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3061faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3062faea38e7Sbellard }
3063faea38e7Sbellard 
3064eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3065eae041feSMax Reitz {
3066eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3067eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3068eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3069eae041feSMax Reitz     }
3070eae041feSMax Reitz     return NULL;
3071eae041feSMax Reitz }
3072eae041feSMax Reitz 
3073a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
30748b9b0cc2SKevin Wolf {
3075bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30768b9b0cc2SKevin Wolf         return;
30778b9b0cc2SKevin Wolf     }
30788b9b0cc2SKevin Wolf 
3079bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
308041c695c7SKevin Wolf }
30818b9b0cc2SKevin Wolf 
308241c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
308341c695c7SKevin Wolf                           const char *tag)
308441c695c7SKevin Wolf {
308541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
30869a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
308741c695c7SKevin Wolf     }
308841c695c7SKevin Wolf 
308941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
309041c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
309141c695c7SKevin Wolf     }
309241c695c7SKevin Wolf 
309341c695c7SKevin Wolf     return -ENOTSUP;
309441c695c7SKevin Wolf }
309541c695c7SKevin Wolf 
30964cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
30974cc70e93SFam Zheng {
30984cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
30999a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
31004cc70e93SFam Zheng     }
31014cc70e93SFam Zheng 
31024cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
31034cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
31044cc70e93SFam Zheng     }
31054cc70e93SFam Zheng 
31064cc70e93SFam Zheng     return -ENOTSUP;
31074cc70e93SFam Zheng }
31084cc70e93SFam Zheng 
310941c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
311041c695c7SKevin Wolf {
3111938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
31129a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
311341c695c7SKevin Wolf     }
311441c695c7SKevin Wolf 
311541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
311641c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
311741c695c7SKevin Wolf     }
311841c695c7SKevin Wolf 
311941c695c7SKevin Wolf     return -ENOTSUP;
312041c695c7SKevin Wolf }
312141c695c7SKevin Wolf 
312241c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
312341c695c7SKevin Wolf {
312441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
31259a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
312641c695c7SKevin Wolf     }
312741c695c7SKevin Wolf 
312841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
312941c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
313041c695c7SKevin Wolf     }
313141c695c7SKevin Wolf 
313241c695c7SKevin Wolf     return false;
31338b9b0cc2SKevin Wolf }
31348b9b0cc2SKevin Wolf 
3135b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3136b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3137b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3138b1b1d783SJeff Cody  * the CWD rather than the chain. */
3139e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3140e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3141e8a6bb9cSMarcelo Tosatti {
3142b1b1d783SJeff Cody     char *filename_full = NULL;
3143b1b1d783SJeff Cody     char *backing_file_full = NULL;
3144b1b1d783SJeff Cody     char *filename_tmp = NULL;
3145b1b1d783SJeff Cody     int is_protocol = 0;
3146b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3147b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3148418661e0SJeff Cody     Error *local_error = NULL;
3149b1b1d783SJeff Cody 
3150b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3151e8a6bb9cSMarcelo Tosatti         return NULL;
3152e8a6bb9cSMarcelo Tosatti     }
3153e8a6bb9cSMarcelo Tosatti 
3154b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3155b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3156b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3157b1b1d783SJeff Cody 
3158b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3159b1b1d783SJeff Cody 
3160760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3161b1b1d783SJeff Cody 
3162b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3163b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3164b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3165b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3166760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3167b1b1d783SJeff Cody                 break;
3168b1b1d783SJeff Cody             }
3169418661e0SJeff Cody             /* Also check against the full backing filename for the image */
3170418661e0SJeff Cody             bdrv_get_full_backing_filename(curr_bs, backing_file_full, PATH_MAX,
3171418661e0SJeff Cody                                            &local_error);
3172418661e0SJeff Cody             if (local_error == NULL) {
3173418661e0SJeff Cody                 if (strcmp(backing_file, backing_file_full) == 0) {
3174418661e0SJeff Cody                     retval = curr_bs->backing->bs;
3175418661e0SJeff Cody                     break;
3176418661e0SJeff Cody                 }
3177418661e0SJeff Cody             } else {
3178418661e0SJeff Cody                 error_free(local_error);
3179418661e0SJeff Cody                 local_error = NULL;
3180418661e0SJeff Cody             }
3181e8a6bb9cSMarcelo Tosatti         } else {
3182b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3183b1b1d783SJeff Cody              * image's filename path */
3184b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3185b1b1d783SJeff Cody                          backing_file);
3186b1b1d783SJeff Cody 
3187b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3188b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3189b1b1d783SJeff Cody                 continue;
3190b1b1d783SJeff Cody             }
3191b1b1d783SJeff Cody 
3192b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3193b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3194b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3195b1b1d783SJeff Cody                          curr_bs->backing_file);
3196b1b1d783SJeff Cody 
3197b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3198b1b1d783SJeff Cody                 continue;
3199b1b1d783SJeff Cody             }
3200b1b1d783SJeff Cody 
3201b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3202760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3203b1b1d783SJeff Cody                 break;
3204b1b1d783SJeff Cody             }
3205e8a6bb9cSMarcelo Tosatti         }
3206e8a6bb9cSMarcelo Tosatti     }
3207e8a6bb9cSMarcelo Tosatti 
3208b1b1d783SJeff Cody     g_free(filename_full);
3209b1b1d783SJeff Cody     g_free(backing_file_full);
3210b1b1d783SJeff Cody     g_free(filename_tmp);
3211b1b1d783SJeff Cody     return retval;
3212e8a6bb9cSMarcelo Tosatti }
3213e8a6bb9cSMarcelo Tosatti 
3214f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3215f198fd1cSBenoît Canet {
3216f198fd1cSBenoît Canet     if (!bs->drv) {
3217f198fd1cSBenoît Canet         return 0;
3218f198fd1cSBenoît Canet     }
3219f198fd1cSBenoît Canet 
3220760e0063SKevin Wolf     if (!bs->backing) {
3221f198fd1cSBenoît Canet         return 0;
3222f198fd1cSBenoît Canet     }
3223f198fd1cSBenoît Canet 
3224760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3225f198fd1cSBenoît Canet }
3226f198fd1cSBenoît Canet 
3227ea2384d3Sbellard void bdrv_init(void)
3228ea2384d3Sbellard {
32295efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3230ea2384d3Sbellard }
3231ce1a14dcSpbrook 
3232eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3233eb852011SMarkus Armbruster {
3234eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3235eb852011SMarkus Armbruster     bdrv_init();
3236eb852011SMarkus Armbruster }
3237eb852011SMarkus Armbruster 
32385a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
32390f15423cSAnthony Liguori {
32400d1c5c91SFam Zheng     BdrvChild *child;
32415a8a30dbSKevin Wolf     Error *local_err = NULL;
32425a8a30dbSKevin Wolf     int ret;
32435a8a30dbSKevin Wolf 
32443456a8d1SKevin Wolf     if (!bs->drv)  {
32453456a8d1SKevin Wolf         return;
32460f15423cSAnthony Liguori     }
32473456a8d1SKevin Wolf 
324804c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
32497ea2d269SAlexey Kardashevskiy         return;
32507ea2d269SAlexey Kardashevskiy     }
32517ea2d269SAlexey Kardashevskiy 
325216e977d5SVladimir Sementsov-Ogievskiy     QLIST_FOREACH(child, &bs->children, next) {
325316e977d5SVladimir Sementsov-Ogievskiy         bdrv_invalidate_cache(child->bs, &local_err);
32545a8a30dbSKevin Wolf         if (local_err) {
32555a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32565a8a30dbSKevin Wolf             return;
32573456a8d1SKevin Wolf         }
32580d1c5c91SFam Zheng     }
32590d1c5c91SFam Zheng 
326016e977d5SVladimir Sementsov-Ogievskiy     bs->open_flags &= ~BDRV_O_INACTIVE;
326116e977d5SVladimir Sementsov-Ogievskiy     if (bs->drv->bdrv_invalidate_cache) {
326216e977d5SVladimir Sementsov-Ogievskiy         bs->drv->bdrv_invalidate_cache(bs, &local_err);
32630d1c5c91SFam Zheng         if (local_err) {
32640d1c5c91SFam Zheng             bs->open_flags |= BDRV_O_INACTIVE;
32650d1c5c91SFam Zheng             error_propagate(errp, local_err);
32660d1c5c91SFam Zheng             return;
32670d1c5c91SFam Zheng         }
32680d1c5c91SFam Zheng     }
32693456a8d1SKevin Wolf 
32705a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
32715a8a30dbSKevin Wolf     if (ret < 0) {
327204c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32735a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
32745a8a30dbSKevin Wolf         return;
32755a8a30dbSKevin Wolf     }
32760f15423cSAnthony Liguori }
32770f15423cSAnthony Liguori 
32785a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
32790f15423cSAnthony Liguori {
32807c8eece4SKevin Wolf     BlockDriverState *bs;
32815a8a30dbSKevin Wolf     Error *local_err = NULL;
328288be7b4bSKevin Wolf     BdrvNextIterator it;
32830f15423cSAnthony Liguori 
328488be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3285ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3286ed78cda3SStefan Hajnoczi 
3287ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32885a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3289ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32905a8a30dbSKevin Wolf         if (local_err) {
32915a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32925a8a30dbSKevin Wolf             return;
32935a8a30dbSKevin Wolf         }
32940f15423cSAnthony Liguori     }
32950f15423cSAnthony Liguori }
32960f15423cSAnthony Liguori 
3297aad0b7a0SFam Zheng static int bdrv_inactivate_recurse(BlockDriverState *bs,
3298aad0b7a0SFam Zheng                                    bool setting_flag)
329976b1c7feSKevin Wolf {
3300aad0b7a0SFam Zheng     BdrvChild *child;
330176b1c7feSKevin Wolf     int ret;
330276b1c7feSKevin Wolf 
3303aad0b7a0SFam Zheng     if (!setting_flag && bs->drv->bdrv_inactivate) {
330476b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
330576b1c7feSKevin Wolf         if (ret < 0) {
330676b1c7feSKevin Wolf             return ret;
330776b1c7feSKevin Wolf         }
330876b1c7feSKevin Wolf     }
330976b1c7feSKevin Wolf 
3310aad0b7a0SFam Zheng     QLIST_FOREACH(child, &bs->children, next) {
3311aad0b7a0SFam Zheng         ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3312aad0b7a0SFam Zheng         if (ret < 0) {
3313aad0b7a0SFam Zheng             return ret;
3314aad0b7a0SFam Zheng         }
3315aad0b7a0SFam Zheng     }
3316aad0b7a0SFam Zheng 
3317aad0b7a0SFam Zheng     if (setting_flag) {
331876b1c7feSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
3319aad0b7a0SFam Zheng     }
332076b1c7feSKevin Wolf     return 0;
332176b1c7feSKevin Wolf }
332276b1c7feSKevin Wolf 
332376b1c7feSKevin Wolf int bdrv_inactivate_all(void)
332476b1c7feSKevin Wolf {
332579720af6SMax Reitz     BlockDriverState *bs = NULL;
332688be7b4bSKevin Wolf     BdrvNextIterator it;
3327aad0b7a0SFam Zheng     int ret = 0;
3328aad0b7a0SFam Zheng     int pass;
332976b1c7feSKevin Wolf 
333088be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3331aad0b7a0SFam Zheng         aio_context_acquire(bdrv_get_aio_context(bs));
3332aad0b7a0SFam Zheng     }
333376b1c7feSKevin Wolf 
3334aad0b7a0SFam Zheng     /* We do two passes of inactivation. The first pass calls to drivers'
3335aad0b7a0SFam Zheng      * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3336aad0b7a0SFam Zheng      * the second pass sets the BDRV_O_INACTIVE flag so that no further write
3337aad0b7a0SFam Zheng      * is allowed. */
3338aad0b7a0SFam Zheng     for (pass = 0; pass < 2; pass++) {
333988be7b4bSKevin Wolf         for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3340aad0b7a0SFam Zheng             ret = bdrv_inactivate_recurse(bs, pass);
334176b1c7feSKevin Wolf             if (ret < 0) {
3342aad0b7a0SFam Zheng                 goto out;
3343aad0b7a0SFam Zheng             }
334476b1c7feSKevin Wolf         }
334576b1c7feSKevin Wolf     }
334676b1c7feSKevin Wolf 
3347aad0b7a0SFam Zheng out:
334888be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3349aad0b7a0SFam Zheng         aio_context_release(bdrv_get_aio_context(bs));
3350aad0b7a0SFam Zheng     }
3351aad0b7a0SFam Zheng 
3352aad0b7a0SFam Zheng     return ret;
335376b1c7feSKevin Wolf }
335476b1c7feSKevin Wolf 
3355f9f05dc5SKevin Wolf /**************************************************************/
335619cb3738Sbellard /* removable device support */
335719cb3738Sbellard 
335819cb3738Sbellard /**
335919cb3738Sbellard  * Return TRUE if the media is present
336019cb3738Sbellard  */
3361e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
336219cb3738Sbellard {
336319cb3738Sbellard     BlockDriver *drv = bs->drv;
336428d7a789SMax Reitz     BdrvChild *child;
3365a1aff5bfSMarkus Armbruster 
3366e031f750SMax Reitz     if (!drv) {
3367e031f750SMax Reitz         return false;
3368e031f750SMax Reitz     }
336928d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3370a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
337119cb3738Sbellard     }
337228d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
337328d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
337428d7a789SMax Reitz             return false;
337528d7a789SMax Reitz         }
337628d7a789SMax Reitz     }
337728d7a789SMax Reitz     return true;
337828d7a789SMax Reitz }
337919cb3738Sbellard 
338019cb3738Sbellard /**
33818e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
33828e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
338319cb3738Sbellard  */
338419cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
338519cb3738Sbellard {
338619cb3738Sbellard     BlockDriver *drv = bs->drv;
338719cb3738Sbellard 
33888e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33898e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33908e49ca46SMarkus Armbruster     }
33918e49ca46SMarkus Armbruster     return -ENOTSUP;
339219cb3738Sbellard }
339319cb3738Sbellard 
339419cb3738Sbellard /**
339519cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
339619cb3738Sbellard  */
3397f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
339819cb3738Sbellard {
339919cb3738Sbellard     BlockDriver *drv = bs->drv;
340019cb3738Sbellard 
3401822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3402822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
340319cb3738Sbellard     }
340419cb3738Sbellard }
340519cb3738Sbellard 
340619cb3738Sbellard /**
340719cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
340819cb3738Sbellard  * to eject it manually).
340919cb3738Sbellard  */
3410025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
341119cb3738Sbellard {
341219cb3738Sbellard     BlockDriver *drv = bs->drv;
341319cb3738Sbellard 
3414025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3415b8c6d095SStefan Hajnoczi 
3416025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3417025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
341819cb3738Sbellard     }
341919cb3738Sbellard }
3420985a03b0Sths 
34219fcb0251SFam Zheng /* Get a reference to bs */
34229fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
34239fcb0251SFam Zheng {
34249fcb0251SFam Zheng     bs->refcnt++;
34259fcb0251SFam Zheng }
34269fcb0251SFam Zheng 
34279fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
34289fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
34299fcb0251SFam Zheng  * deleted. */
34309fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
34319fcb0251SFam Zheng {
34329a4d5ca6SJeff Cody     if (!bs) {
34339a4d5ca6SJeff Cody         return;
34349a4d5ca6SJeff Cody     }
34359fcb0251SFam Zheng     assert(bs->refcnt > 0);
34369fcb0251SFam Zheng     if (--bs->refcnt == 0) {
34379fcb0251SFam Zheng         bdrv_delete(bs);
34389fcb0251SFam Zheng     }
34399fcb0251SFam Zheng }
34409fcb0251SFam Zheng 
3441fbe40ff7SFam Zheng struct BdrvOpBlocker {
3442fbe40ff7SFam Zheng     Error *reason;
3443fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3444fbe40ff7SFam Zheng };
3445fbe40ff7SFam Zheng 
3446fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3447fbe40ff7SFam Zheng {
3448fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3449fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3450fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3451fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3452fbe40ff7SFam Zheng         if (errp) {
3453e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3454e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3455e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3456fbe40ff7SFam Zheng         }
3457fbe40ff7SFam Zheng         return true;
3458fbe40ff7SFam Zheng     }
3459fbe40ff7SFam Zheng     return false;
3460fbe40ff7SFam Zheng }
3461fbe40ff7SFam Zheng 
3462fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3463fbe40ff7SFam Zheng {
3464fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3465fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3466fbe40ff7SFam Zheng 
34675839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3468fbe40ff7SFam Zheng     blocker->reason = reason;
3469fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3470fbe40ff7SFam Zheng }
3471fbe40ff7SFam Zheng 
3472fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3473fbe40ff7SFam Zheng {
3474fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3475fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3476fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3477fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3478fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3479fbe40ff7SFam Zheng             g_free(blocker);
3480fbe40ff7SFam Zheng         }
3481fbe40ff7SFam Zheng     }
3482fbe40ff7SFam Zheng }
3483fbe40ff7SFam Zheng 
3484fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3485fbe40ff7SFam Zheng {
3486fbe40ff7SFam Zheng     int i;
3487fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3488fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3489fbe40ff7SFam Zheng     }
3490fbe40ff7SFam Zheng }
3491fbe40ff7SFam Zheng 
3492fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3493fbe40ff7SFam Zheng {
3494fbe40ff7SFam Zheng     int i;
3495fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3496fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3497fbe40ff7SFam Zheng     }
3498fbe40ff7SFam Zheng }
3499fbe40ff7SFam Zheng 
3500fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3501fbe40ff7SFam Zheng {
3502fbe40ff7SFam Zheng     int i;
3503fbe40ff7SFam Zheng 
3504fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3505fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3506fbe40ff7SFam Zheng             return false;
3507fbe40ff7SFam Zheng         }
3508fbe40ff7SFam Zheng     }
3509fbe40ff7SFam Zheng     return true;
3510fbe40ff7SFam Zheng }
3511fbe40ff7SFam Zheng 
3512d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3513f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3514f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3515f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3516f88e1a42SJes Sorensen {
351783d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
351883d0521aSChunyan Liu     QemuOpts *opts = NULL;
351983d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
352083d0521aSChunyan Liu     int64_t size;
3521f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3522cc84d90fSMax Reitz     Error *local_err = NULL;
3523f88e1a42SJes Sorensen     int ret = 0;
3524f88e1a42SJes Sorensen 
3525f88e1a42SJes Sorensen     /* Find driver and parse its options */
3526f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3527f88e1a42SJes Sorensen     if (!drv) {
352871c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3529d92ada22SLuiz Capitulino         return;
3530f88e1a42SJes Sorensen     }
3531f88e1a42SJes Sorensen 
3532b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3533f88e1a42SJes Sorensen     if (!proto_drv) {
3534d92ada22SLuiz Capitulino         return;
3535f88e1a42SJes Sorensen     }
3536f88e1a42SJes Sorensen 
3537c6149724SMax Reitz     if (!drv->create_opts) {
3538c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3539c6149724SMax Reitz                    drv->format_name);
3540c6149724SMax Reitz         return;
3541c6149724SMax Reitz     }
3542c6149724SMax Reitz 
3543c6149724SMax Reitz     if (!proto_drv->create_opts) {
3544c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3545c6149724SMax Reitz                    proto_drv->format_name);
3546c6149724SMax Reitz         return;
3547c6149724SMax Reitz     }
3548c6149724SMax Reitz 
3549c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3550c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3551f88e1a42SJes Sorensen 
3552f88e1a42SJes Sorensen     /* Create parameter list with default values */
355383d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
355439101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3555f88e1a42SJes Sorensen 
3556f88e1a42SJes Sorensen     /* Parse -o options */
3557f88e1a42SJes Sorensen     if (options) {
3558dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3559dc523cd3SMarkus Armbruster         if (local_err) {
3560dc523cd3SMarkus Armbruster             error_report_err(local_err);
3561dc523cd3SMarkus Armbruster             local_err = NULL;
356283d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3563f88e1a42SJes Sorensen             goto out;
3564f88e1a42SJes Sorensen         }
3565f88e1a42SJes Sorensen     }
3566f88e1a42SJes Sorensen 
3567f88e1a42SJes Sorensen     if (base_filename) {
3568f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35696be4194bSMarkus Armbruster         if (local_err) {
357071c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
357171c79813SLuiz Capitulino                        fmt);
3572f88e1a42SJes Sorensen             goto out;
3573f88e1a42SJes Sorensen         }
3574f88e1a42SJes Sorensen     }
3575f88e1a42SJes Sorensen 
3576f88e1a42SJes Sorensen     if (base_fmt) {
3577f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35786be4194bSMarkus Armbruster         if (local_err) {
357971c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
358071c79813SLuiz Capitulino                              "format '%s'", fmt);
3581f88e1a42SJes Sorensen             goto out;
3582f88e1a42SJes Sorensen         }
3583f88e1a42SJes Sorensen     }
3584f88e1a42SJes Sorensen 
358583d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
358683d0521aSChunyan Liu     if (backing_file) {
358783d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
358871c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
358971c79813SLuiz Capitulino                              "same filename as the backing file");
3590792da93aSJes Sorensen             goto out;
3591792da93aSJes Sorensen         }
3592792da93aSJes Sorensen     }
3593792da93aSJes Sorensen 
359483d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3595f88e1a42SJes Sorensen 
3596f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3597f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
359883d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
359983d0521aSChunyan Liu     if (size == -1) {
360083d0521aSChunyan Liu         if (backing_file) {
360166f6b814SMax Reitz             BlockDriverState *bs;
360229168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
360352bf1e72SMarkus Armbruster             int64_t size;
360463090dacSPaolo Bonzini             int back_flags;
3605e6641719SMax Reitz             QDict *backing_options = NULL;
360663090dacSPaolo Bonzini 
360729168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
360829168018SMax Reitz                                                          full_backing, PATH_MAX,
360929168018SMax Reitz                                                          &local_err);
361029168018SMax Reitz             if (local_err) {
361129168018SMax Reitz                 g_free(full_backing);
361229168018SMax Reitz                 goto out;
361329168018SMax Reitz             }
361429168018SMax Reitz 
361563090dacSPaolo Bonzini             /* backing files always opened read-only */
361661de4c68SKevin Wolf             back_flags = flags;
3617bfd18d1eSKevin Wolf             back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3618f88e1a42SJes Sorensen 
3619e6641719SMax Reitz             if (backing_fmt) {
3620e6641719SMax Reitz                 backing_options = qdict_new();
3621e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3622e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3623e6641719SMax Reitz             }
3624e6641719SMax Reitz 
36255b363937SMax Reitz             bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
36265b363937SMax Reitz                            &local_err);
362729168018SMax Reitz             g_free(full_backing);
36285b363937SMax Reitz             if (!bs) {
3629f88e1a42SJes Sorensen                 goto out;
3630f88e1a42SJes Sorensen             }
363152bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
363252bf1e72SMarkus Armbruster             if (size < 0) {
363352bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
363452bf1e72SMarkus Armbruster                                  backing_file);
363552bf1e72SMarkus Armbruster                 bdrv_unref(bs);
363652bf1e72SMarkus Armbruster                 goto out;
363752bf1e72SMarkus Armbruster             }
3638f88e1a42SJes Sorensen 
363939101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
364066f6b814SMax Reitz 
364166f6b814SMax Reitz             bdrv_unref(bs);
3642f88e1a42SJes Sorensen         } else {
364371c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3644f88e1a42SJes Sorensen             goto out;
3645f88e1a42SJes Sorensen         }
3646f88e1a42SJes Sorensen     }
3647f88e1a42SJes Sorensen 
3648f382d43aSMiroslav Rezanina     if (!quiet) {
3649f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
365043c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3651f88e1a42SJes Sorensen         puts("");
3652f382d43aSMiroslav Rezanina     }
365383d0521aSChunyan Liu 
3654c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
365583d0521aSChunyan Liu 
3656cc84d90fSMax Reitz     if (ret == -EFBIG) {
3657cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3658cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3659cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3660f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
366183d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3662f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3663f3f4d2c0SKevin Wolf         }
3664cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3665cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3666cc84d90fSMax Reitz         error_free(local_err);
3667cc84d90fSMax Reitz         local_err = NULL;
3668f88e1a42SJes Sorensen     }
3669f88e1a42SJes Sorensen 
3670f88e1a42SJes Sorensen out:
367183d0521aSChunyan Liu     qemu_opts_del(opts);
367283d0521aSChunyan Liu     qemu_opts_free(create_opts);
3673cc84d90fSMax Reitz     error_propagate(errp, local_err);
3674cc84d90fSMax Reitz }
367585d126f3SStefan Hajnoczi 
367685d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
367785d126f3SStefan Hajnoczi {
3678dcd04228SStefan Hajnoczi     return bs->aio_context;
3679dcd04228SStefan Hajnoczi }
3680dcd04228SStefan Hajnoczi 
3681e8a095daSStefan Hajnoczi static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
3682e8a095daSStefan Hajnoczi {
3683e8a095daSStefan Hajnoczi     QLIST_REMOVE(ban, list);
3684e8a095daSStefan Hajnoczi     g_free(ban);
3685e8a095daSStefan Hajnoczi }
3686e8a095daSStefan Hajnoczi 
3687dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3688dcd04228SStefan Hajnoczi {
3689e8a095daSStefan Hajnoczi     BdrvAioNotifier *baf, *baf_tmp;
3690b97511c7SMax Reitz     BdrvChild *child;
369133384421SMax Reitz 
3692dcd04228SStefan Hajnoczi     if (!bs->drv) {
3693dcd04228SStefan Hajnoczi         return;
3694dcd04228SStefan Hajnoczi     }
3695dcd04228SStefan Hajnoczi 
3696e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
3697e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
3698e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
3699e8a095daSStefan Hajnoczi         if (baf->deleted) {
3700e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(baf);
3701e8a095daSStefan Hajnoczi         } else {
370233384421SMax Reitz             baf->detach_aio_context(baf->opaque);
370333384421SMax Reitz         }
3704e8a095daSStefan Hajnoczi     }
3705e8a095daSStefan Hajnoczi     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
3706e8a095daSStefan Hajnoczi      * remove remaining aio notifiers if we aren't called again.
3707e8a095daSStefan Hajnoczi      */
3708e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
370933384421SMax Reitz 
3710dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3711dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3712dcd04228SStefan Hajnoczi     }
3713b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3714b97511c7SMax Reitz         bdrv_detach_aio_context(child->bs);
3715dcd04228SStefan Hajnoczi     }
3716dcd04228SStefan Hajnoczi 
3717dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3718dcd04228SStefan Hajnoczi }
3719dcd04228SStefan Hajnoczi 
3720dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3721dcd04228SStefan Hajnoczi                              AioContext *new_context)
3722dcd04228SStefan Hajnoczi {
3723e8a095daSStefan Hajnoczi     BdrvAioNotifier *ban, *ban_tmp;
3724b97511c7SMax Reitz     BdrvChild *child;
372533384421SMax Reitz 
3726dcd04228SStefan Hajnoczi     if (!bs->drv) {
3727dcd04228SStefan Hajnoczi         return;
3728dcd04228SStefan Hajnoczi     }
3729dcd04228SStefan Hajnoczi 
3730dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3731dcd04228SStefan Hajnoczi 
3732b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3733b97511c7SMax Reitz         bdrv_attach_aio_context(child->bs, new_context);
3734dcd04228SStefan Hajnoczi     }
3735dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3736dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3737dcd04228SStefan Hajnoczi     }
373833384421SMax Reitz 
3739e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
3740e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
3741e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
3742e8a095daSStefan Hajnoczi         if (ban->deleted) {
3743e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(ban);
3744e8a095daSStefan Hajnoczi         } else {
374533384421SMax Reitz             ban->attached_aio_context(new_context, ban->opaque);
374633384421SMax Reitz         }
3747dcd04228SStefan Hajnoczi     }
3748e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
3749e8a095daSStefan Hajnoczi }
3750dcd04228SStefan Hajnoczi 
3751dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3752dcd04228SStefan Hajnoczi {
375353ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3754dcd04228SStefan Hajnoczi 
3755dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3756dcd04228SStefan Hajnoczi 
3757dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3758dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3759dcd04228SStefan Hajnoczi      */
3760dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3761dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3762dcd04228SStefan Hajnoczi     aio_context_release(new_context);
376385d126f3SStefan Hajnoczi }
3764d616b224SStefan Hajnoczi 
376533384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
376633384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
376733384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
376833384421SMax Reitz {
376933384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
377033384421SMax Reitz     *ban = (BdrvAioNotifier){
377133384421SMax Reitz         .attached_aio_context = attached_aio_context,
377233384421SMax Reitz         .detach_aio_context   = detach_aio_context,
377333384421SMax Reitz         .opaque               = opaque
377433384421SMax Reitz     };
377533384421SMax Reitz 
377633384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
377733384421SMax Reitz }
377833384421SMax Reitz 
377933384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
378033384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
378133384421SMax Reitz                                                                    void *),
378233384421SMax Reitz                                       void (*detach_aio_context)(void *),
378333384421SMax Reitz                                       void *opaque)
378433384421SMax Reitz {
378533384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
378633384421SMax Reitz 
378733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
378833384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
378933384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
3790e8a095daSStefan Hajnoczi             ban->opaque               == opaque               &&
3791e8a095daSStefan Hajnoczi             ban->deleted              == false)
379233384421SMax Reitz         {
3793e8a095daSStefan Hajnoczi             if (bs->walking_aio_notifiers) {
3794e8a095daSStefan Hajnoczi                 ban->deleted = true;
3795e8a095daSStefan Hajnoczi             } else {
3796e8a095daSStefan Hajnoczi                 bdrv_do_remove_aio_context_notifier(ban);
3797e8a095daSStefan Hajnoczi             }
379833384421SMax Reitz             return;
379933384421SMax Reitz         }
380033384421SMax Reitz     }
380133384421SMax Reitz 
380233384421SMax Reitz     abort();
380333384421SMax Reitz }
380433384421SMax Reitz 
380577485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
38068b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
38076f176b48SMax Reitz {
3808c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
38096f176b48SMax Reitz         return -ENOTSUP;
38106f176b48SMax Reitz     }
38118b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
38126f176b48SMax Reitz }
3813f6186f49SBenoît Canet 
3814b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3815b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3816b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3817b5042a36SBenoît Canet  * node graph.
3818212a5a8fSBenoît Canet  */
3819212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3820212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3821f6186f49SBenoît Canet {
3822b5042a36SBenoît Canet     /* return false if basic checks fails */
3823b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3824b5042a36SBenoît Canet         return false;
3825b5042a36SBenoît Canet     }
3826b5042a36SBenoît Canet 
3827b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3828b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3829b5042a36SBenoît Canet      */
3830b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3831b5042a36SBenoît Canet         return bs == candidate;
3832b5042a36SBenoît Canet     }
3833b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3834b5042a36SBenoît Canet 
3835b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3836b5042a36SBenoît Canet      * the node graph.
3837b5042a36SBenoît Canet      */
3838b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3839212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3840212a5a8fSBenoît Canet     }
3841212a5a8fSBenoît Canet 
3842b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3843b5042a36SBenoît Canet      */
3844b5042a36SBenoît Canet     return false;
3845212a5a8fSBenoît Canet }
3846212a5a8fSBenoît Canet 
3847212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3848212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3849212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3850212a5a8fSBenoît Canet  */
3851212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3852212a5a8fSBenoît Canet {
38537c8eece4SKevin Wolf     BlockDriverState *bs;
385488be7b4bSKevin Wolf     BdrvNextIterator it;
3855212a5a8fSBenoît Canet 
3856212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
385788be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3858212a5a8fSBenoît Canet         bool perm;
3859212a5a8fSBenoît Canet 
3860b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3861e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3862212a5a8fSBenoît Canet 
3863212a5a8fSBenoît Canet         /* candidate is the first non filter */
3864212a5a8fSBenoît Canet         if (perm) {
3865212a5a8fSBenoît Canet             return true;
3866212a5a8fSBenoît Canet         }
3867212a5a8fSBenoît Canet     }
3868212a5a8fSBenoît Canet 
3869212a5a8fSBenoît Canet     return false;
3870f6186f49SBenoît Canet }
387109158f00SBenoît Canet 
3872e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3873e12f3784SWen Congyang                                         const char *node_name, Error **errp)
387409158f00SBenoît Canet {
387509158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38765a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38775a7e7a0bSStefan Hajnoczi 
387809158f00SBenoît Canet     if (!to_replace_bs) {
387909158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
388009158f00SBenoît Canet         return NULL;
388109158f00SBenoît Canet     }
388209158f00SBenoît Canet 
38835a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38845a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38855a7e7a0bSStefan Hajnoczi 
388609158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38875a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38885a7e7a0bSStefan Hajnoczi         goto out;
388909158f00SBenoît Canet     }
389009158f00SBenoît Canet 
389109158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
389209158f00SBenoît Canet      * most non filter in order to prevent data corruption.
389309158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
389409158f00SBenoît Canet      * blocked by the backing blockers.
389509158f00SBenoît Canet      */
3896e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
389709158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
38985a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38995a7e7a0bSStefan Hajnoczi         goto out;
390009158f00SBenoît Canet     }
390109158f00SBenoît Canet 
39025a7e7a0bSStefan Hajnoczi out:
39035a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
390409158f00SBenoît Canet     return to_replace_bs;
390509158f00SBenoît Canet }
3906448ad91dSMing Lei 
390791af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
390891af7014SMax Reitz {
390991af7014SMax Reitz     const QDictEntry *entry;
39109e700c1aSKevin Wolf     QemuOptDesc *desc;
3911260fecf1SKevin Wolf     BdrvChild *child;
391291af7014SMax Reitz     bool found_any = false;
3913260fecf1SKevin Wolf     const char *p;
391491af7014SMax Reitz 
391591af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
391691af7014SMax Reitz          entry = qdict_next(bs->options, entry))
391791af7014SMax Reitz     {
3918260fecf1SKevin Wolf         /* Exclude options for children */
3919260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3920260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3921260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3922260fecf1SKevin Wolf             {
3923260fecf1SKevin Wolf                 break;
3924260fecf1SKevin Wolf             }
3925260fecf1SKevin Wolf         }
3926260fecf1SKevin Wolf         if (child) {
39279e700c1aSKevin Wolf             continue;
39289e700c1aSKevin Wolf         }
39299e700c1aSKevin Wolf 
39309e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
39319e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
39329e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
39339e700c1aSKevin Wolf                 break;
39349e700c1aSKevin Wolf             }
39359e700c1aSKevin Wolf         }
39369e700c1aSKevin Wolf         if (desc->name) {
39379e700c1aSKevin Wolf             continue;
39389e700c1aSKevin Wolf         }
39399e700c1aSKevin Wolf 
394091af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
394191af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
394291af7014SMax Reitz         found_any = true;
394391af7014SMax Reitz     }
394491af7014SMax Reitz 
394591af7014SMax Reitz     return found_any;
394691af7014SMax Reitz }
394791af7014SMax Reitz 
394891af7014SMax Reitz /* Updates the following BDS fields:
394991af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
395091af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
395191af7014SMax Reitz  *                    other options; so reading and writing must return the same
395291af7014SMax Reitz  *                    results, but caching etc. may be different)
395391af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
395491af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
395591af7014SMax Reitz  *                       equalling the given one
395691af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
395791af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
395891af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
395991af7014SMax Reitz  */
396091af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
396191af7014SMax Reitz {
396291af7014SMax Reitz     BlockDriver *drv = bs->drv;
396391af7014SMax Reitz     QDict *opts;
396491af7014SMax Reitz 
396591af7014SMax Reitz     if (!drv) {
396691af7014SMax Reitz         return;
396791af7014SMax Reitz     }
396891af7014SMax Reitz 
396991af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
397091af7014SMax Reitz      * refresh that first */
397191af7014SMax Reitz     if (bs->file) {
39729a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
397391af7014SMax Reitz     }
397491af7014SMax Reitz 
397591af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
397691af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
397791af7014SMax Reitz          * information before refreshing it */
397891af7014SMax Reitz         bs->exact_filename[0] = '\0';
397991af7014SMax Reitz         if (bs->full_open_options) {
398091af7014SMax Reitz             QDECREF(bs->full_open_options);
398191af7014SMax Reitz             bs->full_open_options = NULL;
398291af7014SMax Reitz         }
398391af7014SMax Reitz 
39844cdd01d3SKevin Wolf         opts = qdict_new();
39854cdd01d3SKevin Wolf         append_open_options(opts, bs);
39864cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
39874cdd01d3SKevin Wolf         QDECREF(opts);
398891af7014SMax Reitz     } else if (bs->file) {
398991af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
399091af7014SMax Reitz         bool has_open_options;
399191af7014SMax Reitz 
399291af7014SMax Reitz         bs->exact_filename[0] = '\0';
399391af7014SMax Reitz         if (bs->full_open_options) {
399491af7014SMax Reitz             QDECREF(bs->full_open_options);
399591af7014SMax Reitz             bs->full_open_options = NULL;
399691af7014SMax Reitz         }
399791af7014SMax Reitz 
399891af7014SMax Reitz         opts = qdict_new();
399991af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
400091af7014SMax Reitz 
400191af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
400291af7014SMax Reitz          * the underlying file should suffice for this one as well */
40039a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
40049a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
400591af7014SMax Reitz         }
400691af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
400791af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
400891af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
400991af7014SMax Reitz          * contain a representation of the filename, therefore the following
401091af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
40119a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
401291af7014SMax Reitz             qdict_put_obj(opts, "driver",
401391af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
40149a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
40159a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
40169a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
401791af7014SMax Reitz 
401891af7014SMax Reitz             bs->full_open_options = opts;
401991af7014SMax Reitz         } else {
402091af7014SMax Reitz             QDECREF(opts);
402191af7014SMax Reitz         }
402291af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
402391af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
402491af7014SMax Reitz          * so the full options QDict should be equal to the options given
402591af7014SMax Reitz          * specifically for this block device when it was opened (plus the
402691af7014SMax Reitz          * driver specification).
402791af7014SMax Reitz          * Because those options don't change, there is no need to update
402891af7014SMax Reitz          * full_open_options when it's already set. */
402991af7014SMax Reitz 
403091af7014SMax Reitz         opts = qdict_new();
403191af7014SMax Reitz         append_open_options(opts, bs);
403291af7014SMax Reitz         qdict_put_obj(opts, "driver",
403391af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
403491af7014SMax Reitz 
403591af7014SMax Reitz         if (bs->exact_filename[0]) {
403691af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
403791af7014SMax Reitz              * require this filename to be parsed), but we have to find some
403891af7014SMax Reitz              * default solution here, so just include it. If some block driver
403991af7014SMax Reitz              * does not support pure options without any filename at all or
404091af7014SMax Reitz              * needs some special format of the options QDict, it needs to
404191af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
404291af7014SMax Reitz              */
404391af7014SMax Reitz             qdict_put_obj(opts, "filename",
404491af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
404591af7014SMax Reitz         }
404691af7014SMax Reitz 
404791af7014SMax Reitz         bs->full_open_options = opts;
404891af7014SMax Reitz     }
404991af7014SMax Reitz 
405091af7014SMax Reitz     if (bs->exact_filename[0]) {
405191af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
405291af7014SMax Reitz     } else if (bs->full_open_options) {
405391af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
405491af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
405591af7014SMax Reitz                  qstring_get_str(json));
405691af7014SMax Reitz         QDECREF(json);
405791af7014SMax Reitz     }
405891af7014SMax Reitz }
4059e06018adSWen Congyang 
4060e06018adSWen Congyang /*
4061e06018adSWen Congyang  * Hot add/remove a BDS's child. So the user can take a child offline when
4062e06018adSWen Congyang  * it is broken and take a new child online
4063e06018adSWen Congyang  */
4064e06018adSWen Congyang void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
4065e06018adSWen Congyang                     Error **errp)
4066e06018adSWen Congyang {
4067e06018adSWen Congyang 
4068e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
4069e06018adSWen Congyang         error_setg(errp, "The node %s does not support adding a child",
4070e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
4071e06018adSWen Congyang         return;
4072e06018adSWen Congyang     }
4073e06018adSWen Congyang 
4074e06018adSWen Congyang     if (!QLIST_EMPTY(&child_bs->parents)) {
4075e06018adSWen Congyang         error_setg(errp, "The node %s already has a parent",
4076e06018adSWen Congyang                    child_bs->node_name);
4077e06018adSWen Congyang         return;
4078e06018adSWen Congyang     }
4079e06018adSWen Congyang 
4080e06018adSWen Congyang     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
4081e06018adSWen Congyang }
4082e06018adSWen Congyang 
4083e06018adSWen Congyang void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
4084e06018adSWen Congyang {
4085e06018adSWen Congyang     BdrvChild *tmp;
4086e06018adSWen Congyang 
4087e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
4088e06018adSWen Congyang         error_setg(errp, "The node %s does not support removing a child",
4089e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
4090e06018adSWen Congyang         return;
4091e06018adSWen Congyang     }
4092e06018adSWen Congyang 
4093e06018adSWen Congyang     QLIST_FOREACH(tmp, &parent_bs->children, next) {
4094e06018adSWen Congyang         if (tmp == child) {
4095e06018adSWen Congyang             break;
4096e06018adSWen Congyang         }
4097e06018adSWen Congyang     }
4098e06018adSWen Congyang 
4099e06018adSWen Congyang     if (!tmp) {
4100e06018adSWen Congyang         error_setg(errp, "The node %s does not have a child named %s",
4101e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs),
4102e06018adSWen Congyang                    bdrv_get_device_or_node_name(child->bs));
4103e06018adSWen Congyang         return;
4104e06018adSWen Congyang     }
4105e06018adSWen Congyang 
4106e06018adSWen Congyang     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
4107e06018adSWen Congyang }
4108