xref: /openbmc/qemu/block.c (revision cf2ab8fc345c34f8671fade9230746610e4fc340)
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"
256d519a5fSStefan Hajnoczi #include "trace.h"
26737e150eSPaolo Bonzini #include "block/block_int.h"
27737e150eSPaolo Bonzini #include "block/blockjob.h"
28d49b6836SMarkus Armbruster #include "qemu/error-report.h"
291de7afc9SPaolo Bonzini #include "qemu/module.h"
30cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
3191a097e7SKevin Wolf #include "qapi/qmp/qbool.h"
327b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
33bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
349c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
351de7afc9SPaolo Bonzini #include "qemu/notify.h"
3610817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
37c13163fbSBenoît Canet #include "block/qapi.h"
38b2023818SLuiz Capitulino #include "qmp-commands.h"
391de7afc9SPaolo Bonzini #include "qemu/timer.h"
40a5ee7bd4SWenchao Xia #include "qapi-event.h"
41f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
42f348b6d1SVeronia Bahaa #include "qemu/id.h"
43fc01f7e7Sbellard 
4471e72a19SJuan Quintela #ifdef CONFIG_BSD
457674e7bfSbellard #include <sys/ioctl.h>
4672cf2d4fSBlue Swirl #include <sys/queue.h>
47c5e97233Sblueswir1 #ifndef __DragonFly__
487674e7bfSbellard #include <sys/disk.h>
497674e7bfSbellard #endif
50c5e97233Sblueswir1 #endif
517674e7bfSbellard 
5249dc768dSaliguori #ifdef _WIN32
5349dc768dSaliguori #include <windows.h>
5449dc768dSaliguori #endif
5549dc768dSaliguori 
561c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
571c9805a3SStefan Hajnoczi 
58dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
59dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
60dc364f4cSBenoît Canet 
612c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
622c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
632c1d04e0SMax Reitz 
648a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
658a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
66ea2384d3Sbellard 
675b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
685b363937SMax Reitz                                            const char *reference,
695b363937SMax Reitz                                            QDict *options, int flags,
70f3930ed0SKevin Wolf                                            BlockDriverState *parent,
715b363937SMax Reitz                                            const BdrvChildRole *child_role,
725b363937SMax Reitz                                            Error **errp);
73f3930ed0SKevin Wolf 
74eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
75eb852011SMarkus Armbruster static int use_bdrv_whitelist;
76eb852011SMarkus Armbruster 
779e0b22f4SStefan Hajnoczi #ifdef _WIN32
789e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
799e0b22f4SStefan Hajnoczi {
809e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
819e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
829e0b22f4SStefan Hajnoczi             filename[1] == ':');
839e0b22f4SStefan Hajnoczi }
849e0b22f4SStefan Hajnoczi 
859e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
869e0b22f4SStefan Hajnoczi {
879e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
889e0b22f4SStefan Hajnoczi         filename[2] == '\0')
899e0b22f4SStefan Hajnoczi         return 1;
909e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
919e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
929e0b22f4SStefan Hajnoczi         return 1;
939e0b22f4SStefan Hajnoczi     return 0;
949e0b22f4SStefan Hajnoczi }
959e0b22f4SStefan Hajnoczi #endif
969e0b22f4SStefan Hajnoczi 
97339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
98339064d5SKevin Wolf {
99339064d5SKevin Wolf     if (!bs || !bs->drv) {
100459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
101459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
102339064d5SKevin Wolf     }
103339064d5SKevin Wolf 
104339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
105339064d5SKevin Wolf }
106339064d5SKevin Wolf 
1074196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1084196d2f0SDenis V. Lunev {
1094196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
110459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
111459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1124196d2f0SDenis V. Lunev     }
1134196d2f0SDenis V. Lunev 
1144196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1154196d2f0SDenis V. Lunev }
1164196d2f0SDenis V. Lunev 
1179e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1185c98415bSMax Reitz int path_has_protocol(const char *path)
1199e0b22f4SStefan Hajnoczi {
120947995c0SPaolo Bonzini     const char *p;
121947995c0SPaolo Bonzini 
1229e0b22f4SStefan Hajnoczi #ifdef _WIN32
1239e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1249e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1259e0b22f4SStefan Hajnoczi         return 0;
1269e0b22f4SStefan Hajnoczi     }
127947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
128947995c0SPaolo Bonzini #else
129947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1309e0b22f4SStefan Hajnoczi #endif
1319e0b22f4SStefan Hajnoczi 
132947995c0SPaolo Bonzini     return *p == ':';
1339e0b22f4SStefan Hajnoczi }
1349e0b22f4SStefan Hajnoczi 
13583f64091Sbellard int path_is_absolute(const char *path)
13683f64091Sbellard {
13721664424Sbellard #ifdef _WIN32
13821664424Sbellard     /* specific case for names like: "\\.\d:" */
139f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
14021664424Sbellard         return 1;
141f53f4da9SPaolo Bonzini     }
142f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1433b9f94e1Sbellard #else
144f53f4da9SPaolo Bonzini     return (*path == '/');
1453b9f94e1Sbellard #endif
14683f64091Sbellard }
14783f64091Sbellard 
14883f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
14983f64091Sbellard    path to it by considering it is relative to base_path. URL are
15083f64091Sbellard    supported. */
15183f64091Sbellard void path_combine(char *dest, int dest_size,
15283f64091Sbellard                   const char *base_path,
15383f64091Sbellard                   const char *filename)
15483f64091Sbellard {
15583f64091Sbellard     const char *p, *p1;
15683f64091Sbellard     int len;
15783f64091Sbellard 
15883f64091Sbellard     if (dest_size <= 0)
15983f64091Sbellard         return;
16083f64091Sbellard     if (path_is_absolute(filename)) {
16183f64091Sbellard         pstrcpy(dest, dest_size, filename);
16283f64091Sbellard     } else {
16383f64091Sbellard         p = strchr(base_path, ':');
16483f64091Sbellard         if (p)
16583f64091Sbellard             p++;
16683f64091Sbellard         else
16783f64091Sbellard             p = base_path;
1683b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1693b9f94e1Sbellard #ifdef _WIN32
1703b9f94e1Sbellard         {
1713b9f94e1Sbellard             const char *p2;
1723b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1733b9f94e1Sbellard             if (!p1 || p2 > p1)
1743b9f94e1Sbellard                 p1 = p2;
1753b9f94e1Sbellard         }
1763b9f94e1Sbellard #endif
17783f64091Sbellard         if (p1)
17883f64091Sbellard             p1++;
17983f64091Sbellard         else
18083f64091Sbellard             p1 = base_path;
18183f64091Sbellard         if (p1 > p)
18283f64091Sbellard             p = p1;
18383f64091Sbellard         len = p - base_path;
18483f64091Sbellard         if (len > dest_size - 1)
18583f64091Sbellard             len = dest_size - 1;
18683f64091Sbellard         memcpy(dest, base_path, len);
18783f64091Sbellard         dest[len] = '\0';
18883f64091Sbellard         pstrcat(dest, dest_size, filename);
18983f64091Sbellard     }
19083f64091Sbellard }
19183f64091Sbellard 
1920a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
1930a82855aSMax Reitz                                                   const char *backing,
1949f07429eSMax Reitz                                                   char *dest, size_t sz,
1959f07429eSMax Reitz                                                   Error **errp)
1960a82855aSMax Reitz {
1979f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
1989f07429eSMax Reitz         path_is_absolute(backing))
1999f07429eSMax Reitz     {
2000a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2019f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2029f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2039f07429eSMax Reitz                    backed);
2040a82855aSMax Reitz     } else {
2050a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2060a82855aSMax Reitz     }
2070a82855aSMax Reitz }
2080a82855aSMax Reitz 
2099f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2109f07429eSMax Reitz                                     Error **errp)
211dc5a1371SPaolo Bonzini {
2129f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2139f07429eSMax Reitz 
2149f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2159f07429eSMax Reitz                                                  dest, sz, errp);
216dc5a1371SPaolo Bonzini }
217dc5a1371SPaolo Bonzini 
2180eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2190eb7217eSStefan Hajnoczi {
2208a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
221ea2384d3Sbellard }
222b338082bSbellard 
223e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
224e4e9986bSMarkus Armbruster {
225e4e9986bSMarkus Armbruster     BlockDriverState *bs;
226e4e9986bSMarkus Armbruster     int i;
227e4e9986bSMarkus Armbruster 
2285839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
229e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
230fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
231fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
232fbe40ff7SFam Zheng     }
233d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
2349fcb0251SFam Zheng     bs->refcnt = 1;
235dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
236d7d512f6SPaolo Bonzini 
2372c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
2382c1d04e0SMax Reitz 
239b338082bSbellard     return bs;
240b338082bSbellard }
241b338082bSbellard 
242ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
243ea2384d3Sbellard {
244ea2384d3Sbellard     BlockDriver *drv1;
2458a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2468a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
247ea2384d3Sbellard             return drv1;
248ea2384d3Sbellard         }
2498a22f02aSStefan Hajnoczi     }
250ea2384d3Sbellard     return NULL;
251ea2384d3Sbellard }
252ea2384d3Sbellard 
253b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
254eb852011SMarkus Armbruster {
255b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
256b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
257b64ec4e4SFam Zheng     };
258b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
259b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
260eb852011SMarkus Armbruster     };
261eb852011SMarkus Armbruster     const char **p;
262eb852011SMarkus Armbruster 
263b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
264eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
265b64ec4e4SFam Zheng     }
266eb852011SMarkus Armbruster 
267b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
268eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
269eb852011SMarkus Armbruster             return 1;
270eb852011SMarkus Armbruster         }
271eb852011SMarkus Armbruster     }
272b64ec4e4SFam Zheng     if (read_only) {
273b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
274b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
275b64ec4e4SFam Zheng                 return 1;
276b64ec4e4SFam Zheng             }
277b64ec4e4SFam Zheng         }
278b64ec4e4SFam Zheng     }
279eb852011SMarkus Armbruster     return 0;
280eb852011SMarkus Armbruster }
281eb852011SMarkus Armbruster 
282e6ff69bfSDaniel P. Berrange bool bdrv_uses_whitelist(void)
283e6ff69bfSDaniel P. Berrange {
284e6ff69bfSDaniel P. Berrange     return use_bdrv_whitelist;
285e6ff69bfSDaniel P. Berrange }
286e6ff69bfSDaniel P. Berrange 
2875b7e1542SZhi Yong Wu typedef struct CreateCo {
2885b7e1542SZhi Yong Wu     BlockDriver *drv;
2895b7e1542SZhi Yong Wu     char *filename;
29083d0521aSChunyan Liu     QemuOpts *opts;
2915b7e1542SZhi Yong Wu     int ret;
292cc84d90fSMax Reitz     Error *err;
2935b7e1542SZhi Yong Wu } CreateCo;
2945b7e1542SZhi Yong Wu 
2955b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
2965b7e1542SZhi Yong Wu {
297cc84d90fSMax Reitz     Error *local_err = NULL;
298cc84d90fSMax Reitz     int ret;
299cc84d90fSMax Reitz 
3005b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3015b7e1542SZhi Yong Wu     assert(cco->drv);
3025b7e1542SZhi Yong Wu 
303c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
304cc84d90fSMax Reitz     error_propagate(&cco->err, local_err);
305cc84d90fSMax Reitz     cco->ret = ret;
3065b7e1542SZhi Yong Wu }
3075b7e1542SZhi Yong Wu 
3080e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
30983d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
310ea2384d3Sbellard {
3115b7e1542SZhi Yong Wu     int ret;
3120e7e1989SKevin Wolf 
3135b7e1542SZhi Yong Wu     Coroutine *co;
3145b7e1542SZhi Yong Wu     CreateCo cco = {
3155b7e1542SZhi Yong Wu         .drv = drv,
3165b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
31783d0521aSChunyan Liu         .opts = opts,
3185b7e1542SZhi Yong Wu         .ret = NOT_DONE,
319cc84d90fSMax Reitz         .err = NULL,
3205b7e1542SZhi Yong Wu     };
3215b7e1542SZhi Yong Wu 
322c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
323cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
32480168bffSLuiz Capitulino         ret = -ENOTSUP;
32580168bffSLuiz Capitulino         goto out;
3265b7e1542SZhi Yong Wu     }
3275b7e1542SZhi Yong Wu 
3285b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3295b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3305b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3315b7e1542SZhi Yong Wu     } else {
3325b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3335b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3345b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
335b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3365b7e1542SZhi Yong Wu         }
3375b7e1542SZhi Yong Wu     }
3385b7e1542SZhi Yong Wu 
3395b7e1542SZhi Yong Wu     ret = cco.ret;
340cc84d90fSMax Reitz     if (ret < 0) {
34184d18f06SMarkus Armbruster         if (cco.err) {
342cc84d90fSMax Reitz             error_propagate(errp, cco.err);
343cc84d90fSMax Reitz         } else {
344cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
345cc84d90fSMax Reitz         }
346cc84d90fSMax Reitz     }
3475b7e1542SZhi Yong Wu 
34880168bffSLuiz Capitulino out:
34980168bffSLuiz Capitulino     g_free(cco.filename);
3505b7e1542SZhi Yong Wu     return ret;
351ea2384d3Sbellard }
352ea2384d3Sbellard 
353c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
35484a12e66SChristoph Hellwig {
35584a12e66SChristoph Hellwig     BlockDriver *drv;
356cc84d90fSMax Reitz     Error *local_err = NULL;
357cc84d90fSMax Reitz     int ret;
35884a12e66SChristoph Hellwig 
359b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
36084a12e66SChristoph Hellwig     if (drv == NULL) {
36116905d71SStefan Hajnoczi         return -ENOENT;
36284a12e66SChristoph Hellwig     }
36384a12e66SChristoph Hellwig 
364c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
365cc84d90fSMax Reitz     error_propagate(errp, local_err);
366cc84d90fSMax Reitz     return ret;
36784a12e66SChristoph Hellwig }
36884a12e66SChristoph Hellwig 
369892b7de8SEkaterina Tumanova /**
370892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
371892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
372892b7de8SEkaterina Tumanova  * On failure return -errno.
373892b7de8SEkaterina Tumanova  * @bs must not be empty.
374892b7de8SEkaterina Tumanova  */
375892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
376892b7de8SEkaterina Tumanova {
377892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
378892b7de8SEkaterina Tumanova 
379892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
380892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
381892b7de8SEkaterina Tumanova     }
382892b7de8SEkaterina Tumanova 
383892b7de8SEkaterina Tumanova     return -ENOTSUP;
384892b7de8SEkaterina Tumanova }
385892b7de8SEkaterina Tumanova 
386892b7de8SEkaterina Tumanova /**
387892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
388892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
389892b7de8SEkaterina Tumanova  * On failure return -errno.
390892b7de8SEkaterina Tumanova  * @bs must not be empty.
391892b7de8SEkaterina Tumanova  */
392892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
393892b7de8SEkaterina Tumanova {
394892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
395892b7de8SEkaterina Tumanova 
396892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
397892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
398892b7de8SEkaterina Tumanova     }
399892b7de8SEkaterina Tumanova 
400892b7de8SEkaterina Tumanova     return -ENOTSUP;
401892b7de8SEkaterina Tumanova }
402892b7de8SEkaterina Tumanova 
403eba25057SJim Meyering /*
404eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
405eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
406eba25057SJim Meyering  */
407eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
408eba25057SJim Meyering {
409d5249393Sbellard #ifdef _WIN32
4103b9f94e1Sbellard     char temp_dir[MAX_PATH];
411eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
412eba25057SJim Meyering        have length MAX_PATH or greater.  */
413eba25057SJim Meyering     assert(size >= MAX_PATH);
414eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
415eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
416eba25057SJim Meyering             ? 0 : -GetLastError());
417d5249393Sbellard #else
418ea2384d3Sbellard     int fd;
4197ccfb2ebSblueswir1     const char *tmpdir;
4200badc1eeSaurel32     tmpdir = getenv("TMPDIR");
42169bef793SAmit Shah     if (!tmpdir) {
42269bef793SAmit Shah         tmpdir = "/var/tmp";
42369bef793SAmit Shah     }
424eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
425eba25057SJim Meyering         return -EOVERFLOW;
426ea2384d3Sbellard     }
427eba25057SJim Meyering     fd = mkstemp(filename);
428fe235a06SDunrong Huang     if (fd < 0) {
429fe235a06SDunrong Huang         return -errno;
430fe235a06SDunrong Huang     }
431fe235a06SDunrong Huang     if (close(fd) != 0) {
432fe235a06SDunrong Huang         unlink(filename);
433eba25057SJim Meyering         return -errno;
434eba25057SJim Meyering     }
435eba25057SJim Meyering     return 0;
436d5249393Sbellard #endif
437eba25057SJim Meyering }
438ea2384d3Sbellard 
439f3a5d3f8SChristoph Hellwig /*
440f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
441f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
442f3a5d3f8SChristoph Hellwig  */
443f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
444f3a5d3f8SChristoph Hellwig {
445508c7cb3SChristoph Hellwig     int score_max = 0, score;
446508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
447f3a5d3f8SChristoph Hellwig 
4488a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
449508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
450508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
451508c7cb3SChristoph Hellwig             if (score > score_max) {
452508c7cb3SChristoph Hellwig                 score_max = score;
453508c7cb3SChristoph Hellwig                 drv = d;
454f3a5d3f8SChristoph Hellwig             }
455508c7cb3SChristoph Hellwig         }
456f3a5d3f8SChristoph Hellwig     }
457f3a5d3f8SChristoph Hellwig 
458508c7cb3SChristoph Hellwig     return drv;
459f3a5d3f8SChristoph Hellwig }
460f3a5d3f8SChristoph Hellwig 
46198289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
462b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
463b65a5e12SMax Reitz                                 Error **errp)
46484a12e66SChristoph Hellwig {
46584a12e66SChristoph Hellwig     BlockDriver *drv1;
46684a12e66SChristoph Hellwig     char protocol[128];
46784a12e66SChristoph Hellwig     int len;
46884a12e66SChristoph Hellwig     const char *p;
46984a12e66SChristoph Hellwig 
47066f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
47166f82ceeSKevin Wolf 
47239508e7aSChristoph Hellwig     /*
47339508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
47439508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
47539508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
47639508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
47739508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
47839508e7aSChristoph Hellwig      */
47984a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
48039508e7aSChristoph Hellwig     if (drv1) {
48184a12e66SChristoph Hellwig         return drv1;
48284a12e66SChristoph Hellwig     }
48339508e7aSChristoph Hellwig 
48498289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
485ef810437SMax Reitz         return &bdrv_file;
48639508e7aSChristoph Hellwig     }
48798289620SKevin Wolf 
4889e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4899e0b22f4SStefan Hajnoczi     assert(p != NULL);
49084a12e66SChristoph Hellwig     len = p - filename;
49184a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
49284a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
49384a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
49484a12e66SChristoph Hellwig     protocol[len] = '\0';
49584a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
49684a12e66SChristoph Hellwig         if (drv1->protocol_name &&
49784a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
49884a12e66SChristoph Hellwig             return drv1;
49984a12e66SChristoph Hellwig         }
50084a12e66SChristoph Hellwig     }
501b65a5e12SMax Reitz 
502b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
50384a12e66SChristoph Hellwig     return NULL;
50484a12e66SChristoph Hellwig }
50584a12e66SChristoph Hellwig 
506c6684249SMarkus Armbruster /*
507c6684249SMarkus Armbruster  * Guess image format by probing its contents.
508c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
509c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
510c6684249SMarkus Armbruster  *
511c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5127cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5137cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
514c6684249SMarkus Armbruster  * @filename    is its filename.
515c6684249SMarkus Armbruster  *
516c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
517c6684249SMarkus Armbruster  * probing score.
518c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
519c6684249SMarkus Armbruster  */
52038f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
521c6684249SMarkus Armbruster                             const char *filename)
522c6684249SMarkus Armbruster {
523c6684249SMarkus Armbruster     int score_max = 0, score;
524c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
525c6684249SMarkus Armbruster 
526c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
527c6684249SMarkus Armbruster         if (d->bdrv_probe) {
528c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
529c6684249SMarkus Armbruster             if (score > score_max) {
530c6684249SMarkus Armbruster                 score_max = score;
531c6684249SMarkus Armbruster                 drv = d;
532c6684249SMarkus Armbruster             }
533c6684249SMarkus Armbruster         }
534c6684249SMarkus Armbruster     }
535c6684249SMarkus Armbruster 
536c6684249SMarkus Armbruster     return drv;
537c6684249SMarkus Armbruster }
538c6684249SMarkus Armbruster 
539*cf2ab8fcSKevin Wolf static int find_image_format(BdrvChild *file, const char *filename,
54034b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
541ea2384d3Sbellard {
542*cf2ab8fcSKevin Wolf     BlockDriverState *bs = file->bs;
543c6684249SMarkus Armbruster     BlockDriver *drv;
5447cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
545f500a6d3SKevin Wolf     int ret = 0;
546f8ea0b00SNicholas Bellinger 
54708a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
548b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
549ef810437SMax Reitz         *pdrv = &bdrv_raw;
550c98ac35dSStefan Weil         return ret;
5511a396859SNicholas A. Bellinger     }
552f8ea0b00SNicholas Bellinger 
553*cf2ab8fcSKevin Wolf     ret = bdrv_pread(file, 0, buf, sizeof(buf));
554ea2384d3Sbellard     if (ret < 0) {
55534b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
55634b5d2c6SMax Reitz                          "format");
557c98ac35dSStefan Weil         *pdrv = NULL;
558c98ac35dSStefan Weil         return ret;
559ea2384d3Sbellard     }
560ea2384d3Sbellard 
561c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
562c98ac35dSStefan Weil     if (!drv) {
56334b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
56434b5d2c6SMax Reitz                    "driver found");
565c98ac35dSStefan Weil         ret = -ENOENT;
566c98ac35dSStefan Weil     }
567c98ac35dSStefan Weil     *pdrv = drv;
568c98ac35dSStefan Weil     return ret;
569ea2384d3Sbellard }
570ea2384d3Sbellard 
57151762288SStefan Hajnoczi /**
57251762288SStefan Hajnoczi  * Set the current 'total_sectors' value
57365a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
57451762288SStefan Hajnoczi  */
57551762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
57651762288SStefan Hajnoczi {
57751762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
57851762288SStefan Hajnoczi 
579396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
580b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
581396759adSNicholas Bellinger         return 0;
582396759adSNicholas Bellinger 
58351762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
58451762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
58551762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
58651762288SStefan Hajnoczi         if (length < 0) {
58751762288SStefan Hajnoczi             return length;
58851762288SStefan Hajnoczi         }
5897e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
59051762288SStefan Hajnoczi     }
59151762288SStefan Hajnoczi 
59251762288SStefan Hajnoczi     bs->total_sectors = hint;
59351762288SStefan Hajnoczi     return 0;
59451762288SStefan Hajnoczi }
59551762288SStefan Hajnoczi 
596c3993cdcSStefan Hajnoczi /**
597cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
598cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
599cddff5baSKevin Wolf  */
600cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
601cddff5baSKevin Wolf                               QDict *old_options)
602cddff5baSKevin Wolf {
603cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
604cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
605cddff5baSKevin Wolf     } else {
606cddff5baSKevin Wolf         qdict_join(options, old_options, false);
607cddff5baSKevin Wolf     }
608cddff5baSKevin Wolf }
609cddff5baSKevin Wolf 
610cddff5baSKevin Wolf /**
6119e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6129e8f1835SPaolo Bonzini  *
6139e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6149e8f1835SPaolo Bonzini  */
6159e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6169e8f1835SPaolo Bonzini {
6179e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6189e8f1835SPaolo Bonzini 
6199e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6209e8f1835SPaolo Bonzini         /* do nothing */
6219e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6229e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6239e8f1835SPaolo Bonzini     } else {
6249e8f1835SPaolo Bonzini         return -1;
6259e8f1835SPaolo Bonzini     }
6269e8f1835SPaolo Bonzini 
6279e8f1835SPaolo Bonzini     return 0;
6289e8f1835SPaolo Bonzini }
6299e8f1835SPaolo Bonzini 
6309e8f1835SPaolo Bonzini /**
631c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
632c3993cdcSStefan Hajnoczi  *
633c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
634c3993cdcSStefan Hajnoczi  */
63553e8ae01SKevin Wolf int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
636c3993cdcSStefan Hajnoczi {
637c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
638c3993cdcSStefan Hajnoczi 
639c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
64053e8ae01SKevin Wolf         *writethrough = false;
64153e8ae01SKevin Wolf         *flags |= BDRV_O_NOCACHE;
64292196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
64353e8ae01SKevin Wolf         *writethrough = true;
64492196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
645c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
64653e8ae01SKevin Wolf         *writethrough = false;
647c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
64853e8ae01SKevin Wolf         *writethrough = false;
649c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
650c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
65153e8ae01SKevin Wolf         *writethrough = true;
652c3993cdcSStefan Hajnoczi     } else {
653c3993cdcSStefan Hajnoczi         return -1;
654c3993cdcSStefan Hajnoczi     }
655c3993cdcSStefan Hajnoczi 
656c3993cdcSStefan Hajnoczi     return 0;
657c3993cdcSStefan Hajnoczi }
658c3993cdcSStefan Hajnoczi 
65920018e12SKevin Wolf static void bdrv_child_cb_drained_begin(BdrvChild *child)
66020018e12SKevin Wolf {
66120018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
66220018e12SKevin Wolf     bdrv_drained_begin(bs);
66320018e12SKevin Wolf }
66420018e12SKevin Wolf 
66520018e12SKevin Wolf static void bdrv_child_cb_drained_end(BdrvChild *child)
66620018e12SKevin Wolf {
66720018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
66820018e12SKevin Wolf     bdrv_drained_end(bs);
66920018e12SKevin Wolf }
67020018e12SKevin Wolf 
6710b50cc88SKevin Wolf /*
67273176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
67373176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
67473176beeSKevin Wolf  * flags like a backing file)
675b1e6fc08SKevin Wolf  */
67673176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
67773176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
678b1e6fc08SKevin Wolf {
67973176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
68073176beeSKevin Wolf 
68173176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
68273176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
68373176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
68441869044SKevin Wolf 
68541869044SKevin Wolf     /* aio=native doesn't work for cache.direct=off, so disable it for the
68641869044SKevin Wolf      * temporary snapshot */
68741869044SKevin Wolf     *child_flags &= ~BDRV_O_NATIVE_AIO;
688b1e6fc08SKevin Wolf }
689b1e6fc08SKevin Wolf 
690b1e6fc08SKevin Wolf /*
6918e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
6928e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
6930b50cc88SKevin Wolf  */
6948e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
6958e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
6960b50cc88SKevin Wolf {
6978e2160e2SKevin Wolf     int flags = parent_flags;
6988e2160e2SKevin Wolf 
6990b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7000b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7010b50cc88SKevin Wolf 
70291a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
70391a097e7SKevin Wolf      * the parent. */
70491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
70591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
70691a097e7SKevin Wolf 
7070b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
70891a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
70991a097e7SKevin Wolf      * corresponding parent options. */
71091a097e7SKevin Wolf     flags |= BDRV_O_UNMAP;
7110b50cc88SKevin Wolf 
7120b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
713abb06c5aSDaniel P. Berrange     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
714abb06c5aSDaniel P. Berrange                BDRV_O_NO_IO);
7150b50cc88SKevin Wolf 
7168e2160e2SKevin Wolf     *child_flags = flags;
7170b50cc88SKevin Wolf }
7180b50cc88SKevin Wolf 
719f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7208e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
72120018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
72220018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
723f3930ed0SKevin Wolf };
724f3930ed0SKevin Wolf 
725f3930ed0SKevin Wolf /*
7268e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7278e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7288e2160e2SKevin Wolf  * flags for the parent BDS
729f3930ed0SKevin Wolf  */
7308e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7318e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
732f3930ed0SKevin Wolf {
7338e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7348e2160e2SKevin Wolf                                parent_flags, parent_options);
7358e2160e2SKevin Wolf 
736abb06c5aSDaniel P. Berrange     *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
737f3930ed0SKevin Wolf }
738f3930ed0SKevin Wolf 
739f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7408e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
74120018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
74220018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
743f3930ed0SKevin Wolf };
744f3930ed0SKevin Wolf 
745317fc44eSKevin Wolf /*
7468e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7478e2160e2SKevin Wolf  * given options and flags for the parent BDS
748317fc44eSKevin Wolf  */
7498e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7508e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
751317fc44eSKevin Wolf {
7528e2160e2SKevin Wolf     int flags = parent_flags;
7538e2160e2SKevin Wolf 
754b8816a43SKevin Wolf     /* The cache mode is inherited unmodified for backing files; except WCE,
755b8816a43SKevin Wolf      * which is only applied on the top level (BlockBackend) */
75691a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
75791a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
75891a097e7SKevin Wolf 
759317fc44eSKevin Wolf     /* backing files always opened read-only */
760317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
761317fc44eSKevin Wolf 
762317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7638bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
764317fc44eSKevin Wolf 
7658e2160e2SKevin Wolf     *child_flags = flags;
766317fc44eSKevin Wolf }
767317fc44eSKevin Wolf 
768f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7698e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
77020018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
77120018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
772f3930ed0SKevin Wolf };
773f3930ed0SKevin Wolf 
7747b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7757b272452SKevin Wolf {
77661de4c68SKevin Wolf     int open_flags = flags;
7777b272452SKevin Wolf 
7787b272452SKevin Wolf     /*
7797b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7807b272452SKevin Wolf      * image.
7817b272452SKevin Wolf      */
78220cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7837b272452SKevin Wolf 
7847b272452SKevin Wolf     /*
7857b272452SKevin Wolf      * Snapshots should be writable.
7867b272452SKevin Wolf      */
7878bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7887b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7897b272452SKevin Wolf     }
7907b272452SKevin Wolf 
7917b272452SKevin Wolf     return open_flags;
7927b272452SKevin Wolf }
7937b272452SKevin Wolf 
79491a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
79591a097e7SKevin Wolf {
79691a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
79791a097e7SKevin Wolf 
79891a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
79991a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
80091a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
80191a097e7SKevin Wolf     }
80291a097e7SKevin Wolf 
80391a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
80491a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
80591a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
80691a097e7SKevin Wolf     }
80791a097e7SKevin Wolf }
80891a097e7SKevin Wolf 
80991a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
81091a097e7SKevin Wolf {
81191a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
81291a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
81391a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
81491a097e7SKevin Wolf     }
81591a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
81691a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
81791a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
81891a097e7SKevin Wolf     }
81991a097e7SKevin Wolf }
82091a097e7SKevin Wolf 
821636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8226913c0c2SBenoît Canet                                   const char *node_name,
8236913c0c2SBenoît Canet                                   Error **errp)
8246913c0c2SBenoît Canet {
82515489c76SJeff Cody     char *gen_node_name = NULL;
8266913c0c2SBenoît Canet 
82715489c76SJeff Cody     if (!node_name) {
82815489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
82915489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
83015489c76SJeff Cody         /*
83115489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
83215489c76SJeff Cody          * generated (generated names use characters not available to the user)
83315489c76SJeff Cody          */
8349aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
835636ea370SKevin Wolf         return;
8366913c0c2SBenoît Canet     }
8376913c0c2SBenoît Canet 
8380c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8397f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8400c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8410c5e94eeSBenoît Canet                    node_name);
84215489c76SJeff Cody         goto out;
8430c5e94eeSBenoît Canet     }
8440c5e94eeSBenoît Canet 
8456913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8466913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8476913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
84815489c76SJeff Cody         goto out;
8496913c0c2SBenoît Canet     }
8506913c0c2SBenoît Canet 
8516913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8526913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8536913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
85415489c76SJeff Cody out:
85515489c76SJeff Cody     g_free(gen_node_name);
8566913c0c2SBenoît Canet }
8576913c0c2SBenoît Canet 
85818edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
85918edf289SKevin Wolf     .name = "bdrv_common",
86018edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
86118edf289SKevin Wolf     .desc = {
86218edf289SKevin Wolf         {
86318edf289SKevin Wolf             .name = "node-name",
86418edf289SKevin Wolf             .type = QEMU_OPT_STRING,
86518edf289SKevin Wolf             .help = "Node name of the block device node",
86618edf289SKevin Wolf         },
86762392ebbSKevin Wolf         {
86862392ebbSKevin Wolf             .name = "driver",
86962392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
87062392ebbSKevin Wolf             .help = "Block driver to use for the node",
87162392ebbSKevin Wolf         },
87291a097e7SKevin Wolf         {
87391a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
87491a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87591a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
87691a097e7SKevin Wolf         },
87791a097e7SKevin Wolf         {
87891a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
87991a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
88091a097e7SKevin Wolf             .help = "Ignore flush requests",
88191a097e7SKevin Wolf         },
88218edf289SKevin Wolf         { /* end of list */ }
88318edf289SKevin Wolf     },
88418edf289SKevin Wolf };
88518edf289SKevin Wolf 
886b6ce07aaSKevin Wolf /*
88757915332SKevin Wolf  * Common part for opening disk images and files
888b6ad491aSKevin Wolf  *
889b6ad491aSKevin Wolf  * Removes all processed options from *options.
89057915332SKevin Wolf  */
8919a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
89282dc8b41SKevin Wolf                             QDict *options, Error **errp)
89357915332SKevin Wolf {
89457915332SKevin Wolf     int ret, open_flags;
895035fccdfSKevin Wolf     const char *filename;
89662392ebbSKevin Wolf     const char *driver_name = NULL;
8976913c0c2SBenoît Canet     const char *node_name = NULL;
89818edf289SKevin Wolf     QemuOpts *opts;
89962392ebbSKevin Wolf     BlockDriver *drv;
90034b5d2c6SMax Reitz     Error *local_err = NULL;
90157915332SKevin Wolf 
9026405875cSPaolo Bonzini     assert(bs->file == NULL);
903707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
90457915332SKevin Wolf 
90562392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
90662392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
90762392ebbSKevin Wolf     if (local_err) {
90862392ebbSKevin Wolf         error_propagate(errp, local_err);
90962392ebbSKevin Wolf         ret = -EINVAL;
91062392ebbSKevin Wolf         goto fail_opts;
91162392ebbSKevin Wolf     }
91262392ebbSKevin Wolf 
91362392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
91462392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
91562392ebbSKevin Wolf     assert(drv != NULL);
91662392ebbSKevin Wolf 
91745673671SKevin Wolf     if (file != NULL) {
9189a4f4c31SKevin Wolf         filename = file->bs->filename;
91945673671SKevin Wolf     } else {
92045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
92145673671SKevin Wolf     }
92245673671SKevin Wolf 
923765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
924765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
925765003dbSKevin Wolf                    drv->format_name);
92618edf289SKevin Wolf         ret = -EINVAL;
92718edf289SKevin Wolf         goto fail_opts;
92818edf289SKevin Wolf     }
92918edf289SKevin Wolf 
93082dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
93182dc8b41SKevin Wolf                            drv->format_name);
93262392ebbSKevin Wolf 
93318edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
934636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9350fb6395cSMarkus Armbruster     if (local_err) {
936636ea370SKevin Wolf         error_propagate(errp, local_err);
93718edf289SKevin Wolf         ret = -EINVAL;
93818edf289SKevin Wolf         goto fail_opts;
9395d186eb0SKevin Wolf     }
9405d186eb0SKevin Wolf 
94182dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
942b64ec4e4SFam Zheng 
943b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9448f94a6e4SKevin Wolf         error_setg(errp,
9458f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9468f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9478f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9488f94a6e4SKevin Wolf                    drv->format_name);
94918edf289SKevin Wolf         ret = -ENOTSUP;
95018edf289SKevin Wolf         goto fail_opts;
951b64ec4e4SFam Zheng     }
95257915332SKevin Wolf 
95353fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
95482dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9550ebd24e0SKevin Wolf         if (!bs->read_only) {
95653fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9570ebd24e0SKevin Wolf         } else {
9580ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
95918edf289SKevin Wolf             ret = -EINVAL;
96018edf289SKevin Wolf             goto fail_opts;
9610ebd24e0SKevin Wolf         }
96253fec9d3SStefan Hajnoczi     }
96353fec9d3SStefan Hajnoczi 
964c2ad1b0cSKevin Wolf     if (filename != NULL) {
96557915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
966c2ad1b0cSKevin Wolf     } else {
967c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
968c2ad1b0cSKevin Wolf     }
96991af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97057915332SKevin Wolf 
97157915332SKevin Wolf     bs->drv = drv;
9727267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
97357915332SKevin Wolf 
97491a097e7SKevin Wolf     /* Apply cache mode options */
97591a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
97673ac451fSKevin Wolf 
97766f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
97882dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
97966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9805d186eb0SKevin Wolf         assert(file == NULL);
981030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
98234b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
983f500a6d3SKevin Wolf     } else {
9842af5ef70SKevin Wolf         if (file == NULL) {
98534b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
98634b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9872af5ef70SKevin Wolf             ret = -EINVAL;
9882af5ef70SKevin Wolf             goto free_and_fail;
9892af5ef70SKevin Wolf         }
990f500a6d3SKevin Wolf         bs->file = file;
99134b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
99266f82ceeSKevin Wolf     }
99366f82ceeSKevin Wolf 
99457915332SKevin Wolf     if (ret < 0) {
99584d18f06SMarkus Armbruster         if (local_err) {
99634b5d2c6SMax Reitz             error_propagate(errp, local_err);
9972fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9982fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
99934b5d2c6SMax Reitz         } else {
100034b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
100134b5d2c6SMax Reitz         }
100257915332SKevin Wolf         goto free_and_fail;
100357915332SKevin Wolf     }
100457915332SKevin Wolf 
100551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
100651762288SStefan Hajnoczi     if (ret < 0) {
100734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
100851762288SStefan Hajnoczi         goto free_and_fail;
100957915332SKevin Wolf     }
101051762288SStefan Hajnoczi 
10113baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10123baca891SKevin Wolf     if (local_err) {
10133baca891SKevin Wolf         error_propagate(errp, local_err);
10143baca891SKevin Wolf         ret = -EINVAL;
10153baca891SKevin Wolf         goto free_and_fail;
10163baca891SKevin Wolf     }
10173baca891SKevin Wolf 
1018c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10194196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1020a5b8dd2cSEric Blake     assert(is_power_of_2(bs->bl.request_alignment));
102118edf289SKevin Wolf 
102218edf289SKevin Wolf     qemu_opts_del(opts);
102357915332SKevin Wolf     return 0;
102457915332SKevin Wolf 
102557915332SKevin Wolf free_and_fail:
102666f82ceeSKevin Wolf     bs->file = NULL;
10277267c094SAnthony Liguori     g_free(bs->opaque);
102857915332SKevin Wolf     bs->opaque = NULL;
102957915332SKevin Wolf     bs->drv = NULL;
103018edf289SKevin Wolf fail_opts:
103118edf289SKevin Wolf     qemu_opts_del(opts);
103257915332SKevin Wolf     return ret;
103357915332SKevin Wolf }
103457915332SKevin Wolf 
10355e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10365e5c4f63SKevin Wolf {
10375e5c4f63SKevin Wolf     QObject *options_obj;
10385e5c4f63SKevin Wolf     QDict *options;
10395e5c4f63SKevin Wolf     int ret;
10405e5c4f63SKevin Wolf 
10415e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10425e5c4f63SKevin Wolf     assert(ret);
10435e5c4f63SKevin Wolf 
10445e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10455e5c4f63SKevin Wolf     if (!options_obj) {
10465e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10475e5c4f63SKevin Wolf         return NULL;
10485e5c4f63SKevin Wolf     }
10495e5c4f63SKevin Wolf 
10505e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10515e5c4f63SKevin Wolf         qobject_decref(options_obj);
10525e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10535e5c4f63SKevin Wolf         return NULL;
10545e5c4f63SKevin Wolf     }
10555e5c4f63SKevin Wolf 
10565e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10575e5c4f63SKevin Wolf     qdict_flatten(options);
10585e5c4f63SKevin Wolf 
10595e5c4f63SKevin Wolf     return options;
10605e5c4f63SKevin Wolf }
10615e5c4f63SKevin Wolf 
1062de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1063de3b53f0SKevin Wolf                                 Error **errp)
1064de3b53f0SKevin Wolf {
1065de3b53f0SKevin Wolf     QDict *json_options;
1066de3b53f0SKevin Wolf     Error *local_err = NULL;
1067de3b53f0SKevin Wolf 
1068de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1069de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1070de3b53f0SKevin Wolf         return;
1071de3b53f0SKevin Wolf     }
1072de3b53f0SKevin Wolf 
1073de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1074de3b53f0SKevin Wolf     if (local_err) {
1075de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1076de3b53f0SKevin Wolf         return;
1077de3b53f0SKevin Wolf     }
1078de3b53f0SKevin Wolf 
1079de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1080de3b53f0SKevin Wolf      * specified directly */
1081de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1082de3b53f0SKevin Wolf     QDECREF(json_options);
1083de3b53f0SKevin Wolf     *pfilename = NULL;
1084de3b53f0SKevin Wolf }
1085de3b53f0SKevin Wolf 
108657915332SKevin Wolf /*
1087f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1088f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
108953a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
109053a29513SMax Reitz  * block driver has been specified explicitly.
1091f54120ffSKevin Wolf  */
1092de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1093053e1578SMax Reitz                              int *flags, Error **errp)
1094f54120ffSKevin Wolf {
1095f54120ffSKevin Wolf     const char *drvname;
109653a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1097f54120ffSKevin Wolf     bool parse_filename = false;
1098053e1578SMax Reitz     BlockDriver *drv = NULL;
1099f54120ffSKevin Wolf     Error *local_err = NULL;
1100f54120ffSKevin Wolf 
110153a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1102053e1578SMax Reitz     if (drvname) {
1103053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1104053e1578SMax Reitz         if (!drv) {
1105053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1106053e1578SMax Reitz             return -ENOENT;
1107053e1578SMax Reitz         }
110853a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
110953a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1110053e1578SMax Reitz         protocol = drv->bdrv_file_open;
111153a29513SMax Reitz     }
111253a29513SMax Reitz 
111353a29513SMax Reitz     if (protocol) {
111453a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
111553a29513SMax Reitz     } else {
111653a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
111753a29513SMax Reitz     }
111853a29513SMax Reitz 
111991a097e7SKevin Wolf     /* Translate cache options from flags into options */
112091a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
112191a097e7SKevin Wolf 
1122f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
112317b005f1SKevin Wolf     if (protocol && filename) {
1124f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1125f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1126f54120ffSKevin Wolf             parse_filename = true;
1127f54120ffSKevin Wolf         } else {
1128f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1129f54120ffSKevin Wolf                              "the same time");
1130f54120ffSKevin Wolf             return -EINVAL;
1131f54120ffSKevin Wolf         }
1132f54120ffSKevin Wolf     }
1133f54120ffSKevin Wolf 
1134f54120ffSKevin Wolf     /* Find the right block driver */
1135f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1136f54120ffSKevin Wolf 
113717b005f1SKevin Wolf     if (!drvname && protocol) {
1138f54120ffSKevin Wolf         if (filename) {
1139b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1140f54120ffSKevin Wolf             if (!drv) {
1141f54120ffSKevin Wolf                 return -EINVAL;
1142f54120ffSKevin Wolf             }
1143f54120ffSKevin Wolf 
1144f54120ffSKevin Wolf             drvname = drv->format_name;
1145f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1146f54120ffSKevin Wolf         } else {
1147f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1148f54120ffSKevin Wolf             return -EINVAL;
1149f54120ffSKevin Wolf         }
115017b005f1SKevin Wolf     }
115117b005f1SKevin Wolf 
115217b005f1SKevin Wolf     assert(drv || !protocol);
1153f54120ffSKevin Wolf 
1154f54120ffSKevin Wolf     /* Driver-specific filename parsing */
115517b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1156f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1157f54120ffSKevin Wolf         if (local_err) {
1158f54120ffSKevin Wolf             error_propagate(errp, local_err);
1159f54120ffSKevin Wolf             return -EINVAL;
1160f54120ffSKevin Wolf         }
1161f54120ffSKevin Wolf 
1162f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1163f54120ffSKevin Wolf             qdict_del(*options, "filename");
1164f54120ffSKevin Wolf         }
1165f54120ffSKevin Wolf     }
1166f54120ffSKevin Wolf 
1167f54120ffSKevin Wolf     return 0;
1168f54120ffSKevin Wolf }
1169f54120ffSKevin Wolf 
1170e9740bc6SKevin Wolf static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
1171e9740bc6SKevin Wolf {
1172e9740bc6SKevin Wolf     BlockDriverState *old_bs = child->bs;
1173e9740bc6SKevin Wolf 
1174e9740bc6SKevin Wolf     if (old_bs) {
117536fe1331SKevin Wolf         if (old_bs->quiesce_counter && child->role->drained_end) {
117636fe1331SKevin Wolf             child->role->drained_end(child);
1177e9740bc6SKevin Wolf         }
117836fe1331SKevin Wolf         QLIST_REMOVE(child, next_parent);
1179e9740bc6SKevin Wolf     }
1180e9740bc6SKevin Wolf 
1181e9740bc6SKevin Wolf     child->bs = new_bs;
118236fe1331SKevin Wolf 
118336fe1331SKevin Wolf     if (new_bs) {
118436fe1331SKevin Wolf         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
118536fe1331SKevin Wolf         if (new_bs->quiesce_counter && child->role->drained_begin) {
118636fe1331SKevin Wolf             child->role->drained_begin(child);
118736fe1331SKevin Wolf         }
118836fe1331SKevin Wolf     }
1189e9740bc6SKevin Wolf }
1190e9740bc6SKevin Wolf 
1191f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1192260fecf1SKevin Wolf                                   const char *child_name,
119336fe1331SKevin Wolf                                   const BdrvChildRole *child_role,
119436fe1331SKevin Wolf                                   void *opaque)
1195df581792SKevin Wolf {
1196df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1197df581792SKevin Wolf     *child = (BdrvChild) {
1198e9740bc6SKevin Wolf         .bs     = NULL,
1199260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1200df581792SKevin Wolf         .role   = child_role,
120136fe1331SKevin Wolf         .opaque = opaque,
1202df581792SKevin Wolf     };
1203df581792SKevin Wolf 
1204e9740bc6SKevin Wolf     bdrv_replace_child(child, child_bs);
1205b4b059f6SKevin Wolf 
1206b4b059f6SKevin Wolf     return child;
1207df581792SKevin Wolf }
1208df581792SKevin Wolf 
120998292c61SWen Congyang BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1210f21d96d0SKevin Wolf                              BlockDriverState *child_bs,
1211f21d96d0SKevin Wolf                              const char *child_name,
1212f21d96d0SKevin Wolf                              const BdrvChildRole *child_role)
1213f21d96d0SKevin Wolf {
121436fe1331SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role,
121520018e12SKevin Wolf                                               parent_bs);
1216f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1217f21d96d0SKevin Wolf     return child;
1218f21d96d0SKevin Wolf }
1219f21d96d0SKevin Wolf 
12203f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
122133a60407SKevin Wolf {
1222f21d96d0SKevin Wolf     if (child->next.le_prev) {
122333a60407SKevin Wolf         QLIST_REMOVE(child, next);
1224f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1225f21d96d0SKevin Wolf     }
1226e9740bc6SKevin Wolf 
1227e9740bc6SKevin Wolf     bdrv_replace_child(child, NULL);
1228e9740bc6SKevin Wolf 
1229260fecf1SKevin Wolf     g_free(child->name);
123033a60407SKevin Wolf     g_free(child);
123133a60407SKevin Wolf }
123233a60407SKevin Wolf 
1233f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
123433a60407SKevin Wolf {
1235779020cbSKevin Wolf     BlockDriverState *child_bs;
1236779020cbSKevin Wolf 
1237f21d96d0SKevin Wolf     child_bs = child->bs;
1238f21d96d0SKevin Wolf     bdrv_detach_child(child);
1239f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1240f21d96d0SKevin Wolf }
1241f21d96d0SKevin Wolf 
1242f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1243f21d96d0SKevin Wolf {
1244779020cbSKevin Wolf     if (child == NULL) {
1245779020cbSKevin Wolf         return;
1246779020cbSKevin Wolf     }
124733a60407SKevin Wolf 
124833a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
124933a60407SKevin Wolf         child->bs->inherits_from = NULL;
125033a60407SKevin Wolf     }
125133a60407SKevin Wolf 
1252f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
125333a60407SKevin Wolf }
125433a60407SKevin Wolf 
12555c8cab48SKevin Wolf 
12565c8cab48SKevin Wolf static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
12575c8cab48SKevin Wolf {
12585c8cab48SKevin Wolf     BdrvChild *c;
12595c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
12605c8cab48SKevin Wolf         if (c->role->change_media) {
12615c8cab48SKevin Wolf             c->role->change_media(c, load);
12625c8cab48SKevin Wolf         }
12635c8cab48SKevin Wolf     }
12645c8cab48SKevin Wolf }
12655c8cab48SKevin Wolf 
12665c8cab48SKevin Wolf static void bdrv_parent_cb_resize(BlockDriverState *bs)
12675c8cab48SKevin Wolf {
12685c8cab48SKevin Wolf     BdrvChild *c;
12695c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
12705c8cab48SKevin Wolf         if (c->role->resize) {
12715c8cab48SKevin Wolf             c->role->resize(c);
12725c8cab48SKevin Wolf         }
12735c8cab48SKevin Wolf     }
12745c8cab48SKevin Wolf }
12755c8cab48SKevin Wolf 
12765db15a57SKevin Wolf /*
12775db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12785db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12795db15a57SKevin Wolf  */
12808d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12818d24cce1SFam Zheng {
12825db15a57SKevin Wolf     if (backing_hd) {
12835db15a57SKevin Wolf         bdrv_ref(backing_hd);
12845db15a57SKevin Wolf     }
12858d24cce1SFam Zheng 
1286760e0063SKevin Wolf     if (bs->backing) {
1287826b6ca0SFam Zheng         assert(bs->backing_blocker);
1288760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12895db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1290826b6ca0SFam Zheng     } else if (backing_hd) {
1291826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
129281e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
129381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1294826b6ca0SFam Zheng     }
1295826b6ca0SFam Zheng 
12968d24cce1SFam Zheng     if (!backing_hd) {
1297826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1298826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1299760e0063SKevin Wolf         bs->backing = NULL;
13008d24cce1SFam Zheng         goto out;
13018d24cce1SFam Zheng     }
1302260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
13038d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
13048d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
13058d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
13068d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1307826b6ca0SFam Zheng 
1308760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1309826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1310760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1311826b6ca0SFam Zheng                     bs->backing_blocker);
13128d24cce1SFam Zheng out:
13133baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
13148d24cce1SFam Zheng }
13158d24cce1SFam Zheng 
131631ca6d07SKevin Wolf /*
131731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
131831ca6d07SKevin Wolf  *
1319d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1320d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1321d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1322d9b7b057SKevin Wolf  * BlockdevRef.
1323d9b7b057SKevin Wolf  *
1324d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
132531ca6d07SKevin Wolf  */
1326d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1327d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
13289156df12SPaolo Bonzini {
13291ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1330d9b7b057SKevin Wolf     char *bdref_key_dot;
1331d9b7b057SKevin Wolf     const char *reference = NULL;
1332317fc44eSKevin Wolf     int ret = 0;
13338d24cce1SFam Zheng     BlockDriverState *backing_hd;
1334d9b7b057SKevin Wolf     QDict *options;
1335d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
133634b5d2c6SMax Reitz     Error *local_err = NULL;
13379156df12SPaolo Bonzini 
1338760e0063SKevin Wolf     if (bs->backing != NULL) {
13391ba4b6a5SBenoît Canet         goto free_exit;
13409156df12SPaolo Bonzini     }
13419156df12SPaolo Bonzini 
134231ca6d07SKevin Wolf     /* NULL means an empty set of options */
1343d9b7b057SKevin Wolf     if (parent_options == NULL) {
1344d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1345d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
134631ca6d07SKevin Wolf     }
134731ca6d07SKevin Wolf 
13489156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1349d9b7b057SKevin Wolf 
1350d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1351d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1352d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1353d9b7b057SKevin Wolf 
1354d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1355d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13561cb6f506SKevin Wolf         backing_filename[0] = '\0';
13571cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
135831ca6d07SKevin Wolf         QDECREF(options);
13591ba4b6a5SBenoît Canet         goto free_exit;
1360dbecebddSFam Zheng     } else {
13619f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13629f07429eSMax Reitz                                        &local_err);
13639f07429eSMax Reitz         if (local_err) {
13649f07429eSMax Reitz             ret = -EINVAL;
13659f07429eSMax Reitz             error_propagate(errp, local_err);
13669f07429eSMax Reitz             QDECREF(options);
13679f07429eSMax Reitz             goto free_exit;
13689f07429eSMax Reitz         }
13699156df12SPaolo Bonzini     }
13709156df12SPaolo Bonzini 
13718ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13728ee79e70SKevin Wolf         ret = -EINVAL;
13738ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13748ee79e70SKevin Wolf         QDECREF(options);
13758ee79e70SKevin Wolf         goto free_exit;
13768ee79e70SKevin Wolf     }
13778ee79e70SKevin Wolf 
1378c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1379c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13809156df12SPaolo Bonzini     }
13819156df12SPaolo Bonzini 
13825b363937SMax Reitz     backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
1383d9b7b057SKevin Wolf                                    reference, options, 0, bs, &child_backing,
1384e43bfd9cSMarkus Armbruster                                    errp);
13855b363937SMax Reitz     if (!backing_hd) {
13869156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1387e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13885b363937SMax Reitz         ret = -EINVAL;
13891ba4b6a5SBenoît Canet         goto free_exit;
13909156df12SPaolo Bonzini     }
1391df581792SKevin Wolf 
13925db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13935db15a57SKevin Wolf      * backing_hd reference now */
13948d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13955db15a57SKevin Wolf     bdrv_unref(backing_hd);
1396d80ac658SPeter Feiner 
1397d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1398d9b7b057SKevin Wolf 
13991ba4b6a5SBenoît Canet free_exit:
14001ba4b6a5SBenoît Canet     g_free(backing_filename);
1401d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
14021ba4b6a5SBenoît Canet     return ret;
14039156df12SPaolo Bonzini }
14049156df12SPaolo Bonzini 
1405b6ce07aaSKevin Wolf /*
1406da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1407da557aacSMax Reitz  * device's options.
1408da557aacSMax Reitz  *
1409da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1410b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1411da557aacSMax Reitz  *
1412da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1413da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1414da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1415da557aacSMax Reitz  * BlockdevRef.
1416da557aacSMax Reitz  *
1417da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1418da557aacSMax Reitz  */
1419b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1420f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1421b4b059f6SKevin Wolf                            BlockDriverState* parent,
1422b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1423f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1424da557aacSMax Reitz {
1425b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1426b4b059f6SKevin Wolf     BlockDriverState *bs;
1427da557aacSMax Reitz     QDict *image_options;
1428da557aacSMax Reitz     char *bdref_key_dot;
1429da557aacSMax Reitz     const char *reference;
1430da557aacSMax Reitz 
1431df581792SKevin Wolf     assert(child_role != NULL);
1432f67503e5SMax Reitz 
1433da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1434da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1435da557aacSMax Reitz     g_free(bdref_key_dot);
1436da557aacSMax Reitz 
1437da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1438da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1439b4b059f6SKevin Wolf         if (!allow_none) {
1440da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1441da557aacSMax Reitz                        bdref_key);
1442da557aacSMax Reitz         }
1443b20e61e0SMarkus Armbruster         QDECREF(image_options);
1444da557aacSMax Reitz         goto done;
1445da557aacSMax Reitz     }
1446da557aacSMax Reitz 
14475b363937SMax Reitz     bs = bdrv_open_inherit(filename, reference, image_options, 0,
1448ce343771SMax Reitz                            parent, child_role, errp);
14495b363937SMax Reitz     if (!bs) {
1450df581792SKevin Wolf         goto done;
1451df581792SKevin Wolf     }
1452df581792SKevin Wolf 
1453260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1454da557aacSMax Reitz 
1455da557aacSMax Reitz done:
1456da557aacSMax Reitz     qdict_del(options, bdref_key);
1457b4b059f6SKevin Wolf     return c;
1458b4b059f6SKevin Wolf }
1459b4b059f6SKevin Wolf 
146066836189SMax Reitz static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
146166836189SMax Reitz                                                    int flags,
146266836189SMax Reitz                                                    QDict *snapshot_options,
146366836189SMax Reitz                                                    Error **errp)
1464b998875dSKevin Wolf {
1465b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14661ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1467b998875dSKevin Wolf     int64_t total_size;
146883d0521aSChunyan Liu     QemuOpts *opts = NULL;
1469b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1470b998875dSKevin Wolf     int ret;
1471b998875dSKevin Wolf 
1472b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1473b998875dSKevin Wolf        instead of opening 'filename' directly */
1474b998875dSKevin Wolf 
1475b998875dSKevin Wolf     /* Get the required size from the image */
1476f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1477f187743aSKevin Wolf     if (total_size < 0) {
1478f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14791ba4b6a5SBenoît Canet         goto out;
1480f187743aSKevin Wolf     }
1481b998875dSKevin Wolf 
1482b998875dSKevin Wolf     /* Create the temporary image */
14831ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1484b998875dSKevin Wolf     if (ret < 0) {
1485b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14861ba4b6a5SBenoît Canet         goto out;
1487b998875dSKevin Wolf     }
1488b998875dSKevin Wolf 
1489ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1490c282e1fdSChunyan Liu                             &error_abort);
149139101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1492e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
149383d0521aSChunyan Liu     qemu_opts_del(opts);
1494b998875dSKevin Wolf     if (ret < 0) {
1495e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1496e43bfd9cSMarkus Armbruster                       tmp_filename);
14971ba4b6a5SBenoît Canet         goto out;
1498b998875dSKevin Wolf     }
1499b998875dSKevin Wolf 
150073176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1501b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1502b998875dSKevin Wolf               qstring_from_str("file"));
1503b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1504b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1505e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1506e6641719SMax Reitz               qstring_from_str("qcow2"));
1507b998875dSKevin Wolf 
15085b363937SMax Reitz     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
150973176beeSKevin Wolf     snapshot_options = NULL;
15105b363937SMax Reitz     if (!bs_snapshot) {
15115b363937SMax Reitz         ret = -EINVAL;
15121ba4b6a5SBenoît Canet         goto out;
1513b998875dSKevin Wolf     }
1514b998875dSKevin Wolf 
151566836189SMax Reitz     /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
151666836189SMax Reitz      * call bdrv_unref() on it), so in order to be able to return one, we have
151766836189SMax Reitz      * to increase bs_snapshot's refcount here */
151866836189SMax Reitz     bdrv_ref(bs_snapshot);
1519b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
15201ba4b6a5SBenoît Canet 
152166836189SMax Reitz     g_free(tmp_filename);
152266836189SMax Reitz     return bs_snapshot;
152366836189SMax Reitz 
15241ba4b6a5SBenoît Canet out:
152573176beeSKevin Wolf     QDECREF(snapshot_options);
15261ba4b6a5SBenoît Canet     g_free(tmp_filename);
152766836189SMax Reitz     return NULL;
1528b998875dSKevin Wolf }
1529b998875dSKevin Wolf 
1530da557aacSMax Reitz /*
1531b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1532de9c0cecSKevin Wolf  *
1533de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1534de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1535de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1536de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1537f67503e5SMax Reitz  *
1538f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1539f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1540ddf5636dSMax Reitz  *
1541ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1542ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1543ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1544b6ce07aaSKevin Wolf  */
15455b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
15465b363937SMax Reitz                                            const char *reference,
15475b363937SMax Reitz                                            QDict *options, int flags,
1548f3930ed0SKevin Wolf                                            BlockDriverState *parent,
15495b363937SMax Reitz                                            const BdrvChildRole *child_role,
15505b363937SMax Reitz                                            Error **errp)
1551ea2384d3Sbellard {
1552b6ce07aaSKevin Wolf     int ret;
15539a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15549a4f4c31SKevin Wolf     BlockDriverState *bs;
1555ce343771SMax Reitz     BlockDriver *drv = NULL;
155674fe54f2SKevin Wolf     const char *drvname;
15573e8c2e57SAlberto Garcia     const char *backing;
155834b5d2c6SMax Reitz     Error *local_err = NULL;
155973176beeSKevin Wolf     QDict *snapshot_options = NULL;
1560b1e6fc08SKevin Wolf     int snapshot_flags = 0;
156133e3963eSbellard 
1562f3930ed0SKevin Wolf     assert(!child_role || !flags);
1563f3930ed0SKevin Wolf     assert(!child_role == !parent);
1564f67503e5SMax Reitz 
1565ddf5636dSMax Reitz     if (reference) {
1566ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1567ddf5636dSMax Reitz         QDECREF(options);
1568ddf5636dSMax Reitz 
1569ddf5636dSMax Reitz         if (filename || options_non_empty) {
1570ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1571ddf5636dSMax Reitz                        "additional options or a new filename");
15725b363937SMax Reitz             return NULL;
1573ddf5636dSMax Reitz         }
1574ddf5636dSMax Reitz 
1575ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1576ddf5636dSMax Reitz         if (!bs) {
15775b363937SMax Reitz             return NULL;
1578ddf5636dSMax Reitz         }
157976b22320SKevin Wolf 
1580ddf5636dSMax Reitz         bdrv_ref(bs);
15815b363937SMax Reitz         return bs;
1582ddf5636dSMax Reitz     }
1583ddf5636dSMax Reitz 
1584e4e9986bSMarkus Armbruster     bs = bdrv_new();
1585f67503e5SMax Reitz 
1586de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1587de9c0cecSKevin Wolf     if (options == NULL) {
1588de9c0cecSKevin Wolf         options = qdict_new();
1589de9c0cecSKevin Wolf     }
1590de9c0cecSKevin Wolf 
1591145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1592de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1593de3b53f0SKevin Wolf     if (local_err) {
1594de3b53f0SKevin Wolf         goto fail;
1595de3b53f0SKevin Wolf     }
1596de3b53f0SKevin Wolf 
1597145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1598145f598eSKevin Wolf 
1599f3930ed0SKevin Wolf     if (child_role) {
1600bddcec37SKevin Wolf         bs->inherits_from = parent;
16018e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
16028e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1603f3930ed0SKevin Wolf     }
1604f3930ed0SKevin Wolf 
1605de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1606462f5bcfSKevin Wolf     if (local_err) {
1607462f5bcfSKevin Wolf         goto fail;
1608462f5bcfSKevin Wolf     }
1609462f5bcfSKevin Wolf 
161062392ebbSKevin Wolf     bs->open_flags = flags;
161162392ebbSKevin Wolf     bs->options = options;
161262392ebbSKevin Wolf     options = qdict_clone_shallow(options);
161362392ebbSKevin Wolf 
161476c591b0SKevin Wolf     /* Find the right image format driver */
161576c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
161676c591b0SKevin Wolf     if (drvname) {
161776c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
161876c591b0SKevin Wolf         if (!drv) {
161976c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
162076c591b0SKevin Wolf             goto fail;
162176c591b0SKevin Wolf         }
162276c591b0SKevin Wolf     }
162376c591b0SKevin Wolf 
162476c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
162576c591b0SKevin Wolf 
16263e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
16273e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16283e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16293e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16303e8c2e57SAlberto Garcia     }
16313e8c2e57SAlberto Garcia 
1632f500a6d3SKevin Wolf     /* Open image file without format layer */
1633f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1634be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1635be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1636be028adcSJeff Cody         }
1637b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
163873176beeSKevin Wolf             snapshot_options = qdict_new();
163973176beeSKevin Wolf             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
164073176beeSKevin Wolf                                        flags, options);
16418e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1642b1e6fc08SKevin Wolf         }
1643be028adcSJeff Cody 
1644f3930ed0SKevin Wolf         bs->open_flags = flags;
16451fdd6933SKevin Wolf 
16469a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16471fdd6933SKevin Wolf                                &child_file, true, &local_err);
16481fdd6933SKevin Wolf         if (local_err) {
16498bfea15dSKevin Wolf             goto fail;
1650f500a6d3SKevin Wolf         }
1651f4788adcSKevin Wolf     }
1652f500a6d3SKevin Wolf 
165376c591b0SKevin Wolf     /* Image format probing */
165438f3ef57SKevin Wolf     bs->probed = !drv;
165576c591b0SKevin Wolf     if (!drv && file) {
1656*cf2ab8fcSKevin Wolf         ret = find_image_format(file, filename, &drv, &local_err);
165717b005f1SKevin Wolf         if (ret < 0) {
165817b005f1SKevin Wolf             goto fail;
165917b005f1SKevin Wolf         }
166062392ebbSKevin Wolf         /*
166162392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
166262392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
166362392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
166462392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
166562392ebbSKevin Wolf          *
166662392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
166762392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
166862392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
166962392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
167062392ebbSKevin Wolf          */
167162392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
167262392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
167376c591b0SKevin Wolf     } else if (!drv) {
16742a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16758bfea15dSKevin Wolf         goto fail;
16762a05cbe4SMax Reitz     }
1677f500a6d3SKevin Wolf 
167853a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
167953a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
168053a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
168153a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
168253a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
168353a29513SMax Reitz 
1684b6ce07aaSKevin Wolf     /* Open the image */
168582dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1686b6ce07aaSKevin Wolf     if (ret < 0) {
16878bfea15dSKevin Wolf         goto fail;
16886987307cSChristoph Hellwig     }
16896987307cSChristoph Hellwig 
16902a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16919a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1692f500a6d3SKevin Wolf         file = NULL;
1693f500a6d3SKevin Wolf     }
1694f500a6d3SKevin Wolf 
1695b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16969156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1697d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1698b6ce07aaSKevin Wolf         if (ret < 0) {
1699b6ad491aSKevin Wolf             goto close_and_fail;
1700b6ce07aaSKevin Wolf         }
1701b6ce07aaSKevin Wolf     }
1702b6ce07aaSKevin Wolf 
170391af7014SMax Reitz     bdrv_refresh_filename(bs);
170491af7014SMax Reitz 
1705b6ad491aSKevin Wolf     /* Check if any unknown options were used */
17065acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1707b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
17085acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
17095acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
17105acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
17115acd9d81SMax Reitz         } else {
1712d0e46a55SMax Reitz             error_setg(errp,
1713d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1714d0e46a55SMax Reitz                        drv->format_name, entry->key);
17155acd9d81SMax Reitz         }
1716b6ad491aSKevin Wolf 
1717b6ad491aSKevin Wolf         goto close_and_fail;
1718b6ad491aSKevin Wolf     }
1719b6ad491aSKevin Wolf 
1720b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
17215c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
1722c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1723c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1724c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1725c3adb58fSMarkus Armbruster         error_setg(errp,
1726c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1727c3adb58fSMarkus Armbruster         goto close_and_fail;
1728b6ce07aaSKevin Wolf     }
1729b6ce07aaSKevin Wolf 
1730c3adb58fSMarkus Armbruster     QDECREF(options);
1731dd62f1caSKevin Wolf 
1732dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1733dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1734dd62f1caSKevin Wolf     if (snapshot_flags) {
173566836189SMax Reitz         BlockDriverState *snapshot_bs;
173666836189SMax Reitz         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
173766836189SMax Reitz                                                 snapshot_options, &local_err);
173873176beeSKevin Wolf         snapshot_options = NULL;
1739dd62f1caSKevin Wolf         if (local_err) {
1740dd62f1caSKevin Wolf             goto close_and_fail;
1741dd62f1caSKevin Wolf         }
174266836189SMax Reitz         /* We are not going to return bs but the overlay on top of it
174366836189SMax Reitz          * (snapshot_bs); thus, we have to drop the strong reference to bs
17445b363937SMax Reitz          * (which we obtained by calling bdrv_new()). bs will not be deleted,
17455b363937SMax Reitz          * though, because the overlay still has a reference to it. */
174666836189SMax Reitz         bdrv_unref(bs);
174766836189SMax Reitz         bs = snapshot_bs;
174866836189SMax Reitz     }
174966836189SMax Reitz 
17505b363937SMax Reitz     return bs;
1751b6ce07aaSKevin Wolf 
17528bfea15dSKevin Wolf fail:
1753f500a6d3SKevin Wolf     if (file != NULL) {
17549a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1755f500a6d3SKevin Wolf     }
175673176beeSKevin Wolf     QDECREF(snapshot_options);
1757145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1758de9c0cecSKevin Wolf     QDECREF(bs->options);
1759b6ad491aSKevin Wolf     QDECREF(options);
1760de9c0cecSKevin Wolf     bs->options = NULL;
1761f67503e5SMax Reitz     bdrv_unref(bs);
176234b5d2c6SMax Reitz     error_propagate(errp, local_err);
17635b363937SMax Reitz     return NULL;
1764de9c0cecSKevin Wolf 
1765b6ad491aSKevin Wolf close_and_fail:
1766f67503e5SMax Reitz     bdrv_unref(bs);
176773176beeSKevin Wolf     QDECREF(snapshot_options);
1768b6ad491aSKevin Wolf     QDECREF(options);
176934b5d2c6SMax Reitz     error_propagate(errp, local_err);
17705b363937SMax Reitz     return NULL;
1771b6ce07aaSKevin Wolf }
1772b6ce07aaSKevin Wolf 
17735b363937SMax Reitz BlockDriverState *bdrv_open(const char *filename, const char *reference,
17745b363937SMax Reitz                             QDict *options, int flags, Error **errp)
1775f3930ed0SKevin Wolf {
17765b363937SMax Reitz     return bdrv_open_inherit(filename, reference, options, flags, NULL,
1777ce343771SMax Reitz                              NULL, errp);
1778f3930ed0SKevin Wolf }
1779f3930ed0SKevin Wolf 
1780e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1781e971aa12SJeff Cody      bool prepared;
1782e971aa12SJeff Cody      BDRVReopenState state;
1783e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1784e971aa12SJeff Cody } BlockReopenQueueEntry;
1785e971aa12SJeff Cody 
1786e971aa12SJeff Cody /*
1787e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1788e971aa12SJeff Cody  * reopen of multiple devices.
1789e971aa12SJeff Cody  *
1790e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1791e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1792e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1793e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1794e971aa12SJeff Cody  * atomic 'set'.
1795e971aa12SJeff Cody  *
1796e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1797e971aa12SJeff Cody  *
17984d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17994d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
18004d2cb092SKevin Wolf  *
1801e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1802e971aa12SJeff Cody  *
1803e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1804e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1805e971aa12SJeff Cody  *
1806e971aa12SJeff Cody  */
180728518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
18084d2cb092SKevin Wolf                                                  BlockDriverState *bs,
180928518102SKevin Wolf                                                  QDict *options,
181028518102SKevin Wolf                                                  int flags,
181128518102SKevin Wolf                                                  const BdrvChildRole *role,
181228518102SKevin Wolf                                                  QDict *parent_options,
181328518102SKevin Wolf                                                  int parent_flags)
1814e971aa12SJeff Cody {
1815e971aa12SJeff Cody     assert(bs != NULL);
1816e971aa12SJeff Cody 
1817e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
181867251a31SKevin Wolf     BdrvChild *child;
1819145f598eSKevin Wolf     QDict *old_options, *explicit_options;
182067251a31SKevin Wolf 
1821e971aa12SJeff Cody     if (bs_queue == NULL) {
1822e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1823e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1824e971aa12SJeff Cody     }
1825e971aa12SJeff Cody 
18264d2cb092SKevin Wolf     if (!options) {
18274d2cb092SKevin Wolf         options = qdict_new();
18284d2cb092SKevin Wolf     }
18294d2cb092SKevin Wolf 
183028518102SKevin Wolf     /*
183128518102SKevin Wolf      * Precedence of options:
183228518102SKevin Wolf      * 1. Explicitly passed in options (highest)
183391a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1834145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18358e2160e2SKevin Wolf      * 4. Inherited from parent node
183628518102SKevin Wolf      * 5. Retained from effective options of bs
183728518102SKevin Wolf      */
183828518102SKevin Wolf 
183991a097e7SKevin Wolf     if (!parent_options) {
184091a097e7SKevin Wolf         /*
184191a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
184291a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
184391a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
184491a097e7SKevin Wolf          * not considered.
184591a097e7SKevin Wolf          */
184691a097e7SKevin Wolf         update_options_from_flags(options, flags);
184791a097e7SKevin Wolf     }
184891a097e7SKevin Wolf 
1849145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1850145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1851145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1852145f598eSKevin Wolf     QDECREF(old_options);
1853145f598eSKevin Wolf 
1854145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1855145f598eSKevin Wolf 
185628518102SKevin Wolf     /* Inherit from parent node */
185728518102SKevin Wolf     if (parent_options) {
185828518102SKevin Wolf         assert(!flags);
18598e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
186028518102SKevin Wolf     }
186128518102SKevin Wolf 
186228518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18634d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1864cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18654d2cb092SKevin Wolf     QDECREF(old_options);
18664d2cb092SKevin Wolf 
1867f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1868f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1869f1f25a2eSKevin Wolf 
187067251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18714c9dfe5dSKevin Wolf         QDict *new_child_options;
18724c9dfe5dSKevin Wolf         char *child_key_dot;
187367251a31SKevin Wolf 
18744c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18754c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18764c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
187767251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
187867251a31SKevin Wolf             continue;
187967251a31SKevin Wolf         }
188067251a31SKevin Wolf 
18814c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18824c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18834c9dfe5dSKevin Wolf         g_free(child_key_dot);
18844c9dfe5dSKevin Wolf 
188528518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
188628518102SKevin Wolf                                 child->role, options, flags);
1887e971aa12SJeff Cody     }
1888e971aa12SJeff Cody 
1889e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1890e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1891e971aa12SJeff Cody 
1892e971aa12SJeff Cody     bs_entry->state.bs = bs;
18934d2cb092SKevin Wolf     bs_entry->state.options = options;
1894145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1895e971aa12SJeff Cody     bs_entry->state.flags = flags;
1896e971aa12SJeff Cody 
1897e971aa12SJeff Cody     return bs_queue;
1898e971aa12SJeff Cody }
1899e971aa12SJeff Cody 
190028518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
190128518102SKevin Wolf                                     BlockDriverState *bs,
190228518102SKevin Wolf                                     QDict *options, int flags)
190328518102SKevin Wolf {
190428518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
190528518102SKevin Wolf                                    NULL, NULL, 0);
190628518102SKevin Wolf }
190728518102SKevin Wolf 
1908e971aa12SJeff Cody /*
1909e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1910e971aa12SJeff Cody  *
1911e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1912e971aa12SJeff Cody  * via bdrv_reopen_queue().
1913e971aa12SJeff Cody  *
1914e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1915e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1916e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1917e971aa12SJeff Cody  * data cleaned up.
1918e971aa12SJeff Cody  *
1919e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1920e971aa12SJeff Cody  * to all devices.
1921e971aa12SJeff Cody  *
1922e971aa12SJeff Cody  */
1923e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1924e971aa12SJeff Cody {
1925e971aa12SJeff Cody     int ret = -1;
1926e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1927e971aa12SJeff Cody     Error *local_err = NULL;
1928e971aa12SJeff Cody 
1929e971aa12SJeff Cody     assert(bs_queue != NULL);
1930e971aa12SJeff Cody 
1931e971aa12SJeff Cody     bdrv_drain_all();
1932e971aa12SJeff Cody 
1933e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1934e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1935e971aa12SJeff Cody             error_propagate(errp, local_err);
1936e971aa12SJeff Cody             goto cleanup;
1937e971aa12SJeff Cody         }
1938e971aa12SJeff Cody         bs_entry->prepared = true;
1939e971aa12SJeff Cody     }
1940e971aa12SJeff Cody 
1941e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1942e971aa12SJeff Cody      * changes
1943e971aa12SJeff Cody      */
1944e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1945e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1946e971aa12SJeff Cody     }
1947e971aa12SJeff Cody 
1948e971aa12SJeff Cody     ret = 0;
1949e971aa12SJeff Cody 
1950e971aa12SJeff Cody cleanup:
1951e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1952e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1953e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1954145f598eSKevin Wolf         } else if (ret) {
1955145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1956e971aa12SJeff Cody         }
19574d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1958e971aa12SJeff Cody         g_free(bs_entry);
1959e971aa12SJeff Cody     }
1960e971aa12SJeff Cody     g_free(bs_queue);
1961e971aa12SJeff Cody     return ret;
1962e971aa12SJeff Cody }
1963e971aa12SJeff Cody 
1964e971aa12SJeff Cody 
1965e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1966e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1967e971aa12SJeff Cody {
1968e971aa12SJeff Cody     int ret = -1;
1969e971aa12SJeff Cody     Error *local_err = NULL;
19704d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1971e971aa12SJeff Cody 
1972e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1973e971aa12SJeff Cody     if (local_err != NULL) {
1974e971aa12SJeff Cody         error_propagate(errp, local_err);
1975e971aa12SJeff Cody     }
1976e971aa12SJeff Cody     return ret;
1977e971aa12SJeff Cody }
1978e971aa12SJeff Cody 
1979e971aa12SJeff Cody 
1980e971aa12SJeff Cody /*
1981e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1982e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1983e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1984e971aa12SJeff Cody  *
1985e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1986e971aa12SJeff Cody  * flags are the new open flags
1987e971aa12SJeff Cody  * queue is the reopen queue
1988e971aa12SJeff Cody  *
1989e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1990e971aa12SJeff Cody  * as well.
1991e971aa12SJeff Cody  *
1992e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1993e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1994e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1995e971aa12SJeff Cody  *
1996e971aa12SJeff Cody  */
1997e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1998e971aa12SJeff Cody                         Error **errp)
1999e971aa12SJeff Cody {
2000e971aa12SJeff Cody     int ret = -1;
2001e971aa12SJeff Cody     Error *local_err = NULL;
2002e971aa12SJeff Cody     BlockDriver *drv;
2003ccf9dc07SKevin Wolf     QemuOpts *opts;
2004ccf9dc07SKevin Wolf     const char *value;
2005e971aa12SJeff Cody 
2006e971aa12SJeff Cody     assert(reopen_state != NULL);
2007e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
2008e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2009e971aa12SJeff Cody 
2010ccf9dc07SKevin Wolf     /* Process generic block layer options */
2011ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2012ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2013ccf9dc07SKevin Wolf     if (local_err) {
2014ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2015ccf9dc07SKevin Wolf         ret = -EINVAL;
2016ccf9dc07SKevin Wolf         goto error;
2017ccf9dc07SKevin Wolf     }
2018ccf9dc07SKevin Wolf 
201991a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
202091a097e7SKevin Wolf 
2021ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2022ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2023ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2024ccf9dc07SKevin Wolf     if (value) {
2025ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2026ccf9dc07SKevin Wolf     }
2027ccf9dc07SKevin Wolf 
2028ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2029ccf9dc07SKevin Wolf     if (value) {
2030ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2031ccf9dc07SKevin Wolf     }
2032ccf9dc07SKevin Wolf 
2033e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2034e971aa12SJeff Cody      * to r/w */
2035e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2036e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
203781e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
203881e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2039e971aa12SJeff Cody         goto error;
2040e971aa12SJeff Cody     }
2041e971aa12SJeff Cody 
2042e971aa12SJeff Cody 
2043e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2044e971aa12SJeff Cody     if (ret) {
2045455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2046e971aa12SJeff Cody         goto error;
2047e971aa12SJeff Cody     }
2048e971aa12SJeff Cody 
2049e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2050e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2051e971aa12SJeff Cody         if (ret) {
2052e971aa12SJeff Cody             if (local_err != NULL) {
2053e971aa12SJeff Cody                 error_propagate(errp, local_err);
2054e971aa12SJeff Cody             } else {
2055d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2056e971aa12SJeff Cody                            reopen_state->bs->filename);
2057e971aa12SJeff Cody             }
2058e971aa12SJeff Cody             goto error;
2059e971aa12SJeff Cody         }
2060e971aa12SJeff Cody     } else {
2061e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2062e971aa12SJeff Cody          * handler for each supported drv. */
206381e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206481e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
206581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2066e971aa12SJeff Cody         ret = -1;
2067e971aa12SJeff Cody         goto error;
2068e971aa12SJeff Cody     }
2069e971aa12SJeff Cody 
20704d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20714d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20724d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20734d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20744d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20754d2cb092SKevin Wolf 
20764d2cb092SKevin Wolf         do {
20774d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20784d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20794d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20804d2cb092SKevin Wolf                                                 entry->key);
20814d2cb092SKevin Wolf 
20824d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20834d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20844d2cb092SKevin Wolf                 ret = -EINVAL;
20854d2cb092SKevin Wolf                 goto error;
20864d2cb092SKevin Wolf             }
20874d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20884d2cb092SKevin Wolf     }
20894d2cb092SKevin Wolf 
2090e971aa12SJeff Cody     ret = 0;
2091e971aa12SJeff Cody 
2092e971aa12SJeff Cody error:
2093ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2094e971aa12SJeff Cody     return ret;
2095e971aa12SJeff Cody }
2096e971aa12SJeff Cody 
2097e971aa12SJeff Cody /*
2098e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2099e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2100e971aa12SJeff Cody  * the active BlockDriverState contents.
2101e971aa12SJeff Cody  */
2102e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2103e971aa12SJeff Cody {
2104e971aa12SJeff Cody     BlockDriver *drv;
2105e971aa12SJeff Cody 
2106e971aa12SJeff Cody     assert(reopen_state != NULL);
2107e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2108e971aa12SJeff Cody     assert(drv != NULL);
2109e971aa12SJeff Cody 
2110e971aa12SJeff Cody     /* If there are any driver level actions to take */
2111e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2112e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2113e971aa12SJeff Cody     }
2114e971aa12SJeff Cody 
2115e971aa12SJeff Cody     /* set BDS specific flags now */
2116145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2117145f598eSKevin Wolf 
2118145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2119e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2120e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2121355ef4acSKevin Wolf 
21223baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2123e971aa12SJeff Cody }
2124e971aa12SJeff Cody 
2125e971aa12SJeff Cody /*
2126e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2127e971aa12SJeff Cody  * reopen_state
2128e971aa12SJeff Cody  */
2129e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2130e971aa12SJeff Cody {
2131e971aa12SJeff Cody     BlockDriver *drv;
2132e971aa12SJeff Cody 
2133e971aa12SJeff Cody     assert(reopen_state != NULL);
2134e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2135e971aa12SJeff Cody     assert(drv != NULL);
2136e971aa12SJeff Cody 
2137e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2138e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2139e971aa12SJeff Cody     }
2140145f598eSKevin Wolf 
2141145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2142e971aa12SJeff Cody }
2143e971aa12SJeff Cody 
2144e971aa12SJeff Cody 
214564dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2146fc01f7e7Sbellard {
214733384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
214833384421SMax Reitz 
2149ca9bd24cSMax Reitz     assert(!bs->job);
215030f55fb8SMax Reitz     assert(!bs->refcnt);
215199b7e775SAlberto Garcia 
2152fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
215358fda173SStefan Hajnoczi     bdrv_flush(bs);
215453ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2155fc27291dSPaolo Bonzini 
2156c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2157c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2158c5acdc9aSMax Reitz 
21593cbc002cSPaolo Bonzini     if (bs->drv) {
21606e93e7c4SKevin Wolf         BdrvChild *child, *next;
21616e93e7c4SKevin Wolf 
21629a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21639a4f4c31SKevin Wolf         bs->drv = NULL;
21649a7dedbcSKevin Wolf 
21659a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21669a7dedbcSKevin Wolf 
21679a4f4c31SKevin Wolf         if (bs->file != NULL) {
21689a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21699a4f4c31SKevin Wolf             bs->file = NULL;
21709a4f4c31SKevin Wolf         }
21719a4f4c31SKevin Wolf 
21726e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
217333a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
217433a60407SKevin Wolf              * bdrv_unref_child() here */
2175bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2176bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2177bddcec37SKevin Wolf             }
217833a60407SKevin Wolf             bdrv_detach_child(child);
21796e93e7c4SKevin Wolf         }
21806e93e7c4SKevin Wolf 
21817267c094SAnthony Liguori         g_free(bs->opaque);
2182ea2384d3Sbellard         bs->opaque = NULL;
218353fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2184a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2185a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
21866405875cSPaolo Bonzini         bs->total_sectors = 0;
218754115412SEric Blake         bs->encrypted = false;
218854115412SEric Blake         bs->valid_key = false;
218954115412SEric Blake         bs->sg = false;
2190de9c0cecSKevin Wolf         QDECREF(bs->options);
2191145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2192de9c0cecSKevin Wolf         bs->options = NULL;
219391af7014SMax Reitz         QDECREF(bs->full_open_options);
219491af7014SMax Reitz         bs->full_open_options = NULL;
21959ca11154SPavel Hrdina     }
219666f82ceeSKevin Wolf 
219733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
219833384421SMax Reitz         g_free(ban);
219933384421SMax Reitz     }
220033384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2201fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2202b338082bSbellard }
2203b338082bSbellard 
22042bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22052bc93fedSMORITA Kazutaka {
2206a1a2af07SKevin Wolf     block_job_cancel_sync_all();
22072bc93fedSMORITA Kazutaka 
2208ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2209ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2210ca9bd24cSMax Reitz     bdrv_drain_all();
2211ca9bd24cSMax Reitz 
2212ca9bd24cSMax Reitz     blk_remove_all_bs();
2213ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2214ca9bd24cSMax Reitz 
2215a1a2af07SKevin Wolf     assert(QTAILQ_EMPTY(&all_bdrv_states));
22162bc93fedSMORITA Kazutaka }
22172bc93fedSMORITA Kazutaka 
2218dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2219dd62f1caSKevin Wolf                                        BlockDriverState *to)
2220dd62f1caSKevin Wolf {
22219bd910e2SMax Reitz     BdrvChild *c, *next, *to_c;
2222dd62f1caSKevin Wolf 
2223dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
22249bd910e2SMax Reitz         if (c->role == &child_backing) {
22259bd910e2SMax Reitz             /* @from is generally not allowed to be a backing file, except for
22269bd910e2SMax Reitz              * when @to is the overlay. In that case, @from may not be replaced
22279bd910e2SMax Reitz              * by @to as @to's backing node. */
22289bd910e2SMax Reitz             QLIST_FOREACH(to_c, &to->children, next) {
22299bd910e2SMax Reitz                 if (to_c == c) {
22309bd910e2SMax Reitz                     break;
22319bd910e2SMax Reitz                 }
22329bd910e2SMax Reitz             }
22339bd910e2SMax Reitz             if (to_c) {
22349bd910e2SMax Reitz                 continue;
22359bd910e2SMax Reitz             }
22369bd910e2SMax Reitz         }
22379bd910e2SMax Reitz 
2238dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2239dd62f1caSKevin Wolf         bdrv_ref(to);
2240e9740bc6SKevin Wolf         bdrv_replace_child(c, to);
2241dd62f1caSKevin Wolf         bdrv_unref(from);
2242dd62f1caSKevin Wolf     }
2243dd62f1caSKevin Wolf }
2244dd62f1caSKevin Wolf 
22458802d1fdSJeff Cody /*
22468802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
22478802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
22488802d1fdSJeff Cody  *
22498802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
22508802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
22518802d1fdSJeff Cody  *
2252bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2253f6801b83SJeff Cody  *
22548802d1fdSJeff Cody  * This function does not create any image files.
2255dd62f1caSKevin Wolf  *
2256dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2257dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2258dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2259dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
22608802d1fdSJeff Cody  */
22618802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
22628802d1fdSJeff Cody {
2263dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2264dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
22658802d1fdSJeff Cody 
2266dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2267dd62f1caSKevin Wolf 
226827ccdd52SKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2269dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2270dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2271dd62f1caSKevin Wolf 
2272dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2273dd62f1caSKevin Wolf      * additional reference any more. */
2274dd62f1caSKevin Wolf     bdrv_unref(bs_new);
22758802d1fdSJeff Cody }
22768802d1fdSJeff Cody 
22773f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
22783f09bfbcSKevin Wolf {
22793f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
22803f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
22813f09bfbcSKevin Wolf 
22823f09bfbcSKevin Wolf     bdrv_ref(old);
22833f09bfbcSKevin Wolf 
22843f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
22853f09bfbcSKevin Wolf 
22863f09bfbcSKevin Wolf     bdrv_unref(old);
22873f09bfbcSKevin Wolf }
22883f09bfbcSKevin Wolf 
22894f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2290b338082bSbellard {
22913e914655SPaolo Bonzini     assert(!bs->job);
22923718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
22934f6fd349SFam Zheng     assert(!bs->refcnt);
229418846deeSMarkus Armbruster 
2295e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2296e1b5c52eSStefan Hajnoczi 
22971b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
229863eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
229963eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
230063eaaae0SKevin Wolf     }
23012c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
23022c1d04e0SMax Reitz 
23037267c094SAnthony Liguori     g_free(bs);
2304fc01f7e7Sbellard }
2305fc01f7e7Sbellard 
2306e97fc193Saliguori /*
2307e97fc193Saliguori  * Run consistency checks on an image
2308e97fc193Saliguori  *
2309e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2310a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2311e076f338SKevin Wolf  * check are stored in res.
2312e97fc193Saliguori  */
23134534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2314e97fc193Saliguori {
2315908bcd54SMax Reitz     if (bs->drv == NULL) {
2316908bcd54SMax Reitz         return -ENOMEDIUM;
2317908bcd54SMax Reitz     }
2318e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2319e97fc193Saliguori         return -ENOTSUP;
2320e97fc193Saliguori     }
2321e97fc193Saliguori 
2322e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
23234534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2324e97fc193Saliguori }
2325e97fc193Saliguori 
2326756e6736SKevin Wolf /*
2327756e6736SKevin Wolf  * Return values:
2328756e6736SKevin Wolf  * 0        - success
2329756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2330756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2331756e6736SKevin Wolf  *            image file header
2332756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2333756e6736SKevin Wolf  */
2334756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2335756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2336756e6736SKevin Wolf {
2337756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2338469ef350SPaolo Bonzini     int ret;
2339756e6736SKevin Wolf 
23405f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23415f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23425f377794SPaolo Bonzini         return -EINVAL;
23435f377794SPaolo Bonzini     }
23445f377794SPaolo Bonzini 
2345756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2346469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2347756e6736SKevin Wolf     } else {
2348469ef350SPaolo Bonzini         ret = -ENOTSUP;
2349756e6736SKevin Wolf     }
2350469ef350SPaolo Bonzini 
2351469ef350SPaolo Bonzini     if (ret == 0) {
2352469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2353469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2354469ef350SPaolo Bonzini     }
2355469ef350SPaolo Bonzini     return ret;
2356756e6736SKevin Wolf }
2357756e6736SKevin Wolf 
23586ebdcee2SJeff Cody /*
23596ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23606ebdcee2SJeff Cody  *
23616ebdcee2SJeff Cody  * active is the current topmost image.
23626ebdcee2SJeff Cody  *
23636ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23646ebdcee2SJeff Cody  * or if active == bs.
23654caf0fcdSJeff Cody  *
23664caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
23676ebdcee2SJeff Cody  */
23686ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23696ebdcee2SJeff Cody                                     BlockDriverState *bs)
23706ebdcee2SJeff Cody {
2371760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2372760e0063SKevin Wolf         active = backing_bs(active);
23736ebdcee2SJeff Cody     }
23746ebdcee2SJeff Cody 
23754caf0fcdSJeff Cody     return active;
23766ebdcee2SJeff Cody }
23776ebdcee2SJeff Cody 
23784caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
23794caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
23804caf0fcdSJeff Cody {
23814caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
23826ebdcee2SJeff Cody }
23836ebdcee2SJeff Cody 
23846ebdcee2SJeff Cody /*
23856ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23866ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23876ebdcee2SJeff Cody  *
23886ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23896ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23906ebdcee2SJeff Cody  *
23916ebdcee2SJeff Cody  * E.g., this will convert the following chain:
23926ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
23936ebdcee2SJeff Cody  *
23946ebdcee2SJeff Cody  * to
23956ebdcee2SJeff Cody  *
23966ebdcee2SJeff Cody  * bottom <- base <- active
23976ebdcee2SJeff Cody  *
23986ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
23996ebdcee2SJeff Cody  *
24006ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24016ebdcee2SJeff Cody  *
24026ebdcee2SJeff Cody  * to
24036ebdcee2SJeff Cody  *
24046ebdcee2SJeff Cody  * base <- active
24056ebdcee2SJeff Cody  *
240654e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
240754e26900SJeff Cody  * overlay image metadata.
240854e26900SJeff Cody  *
24096ebdcee2SJeff Cody  * Error conditions:
24106ebdcee2SJeff Cody  *  if active == top, that is considered an error
24116ebdcee2SJeff Cody  *
24126ebdcee2SJeff Cody  */
24136ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
241454e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
24156ebdcee2SJeff Cody {
24166ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24176ebdcee2SJeff Cody     int ret = -EIO;
24186ebdcee2SJeff Cody 
24196ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24206ebdcee2SJeff Cody         goto exit;
24216ebdcee2SJeff Cody     }
24226ebdcee2SJeff Cody 
24236ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24246ebdcee2SJeff Cody 
24256ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24266ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24276ebdcee2SJeff Cody         goto exit;
24286ebdcee2SJeff Cody     }
24296ebdcee2SJeff Cody 
2430760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
24316ebdcee2SJeff Cody      * to do, no intermediate images */
2432760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
24336ebdcee2SJeff Cody         ret = 0;
24346ebdcee2SJeff Cody         goto exit;
24356ebdcee2SJeff Cody     }
24366ebdcee2SJeff Cody 
24375db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
24385db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
24396ebdcee2SJeff Cody         goto exit;
24406ebdcee2SJeff Cody     }
24416ebdcee2SJeff Cody 
24426ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
24435db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
244454e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
24455db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
24466ebdcee2SJeff Cody     if (ret) {
24476ebdcee2SJeff Cody         goto exit;
24486ebdcee2SJeff Cody     }
24495db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
24506ebdcee2SJeff Cody 
24516ebdcee2SJeff Cody     ret = 0;
24526ebdcee2SJeff Cody exit:
24536ebdcee2SJeff Cody     return ret;
24546ebdcee2SJeff Cody }
24556ebdcee2SJeff Cody 
245683f64091Sbellard /**
245783f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
245883f64091Sbellard  */
245983f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
246083f64091Sbellard {
246183f64091Sbellard     BlockDriver *drv = bs->drv;
246251762288SStefan Hajnoczi     int ret;
246383f64091Sbellard     if (!drv)
246419cb3738Sbellard         return -ENOMEDIUM;
246583f64091Sbellard     if (!drv->bdrv_truncate)
246683f64091Sbellard         return -ENOTSUP;
246759f2689dSNaphtali Sprei     if (bs->read_only)
246859f2689dSNaphtali Sprei         return -EACCES;
24699c75e168SJeff Cody 
247051762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
247151762288SStefan Hajnoczi     if (ret == 0) {
247251762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2473ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
24745c8cab48SKevin Wolf         bdrv_parent_cb_resize(bs);
247551762288SStefan Hajnoczi     }
247651762288SStefan Hajnoczi     return ret;
247783f64091Sbellard }
247883f64091Sbellard 
247983f64091Sbellard /**
24804a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
24814a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
24824a1d5e1fSFam Zheng  */
24834a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
24844a1d5e1fSFam Zheng {
24854a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
24864a1d5e1fSFam Zheng     if (!drv) {
24874a1d5e1fSFam Zheng         return -ENOMEDIUM;
24884a1d5e1fSFam Zheng     }
24894a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
24904a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
24914a1d5e1fSFam Zheng     }
24924a1d5e1fSFam Zheng     if (bs->file) {
24939a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
24944a1d5e1fSFam Zheng     }
24954a1d5e1fSFam Zheng     return -ENOTSUP;
24964a1d5e1fSFam Zheng }
24974a1d5e1fSFam Zheng 
24984a1d5e1fSFam Zheng /**
249965a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
250083f64091Sbellard  */
250165a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
250283f64091Sbellard {
250383f64091Sbellard     BlockDriver *drv = bs->drv;
250465a9bb25SMarkus Armbruster 
250583f64091Sbellard     if (!drv)
250619cb3738Sbellard         return -ENOMEDIUM;
250751762288SStefan Hajnoczi 
2508b94a2610SKevin Wolf     if (drv->has_variable_length) {
2509b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2510b94a2610SKevin Wolf         if (ret < 0) {
2511b94a2610SKevin Wolf             return ret;
2512fc01f7e7Sbellard         }
251346a4e4e6SStefan Hajnoczi     }
251465a9bb25SMarkus Armbruster     return bs->total_sectors;
251565a9bb25SMarkus Armbruster }
251665a9bb25SMarkus Armbruster 
251765a9bb25SMarkus Armbruster /**
251865a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
251965a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
252065a9bb25SMarkus Armbruster  */
252165a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
252265a9bb25SMarkus Armbruster {
252365a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
252465a9bb25SMarkus Armbruster 
25254a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
252665a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
252746a4e4e6SStefan Hajnoczi }
2528fc01f7e7Sbellard 
252919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
253096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2531fc01f7e7Sbellard {
253265a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
253365a9bb25SMarkus Armbruster 
253465a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2535fc01f7e7Sbellard }
2536cf98951bSbellard 
253754115412SEric Blake bool bdrv_is_read_only(BlockDriverState *bs)
2538b338082bSbellard {
2539b338082bSbellard     return bs->read_only;
2540b338082bSbellard }
2541b338082bSbellard 
254254115412SEric Blake bool bdrv_is_sg(BlockDriverState *bs)
2543985a03b0Sths {
2544985a03b0Sths     return bs->sg;
2545985a03b0Sths }
2546985a03b0Sths 
254754115412SEric Blake bool bdrv_is_encrypted(BlockDriverState *bs)
2548ea2384d3Sbellard {
2549760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
255054115412SEric Blake         return true;
2551760e0063SKevin Wolf     }
2552ea2384d3Sbellard     return bs->encrypted;
2553ea2384d3Sbellard }
2554ea2384d3Sbellard 
255554115412SEric Blake bool bdrv_key_required(BlockDriverState *bs)
2556c0f4ce77Saliguori {
2557760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2558c0f4ce77Saliguori 
2559760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
256054115412SEric Blake         return true;
2561760e0063SKevin Wolf     }
2562c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2563c0f4ce77Saliguori }
2564c0f4ce77Saliguori 
2565ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2566ea2384d3Sbellard {
2567ea2384d3Sbellard     int ret;
2568760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2569760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2570ea2384d3Sbellard         if (ret < 0)
2571ea2384d3Sbellard             return ret;
2572ea2384d3Sbellard         if (!bs->encrypted)
2573ea2384d3Sbellard             return 0;
2574ea2384d3Sbellard     }
2575fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2576fd04a2aeSShahar Havivi         return -EINVAL;
2577fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2578fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2579fd04a2aeSShahar Havivi     }
2580c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2581bb5fc20fSaliguori     if (ret < 0) {
258254115412SEric Blake         bs->valid_key = false;
2583bb5fc20fSaliguori     } else if (!bs->valid_key) {
2584bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
258554115412SEric Blake         bs->valid_key = true;
25865c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
2587bb5fc20fSaliguori     }
2588c0f4ce77Saliguori     return ret;
2589ea2384d3Sbellard }
2590ea2384d3Sbellard 
25914d2855a3SMarkus Armbruster /*
25924d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
25934d2855a3SMarkus Armbruster  * If @key is non-null:
25944d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
25954d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
25964d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
25974d2855a3SMarkus Armbruster  * If @key is null:
25984d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
25994d2855a3SMarkus Armbruster  *     Else do nothing.
26004d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
26014d2855a3SMarkus Armbruster  */
26024d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
26034d2855a3SMarkus Armbruster {
26044d2855a3SMarkus Armbruster     if (key) {
26054d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
260681e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
260781e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
26084d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2609c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
26104d2855a3SMarkus Armbruster         }
26114d2855a3SMarkus Armbruster     } else {
26124d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2613b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2614b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
261581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
26164d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
26174d2855a3SMarkus Armbruster         }
26184d2855a3SMarkus Armbruster     }
26194d2855a3SMarkus Armbruster }
26204d2855a3SMarkus Armbruster 
2621f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2622ea2384d3Sbellard {
2623f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2624ea2384d3Sbellard }
2625ea2384d3Sbellard 
2626ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2627ada42401SStefan Hajnoczi {
2628ada42401SStefan Hajnoczi     return strcmp(a, b);
2629ada42401SStefan Hajnoczi }
2630ada42401SStefan Hajnoczi 
2631ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2632ea2384d3Sbellard                          void *opaque)
2633ea2384d3Sbellard {
2634ea2384d3Sbellard     BlockDriver *drv;
2635e855e4fbSJeff Cody     int count = 0;
2636ada42401SStefan Hajnoczi     int i;
2637e855e4fbSJeff Cody     const char **formats = NULL;
2638ea2384d3Sbellard 
26398a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2640e855e4fbSJeff Cody         if (drv->format_name) {
2641e855e4fbSJeff Cody             bool found = false;
2642e855e4fbSJeff Cody             int i = count;
2643e855e4fbSJeff Cody             while (formats && i && !found) {
2644e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2645e855e4fbSJeff Cody             }
2646e855e4fbSJeff Cody 
2647e855e4fbSJeff Cody             if (!found) {
26485839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2649e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2650ea2384d3Sbellard             }
2651ea2384d3Sbellard         }
2652e855e4fbSJeff Cody     }
2653ada42401SStefan Hajnoczi 
2654ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2655ada42401SStefan Hajnoczi 
2656ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2657ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2658ada42401SStefan Hajnoczi     }
2659ada42401SStefan Hajnoczi 
2660e855e4fbSJeff Cody     g_free(formats);
2661e855e4fbSJeff Cody }
2662ea2384d3Sbellard 
2663dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2664dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2665dc364f4cSBenoît Canet {
2666dc364f4cSBenoît Canet     BlockDriverState *bs;
2667dc364f4cSBenoît Canet 
2668dc364f4cSBenoît Canet     assert(node_name);
2669dc364f4cSBenoît Canet 
2670dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2671dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2672dc364f4cSBenoît Canet             return bs;
2673dc364f4cSBenoît Canet         }
2674dc364f4cSBenoît Canet     }
2675dc364f4cSBenoît Canet     return NULL;
2676dc364f4cSBenoît Canet }
2677dc364f4cSBenoît Canet 
2678c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2679d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2680c13163fbSBenoît Canet {
2681c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2682c13163fbSBenoît Canet     BlockDriverState *bs;
2683c13163fbSBenoît Canet 
2684c13163fbSBenoît Canet     list = NULL;
2685c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2686c83f9fbaSKevin Wolf         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
2687d5a8ee60SAlberto Garcia         if (!info) {
2688d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2689d5a8ee60SAlberto Garcia             return NULL;
2690d5a8ee60SAlberto Garcia         }
2691c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2692d5a8ee60SAlberto Garcia         entry->value = info;
2693c13163fbSBenoît Canet         entry->next = list;
2694c13163fbSBenoît Canet         list = entry;
2695c13163fbSBenoît Canet     }
2696c13163fbSBenoît Canet 
2697c13163fbSBenoît Canet     return list;
2698c13163fbSBenoît Canet }
2699c13163fbSBenoît Canet 
270012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
270112d3ba82SBenoît Canet                                  const char *node_name,
270212d3ba82SBenoît Canet                                  Error **errp)
270312d3ba82SBenoît Canet {
27047f06d47eSMarkus Armbruster     BlockBackend *blk;
27057f06d47eSMarkus Armbruster     BlockDriverState *bs;
270612d3ba82SBenoît Canet 
270712d3ba82SBenoît Canet     if (device) {
27087f06d47eSMarkus Armbruster         blk = blk_by_name(device);
270912d3ba82SBenoît Canet 
27107f06d47eSMarkus Armbruster         if (blk) {
27119f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
27129f4ed6fbSAlberto Garcia             if (!bs) {
27135433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
27145433c24fSMax Reitz             }
27155433c24fSMax Reitz 
27169f4ed6fbSAlberto Garcia             return bs;
271712d3ba82SBenoît Canet         }
2718dd67fa50SBenoît Canet     }
271912d3ba82SBenoît Canet 
2720dd67fa50SBenoît Canet     if (node_name) {
272112d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
272212d3ba82SBenoît Canet 
2723dd67fa50SBenoît Canet         if (bs) {
2724dd67fa50SBenoît Canet             return bs;
2725dd67fa50SBenoît Canet         }
272612d3ba82SBenoît Canet     }
272712d3ba82SBenoît Canet 
2728dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2729dd67fa50SBenoît Canet                      device ? device : "",
2730dd67fa50SBenoît Canet                      node_name ? node_name : "");
2731dd67fa50SBenoît Canet     return NULL;
273212d3ba82SBenoît Canet }
273312d3ba82SBenoît Canet 
27345a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
27355a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
27365a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
27375a6684d2SJeff Cody {
27385a6684d2SJeff Cody     while (top && top != base) {
2739760e0063SKevin Wolf         top = backing_bs(top);
27405a6684d2SJeff Cody     }
27415a6684d2SJeff Cody 
27425a6684d2SJeff Cody     return top != NULL;
27435a6684d2SJeff Cody }
27445a6684d2SJeff Cody 
274504df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
274604df765aSFam Zheng {
274704df765aSFam Zheng     if (!bs) {
274804df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
274904df765aSFam Zheng     }
275004df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
275104df765aSFam Zheng }
275204df765aSFam Zheng 
275320a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
275420a9e77dSFam Zheng {
275520a9e77dSFam Zheng     return bs->node_name;
275620a9e77dSFam Zheng }
275720a9e77dSFam Zheng 
27581f0c461bSKevin Wolf const char *bdrv_get_parent_name(const BlockDriverState *bs)
27594c265bf9SKevin Wolf {
27604c265bf9SKevin Wolf     BdrvChild *c;
27614c265bf9SKevin Wolf     const char *name;
27624c265bf9SKevin Wolf 
27634c265bf9SKevin Wolf     /* If multiple parents have a name, just pick the first one. */
27644c265bf9SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
27654c265bf9SKevin Wolf         if (c->role->get_name) {
27664c265bf9SKevin Wolf             name = c->role->get_name(c);
27674c265bf9SKevin Wolf             if (name && *name) {
27684c265bf9SKevin Wolf                 return name;
27694c265bf9SKevin Wolf             }
27704c265bf9SKevin Wolf         }
27714c265bf9SKevin Wolf     }
27724c265bf9SKevin Wolf 
27734c265bf9SKevin Wolf     return NULL;
27744c265bf9SKevin Wolf }
27754c265bf9SKevin Wolf 
27767f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2777bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2778ea2384d3Sbellard {
27794c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: "";
2780ea2384d3Sbellard }
2781ea2384d3Sbellard 
27829b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
27839b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
27849b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
27859b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
27869b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
27879b2aa84fSAlberto Garcia {
27884c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: bs->node_name;
27899b2aa84fSAlberto Garcia }
27909b2aa84fSAlberto Garcia 
2791c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2792c8433287SMarkus Armbruster {
2793c8433287SMarkus Armbruster     return bs->open_flags;
2794c8433287SMarkus Armbruster }
2795c8433287SMarkus Armbruster 
27963ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
27973ac21627SPeter Lieven {
27983ac21627SPeter Lieven     return 1;
27993ac21627SPeter Lieven }
28003ac21627SPeter Lieven 
2801f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2802f2feebbdSKevin Wolf {
2803f2feebbdSKevin Wolf     assert(bs->drv);
2804f2feebbdSKevin Wolf 
280511212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
280611212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2807760e0063SKevin Wolf     if (bs->backing) {
280811212d8fSPaolo Bonzini         return 0;
280911212d8fSPaolo Bonzini     }
2810336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2811336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2812f2feebbdSKevin Wolf     }
2813f2feebbdSKevin Wolf 
28143ac21627SPeter Lieven     /* safe default */
28153ac21627SPeter Lieven     return 0;
2816f2feebbdSKevin Wolf }
2817f2feebbdSKevin Wolf 
28184ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
28194ce78691SPeter Lieven {
28204ce78691SPeter Lieven     BlockDriverInfo bdi;
28214ce78691SPeter Lieven 
2822760e0063SKevin Wolf     if (bs->backing) {
28234ce78691SPeter Lieven         return false;
28244ce78691SPeter Lieven     }
28254ce78691SPeter Lieven 
28264ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28274ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
28284ce78691SPeter Lieven     }
28294ce78691SPeter Lieven 
28304ce78691SPeter Lieven     return false;
28314ce78691SPeter Lieven }
28324ce78691SPeter Lieven 
28334ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
28344ce78691SPeter Lieven {
28354ce78691SPeter Lieven     BlockDriverInfo bdi;
28364ce78691SPeter Lieven 
2837760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
28384ce78691SPeter Lieven         return false;
28394ce78691SPeter Lieven     }
28404ce78691SPeter Lieven 
28414ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28424ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
28434ce78691SPeter Lieven     }
28444ce78691SPeter Lieven 
28454ce78691SPeter Lieven     return false;
28464ce78691SPeter Lieven }
28474ce78691SPeter Lieven 
2848045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2849045df330Saliguori {
2850760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2851045df330Saliguori         return bs->backing_file;
2852045df330Saliguori     else if (bs->encrypted)
2853045df330Saliguori         return bs->filename;
2854045df330Saliguori     else
2855045df330Saliguori         return NULL;
2856045df330Saliguori }
2857045df330Saliguori 
285883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
285983f64091Sbellard                                char *filename, int filename_size)
286083f64091Sbellard {
286183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
286283f64091Sbellard }
286383f64091Sbellard 
2864faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2865faea38e7Sbellard {
2866faea38e7Sbellard     BlockDriver *drv = bs->drv;
2867faea38e7Sbellard     if (!drv)
286819cb3738Sbellard         return -ENOMEDIUM;
2869faea38e7Sbellard     if (!drv->bdrv_get_info)
2870faea38e7Sbellard         return -ENOTSUP;
2871faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2872faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2873faea38e7Sbellard }
2874faea38e7Sbellard 
2875eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2876eae041feSMax Reitz {
2877eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2878eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2879eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2880eae041feSMax Reitz     }
2881eae041feSMax Reitz     return NULL;
2882eae041feSMax Reitz }
2883eae041feSMax Reitz 
2884a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
28858b9b0cc2SKevin Wolf {
2886bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
28878b9b0cc2SKevin Wolf         return;
28888b9b0cc2SKevin Wolf     }
28898b9b0cc2SKevin Wolf 
2890bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
289141c695c7SKevin Wolf }
28928b9b0cc2SKevin Wolf 
289341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
289441c695c7SKevin Wolf                           const char *tag)
289541c695c7SKevin Wolf {
289641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
28979a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
289841c695c7SKevin Wolf     }
289941c695c7SKevin Wolf 
290041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
290141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
290241c695c7SKevin Wolf     }
290341c695c7SKevin Wolf 
290441c695c7SKevin Wolf     return -ENOTSUP;
290541c695c7SKevin Wolf }
290641c695c7SKevin Wolf 
29074cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
29084cc70e93SFam Zheng {
29094cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
29109a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
29114cc70e93SFam Zheng     }
29124cc70e93SFam Zheng 
29134cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
29144cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
29154cc70e93SFam Zheng     }
29164cc70e93SFam Zheng 
29174cc70e93SFam Zheng     return -ENOTSUP;
29184cc70e93SFam Zheng }
29194cc70e93SFam Zheng 
292041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
292141c695c7SKevin Wolf {
2922938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
29239a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
292441c695c7SKevin Wolf     }
292541c695c7SKevin Wolf 
292641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
292741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
292841c695c7SKevin Wolf     }
292941c695c7SKevin Wolf 
293041c695c7SKevin Wolf     return -ENOTSUP;
293141c695c7SKevin Wolf }
293241c695c7SKevin Wolf 
293341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
293441c695c7SKevin Wolf {
293541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
29369a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
293741c695c7SKevin Wolf     }
293841c695c7SKevin Wolf 
293941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
294041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
294141c695c7SKevin Wolf     }
294241c695c7SKevin Wolf 
294341c695c7SKevin Wolf     return false;
29448b9b0cc2SKevin Wolf }
29458b9b0cc2SKevin Wolf 
2946199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2947199630b6SBlue Swirl {
2948199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2949199630b6SBlue Swirl }
2950199630b6SBlue Swirl 
2951b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
2952b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
2953b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
2954b1b1d783SJeff Cody  * the CWD rather than the chain. */
2955e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2956e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2957e8a6bb9cSMarcelo Tosatti {
2958b1b1d783SJeff Cody     char *filename_full = NULL;
2959b1b1d783SJeff Cody     char *backing_file_full = NULL;
2960b1b1d783SJeff Cody     char *filename_tmp = NULL;
2961b1b1d783SJeff Cody     int is_protocol = 0;
2962b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
2963b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
2964b1b1d783SJeff Cody 
2965b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
2966e8a6bb9cSMarcelo Tosatti         return NULL;
2967e8a6bb9cSMarcelo Tosatti     }
2968e8a6bb9cSMarcelo Tosatti 
2969b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
2970b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
2971b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
2972b1b1d783SJeff Cody 
2973b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
2974b1b1d783SJeff Cody 
2975760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
2976b1b1d783SJeff Cody 
2977b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
2978b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
2979b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
2980b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
2981760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
2982b1b1d783SJeff Cody                 break;
2983b1b1d783SJeff Cody             }
2984e8a6bb9cSMarcelo Tosatti         } else {
2985b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
2986b1b1d783SJeff Cody              * image's filename path */
2987b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2988b1b1d783SJeff Cody                          backing_file);
2989b1b1d783SJeff Cody 
2990b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
2991b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
2992b1b1d783SJeff Cody                 continue;
2993b1b1d783SJeff Cody             }
2994b1b1d783SJeff Cody 
2995b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
2996b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
2997b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2998b1b1d783SJeff Cody                          curr_bs->backing_file);
2999b1b1d783SJeff Cody 
3000b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3001b1b1d783SJeff Cody                 continue;
3002b1b1d783SJeff Cody             }
3003b1b1d783SJeff Cody 
3004b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3005760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3006b1b1d783SJeff Cody                 break;
3007b1b1d783SJeff Cody             }
3008e8a6bb9cSMarcelo Tosatti         }
3009e8a6bb9cSMarcelo Tosatti     }
3010e8a6bb9cSMarcelo Tosatti 
3011b1b1d783SJeff Cody     g_free(filename_full);
3012b1b1d783SJeff Cody     g_free(backing_file_full);
3013b1b1d783SJeff Cody     g_free(filename_tmp);
3014b1b1d783SJeff Cody     return retval;
3015e8a6bb9cSMarcelo Tosatti }
3016e8a6bb9cSMarcelo Tosatti 
3017f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3018f198fd1cSBenoît Canet {
3019f198fd1cSBenoît Canet     if (!bs->drv) {
3020f198fd1cSBenoît Canet         return 0;
3021f198fd1cSBenoît Canet     }
3022f198fd1cSBenoît Canet 
3023760e0063SKevin Wolf     if (!bs->backing) {
3024f198fd1cSBenoît Canet         return 0;
3025f198fd1cSBenoît Canet     }
3026f198fd1cSBenoît Canet 
3027760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3028f198fd1cSBenoît Canet }
3029f198fd1cSBenoît Canet 
3030ea2384d3Sbellard void bdrv_init(void)
3031ea2384d3Sbellard {
30325efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3033ea2384d3Sbellard }
3034ce1a14dcSpbrook 
3035eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3036eb852011SMarkus Armbruster {
3037eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3038eb852011SMarkus Armbruster     bdrv_init();
3039eb852011SMarkus Armbruster }
3040eb852011SMarkus Armbruster 
30415a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
30420f15423cSAnthony Liguori {
30430d1c5c91SFam Zheng     BdrvChild *child;
30445a8a30dbSKevin Wolf     Error *local_err = NULL;
30455a8a30dbSKevin Wolf     int ret;
30465a8a30dbSKevin Wolf 
30473456a8d1SKevin Wolf     if (!bs->drv)  {
30483456a8d1SKevin Wolf         return;
30490f15423cSAnthony Liguori     }
30503456a8d1SKevin Wolf 
305104c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
30527ea2d269SAlexey Kardashevskiy         return;
30537ea2d269SAlexey Kardashevskiy     }
305404c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
30557ea2d269SAlexey Kardashevskiy 
30563456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
30575a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
30585a8a30dbSKevin Wolf         if (local_err) {
305904c01a5cSKevin Wolf             bs->open_flags |= BDRV_O_INACTIVE;
30605a8a30dbSKevin Wolf             error_propagate(errp, local_err);
30615a8a30dbSKevin Wolf             return;
30623456a8d1SKevin Wolf         }
30630d1c5c91SFam Zheng     }
30640d1c5c91SFam Zheng 
30650d1c5c91SFam Zheng     QLIST_FOREACH(child, &bs->children, next) {
30660d1c5c91SFam Zheng         bdrv_invalidate_cache(child->bs, &local_err);
30670d1c5c91SFam Zheng         if (local_err) {
30680d1c5c91SFam Zheng             bs->open_flags |= BDRV_O_INACTIVE;
30690d1c5c91SFam Zheng             error_propagate(errp, local_err);
30700d1c5c91SFam Zheng             return;
30710d1c5c91SFam Zheng         }
30720d1c5c91SFam Zheng     }
30733456a8d1SKevin Wolf 
30745a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
30755a8a30dbSKevin Wolf     if (ret < 0) {
307604c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
30775a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
30785a8a30dbSKevin Wolf         return;
30795a8a30dbSKevin Wolf     }
30800f15423cSAnthony Liguori }
30810f15423cSAnthony Liguori 
30825a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
30830f15423cSAnthony Liguori {
30847c8eece4SKevin Wolf     BlockDriverState *bs;
30855a8a30dbSKevin Wolf     Error *local_err = NULL;
308688be7b4bSKevin Wolf     BdrvNextIterator it;
30870f15423cSAnthony Liguori 
308888be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3089ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3090ed78cda3SStefan Hajnoczi 
3091ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
30925a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3093ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
30945a8a30dbSKevin Wolf         if (local_err) {
30955a8a30dbSKevin Wolf             error_propagate(errp, local_err);
30965a8a30dbSKevin Wolf             return;
30975a8a30dbSKevin Wolf         }
30980f15423cSAnthony Liguori     }
30990f15423cSAnthony Liguori }
31000f15423cSAnthony Liguori 
3101aad0b7a0SFam Zheng static int bdrv_inactivate_recurse(BlockDriverState *bs,
3102aad0b7a0SFam Zheng                                    bool setting_flag)
310376b1c7feSKevin Wolf {
3104aad0b7a0SFam Zheng     BdrvChild *child;
310576b1c7feSKevin Wolf     int ret;
310676b1c7feSKevin Wolf 
3107aad0b7a0SFam Zheng     if (!setting_flag && bs->drv->bdrv_inactivate) {
310876b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
310976b1c7feSKevin Wolf         if (ret < 0) {
311076b1c7feSKevin Wolf             return ret;
311176b1c7feSKevin Wolf         }
311276b1c7feSKevin Wolf     }
311376b1c7feSKevin Wolf 
3114aad0b7a0SFam Zheng     QLIST_FOREACH(child, &bs->children, next) {
3115aad0b7a0SFam Zheng         ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3116aad0b7a0SFam Zheng         if (ret < 0) {
3117aad0b7a0SFam Zheng             return ret;
3118aad0b7a0SFam Zheng         }
3119aad0b7a0SFam Zheng     }
3120aad0b7a0SFam Zheng 
3121aad0b7a0SFam Zheng     if (setting_flag) {
312276b1c7feSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
3123aad0b7a0SFam Zheng     }
312476b1c7feSKevin Wolf     return 0;
312576b1c7feSKevin Wolf }
312676b1c7feSKevin Wolf 
312776b1c7feSKevin Wolf int bdrv_inactivate_all(void)
312876b1c7feSKevin Wolf {
312979720af6SMax Reitz     BlockDriverState *bs = NULL;
313088be7b4bSKevin Wolf     BdrvNextIterator it;
3131aad0b7a0SFam Zheng     int ret = 0;
3132aad0b7a0SFam Zheng     int pass;
313376b1c7feSKevin Wolf 
313488be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3135aad0b7a0SFam Zheng         aio_context_acquire(bdrv_get_aio_context(bs));
3136aad0b7a0SFam Zheng     }
313776b1c7feSKevin Wolf 
3138aad0b7a0SFam Zheng     /* We do two passes of inactivation. The first pass calls to drivers'
3139aad0b7a0SFam Zheng      * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3140aad0b7a0SFam Zheng      * the second pass sets the BDRV_O_INACTIVE flag so that no further write
3141aad0b7a0SFam Zheng      * is allowed. */
3142aad0b7a0SFam Zheng     for (pass = 0; pass < 2; pass++) {
314388be7b4bSKevin Wolf         for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3144aad0b7a0SFam Zheng             ret = bdrv_inactivate_recurse(bs, pass);
314576b1c7feSKevin Wolf             if (ret < 0) {
3146aad0b7a0SFam Zheng                 goto out;
3147aad0b7a0SFam Zheng             }
314876b1c7feSKevin Wolf         }
314976b1c7feSKevin Wolf     }
315076b1c7feSKevin Wolf 
3151aad0b7a0SFam Zheng out:
315288be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3153aad0b7a0SFam Zheng         aio_context_release(bdrv_get_aio_context(bs));
3154aad0b7a0SFam Zheng     }
3155aad0b7a0SFam Zheng 
3156aad0b7a0SFam Zheng     return ret;
315776b1c7feSKevin Wolf }
315876b1c7feSKevin Wolf 
3159f9f05dc5SKevin Wolf /**************************************************************/
316019cb3738Sbellard /* removable device support */
316119cb3738Sbellard 
316219cb3738Sbellard /**
316319cb3738Sbellard  * Return TRUE if the media is present
316419cb3738Sbellard  */
3165e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
316619cb3738Sbellard {
316719cb3738Sbellard     BlockDriver *drv = bs->drv;
316828d7a789SMax Reitz     BdrvChild *child;
3169a1aff5bfSMarkus Armbruster 
3170e031f750SMax Reitz     if (!drv) {
3171e031f750SMax Reitz         return false;
3172e031f750SMax Reitz     }
317328d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3174a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
317519cb3738Sbellard     }
317628d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
317728d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
317828d7a789SMax Reitz             return false;
317928d7a789SMax Reitz         }
318028d7a789SMax Reitz     }
318128d7a789SMax Reitz     return true;
318228d7a789SMax Reitz }
318319cb3738Sbellard 
318419cb3738Sbellard /**
31858e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
31868e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
318719cb3738Sbellard  */
318819cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
318919cb3738Sbellard {
319019cb3738Sbellard     BlockDriver *drv = bs->drv;
319119cb3738Sbellard 
31928e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
31938e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
31948e49ca46SMarkus Armbruster     }
31958e49ca46SMarkus Armbruster     return -ENOTSUP;
319619cb3738Sbellard }
319719cb3738Sbellard 
319819cb3738Sbellard /**
319919cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
320019cb3738Sbellard  */
3201f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
320219cb3738Sbellard {
320319cb3738Sbellard     BlockDriver *drv = bs->drv;
3204bfb197e0SMarkus Armbruster     const char *device_name;
320519cb3738Sbellard 
3206822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3207822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
320819cb3738Sbellard     }
32096f382ed2SLuiz Capitulino 
3210bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3211bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3212bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3213a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
32146f382ed2SLuiz Capitulino     }
321519cb3738Sbellard }
321619cb3738Sbellard 
321719cb3738Sbellard /**
321819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
321919cb3738Sbellard  * to eject it manually).
322019cb3738Sbellard  */
3221025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
322219cb3738Sbellard {
322319cb3738Sbellard     BlockDriver *drv = bs->drv;
322419cb3738Sbellard 
3225025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3226b8c6d095SStefan Hajnoczi 
3227025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3228025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
322919cb3738Sbellard     }
323019cb3738Sbellard }
3231985a03b0Sths 
32329fcb0251SFam Zheng /* Get a reference to bs */
32339fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
32349fcb0251SFam Zheng {
32359fcb0251SFam Zheng     bs->refcnt++;
32369fcb0251SFam Zheng }
32379fcb0251SFam Zheng 
32389fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
32399fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
32409fcb0251SFam Zheng  * deleted. */
32419fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
32429fcb0251SFam Zheng {
32439a4d5ca6SJeff Cody     if (!bs) {
32449a4d5ca6SJeff Cody         return;
32459a4d5ca6SJeff Cody     }
32469fcb0251SFam Zheng     assert(bs->refcnt > 0);
32479fcb0251SFam Zheng     if (--bs->refcnt == 0) {
32489fcb0251SFam Zheng         bdrv_delete(bs);
32499fcb0251SFam Zheng     }
32509fcb0251SFam Zheng }
32519fcb0251SFam Zheng 
3252fbe40ff7SFam Zheng struct BdrvOpBlocker {
3253fbe40ff7SFam Zheng     Error *reason;
3254fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3255fbe40ff7SFam Zheng };
3256fbe40ff7SFam Zheng 
3257fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3258fbe40ff7SFam Zheng {
3259fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3260fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3261fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3262fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3263fbe40ff7SFam Zheng         if (errp) {
3264e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3265e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3266e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3267fbe40ff7SFam Zheng         }
3268fbe40ff7SFam Zheng         return true;
3269fbe40ff7SFam Zheng     }
3270fbe40ff7SFam Zheng     return false;
3271fbe40ff7SFam Zheng }
3272fbe40ff7SFam Zheng 
3273fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3274fbe40ff7SFam Zheng {
3275fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3276fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3277fbe40ff7SFam Zheng 
32785839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3279fbe40ff7SFam Zheng     blocker->reason = reason;
3280fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3281fbe40ff7SFam Zheng }
3282fbe40ff7SFam Zheng 
3283fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3284fbe40ff7SFam Zheng {
3285fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3286fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3287fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3288fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3289fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3290fbe40ff7SFam Zheng             g_free(blocker);
3291fbe40ff7SFam Zheng         }
3292fbe40ff7SFam Zheng     }
3293fbe40ff7SFam Zheng }
3294fbe40ff7SFam Zheng 
3295fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3296fbe40ff7SFam Zheng {
3297fbe40ff7SFam Zheng     int i;
3298fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3299fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3300fbe40ff7SFam Zheng     }
3301fbe40ff7SFam Zheng }
3302fbe40ff7SFam Zheng 
3303fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3304fbe40ff7SFam Zheng {
3305fbe40ff7SFam Zheng     int i;
3306fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3307fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3308fbe40ff7SFam Zheng     }
3309fbe40ff7SFam Zheng }
3310fbe40ff7SFam Zheng 
3311fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3312fbe40ff7SFam Zheng {
3313fbe40ff7SFam Zheng     int i;
3314fbe40ff7SFam Zheng 
3315fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3316fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3317fbe40ff7SFam Zheng             return false;
3318fbe40ff7SFam Zheng         }
3319fbe40ff7SFam Zheng     }
3320fbe40ff7SFam Zheng     return true;
3321fbe40ff7SFam Zheng }
3322fbe40ff7SFam Zheng 
3323d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3324f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3325f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3326f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3327f88e1a42SJes Sorensen {
332883d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
332983d0521aSChunyan Liu     QemuOpts *opts = NULL;
333083d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
333183d0521aSChunyan Liu     int64_t size;
3332f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3333cc84d90fSMax Reitz     Error *local_err = NULL;
3334f88e1a42SJes Sorensen     int ret = 0;
3335f88e1a42SJes Sorensen 
3336f88e1a42SJes Sorensen     /* Find driver and parse its options */
3337f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3338f88e1a42SJes Sorensen     if (!drv) {
333971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3340d92ada22SLuiz Capitulino         return;
3341f88e1a42SJes Sorensen     }
3342f88e1a42SJes Sorensen 
3343b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3344f88e1a42SJes Sorensen     if (!proto_drv) {
3345d92ada22SLuiz Capitulino         return;
3346f88e1a42SJes Sorensen     }
3347f88e1a42SJes Sorensen 
3348c6149724SMax Reitz     if (!drv->create_opts) {
3349c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3350c6149724SMax Reitz                    drv->format_name);
3351c6149724SMax Reitz         return;
3352c6149724SMax Reitz     }
3353c6149724SMax Reitz 
3354c6149724SMax Reitz     if (!proto_drv->create_opts) {
3355c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3356c6149724SMax Reitz                    proto_drv->format_name);
3357c6149724SMax Reitz         return;
3358c6149724SMax Reitz     }
3359c6149724SMax Reitz 
3360c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3361c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3362f88e1a42SJes Sorensen 
3363f88e1a42SJes Sorensen     /* Create parameter list with default values */
336483d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
336539101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3366f88e1a42SJes Sorensen 
3367f88e1a42SJes Sorensen     /* Parse -o options */
3368f88e1a42SJes Sorensen     if (options) {
3369dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3370dc523cd3SMarkus Armbruster         if (local_err) {
3371dc523cd3SMarkus Armbruster             error_report_err(local_err);
3372dc523cd3SMarkus Armbruster             local_err = NULL;
337383d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3374f88e1a42SJes Sorensen             goto out;
3375f88e1a42SJes Sorensen         }
3376f88e1a42SJes Sorensen     }
3377f88e1a42SJes Sorensen 
3378f88e1a42SJes Sorensen     if (base_filename) {
3379f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
33806be4194bSMarkus Armbruster         if (local_err) {
338171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
338271c79813SLuiz Capitulino                        fmt);
3383f88e1a42SJes Sorensen             goto out;
3384f88e1a42SJes Sorensen         }
3385f88e1a42SJes Sorensen     }
3386f88e1a42SJes Sorensen 
3387f88e1a42SJes Sorensen     if (base_fmt) {
3388f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
33896be4194bSMarkus Armbruster         if (local_err) {
339071c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
339171c79813SLuiz Capitulino                              "format '%s'", fmt);
3392f88e1a42SJes Sorensen             goto out;
3393f88e1a42SJes Sorensen         }
3394f88e1a42SJes Sorensen     }
3395f88e1a42SJes Sorensen 
339683d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
339783d0521aSChunyan Liu     if (backing_file) {
339883d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
339971c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
340071c79813SLuiz Capitulino                              "same filename as the backing file");
3401792da93aSJes Sorensen             goto out;
3402792da93aSJes Sorensen         }
3403792da93aSJes Sorensen     }
3404792da93aSJes Sorensen 
340583d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3406f88e1a42SJes Sorensen 
3407f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3408f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
340983d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
341083d0521aSChunyan Liu     if (size == -1) {
341183d0521aSChunyan Liu         if (backing_file) {
341266f6b814SMax Reitz             BlockDriverState *bs;
341329168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
341452bf1e72SMarkus Armbruster             int64_t size;
341563090dacSPaolo Bonzini             int back_flags;
3416e6641719SMax Reitz             QDict *backing_options = NULL;
341763090dacSPaolo Bonzini 
341829168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
341929168018SMax Reitz                                                          full_backing, PATH_MAX,
342029168018SMax Reitz                                                          &local_err);
342129168018SMax Reitz             if (local_err) {
342229168018SMax Reitz                 g_free(full_backing);
342329168018SMax Reitz                 goto out;
342429168018SMax Reitz             }
342529168018SMax Reitz 
342663090dacSPaolo Bonzini             /* backing files always opened read-only */
342761de4c68SKevin Wolf             back_flags = flags;
3428bfd18d1eSKevin Wolf             back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3429f88e1a42SJes Sorensen 
3430e6641719SMax Reitz             if (backing_fmt) {
3431e6641719SMax Reitz                 backing_options = qdict_new();
3432e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3433e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3434e6641719SMax Reitz             }
3435e6641719SMax Reitz 
34365b363937SMax Reitz             bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
34375b363937SMax Reitz                            &local_err);
343829168018SMax Reitz             g_free(full_backing);
34395b363937SMax Reitz             if (!bs) {
3440f88e1a42SJes Sorensen                 goto out;
3441f88e1a42SJes Sorensen             }
344252bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
344352bf1e72SMarkus Armbruster             if (size < 0) {
344452bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
344552bf1e72SMarkus Armbruster                                  backing_file);
344652bf1e72SMarkus Armbruster                 bdrv_unref(bs);
344752bf1e72SMarkus Armbruster                 goto out;
344852bf1e72SMarkus Armbruster             }
3449f88e1a42SJes Sorensen 
345039101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
345166f6b814SMax Reitz 
345266f6b814SMax Reitz             bdrv_unref(bs);
3453f88e1a42SJes Sorensen         } else {
345471c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3455f88e1a42SJes Sorensen             goto out;
3456f88e1a42SJes Sorensen         }
3457f88e1a42SJes Sorensen     }
3458f88e1a42SJes Sorensen 
3459f382d43aSMiroslav Rezanina     if (!quiet) {
3460f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
346143c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3462f88e1a42SJes Sorensen         puts("");
3463f382d43aSMiroslav Rezanina     }
346483d0521aSChunyan Liu 
3465c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
346683d0521aSChunyan Liu 
3467cc84d90fSMax Reitz     if (ret == -EFBIG) {
3468cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3469cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3470cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3471f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
347283d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3473f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3474f3f4d2c0SKevin Wolf         }
3475cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3476cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3477cc84d90fSMax Reitz         error_free(local_err);
3478cc84d90fSMax Reitz         local_err = NULL;
3479f88e1a42SJes Sorensen     }
3480f88e1a42SJes Sorensen 
3481f88e1a42SJes Sorensen out:
348283d0521aSChunyan Liu     qemu_opts_del(opts);
348383d0521aSChunyan Liu     qemu_opts_free(create_opts);
3484cc84d90fSMax Reitz     error_propagate(errp, local_err);
3485cc84d90fSMax Reitz }
348685d126f3SStefan Hajnoczi 
348785d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
348885d126f3SStefan Hajnoczi {
3489dcd04228SStefan Hajnoczi     return bs->aio_context;
3490dcd04228SStefan Hajnoczi }
3491dcd04228SStefan Hajnoczi 
3492e8a095daSStefan Hajnoczi static void bdrv_do_remove_aio_context_notifier(BdrvAioNotifier *ban)
3493e8a095daSStefan Hajnoczi {
3494e8a095daSStefan Hajnoczi     QLIST_REMOVE(ban, list);
3495e8a095daSStefan Hajnoczi     g_free(ban);
3496e8a095daSStefan Hajnoczi }
3497e8a095daSStefan Hajnoczi 
3498dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3499dcd04228SStefan Hajnoczi {
3500e8a095daSStefan Hajnoczi     BdrvAioNotifier *baf, *baf_tmp;
3501b97511c7SMax Reitz     BdrvChild *child;
350233384421SMax Reitz 
3503dcd04228SStefan Hajnoczi     if (!bs->drv) {
3504dcd04228SStefan Hajnoczi         return;
3505dcd04228SStefan Hajnoczi     }
3506dcd04228SStefan Hajnoczi 
3507e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
3508e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
3509e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(baf, &bs->aio_notifiers, list, baf_tmp) {
3510e8a095daSStefan Hajnoczi         if (baf->deleted) {
3511e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(baf);
3512e8a095daSStefan Hajnoczi         } else {
351333384421SMax Reitz             baf->detach_aio_context(baf->opaque);
351433384421SMax Reitz         }
3515e8a095daSStefan Hajnoczi     }
3516e8a095daSStefan Hajnoczi     /* Never mind iterating again to check for ->deleted.  bdrv_close() will
3517e8a095daSStefan Hajnoczi      * remove remaining aio notifiers if we aren't called again.
3518e8a095daSStefan Hajnoczi      */
3519e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
352033384421SMax Reitz 
3521dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3522dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3523dcd04228SStefan Hajnoczi     }
3524b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3525b97511c7SMax Reitz         bdrv_detach_aio_context(child->bs);
3526dcd04228SStefan Hajnoczi     }
3527dcd04228SStefan Hajnoczi 
3528dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3529dcd04228SStefan Hajnoczi }
3530dcd04228SStefan Hajnoczi 
3531dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3532dcd04228SStefan Hajnoczi                              AioContext *new_context)
3533dcd04228SStefan Hajnoczi {
3534e8a095daSStefan Hajnoczi     BdrvAioNotifier *ban, *ban_tmp;
3535b97511c7SMax Reitz     BdrvChild *child;
353633384421SMax Reitz 
3537dcd04228SStefan Hajnoczi     if (!bs->drv) {
3538dcd04228SStefan Hajnoczi         return;
3539dcd04228SStefan Hajnoczi     }
3540dcd04228SStefan Hajnoczi 
3541dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3542dcd04228SStefan Hajnoczi 
3543b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3544b97511c7SMax Reitz         bdrv_attach_aio_context(child->bs, new_context);
3545dcd04228SStefan Hajnoczi     }
3546dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3547dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3548dcd04228SStefan Hajnoczi     }
354933384421SMax Reitz 
3550e8a095daSStefan Hajnoczi     assert(!bs->walking_aio_notifiers);
3551e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = true;
3552e8a095daSStefan Hajnoczi     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_tmp) {
3553e8a095daSStefan Hajnoczi         if (ban->deleted) {
3554e8a095daSStefan Hajnoczi             bdrv_do_remove_aio_context_notifier(ban);
3555e8a095daSStefan Hajnoczi         } else {
355633384421SMax Reitz             ban->attached_aio_context(new_context, ban->opaque);
355733384421SMax Reitz         }
3558dcd04228SStefan Hajnoczi     }
3559e8a095daSStefan Hajnoczi     bs->walking_aio_notifiers = false;
3560e8a095daSStefan Hajnoczi }
3561dcd04228SStefan Hajnoczi 
3562dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3563dcd04228SStefan Hajnoczi {
356453ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3565dcd04228SStefan Hajnoczi 
3566dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3567dcd04228SStefan Hajnoczi 
3568dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3569dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3570dcd04228SStefan Hajnoczi      */
3571dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3572dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3573dcd04228SStefan Hajnoczi     aio_context_release(new_context);
357485d126f3SStefan Hajnoczi }
3575d616b224SStefan Hajnoczi 
357633384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
357733384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
357833384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
357933384421SMax Reitz {
358033384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
358133384421SMax Reitz     *ban = (BdrvAioNotifier){
358233384421SMax Reitz         .attached_aio_context = attached_aio_context,
358333384421SMax Reitz         .detach_aio_context   = detach_aio_context,
358433384421SMax Reitz         .opaque               = opaque
358533384421SMax Reitz     };
358633384421SMax Reitz 
358733384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
358833384421SMax Reitz }
358933384421SMax Reitz 
359033384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
359133384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
359233384421SMax Reitz                                                                    void *),
359333384421SMax Reitz                                       void (*detach_aio_context)(void *),
359433384421SMax Reitz                                       void *opaque)
359533384421SMax Reitz {
359633384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
359733384421SMax Reitz 
359833384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
359933384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
360033384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
3601e8a095daSStefan Hajnoczi             ban->opaque               == opaque               &&
3602e8a095daSStefan Hajnoczi             ban->deleted              == false)
360333384421SMax Reitz         {
3604e8a095daSStefan Hajnoczi             if (bs->walking_aio_notifiers) {
3605e8a095daSStefan Hajnoczi                 ban->deleted = true;
3606e8a095daSStefan Hajnoczi             } else {
3607e8a095daSStefan Hajnoczi                 bdrv_do_remove_aio_context_notifier(ban);
3608e8a095daSStefan Hajnoczi             }
360933384421SMax Reitz             return;
361033384421SMax Reitz         }
361133384421SMax Reitz     }
361233384421SMax Reitz 
361333384421SMax Reitz     abort();
361433384421SMax Reitz }
361533384421SMax Reitz 
361677485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
36178b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
36186f176b48SMax Reitz {
3619c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
36206f176b48SMax Reitz         return -ENOTSUP;
36216f176b48SMax Reitz     }
36228b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
36236f176b48SMax Reitz }
3624f6186f49SBenoît Canet 
3625b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3626b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3627b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3628b5042a36SBenoît Canet  * node graph.
3629212a5a8fSBenoît Canet  */
3630212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3631212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3632f6186f49SBenoît Canet {
3633b5042a36SBenoît Canet     /* return false if basic checks fails */
3634b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3635b5042a36SBenoît Canet         return false;
3636b5042a36SBenoît Canet     }
3637b5042a36SBenoît Canet 
3638b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3639b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3640b5042a36SBenoît Canet      */
3641b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3642b5042a36SBenoît Canet         return bs == candidate;
3643b5042a36SBenoît Canet     }
3644b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3645b5042a36SBenoît Canet 
3646b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3647b5042a36SBenoît Canet      * the node graph.
3648b5042a36SBenoît Canet      */
3649b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3650212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3651212a5a8fSBenoît Canet     }
3652212a5a8fSBenoît Canet 
3653b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3654b5042a36SBenoît Canet      */
3655b5042a36SBenoît Canet     return false;
3656212a5a8fSBenoît Canet }
3657212a5a8fSBenoît Canet 
3658212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3659212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3660212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3661212a5a8fSBenoît Canet  */
3662212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3663212a5a8fSBenoît Canet {
36647c8eece4SKevin Wolf     BlockDriverState *bs;
366588be7b4bSKevin Wolf     BdrvNextIterator it;
3666212a5a8fSBenoît Canet 
3667212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
366888be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3669212a5a8fSBenoît Canet         bool perm;
3670212a5a8fSBenoît Canet 
3671b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3672e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3673212a5a8fSBenoît Canet 
3674212a5a8fSBenoît Canet         /* candidate is the first non filter */
3675212a5a8fSBenoît Canet         if (perm) {
3676212a5a8fSBenoît Canet             return true;
3677212a5a8fSBenoît Canet         }
3678212a5a8fSBenoît Canet     }
3679212a5a8fSBenoît Canet 
3680212a5a8fSBenoît Canet     return false;
3681f6186f49SBenoît Canet }
368209158f00SBenoît Canet 
3683e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3684e12f3784SWen Congyang                                         const char *node_name, Error **errp)
368509158f00SBenoît Canet {
368609158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
36875a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
36885a7e7a0bSStefan Hajnoczi 
368909158f00SBenoît Canet     if (!to_replace_bs) {
369009158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
369109158f00SBenoît Canet         return NULL;
369209158f00SBenoît Canet     }
369309158f00SBenoît Canet 
36945a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
36955a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
36965a7e7a0bSStefan Hajnoczi 
369709158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
36985a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
36995a7e7a0bSStefan Hajnoczi         goto out;
370009158f00SBenoît Canet     }
370109158f00SBenoît Canet 
370209158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
370309158f00SBenoît Canet      * most non filter in order to prevent data corruption.
370409158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
370509158f00SBenoît Canet      * blocked by the backing blockers.
370609158f00SBenoît Canet      */
3707e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
370809158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
37095a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
37105a7e7a0bSStefan Hajnoczi         goto out;
371109158f00SBenoît Canet     }
371209158f00SBenoît Canet 
37135a7e7a0bSStefan Hajnoczi out:
37145a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
371509158f00SBenoît Canet     return to_replace_bs;
371609158f00SBenoît Canet }
3717448ad91dSMing Lei 
371891af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
371991af7014SMax Reitz {
372091af7014SMax Reitz     const QDictEntry *entry;
37219e700c1aSKevin Wolf     QemuOptDesc *desc;
3722260fecf1SKevin Wolf     BdrvChild *child;
372391af7014SMax Reitz     bool found_any = false;
3724260fecf1SKevin Wolf     const char *p;
372591af7014SMax Reitz 
372691af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
372791af7014SMax Reitz          entry = qdict_next(bs->options, entry))
372891af7014SMax Reitz     {
3729260fecf1SKevin Wolf         /* Exclude options for children */
3730260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3731260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3732260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3733260fecf1SKevin Wolf             {
3734260fecf1SKevin Wolf                 break;
3735260fecf1SKevin Wolf             }
3736260fecf1SKevin Wolf         }
3737260fecf1SKevin Wolf         if (child) {
37389e700c1aSKevin Wolf             continue;
37399e700c1aSKevin Wolf         }
37409e700c1aSKevin Wolf 
37419e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
37429e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
37439e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
37449e700c1aSKevin Wolf                 break;
37459e700c1aSKevin Wolf             }
37469e700c1aSKevin Wolf         }
37479e700c1aSKevin Wolf         if (desc->name) {
37489e700c1aSKevin Wolf             continue;
37499e700c1aSKevin Wolf         }
37509e700c1aSKevin Wolf 
375191af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
375291af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
375391af7014SMax Reitz         found_any = true;
375491af7014SMax Reitz     }
375591af7014SMax Reitz 
375691af7014SMax Reitz     return found_any;
375791af7014SMax Reitz }
375891af7014SMax Reitz 
375991af7014SMax Reitz /* Updates the following BDS fields:
376091af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
376191af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
376291af7014SMax Reitz  *                    other options; so reading and writing must return the same
376391af7014SMax Reitz  *                    results, but caching etc. may be different)
376491af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
376591af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
376691af7014SMax Reitz  *                       equalling the given one
376791af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
376891af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
376991af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
377091af7014SMax Reitz  */
377191af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
377291af7014SMax Reitz {
377391af7014SMax Reitz     BlockDriver *drv = bs->drv;
377491af7014SMax Reitz     QDict *opts;
377591af7014SMax Reitz 
377691af7014SMax Reitz     if (!drv) {
377791af7014SMax Reitz         return;
377891af7014SMax Reitz     }
377991af7014SMax Reitz 
378091af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
378191af7014SMax Reitz      * refresh that first */
378291af7014SMax Reitz     if (bs->file) {
37839a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
378491af7014SMax Reitz     }
378591af7014SMax Reitz 
378691af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
378791af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
378891af7014SMax Reitz          * information before refreshing it */
378991af7014SMax Reitz         bs->exact_filename[0] = '\0';
379091af7014SMax Reitz         if (bs->full_open_options) {
379191af7014SMax Reitz             QDECREF(bs->full_open_options);
379291af7014SMax Reitz             bs->full_open_options = NULL;
379391af7014SMax Reitz         }
379491af7014SMax Reitz 
37954cdd01d3SKevin Wolf         opts = qdict_new();
37964cdd01d3SKevin Wolf         append_open_options(opts, bs);
37974cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
37984cdd01d3SKevin Wolf         QDECREF(opts);
379991af7014SMax Reitz     } else if (bs->file) {
380091af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
380191af7014SMax Reitz         bool has_open_options;
380291af7014SMax Reitz 
380391af7014SMax Reitz         bs->exact_filename[0] = '\0';
380491af7014SMax Reitz         if (bs->full_open_options) {
380591af7014SMax Reitz             QDECREF(bs->full_open_options);
380691af7014SMax Reitz             bs->full_open_options = NULL;
380791af7014SMax Reitz         }
380891af7014SMax Reitz 
380991af7014SMax Reitz         opts = qdict_new();
381091af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
381191af7014SMax Reitz 
381291af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
381391af7014SMax Reitz          * the underlying file should suffice for this one as well */
38149a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
38159a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
381691af7014SMax Reitz         }
381791af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
381891af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
381991af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
382091af7014SMax Reitz          * contain a representation of the filename, therefore the following
382191af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
38229a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
382391af7014SMax Reitz             qdict_put_obj(opts, "driver",
382491af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
38259a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
38269a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
38279a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
382891af7014SMax Reitz 
382991af7014SMax Reitz             bs->full_open_options = opts;
383091af7014SMax Reitz         } else {
383191af7014SMax Reitz             QDECREF(opts);
383291af7014SMax Reitz         }
383391af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
383491af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
383591af7014SMax Reitz          * so the full options QDict should be equal to the options given
383691af7014SMax Reitz          * specifically for this block device when it was opened (plus the
383791af7014SMax Reitz          * driver specification).
383891af7014SMax Reitz          * Because those options don't change, there is no need to update
383991af7014SMax Reitz          * full_open_options when it's already set. */
384091af7014SMax Reitz 
384191af7014SMax Reitz         opts = qdict_new();
384291af7014SMax Reitz         append_open_options(opts, bs);
384391af7014SMax Reitz         qdict_put_obj(opts, "driver",
384491af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
384591af7014SMax Reitz 
384691af7014SMax Reitz         if (bs->exact_filename[0]) {
384791af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
384891af7014SMax Reitz              * require this filename to be parsed), but we have to find some
384991af7014SMax Reitz              * default solution here, so just include it. If some block driver
385091af7014SMax Reitz              * does not support pure options without any filename at all or
385191af7014SMax Reitz              * needs some special format of the options QDict, it needs to
385291af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
385391af7014SMax Reitz              */
385491af7014SMax Reitz             qdict_put_obj(opts, "filename",
385591af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
385691af7014SMax Reitz         }
385791af7014SMax Reitz 
385891af7014SMax Reitz         bs->full_open_options = opts;
385991af7014SMax Reitz     }
386091af7014SMax Reitz 
386191af7014SMax Reitz     if (bs->exact_filename[0]) {
386291af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
386391af7014SMax Reitz     } else if (bs->full_open_options) {
386491af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
386591af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
386691af7014SMax Reitz                  qstring_get_str(json));
386791af7014SMax Reitz         QDECREF(json);
386891af7014SMax Reitz     }
386991af7014SMax Reitz }
3870e06018adSWen Congyang 
3871e06018adSWen Congyang /*
3872e06018adSWen Congyang  * Hot add/remove a BDS's child. So the user can take a child offline when
3873e06018adSWen Congyang  * it is broken and take a new child online
3874e06018adSWen Congyang  */
3875e06018adSWen Congyang void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
3876e06018adSWen Congyang                     Error **errp)
3877e06018adSWen Congyang {
3878e06018adSWen Congyang 
3879e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
3880e06018adSWen Congyang         error_setg(errp, "The node %s does not support adding a child",
3881e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
3882e06018adSWen Congyang         return;
3883e06018adSWen Congyang     }
3884e06018adSWen Congyang 
3885e06018adSWen Congyang     if (!QLIST_EMPTY(&child_bs->parents)) {
3886e06018adSWen Congyang         error_setg(errp, "The node %s already has a parent",
3887e06018adSWen Congyang                    child_bs->node_name);
3888e06018adSWen Congyang         return;
3889e06018adSWen Congyang     }
3890e06018adSWen Congyang 
3891e06018adSWen Congyang     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
3892e06018adSWen Congyang }
3893e06018adSWen Congyang 
3894e06018adSWen Congyang void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
3895e06018adSWen Congyang {
3896e06018adSWen Congyang     BdrvChild *tmp;
3897e06018adSWen Congyang 
3898e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
3899e06018adSWen Congyang         error_setg(errp, "The node %s does not support removing a child",
3900e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
3901e06018adSWen Congyang         return;
3902e06018adSWen Congyang     }
3903e06018adSWen Congyang 
3904e06018adSWen Congyang     QLIST_FOREACH(tmp, &parent_bs->children, next) {
3905e06018adSWen Congyang         if (tmp == child) {
3906e06018adSWen Congyang             break;
3907e06018adSWen Congyang         }
3908e06018adSWen Congyang     }
3909e06018adSWen Congyang 
3910e06018adSWen Congyang     if (!tmp) {
3911e06018adSWen Congyang         error_setg(errp, "The node %s does not have a child named %s",
3912e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs),
3913e06018adSWen Congyang                    bdrv_get_device_or_node_name(child->bs));
3914e06018adSWen Congyang         return;
3915e06018adSWen Congyang     }
3916e06018adSWen Congyang 
3917e06018adSWen Congyang     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
3918e06018adSWen Congyang }
3919