xref: /openbmc/qemu/block.c (revision a1a2af075647bb61e1435ce4c78d99e3f36d928b)
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);
30484d18f06SMarkus Armbruster     if (local_err) {
305cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
306cc84d90fSMax Reitz     }
307cc84d90fSMax Reitz     cco->ret = ret;
3085b7e1542SZhi Yong Wu }
3095b7e1542SZhi Yong Wu 
3100e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
31183d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
312ea2384d3Sbellard {
3135b7e1542SZhi Yong Wu     int ret;
3140e7e1989SKevin Wolf 
3155b7e1542SZhi Yong Wu     Coroutine *co;
3165b7e1542SZhi Yong Wu     CreateCo cco = {
3175b7e1542SZhi Yong Wu         .drv = drv,
3185b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
31983d0521aSChunyan Liu         .opts = opts,
3205b7e1542SZhi Yong Wu         .ret = NOT_DONE,
321cc84d90fSMax Reitz         .err = NULL,
3225b7e1542SZhi Yong Wu     };
3235b7e1542SZhi Yong Wu 
324c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
325cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
32680168bffSLuiz Capitulino         ret = -ENOTSUP;
32780168bffSLuiz Capitulino         goto out;
3285b7e1542SZhi Yong Wu     }
3295b7e1542SZhi Yong Wu 
3305b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3315b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3325b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3335b7e1542SZhi Yong Wu     } else {
3345b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3355b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3365b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
337b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3385b7e1542SZhi Yong Wu         }
3395b7e1542SZhi Yong Wu     }
3405b7e1542SZhi Yong Wu 
3415b7e1542SZhi Yong Wu     ret = cco.ret;
342cc84d90fSMax Reitz     if (ret < 0) {
34384d18f06SMarkus Armbruster         if (cco.err) {
344cc84d90fSMax Reitz             error_propagate(errp, cco.err);
345cc84d90fSMax Reitz         } else {
346cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
347cc84d90fSMax Reitz         }
348cc84d90fSMax Reitz     }
3495b7e1542SZhi Yong Wu 
35080168bffSLuiz Capitulino out:
35180168bffSLuiz Capitulino     g_free(cco.filename);
3525b7e1542SZhi Yong Wu     return ret;
353ea2384d3Sbellard }
354ea2384d3Sbellard 
355c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
35684a12e66SChristoph Hellwig {
35784a12e66SChristoph Hellwig     BlockDriver *drv;
358cc84d90fSMax Reitz     Error *local_err = NULL;
359cc84d90fSMax Reitz     int ret;
36084a12e66SChristoph Hellwig 
361b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
36284a12e66SChristoph Hellwig     if (drv == NULL) {
36316905d71SStefan Hajnoczi         return -ENOENT;
36484a12e66SChristoph Hellwig     }
36584a12e66SChristoph Hellwig 
366c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
36784d18f06SMarkus Armbruster     if (local_err) {
368cc84d90fSMax Reitz         error_propagate(errp, local_err);
369cc84d90fSMax Reitz     }
370cc84d90fSMax Reitz     return ret;
37184a12e66SChristoph Hellwig }
37284a12e66SChristoph Hellwig 
373892b7de8SEkaterina Tumanova /**
374892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
375892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
376892b7de8SEkaterina Tumanova  * On failure return -errno.
377892b7de8SEkaterina Tumanova  * @bs must not be empty.
378892b7de8SEkaterina Tumanova  */
379892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
380892b7de8SEkaterina Tumanova {
381892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
382892b7de8SEkaterina Tumanova 
383892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
384892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
385892b7de8SEkaterina Tumanova     }
386892b7de8SEkaterina Tumanova 
387892b7de8SEkaterina Tumanova     return -ENOTSUP;
388892b7de8SEkaterina Tumanova }
389892b7de8SEkaterina Tumanova 
390892b7de8SEkaterina Tumanova /**
391892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
392892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
393892b7de8SEkaterina Tumanova  * On failure return -errno.
394892b7de8SEkaterina Tumanova  * @bs must not be empty.
395892b7de8SEkaterina Tumanova  */
396892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
397892b7de8SEkaterina Tumanova {
398892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
399892b7de8SEkaterina Tumanova 
400892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
401892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
402892b7de8SEkaterina Tumanova     }
403892b7de8SEkaterina Tumanova 
404892b7de8SEkaterina Tumanova     return -ENOTSUP;
405892b7de8SEkaterina Tumanova }
406892b7de8SEkaterina Tumanova 
407eba25057SJim Meyering /*
408eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
409eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
410eba25057SJim Meyering  */
411eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
412eba25057SJim Meyering {
413d5249393Sbellard #ifdef _WIN32
4143b9f94e1Sbellard     char temp_dir[MAX_PATH];
415eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
416eba25057SJim Meyering        have length MAX_PATH or greater.  */
417eba25057SJim Meyering     assert(size >= MAX_PATH);
418eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
419eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
420eba25057SJim Meyering             ? 0 : -GetLastError());
421d5249393Sbellard #else
422ea2384d3Sbellard     int fd;
4237ccfb2ebSblueswir1     const char *tmpdir;
4240badc1eeSaurel32     tmpdir = getenv("TMPDIR");
42569bef793SAmit Shah     if (!tmpdir) {
42669bef793SAmit Shah         tmpdir = "/var/tmp";
42769bef793SAmit Shah     }
428eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
429eba25057SJim Meyering         return -EOVERFLOW;
430ea2384d3Sbellard     }
431eba25057SJim Meyering     fd = mkstemp(filename);
432fe235a06SDunrong Huang     if (fd < 0) {
433fe235a06SDunrong Huang         return -errno;
434fe235a06SDunrong Huang     }
435fe235a06SDunrong Huang     if (close(fd) != 0) {
436fe235a06SDunrong Huang         unlink(filename);
437eba25057SJim Meyering         return -errno;
438eba25057SJim Meyering     }
439eba25057SJim Meyering     return 0;
440d5249393Sbellard #endif
441eba25057SJim Meyering }
442ea2384d3Sbellard 
443f3a5d3f8SChristoph Hellwig /*
444f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
445f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
446f3a5d3f8SChristoph Hellwig  */
447f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
448f3a5d3f8SChristoph Hellwig {
449508c7cb3SChristoph Hellwig     int score_max = 0, score;
450508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
451f3a5d3f8SChristoph Hellwig 
4528a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
453508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
454508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
455508c7cb3SChristoph Hellwig             if (score > score_max) {
456508c7cb3SChristoph Hellwig                 score_max = score;
457508c7cb3SChristoph Hellwig                 drv = d;
458f3a5d3f8SChristoph Hellwig             }
459508c7cb3SChristoph Hellwig         }
460f3a5d3f8SChristoph Hellwig     }
461f3a5d3f8SChristoph Hellwig 
462508c7cb3SChristoph Hellwig     return drv;
463f3a5d3f8SChristoph Hellwig }
464f3a5d3f8SChristoph Hellwig 
46598289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
466b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
467b65a5e12SMax Reitz                                 Error **errp)
46884a12e66SChristoph Hellwig {
46984a12e66SChristoph Hellwig     BlockDriver *drv1;
47084a12e66SChristoph Hellwig     char protocol[128];
47184a12e66SChristoph Hellwig     int len;
47284a12e66SChristoph Hellwig     const char *p;
47384a12e66SChristoph Hellwig 
47466f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
47566f82ceeSKevin Wolf 
47639508e7aSChristoph Hellwig     /*
47739508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
47839508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
47939508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
48039508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
48139508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
48239508e7aSChristoph Hellwig      */
48384a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
48439508e7aSChristoph Hellwig     if (drv1) {
48584a12e66SChristoph Hellwig         return drv1;
48684a12e66SChristoph Hellwig     }
48739508e7aSChristoph Hellwig 
48898289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
489ef810437SMax Reitz         return &bdrv_file;
49039508e7aSChristoph Hellwig     }
49198289620SKevin Wolf 
4929e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4939e0b22f4SStefan Hajnoczi     assert(p != NULL);
49484a12e66SChristoph Hellwig     len = p - filename;
49584a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
49684a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
49784a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
49884a12e66SChristoph Hellwig     protocol[len] = '\0';
49984a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
50084a12e66SChristoph Hellwig         if (drv1->protocol_name &&
50184a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
50284a12e66SChristoph Hellwig             return drv1;
50384a12e66SChristoph Hellwig         }
50484a12e66SChristoph Hellwig     }
505b65a5e12SMax Reitz 
506b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
50784a12e66SChristoph Hellwig     return NULL;
50884a12e66SChristoph Hellwig }
50984a12e66SChristoph Hellwig 
510c6684249SMarkus Armbruster /*
511c6684249SMarkus Armbruster  * Guess image format by probing its contents.
512c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
513c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
514c6684249SMarkus Armbruster  *
515c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5167cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5177cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
518c6684249SMarkus Armbruster  * @filename    is its filename.
519c6684249SMarkus Armbruster  *
520c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
521c6684249SMarkus Armbruster  * probing score.
522c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
523c6684249SMarkus Armbruster  */
52438f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
525c6684249SMarkus Armbruster                             const char *filename)
526c6684249SMarkus Armbruster {
527c6684249SMarkus Armbruster     int score_max = 0, score;
528c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
529c6684249SMarkus Armbruster 
530c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
531c6684249SMarkus Armbruster         if (d->bdrv_probe) {
532c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
533c6684249SMarkus Armbruster             if (score > score_max) {
534c6684249SMarkus Armbruster                 score_max = score;
535c6684249SMarkus Armbruster                 drv = d;
536c6684249SMarkus Armbruster             }
537c6684249SMarkus Armbruster         }
538c6684249SMarkus Armbruster     }
539c6684249SMarkus Armbruster 
540c6684249SMarkus Armbruster     return drv;
541c6684249SMarkus Armbruster }
542c6684249SMarkus Armbruster 
543f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
54434b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
545ea2384d3Sbellard {
546c6684249SMarkus Armbruster     BlockDriver *drv;
5477cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
548f500a6d3SKevin Wolf     int ret = 0;
549f8ea0b00SNicholas Bellinger 
55008a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
551b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
552ef810437SMax Reitz         *pdrv = &bdrv_raw;
553c98ac35dSStefan Weil         return ret;
5541a396859SNicholas A. Bellinger     }
555f8ea0b00SNicholas Bellinger 
55683f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
557ea2384d3Sbellard     if (ret < 0) {
55834b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
55934b5d2c6SMax Reitz                          "format");
560c98ac35dSStefan Weil         *pdrv = NULL;
561c98ac35dSStefan Weil         return ret;
562ea2384d3Sbellard     }
563ea2384d3Sbellard 
564c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
565c98ac35dSStefan Weil     if (!drv) {
56634b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
56734b5d2c6SMax Reitz                    "driver found");
568c98ac35dSStefan Weil         ret = -ENOENT;
569c98ac35dSStefan Weil     }
570c98ac35dSStefan Weil     *pdrv = drv;
571c98ac35dSStefan Weil     return ret;
572ea2384d3Sbellard }
573ea2384d3Sbellard 
57451762288SStefan Hajnoczi /**
57551762288SStefan Hajnoczi  * Set the current 'total_sectors' value
57665a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
57751762288SStefan Hajnoczi  */
57851762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
57951762288SStefan Hajnoczi {
58051762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
58151762288SStefan Hajnoczi 
582396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
583b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
584396759adSNicholas Bellinger         return 0;
585396759adSNicholas Bellinger 
58651762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
58751762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
58851762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
58951762288SStefan Hajnoczi         if (length < 0) {
59051762288SStefan Hajnoczi             return length;
59151762288SStefan Hajnoczi         }
5927e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
59351762288SStefan Hajnoczi     }
59451762288SStefan Hajnoczi 
59551762288SStefan Hajnoczi     bs->total_sectors = hint;
59651762288SStefan Hajnoczi     return 0;
59751762288SStefan Hajnoczi }
59851762288SStefan Hajnoczi 
599c3993cdcSStefan Hajnoczi /**
600cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
601cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
602cddff5baSKevin Wolf  */
603cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
604cddff5baSKevin Wolf                               QDict *old_options)
605cddff5baSKevin Wolf {
606cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
607cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
608cddff5baSKevin Wolf     } else {
609cddff5baSKevin Wolf         qdict_join(options, old_options, false);
610cddff5baSKevin Wolf     }
611cddff5baSKevin Wolf }
612cddff5baSKevin Wolf 
613cddff5baSKevin Wolf /**
6149e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6159e8f1835SPaolo Bonzini  *
6169e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6179e8f1835SPaolo Bonzini  */
6189e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6199e8f1835SPaolo Bonzini {
6209e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6219e8f1835SPaolo Bonzini 
6229e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6239e8f1835SPaolo Bonzini         /* do nothing */
6249e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6259e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6269e8f1835SPaolo Bonzini     } else {
6279e8f1835SPaolo Bonzini         return -1;
6289e8f1835SPaolo Bonzini     }
6299e8f1835SPaolo Bonzini 
6309e8f1835SPaolo Bonzini     return 0;
6319e8f1835SPaolo Bonzini }
6329e8f1835SPaolo Bonzini 
6339e8f1835SPaolo Bonzini /**
634c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
635c3993cdcSStefan Hajnoczi  *
636c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
637c3993cdcSStefan Hajnoczi  */
63853e8ae01SKevin Wolf int bdrv_parse_cache_mode(const char *mode, int *flags, bool *writethrough)
639c3993cdcSStefan Hajnoczi {
640c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
641c3993cdcSStefan Hajnoczi 
642c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
64353e8ae01SKevin Wolf         *writethrough = false;
64453e8ae01SKevin Wolf         *flags |= BDRV_O_NOCACHE;
64592196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
64653e8ae01SKevin Wolf         *writethrough = true;
64792196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
648c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
64953e8ae01SKevin Wolf         *writethrough = false;
650c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
65153e8ae01SKevin Wolf         *writethrough = false;
652c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
653c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
65453e8ae01SKevin Wolf         *writethrough = true;
655c3993cdcSStefan Hajnoczi     } else {
656c3993cdcSStefan Hajnoczi         return -1;
657c3993cdcSStefan Hajnoczi     }
658c3993cdcSStefan Hajnoczi 
659c3993cdcSStefan Hajnoczi     return 0;
660c3993cdcSStefan Hajnoczi }
661c3993cdcSStefan Hajnoczi 
66220018e12SKevin Wolf static void bdrv_child_cb_drained_begin(BdrvChild *child)
66320018e12SKevin Wolf {
66420018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
66520018e12SKevin Wolf     bdrv_drained_begin(bs);
66620018e12SKevin Wolf }
66720018e12SKevin Wolf 
66820018e12SKevin Wolf static void bdrv_child_cb_drained_end(BdrvChild *child)
66920018e12SKevin Wolf {
67020018e12SKevin Wolf     BlockDriverState *bs = child->opaque;
67120018e12SKevin Wolf     bdrv_drained_end(bs);
67220018e12SKevin Wolf }
67320018e12SKevin Wolf 
6740b50cc88SKevin Wolf /*
67573176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
67673176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
67773176beeSKevin Wolf  * flags like a backing file)
678b1e6fc08SKevin Wolf  */
67973176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
68073176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
681b1e6fc08SKevin Wolf {
68273176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
68373176beeSKevin Wolf 
68473176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
68573176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
68673176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
687b1e6fc08SKevin Wolf }
688b1e6fc08SKevin Wolf 
689b1e6fc08SKevin Wolf /*
6908e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
6918e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
6920b50cc88SKevin Wolf  */
6938e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
6948e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
6950b50cc88SKevin Wolf {
6968e2160e2SKevin Wolf     int flags = parent_flags;
6978e2160e2SKevin Wolf 
6980b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6990b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7000b50cc88SKevin Wolf 
70191a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
70291a097e7SKevin Wolf      * the parent. */
70391a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
70491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
70591a097e7SKevin Wolf 
7060b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
70791a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
70891a097e7SKevin Wolf      * corresponding parent options. */
70991a097e7SKevin Wolf     flags |= BDRV_O_UNMAP;
7100b50cc88SKevin Wolf 
7110b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
712abb06c5aSDaniel P. Berrange     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
713abb06c5aSDaniel P. Berrange                BDRV_O_NO_IO);
7140b50cc88SKevin Wolf 
7158e2160e2SKevin Wolf     *child_flags = flags;
7160b50cc88SKevin Wolf }
7170b50cc88SKevin Wolf 
718f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7198e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
72020018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
72120018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
722f3930ed0SKevin Wolf };
723f3930ed0SKevin Wolf 
724f3930ed0SKevin Wolf /*
7258e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7268e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7278e2160e2SKevin Wolf  * flags for the parent BDS
728f3930ed0SKevin Wolf  */
7298e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7308e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
731f3930ed0SKevin Wolf {
7328e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7338e2160e2SKevin Wolf                                parent_flags, parent_options);
7348e2160e2SKevin Wolf 
735abb06c5aSDaniel P. Berrange     *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
736f3930ed0SKevin Wolf }
737f3930ed0SKevin Wolf 
738f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7398e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
74020018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
74120018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
742f3930ed0SKevin Wolf };
743f3930ed0SKevin Wolf 
744317fc44eSKevin Wolf /*
7458e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7468e2160e2SKevin Wolf  * given options and flags for the parent BDS
747317fc44eSKevin Wolf  */
7488e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7498e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
750317fc44eSKevin Wolf {
7518e2160e2SKevin Wolf     int flags = parent_flags;
7528e2160e2SKevin Wolf 
753b8816a43SKevin Wolf     /* The cache mode is inherited unmodified for backing files; except WCE,
754b8816a43SKevin Wolf      * which is only applied on the top level (BlockBackend) */
75591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
75691a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
75791a097e7SKevin Wolf 
758317fc44eSKevin Wolf     /* backing files always opened read-only */
759317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
760317fc44eSKevin Wolf 
761317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7628bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
763317fc44eSKevin Wolf 
7648e2160e2SKevin Wolf     *child_flags = flags;
765317fc44eSKevin Wolf }
766317fc44eSKevin Wolf 
767f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7688e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
76920018e12SKevin Wolf     .drained_begin   = bdrv_child_cb_drained_begin,
77020018e12SKevin Wolf     .drained_end     = bdrv_child_cb_drained_end,
771f3930ed0SKevin Wolf };
772f3930ed0SKevin Wolf 
7737b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7747b272452SKevin Wolf {
77561de4c68SKevin Wolf     int open_flags = flags;
7767b272452SKevin Wolf 
7777b272452SKevin Wolf     /*
7787b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7797b272452SKevin Wolf      * image.
7807b272452SKevin Wolf      */
78120cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7827b272452SKevin Wolf 
7837b272452SKevin Wolf     /*
7847b272452SKevin Wolf      * Snapshots should be writable.
7857b272452SKevin Wolf      */
7868bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7877b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7887b272452SKevin Wolf     }
7897b272452SKevin Wolf 
7907b272452SKevin Wolf     return open_flags;
7917b272452SKevin Wolf }
7927b272452SKevin Wolf 
79391a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
79491a097e7SKevin Wolf {
79591a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
79691a097e7SKevin Wolf 
79791a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
79891a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
79991a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
80091a097e7SKevin Wolf     }
80191a097e7SKevin Wolf 
80291a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
80391a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
80491a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
80591a097e7SKevin Wolf     }
80691a097e7SKevin Wolf }
80791a097e7SKevin Wolf 
80891a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
80991a097e7SKevin Wolf {
81091a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
81191a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
81291a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
81391a097e7SKevin Wolf     }
81491a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
81591a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
81691a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
81791a097e7SKevin Wolf     }
81891a097e7SKevin Wolf }
81991a097e7SKevin Wolf 
820636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8216913c0c2SBenoît Canet                                   const char *node_name,
8226913c0c2SBenoît Canet                                   Error **errp)
8236913c0c2SBenoît Canet {
82415489c76SJeff Cody     char *gen_node_name = NULL;
8256913c0c2SBenoît Canet 
82615489c76SJeff Cody     if (!node_name) {
82715489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
82815489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
82915489c76SJeff Cody         /*
83015489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
83115489c76SJeff Cody          * generated (generated names use characters not available to the user)
83215489c76SJeff Cody          */
8339aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
834636ea370SKevin Wolf         return;
8356913c0c2SBenoît Canet     }
8366913c0c2SBenoît Canet 
8370c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8387f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8390c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8400c5e94eeSBenoît Canet                    node_name);
84115489c76SJeff Cody         goto out;
8420c5e94eeSBenoît Canet     }
8430c5e94eeSBenoît Canet 
8446913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8456913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8466913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
84715489c76SJeff Cody         goto out;
8486913c0c2SBenoît Canet     }
8496913c0c2SBenoît Canet 
8506913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8516913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8526913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
85315489c76SJeff Cody out:
85415489c76SJeff Cody     g_free(gen_node_name);
8556913c0c2SBenoît Canet }
8566913c0c2SBenoît Canet 
85718edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
85818edf289SKevin Wolf     .name = "bdrv_common",
85918edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
86018edf289SKevin Wolf     .desc = {
86118edf289SKevin Wolf         {
86218edf289SKevin Wolf             .name = "node-name",
86318edf289SKevin Wolf             .type = QEMU_OPT_STRING,
86418edf289SKevin Wolf             .help = "Node name of the block device node",
86518edf289SKevin Wolf         },
86662392ebbSKevin Wolf         {
86762392ebbSKevin Wolf             .name = "driver",
86862392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
86962392ebbSKevin Wolf             .help = "Block driver to use for the node",
87062392ebbSKevin Wolf         },
87191a097e7SKevin Wolf         {
87291a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
87391a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87491a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
87591a097e7SKevin Wolf         },
87691a097e7SKevin Wolf         {
87791a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
87891a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87991a097e7SKevin Wolf             .help = "Ignore flush requests",
88091a097e7SKevin Wolf         },
88118edf289SKevin Wolf         { /* end of list */ }
88218edf289SKevin Wolf     },
88318edf289SKevin Wolf };
88418edf289SKevin Wolf 
885b6ce07aaSKevin Wolf /*
88657915332SKevin Wolf  * Common part for opening disk images and files
887b6ad491aSKevin Wolf  *
888b6ad491aSKevin Wolf  * Removes all processed options from *options.
88957915332SKevin Wolf  */
8909a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
89182dc8b41SKevin Wolf                             QDict *options, Error **errp)
89257915332SKevin Wolf {
89357915332SKevin Wolf     int ret, open_flags;
894035fccdfSKevin Wolf     const char *filename;
89562392ebbSKevin Wolf     const char *driver_name = NULL;
8966913c0c2SBenoît Canet     const char *node_name = NULL;
89718edf289SKevin Wolf     QemuOpts *opts;
89862392ebbSKevin Wolf     BlockDriver *drv;
89934b5d2c6SMax Reitz     Error *local_err = NULL;
90057915332SKevin Wolf 
9016405875cSPaolo Bonzini     assert(bs->file == NULL);
902707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
90357915332SKevin Wolf 
90462392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
90562392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
90662392ebbSKevin Wolf     if (local_err) {
90762392ebbSKevin Wolf         error_propagate(errp, local_err);
90862392ebbSKevin Wolf         ret = -EINVAL;
90962392ebbSKevin Wolf         goto fail_opts;
91062392ebbSKevin Wolf     }
91162392ebbSKevin Wolf 
91262392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
91362392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
91462392ebbSKevin Wolf     assert(drv != NULL);
91562392ebbSKevin Wolf 
91645673671SKevin Wolf     if (file != NULL) {
9179a4f4c31SKevin Wolf         filename = file->bs->filename;
91845673671SKevin Wolf     } else {
91945673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
92045673671SKevin Wolf     }
92145673671SKevin Wolf 
922765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
923765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
924765003dbSKevin Wolf                    drv->format_name);
92518edf289SKevin Wolf         ret = -EINVAL;
92618edf289SKevin Wolf         goto fail_opts;
92718edf289SKevin Wolf     }
92818edf289SKevin Wolf 
92982dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
93082dc8b41SKevin Wolf                            drv->format_name);
93162392ebbSKevin Wolf 
93218edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
933636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9340fb6395cSMarkus Armbruster     if (local_err) {
935636ea370SKevin Wolf         error_propagate(errp, local_err);
93618edf289SKevin Wolf         ret = -EINVAL;
93718edf289SKevin Wolf         goto fail_opts;
9385d186eb0SKevin Wolf     }
9395d186eb0SKevin Wolf 
940c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9410d51b4deSAsias He     bs->zero_beyond_eof = true;
94282dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
943b64ec4e4SFam Zheng 
944b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9458f94a6e4SKevin Wolf         error_setg(errp,
9468f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9478f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9488f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9498f94a6e4SKevin Wolf                    drv->format_name);
95018edf289SKevin Wolf         ret = -ENOTSUP;
95118edf289SKevin Wolf         goto fail_opts;
952b64ec4e4SFam Zheng     }
95357915332SKevin Wolf 
95453fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
95582dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9560ebd24e0SKevin Wolf         if (!bs->read_only) {
95753fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9580ebd24e0SKevin Wolf         } else {
9590ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
96018edf289SKevin Wolf             ret = -EINVAL;
96118edf289SKevin Wolf             goto fail_opts;
9620ebd24e0SKevin Wolf         }
96353fec9d3SStefan Hajnoczi     }
96453fec9d3SStefan Hajnoczi 
965c2ad1b0cSKevin Wolf     if (filename != NULL) {
96657915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
967c2ad1b0cSKevin Wolf     } else {
968c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
969c2ad1b0cSKevin Wolf     }
97091af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97157915332SKevin Wolf 
97257915332SKevin Wolf     bs->drv = drv;
9737267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
97457915332SKevin Wolf 
97591a097e7SKevin Wolf     /* Apply cache mode options */
97691a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
97773ac451fSKevin Wolf 
97866f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
97982dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
98066f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9815d186eb0SKevin Wolf         assert(file == NULL);
982030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
98334b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
984f500a6d3SKevin Wolf     } else {
9852af5ef70SKevin Wolf         if (file == NULL) {
98634b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
98734b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9882af5ef70SKevin Wolf             ret = -EINVAL;
9892af5ef70SKevin Wolf             goto free_and_fail;
9902af5ef70SKevin Wolf         }
991f500a6d3SKevin Wolf         bs->file = file;
99234b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
99366f82ceeSKevin Wolf     }
99466f82ceeSKevin Wolf 
99557915332SKevin Wolf     if (ret < 0) {
99684d18f06SMarkus Armbruster         if (local_err) {
99734b5d2c6SMax Reitz             error_propagate(errp, local_err);
9982fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9992fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
100034b5d2c6SMax Reitz         } else {
100134b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
100234b5d2c6SMax Reitz         }
100357915332SKevin Wolf         goto free_and_fail;
100457915332SKevin Wolf     }
100557915332SKevin Wolf 
100651762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
100751762288SStefan Hajnoczi     if (ret < 0) {
100834b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
100951762288SStefan Hajnoczi         goto free_and_fail;
101057915332SKevin Wolf     }
101151762288SStefan Hajnoczi 
10123baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10133baca891SKevin Wolf     if (local_err) {
10143baca891SKevin Wolf         error_propagate(errp, local_err);
10153baca891SKevin Wolf         ret = -EINVAL;
10163baca891SKevin Wolf         goto free_and_fail;
10173baca891SKevin Wolf     }
10183baca891SKevin Wolf 
1019c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10204196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1021b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
102218edf289SKevin Wolf 
102318edf289SKevin Wolf     qemu_opts_del(opts);
102457915332SKevin Wolf     return 0;
102557915332SKevin Wolf 
102657915332SKevin Wolf free_and_fail:
102766f82ceeSKevin Wolf     bs->file = NULL;
10287267c094SAnthony Liguori     g_free(bs->opaque);
102957915332SKevin Wolf     bs->opaque = NULL;
103057915332SKevin Wolf     bs->drv = NULL;
103118edf289SKevin Wolf fail_opts:
103218edf289SKevin Wolf     qemu_opts_del(opts);
103357915332SKevin Wolf     return ret;
103457915332SKevin Wolf }
103557915332SKevin Wolf 
10365e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10375e5c4f63SKevin Wolf {
10385e5c4f63SKevin Wolf     QObject *options_obj;
10395e5c4f63SKevin Wolf     QDict *options;
10405e5c4f63SKevin Wolf     int ret;
10415e5c4f63SKevin Wolf 
10425e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10435e5c4f63SKevin Wolf     assert(ret);
10445e5c4f63SKevin Wolf 
10455e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10465e5c4f63SKevin Wolf     if (!options_obj) {
10475e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10485e5c4f63SKevin Wolf         return NULL;
10495e5c4f63SKevin Wolf     }
10505e5c4f63SKevin Wolf 
10515e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10525e5c4f63SKevin Wolf         qobject_decref(options_obj);
10535e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10545e5c4f63SKevin Wolf         return NULL;
10555e5c4f63SKevin Wolf     }
10565e5c4f63SKevin Wolf 
10575e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10585e5c4f63SKevin Wolf     qdict_flatten(options);
10595e5c4f63SKevin Wolf 
10605e5c4f63SKevin Wolf     return options;
10615e5c4f63SKevin Wolf }
10625e5c4f63SKevin Wolf 
1063de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1064de3b53f0SKevin Wolf                                 Error **errp)
1065de3b53f0SKevin Wolf {
1066de3b53f0SKevin Wolf     QDict *json_options;
1067de3b53f0SKevin Wolf     Error *local_err = NULL;
1068de3b53f0SKevin Wolf 
1069de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1070de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1071de3b53f0SKevin Wolf         return;
1072de3b53f0SKevin Wolf     }
1073de3b53f0SKevin Wolf 
1074de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1075de3b53f0SKevin Wolf     if (local_err) {
1076de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1077de3b53f0SKevin Wolf         return;
1078de3b53f0SKevin Wolf     }
1079de3b53f0SKevin Wolf 
1080de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1081de3b53f0SKevin Wolf      * specified directly */
1082de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1083de3b53f0SKevin Wolf     QDECREF(json_options);
1084de3b53f0SKevin Wolf     *pfilename = NULL;
1085de3b53f0SKevin Wolf }
1086de3b53f0SKevin Wolf 
108757915332SKevin Wolf /*
1088f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1089f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
109053a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
109153a29513SMax Reitz  * block driver has been specified explicitly.
1092f54120ffSKevin Wolf  */
1093de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1094053e1578SMax Reitz                              int *flags, Error **errp)
1095f54120ffSKevin Wolf {
1096f54120ffSKevin Wolf     const char *drvname;
109753a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1098f54120ffSKevin Wolf     bool parse_filename = false;
1099053e1578SMax Reitz     BlockDriver *drv = NULL;
1100f54120ffSKevin Wolf     Error *local_err = NULL;
1101f54120ffSKevin Wolf 
110253a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1103053e1578SMax Reitz     if (drvname) {
1104053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1105053e1578SMax Reitz         if (!drv) {
1106053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1107053e1578SMax Reitz             return -ENOENT;
1108053e1578SMax Reitz         }
110953a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
111053a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1111053e1578SMax Reitz         protocol = drv->bdrv_file_open;
111253a29513SMax Reitz     }
111353a29513SMax Reitz 
111453a29513SMax Reitz     if (protocol) {
111553a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
111653a29513SMax Reitz     } else {
111753a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
111853a29513SMax Reitz     }
111953a29513SMax Reitz 
112091a097e7SKevin Wolf     /* Translate cache options from flags into options */
112191a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
112291a097e7SKevin Wolf 
1123f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
112417b005f1SKevin Wolf     if (protocol && filename) {
1125f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1126f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1127f54120ffSKevin Wolf             parse_filename = true;
1128f54120ffSKevin Wolf         } else {
1129f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1130f54120ffSKevin Wolf                              "the same time");
1131f54120ffSKevin Wolf             return -EINVAL;
1132f54120ffSKevin Wolf         }
1133f54120ffSKevin Wolf     }
1134f54120ffSKevin Wolf 
1135f54120ffSKevin Wolf     /* Find the right block driver */
1136f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1137f54120ffSKevin Wolf 
113817b005f1SKevin Wolf     if (!drvname && protocol) {
1139f54120ffSKevin Wolf         if (filename) {
1140b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1141f54120ffSKevin Wolf             if (!drv) {
1142f54120ffSKevin Wolf                 return -EINVAL;
1143f54120ffSKevin Wolf             }
1144f54120ffSKevin Wolf 
1145f54120ffSKevin Wolf             drvname = drv->format_name;
1146f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1147f54120ffSKevin Wolf         } else {
1148f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1149f54120ffSKevin Wolf             return -EINVAL;
1150f54120ffSKevin Wolf         }
115117b005f1SKevin Wolf     }
115217b005f1SKevin Wolf 
115317b005f1SKevin Wolf     assert(drv || !protocol);
1154f54120ffSKevin Wolf 
1155f54120ffSKevin Wolf     /* Driver-specific filename parsing */
115617b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1157f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1158f54120ffSKevin Wolf         if (local_err) {
1159f54120ffSKevin Wolf             error_propagate(errp, local_err);
1160f54120ffSKevin Wolf             return -EINVAL;
1161f54120ffSKevin Wolf         }
1162f54120ffSKevin Wolf 
1163f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1164f54120ffSKevin Wolf             qdict_del(*options, "filename");
1165f54120ffSKevin Wolf         }
1166f54120ffSKevin Wolf     }
1167f54120ffSKevin Wolf 
1168f54120ffSKevin Wolf     return 0;
1169f54120ffSKevin Wolf }
1170f54120ffSKevin Wolf 
1171e9740bc6SKevin Wolf static void bdrv_replace_child(BdrvChild *child, BlockDriverState *new_bs)
1172e9740bc6SKevin Wolf {
1173e9740bc6SKevin Wolf     BlockDriverState *old_bs = child->bs;
1174e9740bc6SKevin Wolf 
1175e9740bc6SKevin Wolf     if (old_bs) {
117636fe1331SKevin Wolf         if (old_bs->quiesce_counter && child->role->drained_end) {
117736fe1331SKevin Wolf             child->role->drained_end(child);
1178e9740bc6SKevin Wolf         }
117936fe1331SKevin Wolf         QLIST_REMOVE(child, next_parent);
1180e9740bc6SKevin Wolf     }
1181e9740bc6SKevin Wolf 
1182e9740bc6SKevin Wolf     child->bs = new_bs;
118336fe1331SKevin Wolf 
118436fe1331SKevin Wolf     if (new_bs) {
118536fe1331SKevin Wolf         QLIST_INSERT_HEAD(&new_bs->parents, child, next_parent);
118636fe1331SKevin Wolf         if (new_bs->quiesce_counter && child->role->drained_begin) {
118736fe1331SKevin Wolf             child->role->drained_begin(child);
118836fe1331SKevin Wolf         }
118936fe1331SKevin Wolf     }
1190e9740bc6SKevin Wolf }
1191e9740bc6SKevin Wolf 
1192f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1193260fecf1SKevin Wolf                                   const char *child_name,
119436fe1331SKevin Wolf                                   const BdrvChildRole *child_role,
119536fe1331SKevin Wolf                                   void *opaque)
1196df581792SKevin Wolf {
1197df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1198df581792SKevin Wolf     *child = (BdrvChild) {
1199e9740bc6SKevin Wolf         .bs     = NULL,
1200260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1201df581792SKevin Wolf         .role   = child_role,
120236fe1331SKevin Wolf         .opaque = opaque,
1203df581792SKevin Wolf     };
1204df581792SKevin Wolf 
1205e9740bc6SKevin Wolf     bdrv_replace_child(child, child_bs);
1206b4b059f6SKevin Wolf 
1207b4b059f6SKevin Wolf     return child;
1208df581792SKevin Wolf }
1209df581792SKevin Wolf 
121098292c61SWen Congyang BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1211f21d96d0SKevin Wolf                              BlockDriverState *child_bs,
1212f21d96d0SKevin Wolf                              const char *child_name,
1213f21d96d0SKevin Wolf                              const BdrvChildRole *child_role)
1214f21d96d0SKevin Wolf {
121536fe1331SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role,
121620018e12SKevin Wolf                                               parent_bs);
1217f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1218f21d96d0SKevin Wolf     return child;
1219f21d96d0SKevin Wolf }
1220f21d96d0SKevin Wolf 
12213f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
122233a60407SKevin Wolf {
1223f21d96d0SKevin Wolf     if (child->next.le_prev) {
122433a60407SKevin Wolf         QLIST_REMOVE(child, next);
1225f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1226f21d96d0SKevin Wolf     }
1227e9740bc6SKevin Wolf 
1228e9740bc6SKevin Wolf     bdrv_replace_child(child, NULL);
1229e9740bc6SKevin Wolf 
1230260fecf1SKevin Wolf     g_free(child->name);
123133a60407SKevin Wolf     g_free(child);
123233a60407SKevin Wolf }
123333a60407SKevin Wolf 
1234f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
123533a60407SKevin Wolf {
1236779020cbSKevin Wolf     BlockDriverState *child_bs;
1237779020cbSKevin Wolf 
1238f21d96d0SKevin Wolf     child_bs = child->bs;
1239f21d96d0SKevin Wolf     bdrv_detach_child(child);
1240f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1241f21d96d0SKevin Wolf }
1242f21d96d0SKevin Wolf 
1243f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1244f21d96d0SKevin Wolf {
1245779020cbSKevin Wolf     if (child == NULL) {
1246779020cbSKevin Wolf         return;
1247779020cbSKevin Wolf     }
124833a60407SKevin Wolf 
124933a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
125033a60407SKevin Wolf         child->bs->inherits_from = NULL;
125133a60407SKevin Wolf     }
125233a60407SKevin Wolf 
1253f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
125433a60407SKevin Wolf }
125533a60407SKevin Wolf 
12565c8cab48SKevin Wolf 
12575c8cab48SKevin Wolf static void bdrv_parent_cb_change_media(BlockDriverState *bs, bool load)
12585c8cab48SKevin Wolf {
12595c8cab48SKevin Wolf     BdrvChild *c;
12605c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
12615c8cab48SKevin Wolf         if (c->role->change_media) {
12625c8cab48SKevin Wolf             c->role->change_media(c, load);
12635c8cab48SKevin Wolf         }
12645c8cab48SKevin Wolf     }
12655c8cab48SKevin Wolf }
12665c8cab48SKevin Wolf 
12675c8cab48SKevin Wolf static void bdrv_parent_cb_resize(BlockDriverState *bs)
12685c8cab48SKevin Wolf {
12695c8cab48SKevin Wolf     BdrvChild *c;
12705c8cab48SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
12715c8cab48SKevin Wolf         if (c->role->resize) {
12725c8cab48SKevin Wolf             c->role->resize(c);
12735c8cab48SKevin Wolf         }
12745c8cab48SKevin Wolf     }
12755c8cab48SKevin Wolf }
12765c8cab48SKevin Wolf 
12775db15a57SKevin Wolf /*
12785db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12795db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12805db15a57SKevin Wolf  */
12818d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12828d24cce1SFam Zheng {
12835db15a57SKevin Wolf     if (backing_hd) {
12845db15a57SKevin Wolf         bdrv_ref(backing_hd);
12855db15a57SKevin Wolf     }
12868d24cce1SFam Zheng 
1287760e0063SKevin Wolf     if (bs->backing) {
1288826b6ca0SFam Zheng         assert(bs->backing_blocker);
1289760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12905db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1291826b6ca0SFam Zheng     } else if (backing_hd) {
1292826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
129381e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
129481e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1295826b6ca0SFam Zheng     }
1296826b6ca0SFam Zheng 
12978d24cce1SFam Zheng     if (!backing_hd) {
1298826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1299826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1300760e0063SKevin Wolf         bs->backing = NULL;
13018d24cce1SFam Zheng         goto out;
13028d24cce1SFam Zheng     }
1303260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
13048d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
13058d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
13068d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
13078d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1308826b6ca0SFam Zheng 
1309760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1310826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1311760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1312826b6ca0SFam Zheng                     bs->backing_blocker);
13138d24cce1SFam Zheng out:
13143baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
13158d24cce1SFam Zheng }
13168d24cce1SFam Zheng 
131731ca6d07SKevin Wolf /*
131831ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
131931ca6d07SKevin Wolf  *
1320d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1321d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1322d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1323d9b7b057SKevin Wolf  * BlockdevRef.
1324d9b7b057SKevin Wolf  *
1325d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
132631ca6d07SKevin Wolf  */
1327d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1328d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
13299156df12SPaolo Bonzini {
13301ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1331d9b7b057SKevin Wolf     char *bdref_key_dot;
1332d9b7b057SKevin Wolf     const char *reference = NULL;
1333317fc44eSKevin Wolf     int ret = 0;
13348d24cce1SFam Zheng     BlockDriverState *backing_hd;
1335d9b7b057SKevin Wolf     QDict *options;
1336d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
133734b5d2c6SMax Reitz     Error *local_err = NULL;
13389156df12SPaolo Bonzini 
1339760e0063SKevin Wolf     if (bs->backing != NULL) {
13401ba4b6a5SBenoît Canet         goto free_exit;
13419156df12SPaolo Bonzini     }
13429156df12SPaolo Bonzini 
134331ca6d07SKevin Wolf     /* NULL means an empty set of options */
1344d9b7b057SKevin Wolf     if (parent_options == NULL) {
1345d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1346d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
134731ca6d07SKevin Wolf     }
134831ca6d07SKevin Wolf 
13499156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1350d9b7b057SKevin Wolf 
1351d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1352d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1353d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1354d9b7b057SKevin Wolf 
1355d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1356d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13571cb6f506SKevin Wolf         backing_filename[0] = '\0';
13581cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
135931ca6d07SKevin Wolf         QDECREF(options);
13601ba4b6a5SBenoît Canet         goto free_exit;
1361dbecebddSFam Zheng     } else {
13629f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13639f07429eSMax Reitz                                        &local_err);
13649f07429eSMax Reitz         if (local_err) {
13659f07429eSMax Reitz             ret = -EINVAL;
13669f07429eSMax Reitz             error_propagate(errp, local_err);
13679f07429eSMax Reitz             QDECREF(options);
13689f07429eSMax Reitz             goto free_exit;
13699f07429eSMax Reitz         }
13709156df12SPaolo Bonzini     }
13719156df12SPaolo Bonzini 
13728ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13738ee79e70SKevin Wolf         ret = -EINVAL;
13748ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13758ee79e70SKevin Wolf         QDECREF(options);
13768ee79e70SKevin Wolf         goto free_exit;
13778ee79e70SKevin Wolf     }
13788ee79e70SKevin Wolf 
1379c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1380c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13819156df12SPaolo Bonzini     }
13829156df12SPaolo Bonzini 
13835b363937SMax Reitz     backing_hd = bdrv_open_inherit(*backing_filename ? backing_filename : NULL,
1384d9b7b057SKevin Wolf                                    reference, options, 0, bs, &child_backing,
1385e43bfd9cSMarkus Armbruster                                    errp);
13865b363937SMax Reitz     if (!backing_hd) {
13879156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1388e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13895b363937SMax Reitz         ret = -EINVAL;
13901ba4b6a5SBenoît Canet         goto free_exit;
13919156df12SPaolo Bonzini     }
1392df581792SKevin Wolf 
13935db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13945db15a57SKevin Wolf      * backing_hd reference now */
13958d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13965db15a57SKevin Wolf     bdrv_unref(backing_hd);
1397d80ac658SPeter Feiner 
1398d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1399d9b7b057SKevin Wolf 
14001ba4b6a5SBenoît Canet free_exit:
14011ba4b6a5SBenoît Canet     g_free(backing_filename);
1402d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
14031ba4b6a5SBenoît Canet     return ret;
14049156df12SPaolo Bonzini }
14059156df12SPaolo Bonzini 
1406b6ce07aaSKevin Wolf /*
1407da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1408da557aacSMax Reitz  * device's options.
1409da557aacSMax Reitz  *
1410da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1411b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1412da557aacSMax Reitz  *
1413da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1414da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1415da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1416da557aacSMax Reitz  * BlockdevRef.
1417da557aacSMax Reitz  *
1418da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1419da557aacSMax Reitz  */
1420b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1421f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1422b4b059f6SKevin Wolf                            BlockDriverState* parent,
1423b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1424f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1425da557aacSMax Reitz {
1426b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1427b4b059f6SKevin Wolf     BlockDriverState *bs;
1428da557aacSMax Reitz     QDict *image_options;
1429da557aacSMax Reitz     char *bdref_key_dot;
1430da557aacSMax Reitz     const char *reference;
1431da557aacSMax Reitz 
1432df581792SKevin Wolf     assert(child_role != NULL);
1433f67503e5SMax Reitz 
1434da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1435da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1436da557aacSMax Reitz     g_free(bdref_key_dot);
1437da557aacSMax Reitz 
1438da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1439da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1440b4b059f6SKevin Wolf         if (!allow_none) {
1441da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1442da557aacSMax Reitz                        bdref_key);
1443da557aacSMax Reitz         }
1444b20e61e0SMarkus Armbruster         QDECREF(image_options);
1445da557aacSMax Reitz         goto done;
1446da557aacSMax Reitz     }
1447da557aacSMax Reitz 
14485b363937SMax Reitz     bs = bdrv_open_inherit(filename, reference, image_options, 0,
1449ce343771SMax Reitz                            parent, child_role, errp);
14505b363937SMax Reitz     if (!bs) {
1451df581792SKevin Wolf         goto done;
1452df581792SKevin Wolf     }
1453df581792SKevin Wolf 
1454260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1455da557aacSMax Reitz 
1456da557aacSMax Reitz done:
1457da557aacSMax Reitz     qdict_del(options, bdref_key);
1458b4b059f6SKevin Wolf     return c;
1459b4b059f6SKevin Wolf }
1460b4b059f6SKevin Wolf 
146166836189SMax Reitz static BlockDriverState *bdrv_append_temp_snapshot(BlockDriverState *bs,
146266836189SMax Reitz                                                    int flags,
146366836189SMax Reitz                                                    QDict *snapshot_options,
146466836189SMax Reitz                                                    Error **errp)
1465b998875dSKevin Wolf {
1466b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14671ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1468b998875dSKevin Wolf     int64_t total_size;
146983d0521aSChunyan Liu     QemuOpts *opts = NULL;
1470b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1471b998875dSKevin Wolf     int ret;
1472b998875dSKevin Wolf 
1473b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1474b998875dSKevin Wolf        instead of opening 'filename' directly */
1475b998875dSKevin Wolf 
1476b998875dSKevin Wolf     /* Get the required size from the image */
1477f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1478f187743aSKevin Wolf     if (total_size < 0) {
1479f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14801ba4b6a5SBenoît Canet         goto out;
1481f187743aSKevin Wolf     }
1482b998875dSKevin Wolf 
1483b998875dSKevin Wolf     /* Create the temporary image */
14841ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1485b998875dSKevin Wolf     if (ret < 0) {
1486b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14871ba4b6a5SBenoît Canet         goto out;
1488b998875dSKevin Wolf     }
1489b998875dSKevin Wolf 
1490ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1491c282e1fdSChunyan Liu                             &error_abort);
149239101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1493e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
149483d0521aSChunyan Liu     qemu_opts_del(opts);
1495b998875dSKevin Wolf     if (ret < 0) {
1496e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1497e43bfd9cSMarkus Armbruster                       tmp_filename);
14981ba4b6a5SBenoît Canet         goto out;
1499b998875dSKevin Wolf     }
1500b998875dSKevin Wolf 
150173176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1502b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1503b998875dSKevin Wolf               qstring_from_str("file"));
1504b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1505b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1506e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1507e6641719SMax Reitz               qstring_from_str("qcow2"));
1508b998875dSKevin Wolf 
15095b363937SMax Reitz     bs_snapshot = bdrv_open(NULL, NULL, snapshot_options, flags, errp);
151073176beeSKevin Wolf     snapshot_options = NULL;
15115b363937SMax Reitz     if (!bs_snapshot) {
15125b363937SMax Reitz         ret = -EINVAL;
15131ba4b6a5SBenoît Canet         goto out;
1514b998875dSKevin Wolf     }
1515b998875dSKevin Wolf 
151666836189SMax Reitz     /* bdrv_append() consumes a strong reference to bs_snapshot (i.e. it will
151766836189SMax Reitz      * call bdrv_unref() on it), so in order to be able to return one, we have
151866836189SMax Reitz      * to increase bs_snapshot's refcount here */
151966836189SMax Reitz     bdrv_ref(bs_snapshot);
1520b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
15211ba4b6a5SBenoît Canet 
152266836189SMax Reitz     g_free(tmp_filename);
152366836189SMax Reitz     return bs_snapshot;
152466836189SMax Reitz 
15251ba4b6a5SBenoît Canet out:
152673176beeSKevin Wolf     QDECREF(snapshot_options);
15271ba4b6a5SBenoît Canet     g_free(tmp_filename);
152866836189SMax Reitz     return NULL;
1529b998875dSKevin Wolf }
1530b998875dSKevin Wolf 
1531da557aacSMax Reitz /*
1532b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1533de9c0cecSKevin Wolf  *
1534de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1535de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1536de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1537de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1538f67503e5SMax Reitz  *
1539f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1540f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1541ddf5636dSMax Reitz  *
1542ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1543ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1544ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1545b6ce07aaSKevin Wolf  */
15465b363937SMax Reitz static BlockDriverState *bdrv_open_inherit(const char *filename,
15475b363937SMax Reitz                                            const char *reference,
15485b363937SMax Reitz                                            QDict *options, int flags,
1549f3930ed0SKevin Wolf                                            BlockDriverState *parent,
15505b363937SMax Reitz                                            const BdrvChildRole *child_role,
15515b363937SMax Reitz                                            Error **errp)
1552ea2384d3Sbellard {
1553b6ce07aaSKevin Wolf     int ret;
15549a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15559a4f4c31SKevin Wolf     BlockDriverState *bs;
1556ce343771SMax Reitz     BlockDriver *drv = NULL;
155774fe54f2SKevin Wolf     const char *drvname;
15583e8c2e57SAlberto Garcia     const char *backing;
155934b5d2c6SMax Reitz     Error *local_err = NULL;
156073176beeSKevin Wolf     QDict *snapshot_options = NULL;
1561b1e6fc08SKevin Wolf     int snapshot_flags = 0;
156233e3963eSbellard 
1563f3930ed0SKevin Wolf     assert(!child_role || !flags);
1564f3930ed0SKevin Wolf     assert(!child_role == !parent);
1565f67503e5SMax Reitz 
1566ddf5636dSMax Reitz     if (reference) {
1567ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1568ddf5636dSMax Reitz         QDECREF(options);
1569ddf5636dSMax Reitz 
1570ddf5636dSMax Reitz         if (filename || options_non_empty) {
1571ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1572ddf5636dSMax Reitz                        "additional options or a new filename");
15735b363937SMax Reitz             return NULL;
1574ddf5636dSMax Reitz         }
1575ddf5636dSMax Reitz 
1576ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1577ddf5636dSMax Reitz         if (!bs) {
15785b363937SMax Reitz             return NULL;
1579ddf5636dSMax Reitz         }
158076b22320SKevin Wolf 
1581ddf5636dSMax Reitz         bdrv_ref(bs);
15825b363937SMax Reitz         return bs;
1583ddf5636dSMax Reitz     }
1584ddf5636dSMax Reitz 
1585e4e9986bSMarkus Armbruster     bs = bdrv_new();
1586f67503e5SMax Reitz 
1587de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1588de9c0cecSKevin Wolf     if (options == NULL) {
1589de9c0cecSKevin Wolf         options = qdict_new();
1590de9c0cecSKevin Wolf     }
1591de9c0cecSKevin Wolf 
1592145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1593de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1594de3b53f0SKevin Wolf     if (local_err) {
1595de3b53f0SKevin Wolf         goto fail;
1596de3b53f0SKevin Wolf     }
1597de3b53f0SKevin Wolf 
1598145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1599145f598eSKevin Wolf 
1600f3930ed0SKevin Wolf     if (child_role) {
1601bddcec37SKevin Wolf         bs->inherits_from = parent;
16028e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
16038e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1604f3930ed0SKevin Wolf     }
1605f3930ed0SKevin Wolf 
1606de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1607462f5bcfSKevin Wolf     if (local_err) {
1608462f5bcfSKevin Wolf         goto fail;
1609462f5bcfSKevin Wolf     }
1610462f5bcfSKevin Wolf 
161162392ebbSKevin Wolf     bs->open_flags = flags;
161262392ebbSKevin Wolf     bs->options = options;
161362392ebbSKevin Wolf     options = qdict_clone_shallow(options);
161462392ebbSKevin Wolf 
161576c591b0SKevin Wolf     /* Find the right image format driver */
161676c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
161776c591b0SKevin Wolf     if (drvname) {
161876c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
161976c591b0SKevin Wolf         if (!drv) {
162076c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
162176c591b0SKevin Wolf             goto fail;
162276c591b0SKevin Wolf         }
162376c591b0SKevin Wolf     }
162476c591b0SKevin Wolf 
162576c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
162676c591b0SKevin Wolf 
16273e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
16283e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16293e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16303e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16313e8c2e57SAlberto Garcia     }
16323e8c2e57SAlberto Garcia 
1633f500a6d3SKevin Wolf     /* Open image file without format layer */
1634f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1635be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1636be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1637be028adcSJeff Cody         }
1638b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
163973176beeSKevin Wolf             snapshot_options = qdict_new();
164073176beeSKevin Wolf             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
164173176beeSKevin Wolf                                        flags, options);
16428e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1643b1e6fc08SKevin Wolf         }
1644be028adcSJeff Cody 
1645f3930ed0SKevin Wolf         bs->open_flags = flags;
16461fdd6933SKevin Wolf 
16479a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16481fdd6933SKevin Wolf                                &child_file, true, &local_err);
16491fdd6933SKevin Wolf         if (local_err) {
16508bfea15dSKevin Wolf             goto fail;
1651f500a6d3SKevin Wolf         }
1652f4788adcSKevin Wolf     }
1653f500a6d3SKevin Wolf 
165476c591b0SKevin Wolf     /* Image format probing */
165538f3ef57SKevin Wolf     bs->probed = !drv;
165676c591b0SKevin Wolf     if (!drv && file) {
16579a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
165817b005f1SKevin Wolf         if (ret < 0) {
165917b005f1SKevin Wolf             goto fail;
166017b005f1SKevin Wolf         }
166162392ebbSKevin Wolf         /*
166262392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
166362392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
166462392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
166562392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
166662392ebbSKevin Wolf          *
166762392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
166862392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
166962392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
167062392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
167162392ebbSKevin Wolf          */
167262392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
167362392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
167476c591b0SKevin Wolf     } else if (!drv) {
16752a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16768bfea15dSKevin Wolf         goto fail;
16772a05cbe4SMax Reitz     }
1678f500a6d3SKevin Wolf 
167953a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
168053a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
168153a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
168253a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
168353a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
168453a29513SMax Reitz 
1685b6ce07aaSKevin Wolf     /* Open the image */
168682dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1687b6ce07aaSKevin Wolf     if (ret < 0) {
16888bfea15dSKevin Wolf         goto fail;
16896987307cSChristoph Hellwig     }
16906987307cSChristoph Hellwig 
16912a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16929a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1693f500a6d3SKevin Wolf         file = NULL;
1694f500a6d3SKevin Wolf     }
1695f500a6d3SKevin Wolf 
1696b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16979156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1698d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1699b6ce07aaSKevin Wolf         if (ret < 0) {
1700b6ad491aSKevin Wolf             goto close_and_fail;
1701b6ce07aaSKevin Wolf         }
1702b6ce07aaSKevin Wolf     }
1703b6ce07aaSKevin Wolf 
170491af7014SMax Reitz     bdrv_refresh_filename(bs);
170591af7014SMax Reitz 
1706b6ad491aSKevin Wolf     /* Check if any unknown options were used */
17075acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1708b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
17095acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
17105acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
17115acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
17125acd9d81SMax Reitz         } else {
1713d0e46a55SMax Reitz             error_setg(errp,
1714d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1715d0e46a55SMax Reitz                        drv->format_name, entry->key);
17165acd9d81SMax Reitz         }
1717b6ad491aSKevin Wolf 
1718b6ad491aSKevin Wolf         goto close_and_fail;
1719b6ad491aSKevin Wolf     }
1720b6ad491aSKevin Wolf 
1721b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
17225c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
1723c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1724c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1725c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1726c3adb58fSMarkus Armbruster         error_setg(errp,
1727c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1728c3adb58fSMarkus Armbruster         goto close_and_fail;
1729b6ce07aaSKevin Wolf     }
1730b6ce07aaSKevin Wolf 
1731c3adb58fSMarkus Armbruster     QDECREF(options);
1732dd62f1caSKevin Wolf 
1733dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1734dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1735dd62f1caSKevin Wolf     if (snapshot_flags) {
173666836189SMax Reitz         BlockDriverState *snapshot_bs;
173766836189SMax Reitz         snapshot_bs = bdrv_append_temp_snapshot(bs, snapshot_flags,
173866836189SMax Reitz                                                 snapshot_options, &local_err);
173973176beeSKevin Wolf         snapshot_options = NULL;
1740dd62f1caSKevin Wolf         if (local_err) {
1741dd62f1caSKevin Wolf             goto close_and_fail;
1742dd62f1caSKevin Wolf         }
174366836189SMax Reitz         /* We are not going to return bs but the overlay on top of it
174466836189SMax Reitz          * (snapshot_bs); thus, we have to drop the strong reference to bs
17455b363937SMax Reitz          * (which we obtained by calling bdrv_new()). bs will not be deleted,
17465b363937SMax Reitz          * though, because the overlay still has a reference to it. */
174766836189SMax Reitz         bdrv_unref(bs);
174866836189SMax Reitz         bs = snapshot_bs;
174966836189SMax Reitz     }
175066836189SMax Reitz 
17515b363937SMax Reitz     return bs;
1752b6ce07aaSKevin Wolf 
17538bfea15dSKevin Wolf fail:
1754f500a6d3SKevin Wolf     if (file != NULL) {
17559a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1756f500a6d3SKevin Wolf     }
175773176beeSKevin Wolf     QDECREF(snapshot_options);
1758145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1759de9c0cecSKevin Wolf     QDECREF(bs->options);
1760b6ad491aSKevin Wolf     QDECREF(options);
1761de9c0cecSKevin Wolf     bs->options = NULL;
1762f67503e5SMax Reitz     bdrv_unref(bs);
176384d18f06SMarkus Armbruster     if (local_err) {
176434b5d2c6SMax Reitz         error_propagate(errp, local_err);
176534b5d2c6SMax Reitz     }
17665b363937SMax Reitz     return NULL;
1767de9c0cecSKevin Wolf 
1768b6ad491aSKevin Wolf close_and_fail:
1769f67503e5SMax Reitz     bdrv_unref(bs);
177073176beeSKevin Wolf     QDECREF(snapshot_options);
1771b6ad491aSKevin Wolf     QDECREF(options);
177284d18f06SMarkus Armbruster     if (local_err) {
177334b5d2c6SMax Reitz         error_propagate(errp, local_err);
177434b5d2c6SMax Reitz     }
17755b363937SMax Reitz     return NULL;
1776b6ce07aaSKevin Wolf }
1777b6ce07aaSKevin Wolf 
17785b363937SMax Reitz BlockDriverState *bdrv_open(const char *filename, const char *reference,
17795b363937SMax Reitz                             QDict *options, int flags, Error **errp)
1780f3930ed0SKevin Wolf {
17815b363937SMax Reitz     return bdrv_open_inherit(filename, reference, options, flags, NULL,
1782ce343771SMax Reitz                              NULL, errp);
1783f3930ed0SKevin Wolf }
1784f3930ed0SKevin Wolf 
1785e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1786e971aa12SJeff Cody      bool prepared;
1787e971aa12SJeff Cody      BDRVReopenState state;
1788e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1789e971aa12SJeff Cody } BlockReopenQueueEntry;
1790e971aa12SJeff Cody 
1791e971aa12SJeff Cody /*
1792e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1793e971aa12SJeff Cody  * reopen of multiple devices.
1794e971aa12SJeff Cody  *
1795e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1796e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1797e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1798e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1799e971aa12SJeff Cody  * atomic 'set'.
1800e971aa12SJeff Cody  *
1801e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1802e971aa12SJeff Cody  *
18034d2cb092SKevin Wolf  * options contains the changed options for the associated bs
18044d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
18054d2cb092SKevin Wolf  *
1806e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1807e971aa12SJeff Cody  *
1808e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1809e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1810e971aa12SJeff Cody  *
1811e971aa12SJeff Cody  */
181228518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
18134d2cb092SKevin Wolf                                                  BlockDriverState *bs,
181428518102SKevin Wolf                                                  QDict *options,
181528518102SKevin Wolf                                                  int flags,
181628518102SKevin Wolf                                                  const BdrvChildRole *role,
181728518102SKevin Wolf                                                  QDict *parent_options,
181828518102SKevin Wolf                                                  int parent_flags)
1819e971aa12SJeff Cody {
1820e971aa12SJeff Cody     assert(bs != NULL);
1821e971aa12SJeff Cody 
1822e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
182367251a31SKevin Wolf     BdrvChild *child;
1824145f598eSKevin Wolf     QDict *old_options, *explicit_options;
182567251a31SKevin Wolf 
1826e971aa12SJeff Cody     if (bs_queue == NULL) {
1827e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1828e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1829e971aa12SJeff Cody     }
1830e971aa12SJeff Cody 
18314d2cb092SKevin Wolf     if (!options) {
18324d2cb092SKevin Wolf         options = qdict_new();
18334d2cb092SKevin Wolf     }
18344d2cb092SKevin Wolf 
183528518102SKevin Wolf     /*
183628518102SKevin Wolf      * Precedence of options:
183728518102SKevin Wolf      * 1. Explicitly passed in options (highest)
183891a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1839145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18408e2160e2SKevin Wolf      * 4. Inherited from parent node
184128518102SKevin Wolf      * 5. Retained from effective options of bs
184228518102SKevin Wolf      */
184328518102SKevin Wolf 
184491a097e7SKevin Wolf     if (!parent_options) {
184591a097e7SKevin Wolf         /*
184691a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
184791a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
184891a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
184991a097e7SKevin Wolf          * not considered.
185091a097e7SKevin Wolf          */
185191a097e7SKevin Wolf         update_options_from_flags(options, flags);
185291a097e7SKevin Wolf     }
185391a097e7SKevin Wolf 
1854145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1855145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1856145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1857145f598eSKevin Wolf     QDECREF(old_options);
1858145f598eSKevin Wolf 
1859145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1860145f598eSKevin Wolf 
186128518102SKevin Wolf     /* Inherit from parent node */
186228518102SKevin Wolf     if (parent_options) {
186328518102SKevin Wolf         assert(!flags);
18648e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
186528518102SKevin Wolf     }
186628518102SKevin Wolf 
186728518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18684d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1869cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18704d2cb092SKevin Wolf     QDECREF(old_options);
18714d2cb092SKevin Wolf 
1872f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1873f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1874f1f25a2eSKevin Wolf 
187567251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18764c9dfe5dSKevin Wolf         QDict *new_child_options;
18774c9dfe5dSKevin Wolf         char *child_key_dot;
187867251a31SKevin Wolf 
18794c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18804c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18814c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
188267251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
188367251a31SKevin Wolf             continue;
188467251a31SKevin Wolf         }
188567251a31SKevin Wolf 
18864c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18874c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18884c9dfe5dSKevin Wolf         g_free(child_key_dot);
18894c9dfe5dSKevin Wolf 
189028518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
189128518102SKevin Wolf                                 child->role, options, flags);
1892e971aa12SJeff Cody     }
1893e971aa12SJeff Cody 
1894e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1895e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1896e971aa12SJeff Cody 
1897e971aa12SJeff Cody     bs_entry->state.bs = bs;
18984d2cb092SKevin Wolf     bs_entry->state.options = options;
1899145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1900e971aa12SJeff Cody     bs_entry->state.flags = flags;
1901e971aa12SJeff Cody 
1902e971aa12SJeff Cody     return bs_queue;
1903e971aa12SJeff Cody }
1904e971aa12SJeff Cody 
190528518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
190628518102SKevin Wolf                                     BlockDriverState *bs,
190728518102SKevin Wolf                                     QDict *options, int flags)
190828518102SKevin Wolf {
190928518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
191028518102SKevin Wolf                                    NULL, NULL, 0);
191128518102SKevin Wolf }
191228518102SKevin Wolf 
1913e971aa12SJeff Cody /*
1914e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1915e971aa12SJeff Cody  *
1916e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1917e971aa12SJeff Cody  * via bdrv_reopen_queue().
1918e971aa12SJeff Cody  *
1919e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1920e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1921e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1922e971aa12SJeff Cody  * data cleaned up.
1923e971aa12SJeff Cody  *
1924e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1925e971aa12SJeff Cody  * to all devices.
1926e971aa12SJeff Cody  *
1927e971aa12SJeff Cody  */
1928e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1929e971aa12SJeff Cody {
1930e971aa12SJeff Cody     int ret = -1;
1931e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1932e971aa12SJeff Cody     Error *local_err = NULL;
1933e971aa12SJeff Cody 
1934e971aa12SJeff Cody     assert(bs_queue != NULL);
1935e971aa12SJeff Cody 
1936e971aa12SJeff Cody     bdrv_drain_all();
1937e971aa12SJeff Cody 
1938e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1939e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1940e971aa12SJeff Cody             error_propagate(errp, local_err);
1941e971aa12SJeff Cody             goto cleanup;
1942e971aa12SJeff Cody         }
1943e971aa12SJeff Cody         bs_entry->prepared = true;
1944e971aa12SJeff Cody     }
1945e971aa12SJeff Cody 
1946e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1947e971aa12SJeff Cody      * changes
1948e971aa12SJeff Cody      */
1949e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1950e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1951e971aa12SJeff Cody     }
1952e971aa12SJeff Cody 
1953e971aa12SJeff Cody     ret = 0;
1954e971aa12SJeff Cody 
1955e971aa12SJeff Cody cleanup:
1956e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1957e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1958e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1959145f598eSKevin Wolf         } else if (ret) {
1960145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1961e971aa12SJeff Cody         }
19624d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1963e971aa12SJeff Cody         g_free(bs_entry);
1964e971aa12SJeff Cody     }
1965e971aa12SJeff Cody     g_free(bs_queue);
1966e971aa12SJeff Cody     return ret;
1967e971aa12SJeff Cody }
1968e971aa12SJeff Cody 
1969e971aa12SJeff Cody 
1970e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1971e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1972e971aa12SJeff Cody {
1973e971aa12SJeff Cody     int ret = -1;
1974e971aa12SJeff Cody     Error *local_err = NULL;
19754d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1976e971aa12SJeff Cody 
1977e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1978e971aa12SJeff Cody     if (local_err != NULL) {
1979e971aa12SJeff Cody         error_propagate(errp, local_err);
1980e971aa12SJeff Cody     }
1981e971aa12SJeff Cody     return ret;
1982e971aa12SJeff Cody }
1983e971aa12SJeff Cody 
1984e971aa12SJeff Cody 
1985e971aa12SJeff Cody /*
1986e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1987e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1988e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1989e971aa12SJeff Cody  *
1990e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1991e971aa12SJeff Cody  * flags are the new open flags
1992e971aa12SJeff Cody  * queue is the reopen queue
1993e971aa12SJeff Cody  *
1994e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1995e971aa12SJeff Cody  * as well.
1996e971aa12SJeff Cody  *
1997e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1998e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1999e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
2000e971aa12SJeff Cody  *
2001e971aa12SJeff Cody  */
2002e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
2003e971aa12SJeff Cody                         Error **errp)
2004e971aa12SJeff Cody {
2005e971aa12SJeff Cody     int ret = -1;
2006e971aa12SJeff Cody     Error *local_err = NULL;
2007e971aa12SJeff Cody     BlockDriver *drv;
2008ccf9dc07SKevin Wolf     QemuOpts *opts;
2009ccf9dc07SKevin Wolf     const char *value;
2010e971aa12SJeff Cody 
2011e971aa12SJeff Cody     assert(reopen_state != NULL);
2012e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
2013e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2014e971aa12SJeff Cody 
2015ccf9dc07SKevin Wolf     /* Process generic block layer options */
2016ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2017ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2018ccf9dc07SKevin Wolf     if (local_err) {
2019ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2020ccf9dc07SKevin Wolf         ret = -EINVAL;
2021ccf9dc07SKevin Wolf         goto error;
2022ccf9dc07SKevin Wolf     }
2023ccf9dc07SKevin Wolf 
202491a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
202591a097e7SKevin Wolf 
2026ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2027ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2028ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2029ccf9dc07SKevin Wolf     if (value) {
2030ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2031ccf9dc07SKevin Wolf     }
2032ccf9dc07SKevin Wolf 
2033ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2034ccf9dc07SKevin Wolf     if (value) {
2035ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2036ccf9dc07SKevin Wolf     }
2037ccf9dc07SKevin Wolf 
2038e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2039e971aa12SJeff Cody      * to r/w */
2040e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2041e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
204281e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
204381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2044e971aa12SJeff Cody         goto error;
2045e971aa12SJeff Cody     }
2046e971aa12SJeff Cody 
2047e971aa12SJeff Cody 
2048e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2049e971aa12SJeff Cody     if (ret) {
2050455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2051e971aa12SJeff Cody         goto error;
2052e971aa12SJeff Cody     }
2053e971aa12SJeff Cody 
2054e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2055e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2056e971aa12SJeff Cody         if (ret) {
2057e971aa12SJeff Cody             if (local_err != NULL) {
2058e971aa12SJeff Cody                 error_propagate(errp, local_err);
2059e971aa12SJeff Cody             } else {
2060d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2061e971aa12SJeff Cody                            reopen_state->bs->filename);
2062e971aa12SJeff Cody             }
2063e971aa12SJeff Cody             goto error;
2064e971aa12SJeff Cody         }
2065e971aa12SJeff Cody     } else {
2066e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2067e971aa12SJeff Cody          * handler for each supported drv. */
206881e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206981e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
207081e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2071e971aa12SJeff Cody         ret = -1;
2072e971aa12SJeff Cody         goto error;
2073e971aa12SJeff Cody     }
2074e971aa12SJeff Cody 
20754d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20764d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20774d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20784d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20794d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20804d2cb092SKevin Wolf 
20814d2cb092SKevin Wolf         do {
20824d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20834d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20844d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20854d2cb092SKevin Wolf                                                 entry->key);
20864d2cb092SKevin Wolf 
20874d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20884d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20894d2cb092SKevin Wolf                 ret = -EINVAL;
20904d2cb092SKevin Wolf                 goto error;
20914d2cb092SKevin Wolf             }
20924d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20934d2cb092SKevin Wolf     }
20944d2cb092SKevin Wolf 
2095e971aa12SJeff Cody     ret = 0;
2096e971aa12SJeff Cody 
2097e971aa12SJeff Cody error:
2098ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2099e971aa12SJeff Cody     return ret;
2100e971aa12SJeff Cody }
2101e971aa12SJeff Cody 
2102e971aa12SJeff Cody /*
2103e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2104e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2105e971aa12SJeff Cody  * the active BlockDriverState contents.
2106e971aa12SJeff Cody  */
2107e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2108e971aa12SJeff Cody {
2109e971aa12SJeff Cody     BlockDriver *drv;
2110e971aa12SJeff Cody 
2111e971aa12SJeff Cody     assert(reopen_state != NULL);
2112e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2113e971aa12SJeff Cody     assert(drv != NULL);
2114e971aa12SJeff Cody 
2115e971aa12SJeff Cody     /* If there are any driver level actions to take */
2116e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2117e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2118e971aa12SJeff Cody     }
2119e971aa12SJeff Cody 
2120e971aa12SJeff Cody     /* set BDS specific flags now */
2121145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2122145f598eSKevin Wolf 
2123145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2124e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2125e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2126355ef4acSKevin Wolf 
21273baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2128e971aa12SJeff Cody }
2129e971aa12SJeff Cody 
2130e971aa12SJeff Cody /*
2131e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2132e971aa12SJeff Cody  * reopen_state
2133e971aa12SJeff Cody  */
2134e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2135e971aa12SJeff Cody {
2136e971aa12SJeff Cody     BlockDriver *drv;
2137e971aa12SJeff Cody 
2138e971aa12SJeff Cody     assert(reopen_state != NULL);
2139e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2140e971aa12SJeff Cody     assert(drv != NULL);
2141e971aa12SJeff Cody 
2142e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2143e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2144e971aa12SJeff Cody     }
2145145f598eSKevin Wolf 
2146145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2147e971aa12SJeff Cody }
2148e971aa12SJeff Cody 
2149e971aa12SJeff Cody 
215064dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2151fc01f7e7Sbellard {
215233384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
215333384421SMax Reitz 
2154ca9bd24cSMax Reitz     assert(!bs->job);
215530f55fb8SMax Reitz     assert(!bs->refcnt);
215699b7e775SAlberto Garcia 
2157fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
215858fda173SStefan Hajnoczi     bdrv_flush(bs);
215953ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2160fc27291dSPaolo Bonzini 
2161c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2162c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2163c5acdc9aSMax Reitz 
21643cbc002cSPaolo Bonzini     if (bs->drv) {
21656e93e7c4SKevin Wolf         BdrvChild *child, *next;
21666e93e7c4SKevin Wolf 
21679a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21689a4f4c31SKevin Wolf         bs->drv = NULL;
21699a7dedbcSKevin Wolf 
21709a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21719a7dedbcSKevin Wolf 
21729a4f4c31SKevin Wolf         if (bs->file != NULL) {
21739a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21749a4f4c31SKevin Wolf             bs->file = NULL;
21759a4f4c31SKevin Wolf         }
21769a4f4c31SKevin Wolf 
21776e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
217833a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
217933a60407SKevin Wolf              * bdrv_unref_child() here */
2180bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2181bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2182bddcec37SKevin Wolf             }
218333a60407SKevin Wolf             bdrv_detach_child(child);
21846e93e7c4SKevin Wolf         }
21856e93e7c4SKevin Wolf 
21867267c094SAnthony Liguori         g_free(bs->opaque);
2187ea2384d3Sbellard         bs->opaque = NULL;
218853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2189a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2190a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
21916405875cSPaolo Bonzini         bs->total_sectors = 0;
21926405875cSPaolo Bonzini         bs->encrypted = 0;
21936405875cSPaolo Bonzini         bs->valid_key = 0;
21946405875cSPaolo Bonzini         bs->sg = 0;
21950d51b4deSAsias He         bs->zero_beyond_eof = false;
2196de9c0cecSKevin Wolf         QDECREF(bs->options);
2197145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2198de9c0cecSKevin Wolf         bs->options = NULL;
219991af7014SMax Reitz         QDECREF(bs->full_open_options);
220091af7014SMax Reitz         bs->full_open_options = NULL;
22019ca11154SPavel Hrdina     }
220266f82ceeSKevin Wolf 
220333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
220433384421SMax Reitz         g_free(ban);
220533384421SMax Reitz     }
220633384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2207fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2208b338082bSbellard }
2209b338082bSbellard 
22102bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22112bc93fedSMORITA Kazutaka {
2212*a1a2af07SKevin Wolf     block_job_cancel_sync_all();
22132bc93fedSMORITA Kazutaka 
2214ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2215ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2216ca9bd24cSMax Reitz     bdrv_drain_all();
2217ca9bd24cSMax Reitz 
2218ca9bd24cSMax Reitz     blk_remove_all_bs();
2219ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2220ca9bd24cSMax Reitz 
2221*a1a2af07SKevin Wolf     assert(QTAILQ_EMPTY(&all_bdrv_states));
22222bc93fedSMORITA Kazutaka }
22232bc93fedSMORITA Kazutaka 
2224dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2225dd62f1caSKevin Wolf                                        BlockDriverState *to)
2226dd62f1caSKevin Wolf {
2227dd62f1caSKevin Wolf     BdrvChild *c, *next;
2228dd62f1caSKevin Wolf 
2229dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2230dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2231dd62f1caSKevin Wolf         bdrv_ref(to);
2232e9740bc6SKevin Wolf         bdrv_replace_child(c, to);
2233dd62f1caSKevin Wolf         bdrv_unref(from);
2234dd62f1caSKevin Wolf     }
2235dd62f1caSKevin Wolf }
2236dd62f1caSKevin Wolf 
22378802d1fdSJeff Cody /*
22388802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
22398802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
22408802d1fdSJeff Cody  *
22418802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
22428802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
22438802d1fdSJeff Cody  *
2244bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2245f6801b83SJeff Cody  *
22468802d1fdSJeff Cody  * This function does not create any image files.
2247dd62f1caSKevin Wolf  *
2248dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2249dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2250dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2251dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
22528802d1fdSJeff Cody  */
22538802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
22548802d1fdSJeff Cody {
2255dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2256dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
22578802d1fdSJeff Cody 
2258dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2259dd62f1caSKevin Wolf 
226027ccdd52SKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2261dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2262dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2263dd62f1caSKevin Wolf 
2264dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2265dd62f1caSKevin Wolf      * additional reference any more. */
2266dd62f1caSKevin Wolf     bdrv_unref(bs_new);
22678802d1fdSJeff Cody }
22688802d1fdSJeff Cody 
22693f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
22703f09bfbcSKevin Wolf {
22713f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
22723f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
22733f09bfbcSKevin Wolf 
22743f09bfbcSKevin Wolf     bdrv_ref(old);
22753f09bfbcSKevin Wolf 
22763f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
22773f09bfbcSKevin Wolf 
22783f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
22793f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
22803f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
22813f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
22823f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
22833f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
22843f09bfbcSKevin Wolf     }
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 
23268a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
23278a426614SKevin Wolf 
232833e3963eSbellard /* commit COW file into the raw image */
232933e3963eSbellard int bdrv_commit(BlockDriverState *bs)
233033e3963eSbellard {
233119cb3738Sbellard     BlockDriver *drv = bs->drv;
233272706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
23338a426614SKevin Wolf     int n, ro, open_flags;
23340bce597dSJeff Cody     int ret = 0;
233572706ea4SJeff Cody     uint8_t *buf = NULL;
233633e3963eSbellard 
233719cb3738Sbellard     if (!drv)
233819cb3738Sbellard         return -ENOMEDIUM;
233933e3963eSbellard 
2340760e0063SKevin Wolf     if (!bs->backing) {
23414dca4b63SNaphtali Sprei         return -ENOTSUP;
23424dca4b63SNaphtali Sprei     }
23434dca4b63SNaphtali Sprei 
2344bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2345760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
23462d3735d3SStefan Hajnoczi         return -EBUSY;
23472d3735d3SStefan Hajnoczi     }
23482d3735d3SStefan Hajnoczi 
2349760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2350760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
23514dca4b63SNaphtali Sprei 
23524dca4b63SNaphtali Sprei     if (ro) {
2353760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
23540bce597dSJeff Cody             return -EACCES;
23554dca4b63SNaphtali Sprei         }
2356ea2384d3Sbellard     }
2357ea2384d3Sbellard 
235872706ea4SJeff Cody     length = bdrv_getlength(bs);
235972706ea4SJeff Cody     if (length < 0) {
236072706ea4SJeff Cody         ret = length;
236172706ea4SJeff Cody         goto ro_cleanup;
236272706ea4SJeff Cody     }
236372706ea4SJeff Cody 
2364760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
236572706ea4SJeff Cody     if (backing_length < 0) {
236672706ea4SJeff Cody         ret = backing_length;
236772706ea4SJeff Cody         goto ro_cleanup;
236872706ea4SJeff Cody     }
236972706ea4SJeff Cody 
237072706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
237172706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
237272706ea4SJeff Cody      * we must return an error */
237372706ea4SJeff Cody     if (length > backing_length) {
2374760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
237572706ea4SJeff Cody         if (ret < 0) {
237672706ea4SJeff Cody             goto ro_cleanup;
237772706ea4SJeff Cody         }
237872706ea4SJeff Cody     }
237972706ea4SJeff Cody 
238072706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2381857d4f46SKevin Wolf 
2382857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2383760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2384857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2385857d4f46SKevin Wolf     if (buf == NULL) {
2386857d4f46SKevin Wolf         ret = -ENOMEM;
2387857d4f46SKevin Wolf         goto ro_cleanup;
2388857d4f46SKevin Wolf     }
23898a426614SKevin Wolf 
23908a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2391d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2392d663640cSPaolo Bonzini         if (ret < 0) {
2393d663640cSPaolo Bonzini             goto ro_cleanup;
2394d663640cSPaolo Bonzini         }
2395d663640cSPaolo Bonzini         if (ret) {
2396dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2397dabfa6ccSKevin Wolf             if (ret < 0) {
23984dca4b63SNaphtali Sprei                 goto ro_cleanup;
239933e3963eSbellard             }
240033e3963eSbellard 
2401760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2402dabfa6ccSKevin Wolf             if (ret < 0) {
24034dca4b63SNaphtali Sprei                 goto ro_cleanup;
240433e3963eSbellard             }
240533e3963eSbellard         }
240633e3963eSbellard     }
240795389c86Sbellard 
24081d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
24091d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2410dabfa6ccSKevin Wolf         if (ret < 0) {
2411dabfa6ccSKevin Wolf             goto ro_cleanup;
2412dabfa6ccSKevin Wolf         }
24131d44952fSChristoph Hellwig         bdrv_flush(bs);
24141d44952fSChristoph Hellwig     }
241595389c86Sbellard 
24163f5075aeSChristoph Hellwig     /*
24173f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24183f5075aeSChristoph Hellwig      * stable on disk.
24193f5075aeSChristoph Hellwig      */
2420760e0063SKevin Wolf     if (bs->backing) {
2421760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2422dabfa6ccSKevin Wolf     }
24234dca4b63SNaphtali Sprei 
2424dabfa6ccSKevin Wolf     ret = 0;
24254dca4b63SNaphtali Sprei ro_cleanup:
2426857d4f46SKevin Wolf     qemu_vfree(buf);
24274dca4b63SNaphtali Sprei 
24284dca4b63SNaphtali Sprei     if (ro) {
24290bce597dSJeff Cody         /* ignoring error return here */
2430760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
24314dca4b63SNaphtali Sprei     }
24324dca4b63SNaphtali Sprei 
24331d44952fSChristoph Hellwig     return ret;
243433e3963eSbellard }
243533e3963eSbellard 
2436756e6736SKevin Wolf /*
2437756e6736SKevin Wolf  * Return values:
2438756e6736SKevin Wolf  * 0        - success
2439756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2440756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2441756e6736SKevin Wolf  *            image file header
2442756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2443756e6736SKevin Wolf  */
2444756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2445756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2446756e6736SKevin Wolf {
2447756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2448469ef350SPaolo Bonzini     int ret;
2449756e6736SKevin Wolf 
24505f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
24515f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
24525f377794SPaolo Bonzini         return -EINVAL;
24535f377794SPaolo Bonzini     }
24545f377794SPaolo Bonzini 
2455756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2456469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2457756e6736SKevin Wolf     } else {
2458469ef350SPaolo Bonzini         ret = -ENOTSUP;
2459756e6736SKevin Wolf     }
2460469ef350SPaolo Bonzini 
2461469ef350SPaolo Bonzini     if (ret == 0) {
2462469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2463469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2464469ef350SPaolo Bonzini     }
2465469ef350SPaolo Bonzini     return ret;
2466756e6736SKevin Wolf }
2467756e6736SKevin Wolf 
24686ebdcee2SJeff Cody /*
24696ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
24706ebdcee2SJeff Cody  *
24716ebdcee2SJeff Cody  * active is the current topmost image.
24726ebdcee2SJeff Cody  *
24736ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24746ebdcee2SJeff Cody  * or if active == bs.
24754caf0fcdSJeff Cody  *
24764caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
24776ebdcee2SJeff Cody  */
24786ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24796ebdcee2SJeff Cody                                     BlockDriverState *bs)
24806ebdcee2SJeff Cody {
2481760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2482760e0063SKevin Wolf         active = backing_bs(active);
24836ebdcee2SJeff Cody     }
24846ebdcee2SJeff Cody 
24854caf0fcdSJeff Cody     return active;
24866ebdcee2SJeff Cody }
24876ebdcee2SJeff Cody 
24884caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
24894caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
24904caf0fcdSJeff Cody {
24914caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
24926ebdcee2SJeff Cody }
24936ebdcee2SJeff Cody 
24946ebdcee2SJeff Cody /*
24956ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24966ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24976ebdcee2SJeff Cody  *
24986ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
24996ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25006ebdcee2SJeff Cody  *
25016ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25026ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25036ebdcee2SJeff Cody  *
25046ebdcee2SJeff Cody  * to
25056ebdcee2SJeff Cody  *
25066ebdcee2SJeff Cody  * bottom <- base <- active
25076ebdcee2SJeff Cody  *
25086ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25096ebdcee2SJeff Cody  *
25106ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25116ebdcee2SJeff Cody  *
25126ebdcee2SJeff Cody  * to
25136ebdcee2SJeff Cody  *
25146ebdcee2SJeff Cody  * base <- active
25156ebdcee2SJeff Cody  *
251654e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
251754e26900SJeff Cody  * overlay image metadata.
251854e26900SJeff Cody  *
25196ebdcee2SJeff Cody  * Error conditions:
25206ebdcee2SJeff Cody  *  if active == top, that is considered an error
25216ebdcee2SJeff Cody  *
25226ebdcee2SJeff Cody  */
25236ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
252454e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
25256ebdcee2SJeff Cody {
25266ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25276ebdcee2SJeff Cody     int ret = -EIO;
25286ebdcee2SJeff Cody 
25296ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25306ebdcee2SJeff Cody         goto exit;
25316ebdcee2SJeff Cody     }
25326ebdcee2SJeff Cody 
25336ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25346ebdcee2SJeff Cody 
25356ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25366ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25376ebdcee2SJeff Cody         goto exit;
25386ebdcee2SJeff Cody     }
25396ebdcee2SJeff Cody 
2540760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
25416ebdcee2SJeff Cody      * to do, no intermediate images */
2542760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
25436ebdcee2SJeff Cody         ret = 0;
25446ebdcee2SJeff Cody         goto exit;
25456ebdcee2SJeff Cody     }
25466ebdcee2SJeff Cody 
25475db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
25485db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
25496ebdcee2SJeff Cody         goto exit;
25506ebdcee2SJeff Cody     }
25516ebdcee2SJeff Cody 
25526ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25535db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
255454e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
25555db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
25566ebdcee2SJeff Cody     if (ret) {
25576ebdcee2SJeff Cody         goto exit;
25586ebdcee2SJeff Cody     }
25595db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
25606ebdcee2SJeff Cody 
25616ebdcee2SJeff Cody     ret = 0;
25626ebdcee2SJeff Cody exit:
25636ebdcee2SJeff Cody     return ret;
25646ebdcee2SJeff Cody }
25656ebdcee2SJeff Cody 
256683f64091Sbellard /**
256783f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
256883f64091Sbellard  */
256983f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
257083f64091Sbellard {
257183f64091Sbellard     BlockDriver *drv = bs->drv;
257251762288SStefan Hajnoczi     int ret;
257383f64091Sbellard     if (!drv)
257419cb3738Sbellard         return -ENOMEDIUM;
257583f64091Sbellard     if (!drv->bdrv_truncate)
257683f64091Sbellard         return -ENOTSUP;
257759f2689dSNaphtali Sprei     if (bs->read_only)
257859f2689dSNaphtali Sprei         return -EACCES;
25799c75e168SJeff Cody 
258051762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
258151762288SStefan Hajnoczi     if (ret == 0) {
258251762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2583ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
25845c8cab48SKevin Wolf         bdrv_parent_cb_resize(bs);
258551762288SStefan Hajnoczi     }
258651762288SStefan Hajnoczi     return ret;
258783f64091Sbellard }
258883f64091Sbellard 
258983f64091Sbellard /**
25904a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
25914a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
25924a1d5e1fSFam Zheng  */
25934a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
25944a1d5e1fSFam Zheng {
25954a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
25964a1d5e1fSFam Zheng     if (!drv) {
25974a1d5e1fSFam Zheng         return -ENOMEDIUM;
25984a1d5e1fSFam Zheng     }
25994a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26004a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26014a1d5e1fSFam Zheng     }
26024a1d5e1fSFam Zheng     if (bs->file) {
26039a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26044a1d5e1fSFam Zheng     }
26054a1d5e1fSFam Zheng     return -ENOTSUP;
26064a1d5e1fSFam Zheng }
26074a1d5e1fSFam Zheng 
26084a1d5e1fSFam Zheng /**
260965a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
261083f64091Sbellard  */
261165a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
261283f64091Sbellard {
261383f64091Sbellard     BlockDriver *drv = bs->drv;
261465a9bb25SMarkus Armbruster 
261583f64091Sbellard     if (!drv)
261619cb3738Sbellard         return -ENOMEDIUM;
261751762288SStefan Hajnoczi 
2618b94a2610SKevin Wolf     if (drv->has_variable_length) {
2619b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2620b94a2610SKevin Wolf         if (ret < 0) {
2621b94a2610SKevin Wolf             return ret;
2622fc01f7e7Sbellard         }
262346a4e4e6SStefan Hajnoczi     }
262465a9bb25SMarkus Armbruster     return bs->total_sectors;
262565a9bb25SMarkus Armbruster }
262665a9bb25SMarkus Armbruster 
262765a9bb25SMarkus Armbruster /**
262865a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
262965a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
263065a9bb25SMarkus Armbruster  */
263165a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
263265a9bb25SMarkus Armbruster {
263365a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
263465a9bb25SMarkus Armbruster 
26354a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
263665a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
263746a4e4e6SStefan Hajnoczi }
2638fc01f7e7Sbellard 
263919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
264096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2641fc01f7e7Sbellard {
264265a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
264365a9bb25SMarkus Armbruster 
264465a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2645fc01f7e7Sbellard }
2646cf98951bSbellard 
2647b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2648b338082bSbellard {
2649b338082bSbellard     return bs->read_only;
2650b338082bSbellard }
2651b338082bSbellard 
2652985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2653985a03b0Sths {
2654985a03b0Sths     return bs->sg;
2655985a03b0Sths }
2656985a03b0Sths 
2657ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2658ea2384d3Sbellard {
2659760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2660ea2384d3Sbellard         return 1;
2661760e0063SKevin Wolf     }
2662ea2384d3Sbellard     return bs->encrypted;
2663ea2384d3Sbellard }
2664ea2384d3Sbellard 
2665c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2666c0f4ce77Saliguori {
2667760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2668c0f4ce77Saliguori 
2669760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2670c0f4ce77Saliguori         return 1;
2671760e0063SKevin Wolf     }
2672c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2673c0f4ce77Saliguori }
2674c0f4ce77Saliguori 
2675ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2676ea2384d3Sbellard {
2677ea2384d3Sbellard     int ret;
2678760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2679760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2680ea2384d3Sbellard         if (ret < 0)
2681ea2384d3Sbellard             return ret;
2682ea2384d3Sbellard         if (!bs->encrypted)
2683ea2384d3Sbellard             return 0;
2684ea2384d3Sbellard     }
2685fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2686fd04a2aeSShahar Havivi         return -EINVAL;
2687fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2688fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2689fd04a2aeSShahar Havivi     }
2690c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2691bb5fc20fSaliguori     if (ret < 0) {
2692bb5fc20fSaliguori         bs->valid_key = 0;
2693bb5fc20fSaliguori     } else if (!bs->valid_key) {
2694bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
26955c8cab48SKevin Wolf         bs->valid_key = 1;
26965c8cab48SKevin Wolf         bdrv_parent_cb_change_media(bs, true);
2697bb5fc20fSaliguori     }
2698c0f4ce77Saliguori     return ret;
2699ea2384d3Sbellard }
2700ea2384d3Sbellard 
27014d2855a3SMarkus Armbruster /*
27024d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
27034d2855a3SMarkus Armbruster  * If @key is non-null:
27044d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
27054d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
27064d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
27074d2855a3SMarkus Armbruster  * If @key is null:
27084d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
27094d2855a3SMarkus Armbruster  *     Else do nothing.
27104d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
27114d2855a3SMarkus Armbruster  */
27124d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
27134d2855a3SMarkus Armbruster {
27144d2855a3SMarkus Armbruster     if (key) {
27154d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
271681e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
271781e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
27184d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2719c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
27204d2855a3SMarkus Armbruster         }
27214d2855a3SMarkus Armbruster     } else {
27224d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2723b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2724b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
272581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
27264d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
27274d2855a3SMarkus Armbruster         }
27284d2855a3SMarkus Armbruster     }
27294d2855a3SMarkus Armbruster }
27304d2855a3SMarkus Armbruster 
2731f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2732ea2384d3Sbellard {
2733f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2734ea2384d3Sbellard }
2735ea2384d3Sbellard 
2736ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2737ada42401SStefan Hajnoczi {
2738ada42401SStefan Hajnoczi     return strcmp(a, b);
2739ada42401SStefan Hajnoczi }
2740ada42401SStefan Hajnoczi 
2741ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2742ea2384d3Sbellard                          void *opaque)
2743ea2384d3Sbellard {
2744ea2384d3Sbellard     BlockDriver *drv;
2745e855e4fbSJeff Cody     int count = 0;
2746ada42401SStefan Hajnoczi     int i;
2747e855e4fbSJeff Cody     const char **formats = NULL;
2748ea2384d3Sbellard 
27498a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2750e855e4fbSJeff Cody         if (drv->format_name) {
2751e855e4fbSJeff Cody             bool found = false;
2752e855e4fbSJeff Cody             int i = count;
2753e855e4fbSJeff Cody             while (formats && i && !found) {
2754e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2755e855e4fbSJeff Cody             }
2756e855e4fbSJeff Cody 
2757e855e4fbSJeff Cody             if (!found) {
27585839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2759e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2760ea2384d3Sbellard             }
2761ea2384d3Sbellard         }
2762e855e4fbSJeff Cody     }
2763ada42401SStefan Hajnoczi 
2764ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2765ada42401SStefan Hajnoczi 
2766ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2767ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2768ada42401SStefan Hajnoczi     }
2769ada42401SStefan Hajnoczi 
2770e855e4fbSJeff Cody     g_free(formats);
2771e855e4fbSJeff Cody }
2772ea2384d3Sbellard 
2773dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2774dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2775dc364f4cSBenoît Canet {
2776dc364f4cSBenoît Canet     BlockDriverState *bs;
2777dc364f4cSBenoît Canet 
2778dc364f4cSBenoît Canet     assert(node_name);
2779dc364f4cSBenoît Canet 
2780dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2781dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2782dc364f4cSBenoît Canet             return bs;
2783dc364f4cSBenoît Canet         }
2784dc364f4cSBenoît Canet     }
2785dc364f4cSBenoît Canet     return NULL;
2786dc364f4cSBenoît Canet }
2787dc364f4cSBenoît Canet 
2788c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2789d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2790c13163fbSBenoît Canet {
2791c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2792c13163fbSBenoît Canet     BlockDriverState *bs;
2793c13163fbSBenoît Canet 
2794c13163fbSBenoît Canet     list = NULL;
2795c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2796c83f9fbaSKevin Wolf         BlockDeviceInfo *info = bdrv_block_device_info(NULL, bs, errp);
2797d5a8ee60SAlberto Garcia         if (!info) {
2798d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2799d5a8ee60SAlberto Garcia             return NULL;
2800d5a8ee60SAlberto Garcia         }
2801c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2802d5a8ee60SAlberto Garcia         entry->value = info;
2803c13163fbSBenoît Canet         entry->next = list;
2804c13163fbSBenoît Canet         list = entry;
2805c13163fbSBenoît Canet     }
2806c13163fbSBenoît Canet 
2807c13163fbSBenoît Canet     return list;
2808c13163fbSBenoît Canet }
2809c13163fbSBenoît Canet 
281012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
281112d3ba82SBenoît Canet                                  const char *node_name,
281212d3ba82SBenoît Canet                                  Error **errp)
281312d3ba82SBenoît Canet {
28147f06d47eSMarkus Armbruster     BlockBackend *blk;
28157f06d47eSMarkus Armbruster     BlockDriverState *bs;
281612d3ba82SBenoît Canet 
281712d3ba82SBenoît Canet     if (device) {
28187f06d47eSMarkus Armbruster         blk = blk_by_name(device);
281912d3ba82SBenoît Canet 
28207f06d47eSMarkus Armbruster         if (blk) {
28219f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
28229f4ed6fbSAlberto Garcia             if (!bs) {
28235433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
28245433c24fSMax Reitz             }
28255433c24fSMax Reitz 
28269f4ed6fbSAlberto Garcia             return bs;
282712d3ba82SBenoît Canet         }
2828dd67fa50SBenoît Canet     }
282912d3ba82SBenoît Canet 
2830dd67fa50SBenoît Canet     if (node_name) {
283112d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
283212d3ba82SBenoît Canet 
2833dd67fa50SBenoît Canet         if (bs) {
2834dd67fa50SBenoît Canet             return bs;
2835dd67fa50SBenoît Canet         }
283612d3ba82SBenoît Canet     }
283712d3ba82SBenoît Canet 
2838dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2839dd67fa50SBenoît Canet                      device ? device : "",
2840dd67fa50SBenoît Canet                      node_name ? node_name : "");
2841dd67fa50SBenoît Canet     return NULL;
284212d3ba82SBenoît Canet }
284312d3ba82SBenoît Canet 
28445a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
28455a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
28465a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
28475a6684d2SJeff Cody {
28485a6684d2SJeff Cody     while (top && top != base) {
2849760e0063SKevin Wolf         top = backing_bs(top);
28505a6684d2SJeff Cody     }
28515a6684d2SJeff Cody 
28525a6684d2SJeff Cody     return top != NULL;
28535a6684d2SJeff Cody }
28545a6684d2SJeff Cody 
285504df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
285604df765aSFam Zheng {
285704df765aSFam Zheng     if (!bs) {
285804df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
285904df765aSFam Zheng     }
286004df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
286104df765aSFam Zheng }
286204df765aSFam Zheng 
286320a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
286420a9e77dSFam Zheng {
286520a9e77dSFam Zheng     return bs->node_name;
286620a9e77dSFam Zheng }
286720a9e77dSFam Zheng 
28681f0c461bSKevin Wolf const char *bdrv_get_parent_name(const BlockDriverState *bs)
28694c265bf9SKevin Wolf {
28704c265bf9SKevin Wolf     BdrvChild *c;
28714c265bf9SKevin Wolf     const char *name;
28724c265bf9SKevin Wolf 
28734c265bf9SKevin Wolf     /* If multiple parents have a name, just pick the first one. */
28744c265bf9SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
28754c265bf9SKevin Wolf         if (c->role->get_name) {
28764c265bf9SKevin Wolf             name = c->role->get_name(c);
28774c265bf9SKevin Wolf             if (name && *name) {
28784c265bf9SKevin Wolf                 return name;
28794c265bf9SKevin Wolf             }
28804c265bf9SKevin Wolf         }
28814c265bf9SKevin Wolf     }
28824c265bf9SKevin Wolf 
28834c265bf9SKevin Wolf     return NULL;
28844c265bf9SKevin Wolf }
28854c265bf9SKevin Wolf 
28867f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2887bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2888ea2384d3Sbellard {
28894c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: "";
2890ea2384d3Sbellard }
2891ea2384d3Sbellard 
28929b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
28939b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
28949b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
28959b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
28969b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
28979b2aa84fSAlberto Garcia {
28984c265bf9SKevin Wolf     return bdrv_get_parent_name(bs) ?: bs->node_name;
28999b2aa84fSAlberto Garcia }
29009b2aa84fSAlberto Garcia 
2901c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2902c8433287SMarkus Armbruster {
2903c8433287SMarkus Armbruster     return bs->open_flags;
2904c8433287SMarkus Armbruster }
2905c8433287SMarkus Armbruster 
29063ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
29073ac21627SPeter Lieven {
29083ac21627SPeter Lieven     return 1;
29093ac21627SPeter Lieven }
29103ac21627SPeter Lieven 
2911f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2912f2feebbdSKevin Wolf {
2913f2feebbdSKevin Wolf     assert(bs->drv);
2914f2feebbdSKevin Wolf 
291511212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
291611212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2917760e0063SKevin Wolf     if (bs->backing) {
291811212d8fSPaolo Bonzini         return 0;
291911212d8fSPaolo Bonzini     }
2920336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2921336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2922f2feebbdSKevin Wolf     }
2923f2feebbdSKevin Wolf 
29243ac21627SPeter Lieven     /* safe default */
29253ac21627SPeter Lieven     return 0;
2926f2feebbdSKevin Wolf }
2927f2feebbdSKevin Wolf 
29284ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
29294ce78691SPeter Lieven {
29304ce78691SPeter Lieven     BlockDriverInfo bdi;
29314ce78691SPeter Lieven 
2932760e0063SKevin Wolf     if (bs->backing) {
29334ce78691SPeter Lieven         return false;
29344ce78691SPeter Lieven     }
29354ce78691SPeter Lieven 
29364ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29374ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
29384ce78691SPeter Lieven     }
29394ce78691SPeter Lieven 
29404ce78691SPeter Lieven     return false;
29414ce78691SPeter Lieven }
29424ce78691SPeter Lieven 
29434ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
29444ce78691SPeter Lieven {
29454ce78691SPeter Lieven     BlockDriverInfo bdi;
29464ce78691SPeter Lieven 
2947760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
29484ce78691SPeter Lieven         return false;
29494ce78691SPeter Lieven     }
29504ce78691SPeter Lieven 
29514ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29524ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
29534ce78691SPeter Lieven     }
29544ce78691SPeter Lieven 
29554ce78691SPeter Lieven     return false;
29564ce78691SPeter Lieven }
29574ce78691SPeter Lieven 
2958045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2959045df330Saliguori {
2960760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2961045df330Saliguori         return bs->backing_file;
2962045df330Saliguori     else if (bs->encrypted)
2963045df330Saliguori         return bs->filename;
2964045df330Saliguori     else
2965045df330Saliguori         return NULL;
2966045df330Saliguori }
2967045df330Saliguori 
296883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
296983f64091Sbellard                                char *filename, int filename_size)
297083f64091Sbellard {
297183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
297283f64091Sbellard }
297383f64091Sbellard 
2974faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2975faea38e7Sbellard {
2976faea38e7Sbellard     BlockDriver *drv = bs->drv;
2977faea38e7Sbellard     if (!drv)
297819cb3738Sbellard         return -ENOMEDIUM;
2979faea38e7Sbellard     if (!drv->bdrv_get_info)
2980faea38e7Sbellard         return -ENOTSUP;
2981faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2982faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2983faea38e7Sbellard }
2984faea38e7Sbellard 
2985eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2986eae041feSMax Reitz {
2987eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2988eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2989eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2990eae041feSMax Reitz     }
2991eae041feSMax Reitz     return NULL;
2992eae041feSMax Reitz }
2993eae041feSMax Reitz 
2994a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
29958b9b0cc2SKevin Wolf {
2996bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
29978b9b0cc2SKevin Wolf         return;
29988b9b0cc2SKevin Wolf     }
29998b9b0cc2SKevin Wolf 
3000bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
300141c695c7SKevin Wolf }
30028b9b0cc2SKevin Wolf 
300341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
300441c695c7SKevin Wolf                           const char *tag)
300541c695c7SKevin Wolf {
300641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
30079a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
300841c695c7SKevin Wolf     }
300941c695c7SKevin Wolf 
301041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
301141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
301241c695c7SKevin Wolf     }
301341c695c7SKevin Wolf 
301441c695c7SKevin Wolf     return -ENOTSUP;
301541c695c7SKevin Wolf }
301641c695c7SKevin Wolf 
30174cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
30184cc70e93SFam Zheng {
30194cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
30209a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
30214cc70e93SFam Zheng     }
30224cc70e93SFam Zheng 
30234cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
30244cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
30254cc70e93SFam Zheng     }
30264cc70e93SFam Zheng 
30274cc70e93SFam Zheng     return -ENOTSUP;
30284cc70e93SFam Zheng }
30294cc70e93SFam Zheng 
303041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
303141c695c7SKevin Wolf {
3032938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
30339a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
303441c695c7SKevin Wolf     }
303541c695c7SKevin Wolf 
303641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
303741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
303841c695c7SKevin Wolf     }
303941c695c7SKevin Wolf 
304041c695c7SKevin Wolf     return -ENOTSUP;
304141c695c7SKevin Wolf }
304241c695c7SKevin Wolf 
304341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
304441c695c7SKevin Wolf {
304541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
30469a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
304741c695c7SKevin Wolf     }
304841c695c7SKevin Wolf 
304941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
305041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
305141c695c7SKevin Wolf     }
305241c695c7SKevin Wolf 
305341c695c7SKevin Wolf     return false;
30548b9b0cc2SKevin Wolf }
30558b9b0cc2SKevin Wolf 
3056199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3057199630b6SBlue Swirl {
3058199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3059199630b6SBlue Swirl }
3060199630b6SBlue Swirl 
3061b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3062b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3063b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3064b1b1d783SJeff Cody  * the CWD rather than the chain. */
3065e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3066e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3067e8a6bb9cSMarcelo Tosatti {
3068b1b1d783SJeff Cody     char *filename_full = NULL;
3069b1b1d783SJeff Cody     char *backing_file_full = NULL;
3070b1b1d783SJeff Cody     char *filename_tmp = NULL;
3071b1b1d783SJeff Cody     int is_protocol = 0;
3072b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3073b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3074b1b1d783SJeff Cody 
3075b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3076e8a6bb9cSMarcelo Tosatti         return NULL;
3077e8a6bb9cSMarcelo Tosatti     }
3078e8a6bb9cSMarcelo Tosatti 
3079b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3080b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3081b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3082b1b1d783SJeff Cody 
3083b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3084b1b1d783SJeff Cody 
3085760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3086b1b1d783SJeff Cody 
3087b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3088b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3089b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3090b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3091760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3092b1b1d783SJeff Cody                 break;
3093b1b1d783SJeff Cody             }
3094e8a6bb9cSMarcelo Tosatti         } else {
3095b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3096b1b1d783SJeff Cody              * image's filename path */
3097b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3098b1b1d783SJeff Cody                          backing_file);
3099b1b1d783SJeff Cody 
3100b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3101b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3102b1b1d783SJeff Cody                 continue;
3103b1b1d783SJeff Cody             }
3104b1b1d783SJeff Cody 
3105b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3106b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3107b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3108b1b1d783SJeff Cody                          curr_bs->backing_file);
3109b1b1d783SJeff Cody 
3110b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3111b1b1d783SJeff Cody                 continue;
3112b1b1d783SJeff Cody             }
3113b1b1d783SJeff Cody 
3114b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3115760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3116b1b1d783SJeff Cody                 break;
3117b1b1d783SJeff Cody             }
3118e8a6bb9cSMarcelo Tosatti         }
3119e8a6bb9cSMarcelo Tosatti     }
3120e8a6bb9cSMarcelo Tosatti 
3121b1b1d783SJeff Cody     g_free(filename_full);
3122b1b1d783SJeff Cody     g_free(backing_file_full);
3123b1b1d783SJeff Cody     g_free(filename_tmp);
3124b1b1d783SJeff Cody     return retval;
3125e8a6bb9cSMarcelo Tosatti }
3126e8a6bb9cSMarcelo Tosatti 
3127f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3128f198fd1cSBenoît Canet {
3129f198fd1cSBenoît Canet     if (!bs->drv) {
3130f198fd1cSBenoît Canet         return 0;
3131f198fd1cSBenoît Canet     }
3132f198fd1cSBenoît Canet 
3133760e0063SKevin Wolf     if (!bs->backing) {
3134f198fd1cSBenoît Canet         return 0;
3135f198fd1cSBenoît Canet     }
3136f198fd1cSBenoît Canet 
3137760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3138f198fd1cSBenoît Canet }
3139f198fd1cSBenoît Canet 
3140ea2384d3Sbellard void bdrv_init(void)
3141ea2384d3Sbellard {
31425efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3143ea2384d3Sbellard }
3144ce1a14dcSpbrook 
3145eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3146eb852011SMarkus Armbruster {
3147eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3148eb852011SMarkus Armbruster     bdrv_init();
3149eb852011SMarkus Armbruster }
3150eb852011SMarkus Armbruster 
31515a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
31520f15423cSAnthony Liguori {
31530d1c5c91SFam Zheng     BdrvChild *child;
31545a8a30dbSKevin Wolf     Error *local_err = NULL;
31555a8a30dbSKevin Wolf     int ret;
31565a8a30dbSKevin Wolf 
31573456a8d1SKevin Wolf     if (!bs->drv)  {
31583456a8d1SKevin Wolf         return;
31590f15423cSAnthony Liguori     }
31603456a8d1SKevin Wolf 
316104c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
31627ea2d269SAlexey Kardashevskiy         return;
31637ea2d269SAlexey Kardashevskiy     }
316404c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
31657ea2d269SAlexey Kardashevskiy 
31663456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
31675a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
31685a8a30dbSKevin Wolf         if (local_err) {
316904c01a5cSKevin Wolf             bs->open_flags |= BDRV_O_INACTIVE;
31705a8a30dbSKevin Wolf             error_propagate(errp, local_err);
31715a8a30dbSKevin Wolf             return;
31723456a8d1SKevin Wolf         }
31730d1c5c91SFam Zheng     }
31740d1c5c91SFam Zheng 
31750d1c5c91SFam Zheng     QLIST_FOREACH(child, &bs->children, next) {
31760d1c5c91SFam Zheng         bdrv_invalidate_cache(child->bs, &local_err);
31770d1c5c91SFam Zheng         if (local_err) {
31780d1c5c91SFam Zheng             bs->open_flags |= BDRV_O_INACTIVE;
31790d1c5c91SFam Zheng             error_propagate(errp, local_err);
31800d1c5c91SFam Zheng             return;
31810d1c5c91SFam Zheng         }
31820d1c5c91SFam Zheng     }
31833456a8d1SKevin Wolf 
31845a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
31855a8a30dbSKevin Wolf     if (ret < 0) {
318604c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
31875a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
31885a8a30dbSKevin Wolf         return;
31895a8a30dbSKevin Wolf     }
31900f15423cSAnthony Liguori }
31910f15423cSAnthony Liguori 
31925a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
31930f15423cSAnthony Liguori {
31947c8eece4SKevin Wolf     BlockDriverState *bs;
31955a8a30dbSKevin Wolf     Error *local_err = NULL;
319688be7b4bSKevin Wolf     BdrvNextIterator it;
31970f15423cSAnthony Liguori 
319888be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3199ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3200ed78cda3SStefan Hajnoczi 
3201ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32025a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3203ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32045a8a30dbSKevin Wolf         if (local_err) {
32055a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32065a8a30dbSKevin Wolf             return;
32075a8a30dbSKevin Wolf         }
32080f15423cSAnthony Liguori     }
32090f15423cSAnthony Liguori }
32100f15423cSAnthony Liguori 
3211aad0b7a0SFam Zheng static int bdrv_inactivate_recurse(BlockDriverState *bs,
3212aad0b7a0SFam Zheng                                    bool setting_flag)
321376b1c7feSKevin Wolf {
3214aad0b7a0SFam Zheng     BdrvChild *child;
321576b1c7feSKevin Wolf     int ret;
321676b1c7feSKevin Wolf 
3217aad0b7a0SFam Zheng     if (!setting_flag && bs->drv->bdrv_inactivate) {
321876b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
321976b1c7feSKevin Wolf         if (ret < 0) {
322076b1c7feSKevin Wolf             return ret;
322176b1c7feSKevin Wolf         }
322276b1c7feSKevin Wolf     }
322376b1c7feSKevin Wolf 
3224aad0b7a0SFam Zheng     QLIST_FOREACH(child, &bs->children, next) {
3225aad0b7a0SFam Zheng         ret = bdrv_inactivate_recurse(child->bs, setting_flag);
3226aad0b7a0SFam Zheng         if (ret < 0) {
3227aad0b7a0SFam Zheng             return ret;
3228aad0b7a0SFam Zheng         }
3229aad0b7a0SFam Zheng     }
3230aad0b7a0SFam Zheng 
3231aad0b7a0SFam Zheng     if (setting_flag) {
323276b1c7feSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
3233aad0b7a0SFam Zheng     }
323476b1c7feSKevin Wolf     return 0;
323576b1c7feSKevin Wolf }
323676b1c7feSKevin Wolf 
323776b1c7feSKevin Wolf int bdrv_inactivate_all(void)
323876b1c7feSKevin Wolf {
323979720af6SMax Reitz     BlockDriverState *bs = NULL;
324088be7b4bSKevin Wolf     BdrvNextIterator it;
3241aad0b7a0SFam Zheng     int ret = 0;
3242aad0b7a0SFam Zheng     int pass;
324376b1c7feSKevin Wolf 
324488be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3245aad0b7a0SFam Zheng         aio_context_acquire(bdrv_get_aio_context(bs));
3246aad0b7a0SFam Zheng     }
324776b1c7feSKevin Wolf 
3248aad0b7a0SFam Zheng     /* We do two passes of inactivation. The first pass calls to drivers'
3249aad0b7a0SFam Zheng      * .bdrv_inactivate callbacks recursively so all cache is flushed to disk;
3250aad0b7a0SFam Zheng      * the second pass sets the BDRV_O_INACTIVE flag so that no further write
3251aad0b7a0SFam Zheng      * is allowed. */
3252aad0b7a0SFam Zheng     for (pass = 0; pass < 2; pass++) {
325388be7b4bSKevin Wolf         for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3254aad0b7a0SFam Zheng             ret = bdrv_inactivate_recurse(bs, pass);
325576b1c7feSKevin Wolf             if (ret < 0) {
3256aad0b7a0SFam Zheng                 goto out;
3257aad0b7a0SFam Zheng             }
325876b1c7feSKevin Wolf         }
325976b1c7feSKevin Wolf     }
326076b1c7feSKevin Wolf 
3261aad0b7a0SFam Zheng out:
326288be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3263aad0b7a0SFam Zheng         aio_context_release(bdrv_get_aio_context(bs));
3264aad0b7a0SFam Zheng     }
3265aad0b7a0SFam Zheng 
3266aad0b7a0SFam Zheng     return ret;
326776b1c7feSKevin Wolf }
326876b1c7feSKevin Wolf 
3269f9f05dc5SKevin Wolf /**************************************************************/
327019cb3738Sbellard /* removable device support */
327119cb3738Sbellard 
327219cb3738Sbellard /**
327319cb3738Sbellard  * Return TRUE if the media is present
327419cb3738Sbellard  */
3275e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
327619cb3738Sbellard {
327719cb3738Sbellard     BlockDriver *drv = bs->drv;
327828d7a789SMax Reitz     BdrvChild *child;
3279a1aff5bfSMarkus Armbruster 
3280e031f750SMax Reitz     if (!drv) {
3281e031f750SMax Reitz         return false;
3282e031f750SMax Reitz     }
328328d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3284a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
328519cb3738Sbellard     }
328628d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
328728d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
328828d7a789SMax Reitz             return false;
328928d7a789SMax Reitz         }
329028d7a789SMax Reitz     }
329128d7a789SMax Reitz     return true;
329228d7a789SMax Reitz }
329319cb3738Sbellard 
329419cb3738Sbellard /**
32958e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
32968e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
329719cb3738Sbellard  */
329819cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
329919cb3738Sbellard {
330019cb3738Sbellard     BlockDriver *drv = bs->drv;
330119cb3738Sbellard 
33028e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33038e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33048e49ca46SMarkus Armbruster     }
33058e49ca46SMarkus Armbruster     return -ENOTSUP;
330619cb3738Sbellard }
330719cb3738Sbellard 
330819cb3738Sbellard /**
330919cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
331019cb3738Sbellard  */
3311f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
331219cb3738Sbellard {
331319cb3738Sbellard     BlockDriver *drv = bs->drv;
3314bfb197e0SMarkus Armbruster     const char *device_name;
331519cb3738Sbellard 
3316822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3317822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
331819cb3738Sbellard     }
33196f382ed2SLuiz Capitulino 
3320bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3321bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3322bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3323a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
33246f382ed2SLuiz Capitulino     }
332519cb3738Sbellard }
332619cb3738Sbellard 
332719cb3738Sbellard /**
332819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
332919cb3738Sbellard  * to eject it manually).
333019cb3738Sbellard  */
3331025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
333219cb3738Sbellard {
333319cb3738Sbellard     BlockDriver *drv = bs->drv;
333419cb3738Sbellard 
3335025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3336b8c6d095SStefan Hajnoczi 
3337025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3338025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
333919cb3738Sbellard     }
334019cb3738Sbellard }
3341985a03b0Sths 
33429fcb0251SFam Zheng /* Get a reference to bs */
33439fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
33449fcb0251SFam Zheng {
33459fcb0251SFam Zheng     bs->refcnt++;
33469fcb0251SFam Zheng }
33479fcb0251SFam Zheng 
33489fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
33499fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
33509fcb0251SFam Zheng  * deleted. */
33519fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
33529fcb0251SFam Zheng {
33539a4d5ca6SJeff Cody     if (!bs) {
33549a4d5ca6SJeff Cody         return;
33559a4d5ca6SJeff Cody     }
33569fcb0251SFam Zheng     assert(bs->refcnt > 0);
33579fcb0251SFam Zheng     if (--bs->refcnt == 0) {
33589fcb0251SFam Zheng         bdrv_delete(bs);
33599fcb0251SFam Zheng     }
33609fcb0251SFam Zheng }
33619fcb0251SFam Zheng 
3362fbe40ff7SFam Zheng struct BdrvOpBlocker {
3363fbe40ff7SFam Zheng     Error *reason;
3364fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3365fbe40ff7SFam Zheng };
3366fbe40ff7SFam Zheng 
3367fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3368fbe40ff7SFam Zheng {
3369fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3370fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3371fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3372fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3373fbe40ff7SFam Zheng         if (errp) {
3374e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3375e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3376e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3377fbe40ff7SFam Zheng         }
3378fbe40ff7SFam Zheng         return true;
3379fbe40ff7SFam Zheng     }
3380fbe40ff7SFam Zheng     return false;
3381fbe40ff7SFam Zheng }
3382fbe40ff7SFam Zheng 
3383fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3384fbe40ff7SFam Zheng {
3385fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3386fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3387fbe40ff7SFam Zheng 
33885839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3389fbe40ff7SFam Zheng     blocker->reason = reason;
3390fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3391fbe40ff7SFam Zheng }
3392fbe40ff7SFam Zheng 
3393fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3394fbe40ff7SFam Zheng {
3395fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3396fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3397fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3398fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3399fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3400fbe40ff7SFam Zheng             g_free(blocker);
3401fbe40ff7SFam Zheng         }
3402fbe40ff7SFam Zheng     }
3403fbe40ff7SFam Zheng }
3404fbe40ff7SFam Zheng 
3405fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3406fbe40ff7SFam Zheng {
3407fbe40ff7SFam Zheng     int i;
3408fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3409fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3410fbe40ff7SFam Zheng     }
3411fbe40ff7SFam Zheng }
3412fbe40ff7SFam Zheng 
3413fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3414fbe40ff7SFam Zheng {
3415fbe40ff7SFam Zheng     int i;
3416fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3417fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3418fbe40ff7SFam Zheng     }
3419fbe40ff7SFam Zheng }
3420fbe40ff7SFam Zheng 
3421fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3422fbe40ff7SFam Zheng {
3423fbe40ff7SFam Zheng     int i;
3424fbe40ff7SFam Zheng 
3425fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3426fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3427fbe40ff7SFam Zheng             return false;
3428fbe40ff7SFam Zheng         }
3429fbe40ff7SFam Zheng     }
3430fbe40ff7SFam Zheng     return true;
3431fbe40ff7SFam Zheng }
3432fbe40ff7SFam Zheng 
3433d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3434f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3435f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3436f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3437f88e1a42SJes Sorensen {
343883d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
343983d0521aSChunyan Liu     QemuOpts *opts = NULL;
344083d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
344183d0521aSChunyan Liu     int64_t size;
3442f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3443cc84d90fSMax Reitz     Error *local_err = NULL;
3444f88e1a42SJes Sorensen     int ret = 0;
3445f88e1a42SJes Sorensen 
3446f88e1a42SJes Sorensen     /* Find driver and parse its options */
3447f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3448f88e1a42SJes Sorensen     if (!drv) {
344971c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3450d92ada22SLuiz Capitulino         return;
3451f88e1a42SJes Sorensen     }
3452f88e1a42SJes Sorensen 
3453b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3454f88e1a42SJes Sorensen     if (!proto_drv) {
3455d92ada22SLuiz Capitulino         return;
3456f88e1a42SJes Sorensen     }
3457f88e1a42SJes Sorensen 
3458c6149724SMax Reitz     if (!drv->create_opts) {
3459c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3460c6149724SMax Reitz                    drv->format_name);
3461c6149724SMax Reitz         return;
3462c6149724SMax Reitz     }
3463c6149724SMax Reitz 
3464c6149724SMax Reitz     if (!proto_drv->create_opts) {
3465c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3466c6149724SMax Reitz                    proto_drv->format_name);
3467c6149724SMax Reitz         return;
3468c6149724SMax Reitz     }
3469c6149724SMax Reitz 
3470c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3471c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3472f88e1a42SJes Sorensen 
3473f88e1a42SJes Sorensen     /* Create parameter list with default values */
347483d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
347539101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3476f88e1a42SJes Sorensen 
3477f88e1a42SJes Sorensen     /* Parse -o options */
3478f88e1a42SJes Sorensen     if (options) {
3479dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3480dc523cd3SMarkus Armbruster         if (local_err) {
3481dc523cd3SMarkus Armbruster             error_report_err(local_err);
3482dc523cd3SMarkus Armbruster             local_err = NULL;
348383d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3484f88e1a42SJes Sorensen             goto out;
3485f88e1a42SJes Sorensen         }
3486f88e1a42SJes Sorensen     }
3487f88e1a42SJes Sorensen 
3488f88e1a42SJes Sorensen     if (base_filename) {
3489f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
34906be4194bSMarkus Armbruster         if (local_err) {
349171c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
349271c79813SLuiz Capitulino                        fmt);
3493f88e1a42SJes Sorensen             goto out;
3494f88e1a42SJes Sorensen         }
3495f88e1a42SJes Sorensen     }
3496f88e1a42SJes Sorensen 
3497f88e1a42SJes Sorensen     if (base_fmt) {
3498f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
34996be4194bSMarkus Armbruster         if (local_err) {
350071c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
350171c79813SLuiz Capitulino                              "format '%s'", fmt);
3502f88e1a42SJes Sorensen             goto out;
3503f88e1a42SJes Sorensen         }
3504f88e1a42SJes Sorensen     }
3505f88e1a42SJes Sorensen 
350683d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
350783d0521aSChunyan Liu     if (backing_file) {
350883d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
350971c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
351071c79813SLuiz Capitulino                              "same filename as the backing file");
3511792da93aSJes Sorensen             goto out;
3512792da93aSJes Sorensen         }
3513792da93aSJes Sorensen     }
3514792da93aSJes Sorensen 
351583d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3516f88e1a42SJes Sorensen 
3517f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3518f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
351983d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
352083d0521aSChunyan Liu     if (size == -1) {
352183d0521aSChunyan Liu         if (backing_file) {
352266f6b814SMax Reitz             BlockDriverState *bs;
352329168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
352452bf1e72SMarkus Armbruster             int64_t size;
352563090dacSPaolo Bonzini             int back_flags;
3526e6641719SMax Reitz             QDict *backing_options = NULL;
352763090dacSPaolo Bonzini 
352829168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
352929168018SMax Reitz                                                          full_backing, PATH_MAX,
353029168018SMax Reitz                                                          &local_err);
353129168018SMax Reitz             if (local_err) {
353229168018SMax Reitz                 g_free(full_backing);
353329168018SMax Reitz                 goto out;
353429168018SMax Reitz             }
353529168018SMax Reitz 
353663090dacSPaolo Bonzini             /* backing files always opened read-only */
353761de4c68SKevin Wolf             back_flags = flags;
3538bfd18d1eSKevin Wolf             back_flags &= ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3539f88e1a42SJes Sorensen 
3540e6641719SMax Reitz             if (backing_fmt) {
3541e6641719SMax Reitz                 backing_options = qdict_new();
3542e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3543e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3544e6641719SMax Reitz             }
3545e6641719SMax Reitz 
35465b363937SMax Reitz             bs = bdrv_open(full_backing, NULL, backing_options, back_flags,
35475b363937SMax Reitz                            &local_err);
354829168018SMax Reitz             g_free(full_backing);
35495b363937SMax Reitz             if (!bs) {
3550f88e1a42SJes Sorensen                 goto out;
3551f88e1a42SJes Sorensen             }
355252bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
355352bf1e72SMarkus Armbruster             if (size < 0) {
355452bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
355552bf1e72SMarkus Armbruster                                  backing_file);
355652bf1e72SMarkus Armbruster                 bdrv_unref(bs);
355752bf1e72SMarkus Armbruster                 goto out;
355852bf1e72SMarkus Armbruster             }
3559f88e1a42SJes Sorensen 
356039101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
356166f6b814SMax Reitz 
356266f6b814SMax Reitz             bdrv_unref(bs);
3563f88e1a42SJes Sorensen         } else {
356471c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3565f88e1a42SJes Sorensen             goto out;
3566f88e1a42SJes Sorensen         }
3567f88e1a42SJes Sorensen     }
3568f88e1a42SJes Sorensen 
3569f382d43aSMiroslav Rezanina     if (!quiet) {
3570f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
357143c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3572f88e1a42SJes Sorensen         puts("");
3573f382d43aSMiroslav Rezanina     }
357483d0521aSChunyan Liu 
3575c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
357683d0521aSChunyan Liu 
3577cc84d90fSMax Reitz     if (ret == -EFBIG) {
3578cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3579cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3580cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3581f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
358283d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3583f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3584f3f4d2c0SKevin Wolf         }
3585cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3586cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3587cc84d90fSMax Reitz         error_free(local_err);
3588cc84d90fSMax Reitz         local_err = NULL;
3589f88e1a42SJes Sorensen     }
3590f88e1a42SJes Sorensen 
3591f88e1a42SJes Sorensen out:
359283d0521aSChunyan Liu     qemu_opts_del(opts);
359383d0521aSChunyan Liu     qemu_opts_free(create_opts);
359484d18f06SMarkus Armbruster     if (local_err) {
3595cc84d90fSMax Reitz         error_propagate(errp, local_err);
3596cc84d90fSMax Reitz     }
3597f88e1a42SJes Sorensen }
359885d126f3SStefan Hajnoczi 
359985d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
360085d126f3SStefan Hajnoczi {
3601dcd04228SStefan Hajnoczi     return bs->aio_context;
3602dcd04228SStefan Hajnoczi }
3603dcd04228SStefan Hajnoczi 
3604dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3605dcd04228SStefan Hajnoczi {
360633384421SMax Reitz     BdrvAioNotifier *baf;
3607b97511c7SMax Reitz     BdrvChild *child;
360833384421SMax Reitz 
3609dcd04228SStefan Hajnoczi     if (!bs->drv) {
3610dcd04228SStefan Hajnoczi         return;
3611dcd04228SStefan Hajnoczi     }
3612dcd04228SStefan Hajnoczi 
361333384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
361433384421SMax Reitz         baf->detach_aio_context(baf->opaque);
361533384421SMax Reitz     }
361633384421SMax Reitz 
3617dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3618dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3619dcd04228SStefan Hajnoczi     }
3620b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3621b97511c7SMax Reitz         bdrv_detach_aio_context(child->bs);
3622dcd04228SStefan Hajnoczi     }
3623dcd04228SStefan Hajnoczi 
3624dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3625dcd04228SStefan Hajnoczi }
3626dcd04228SStefan Hajnoczi 
3627dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3628dcd04228SStefan Hajnoczi                              AioContext *new_context)
3629dcd04228SStefan Hajnoczi {
363033384421SMax Reitz     BdrvAioNotifier *ban;
3631b97511c7SMax Reitz     BdrvChild *child;
363233384421SMax Reitz 
3633dcd04228SStefan Hajnoczi     if (!bs->drv) {
3634dcd04228SStefan Hajnoczi         return;
3635dcd04228SStefan Hajnoczi     }
3636dcd04228SStefan Hajnoczi 
3637dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3638dcd04228SStefan Hajnoczi 
3639b97511c7SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
3640b97511c7SMax Reitz         bdrv_attach_aio_context(child->bs, new_context);
3641dcd04228SStefan Hajnoczi     }
3642dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3643dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3644dcd04228SStefan Hajnoczi     }
364533384421SMax Reitz 
364633384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
364733384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
364833384421SMax Reitz     }
3649dcd04228SStefan Hajnoczi }
3650dcd04228SStefan Hajnoczi 
3651dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3652dcd04228SStefan Hajnoczi {
365353ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3654dcd04228SStefan Hajnoczi 
3655dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3656dcd04228SStefan Hajnoczi 
3657dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3658dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3659dcd04228SStefan Hajnoczi      */
3660dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3661dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3662dcd04228SStefan Hajnoczi     aio_context_release(new_context);
366385d126f3SStefan Hajnoczi }
3664d616b224SStefan Hajnoczi 
366533384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
366633384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
366733384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
366833384421SMax Reitz {
366933384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
367033384421SMax Reitz     *ban = (BdrvAioNotifier){
367133384421SMax Reitz         .attached_aio_context = attached_aio_context,
367233384421SMax Reitz         .detach_aio_context   = detach_aio_context,
367333384421SMax Reitz         .opaque               = opaque
367433384421SMax Reitz     };
367533384421SMax Reitz 
367633384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
367733384421SMax Reitz }
367833384421SMax Reitz 
367933384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
368033384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
368133384421SMax Reitz                                                                    void *),
368233384421SMax Reitz                                       void (*detach_aio_context)(void *),
368333384421SMax Reitz                                       void *opaque)
368433384421SMax Reitz {
368533384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
368633384421SMax Reitz 
368733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
368833384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
368933384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
369033384421SMax Reitz             ban->opaque               == opaque)
369133384421SMax Reitz         {
369233384421SMax Reitz             QLIST_REMOVE(ban, list);
369333384421SMax Reitz             g_free(ban);
369433384421SMax Reitz 
369533384421SMax Reitz             return;
369633384421SMax Reitz         }
369733384421SMax Reitz     }
369833384421SMax Reitz 
369933384421SMax Reitz     abort();
370033384421SMax Reitz }
370133384421SMax Reitz 
370277485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
37038b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
37046f176b48SMax Reitz {
3705c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
37066f176b48SMax Reitz         return -ENOTSUP;
37076f176b48SMax Reitz     }
37088b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
37096f176b48SMax Reitz }
3710f6186f49SBenoît Canet 
3711b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3712b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3713b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3714b5042a36SBenoît Canet  * node graph.
3715212a5a8fSBenoît Canet  */
3716212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3717212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3718f6186f49SBenoît Canet {
3719b5042a36SBenoît Canet     /* return false if basic checks fails */
3720b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3721b5042a36SBenoît Canet         return false;
3722b5042a36SBenoît Canet     }
3723b5042a36SBenoît Canet 
3724b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3725b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3726b5042a36SBenoît Canet      */
3727b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3728b5042a36SBenoît Canet         return bs == candidate;
3729b5042a36SBenoît Canet     }
3730b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3731b5042a36SBenoît Canet 
3732b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3733b5042a36SBenoît Canet      * the node graph.
3734b5042a36SBenoît Canet      */
3735b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3736212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3737212a5a8fSBenoît Canet     }
3738212a5a8fSBenoît Canet 
3739b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3740b5042a36SBenoît Canet      */
3741b5042a36SBenoît Canet     return false;
3742212a5a8fSBenoît Canet }
3743212a5a8fSBenoît Canet 
3744212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3745212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3746212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3747212a5a8fSBenoît Canet  */
3748212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3749212a5a8fSBenoît Canet {
37507c8eece4SKevin Wolf     BlockDriverState *bs;
375188be7b4bSKevin Wolf     BdrvNextIterator it;
3752212a5a8fSBenoît Canet 
3753212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
375488be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
3755212a5a8fSBenoît Canet         bool perm;
3756212a5a8fSBenoît Canet 
3757b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3758e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3759212a5a8fSBenoît Canet 
3760212a5a8fSBenoît Canet         /* candidate is the first non filter */
3761212a5a8fSBenoît Canet         if (perm) {
3762212a5a8fSBenoît Canet             return true;
3763212a5a8fSBenoît Canet         }
3764212a5a8fSBenoît Canet     }
3765212a5a8fSBenoît Canet 
3766212a5a8fSBenoît Canet     return false;
3767f6186f49SBenoît Canet }
376809158f00SBenoît Canet 
3769e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3770e12f3784SWen Congyang                                         const char *node_name, Error **errp)
377109158f00SBenoît Canet {
377209158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
37735a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
37745a7e7a0bSStefan Hajnoczi 
377509158f00SBenoît Canet     if (!to_replace_bs) {
377609158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
377709158f00SBenoît Canet         return NULL;
377809158f00SBenoît Canet     }
377909158f00SBenoît Canet 
37805a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
37815a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
37825a7e7a0bSStefan Hajnoczi 
378309158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
37845a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
37855a7e7a0bSStefan Hajnoczi         goto out;
378609158f00SBenoît Canet     }
378709158f00SBenoît Canet 
378809158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
378909158f00SBenoît Canet      * most non filter in order to prevent data corruption.
379009158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
379109158f00SBenoît Canet      * blocked by the backing blockers.
379209158f00SBenoît Canet      */
3793e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
379409158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
37955a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
37965a7e7a0bSStefan Hajnoczi         goto out;
379709158f00SBenoît Canet     }
379809158f00SBenoît Canet 
37995a7e7a0bSStefan Hajnoczi out:
38005a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
380109158f00SBenoît Canet     return to_replace_bs;
380209158f00SBenoît Canet }
3803448ad91dSMing Lei 
380491af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
380591af7014SMax Reitz {
380691af7014SMax Reitz     const QDictEntry *entry;
38079e700c1aSKevin Wolf     QemuOptDesc *desc;
3808260fecf1SKevin Wolf     BdrvChild *child;
380991af7014SMax Reitz     bool found_any = false;
3810260fecf1SKevin Wolf     const char *p;
381191af7014SMax Reitz 
381291af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
381391af7014SMax Reitz          entry = qdict_next(bs->options, entry))
381491af7014SMax Reitz     {
3815260fecf1SKevin Wolf         /* Exclude options for children */
3816260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3817260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3818260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3819260fecf1SKevin Wolf             {
3820260fecf1SKevin Wolf                 break;
3821260fecf1SKevin Wolf             }
3822260fecf1SKevin Wolf         }
3823260fecf1SKevin Wolf         if (child) {
38249e700c1aSKevin Wolf             continue;
38259e700c1aSKevin Wolf         }
38269e700c1aSKevin Wolf 
38279e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
38289e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
38299e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
38309e700c1aSKevin Wolf                 break;
38319e700c1aSKevin Wolf             }
38329e700c1aSKevin Wolf         }
38339e700c1aSKevin Wolf         if (desc->name) {
38349e700c1aSKevin Wolf             continue;
38359e700c1aSKevin Wolf         }
38369e700c1aSKevin Wolf 
383791af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
383891af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
383991af7014SMax Reitz         found_any = true;
384091af7014SMax Reitz     }
384191af7014SMax Reitz 
384291af7014SMax Reitz     return found_any;
384391af7014SMax Reitz }
384491af7014SMax Reitz 
384591af7014SMax Reitz /* Updates the following BDS fields:
384691af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
384791af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
384891af7014SMax Reitz  *                    other options; so reading and writing must return the same
384991af7014SMax Reitz  *                    results, but caching etc. may be different)
385091af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
385191af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
385291af7014SMax Reitz  *                       equalling the given one
385391af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
385491af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
385591af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
385691af7014SMax Reitz  */
385791af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
385891af7014SMax Reitz {
385991af7014SMax Reitz     BlockDriver *drv = bs->drv;
386091af7014SMax Reitz     QDict *opts;
386191af7014SMax Reitz 
386291af7014SMax Reitz     if (!drv) {
386391af7014SMax Reitz         return;
386491af7014SMax Reitz     }
386591af7014SMax Reitz 
386691af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
386791af7014SMax Reitz      * refresh that first */
386891af7014SMax Reitz     if (bs->file) {
38699a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
387091af7014SMax Reitz     }
387191af7014SMax Reitz 
387291af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
387391af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
387491af7014SMax Reitz          * information before refreshing it */
387591af7014SMax Reitz         bs->exact_filename[0] = '\0';
387691af7014SMax Reitz         if (bs->full_open_options) {
387791af7014SMax Reitz             QDECREF(bs->full_open_options);
387891af7014SMax Reitz             bs->full_open_options = NULL;
387991af7014SMax Reitz         }
388091af7014SMax Reitz 
38814cdd01d3SKevin Wolf         opts = qdict_new();
38824cdd01d3SKevin Wolf         append_open_options(opts, bs);
38834cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
38844cdd01d3SKevin Wolf         QDECREF(opts);
388591af7014SMax Reitz     } else if (bs->file) {
388691af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
388791af7014SMax Reitz         bool has_open_options;
388891af7014SMax Reitz 
388991af7014SMax Reitz         bs->exact_filename[0] = '\0';
389091af7014SMax Reitz         if (bs->full_open_options) {
389191af7014SMax Reitz             QDECREF(bs->full_open_options);
389291af7014SMax Reitz             bs->full_open_options = NULL;
389391af7014SMax Reitz         }
389491af7014SMax Reitz 
389591af7014SMax Reitz         opts = qdict_new();
389691af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
389791af7014SMax Reitz 
389891af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
389991af7014SMax Reitz          * the underlying file should suffice for this one as well */
39009a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
39019a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
390291af7014SMax Reitz         }
390391af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
390491af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
390591af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
390691af7014SMax Reitz          * contain a representation of the filename, therefore the following
390791af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
39089a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
390991af7014SMax Reitz             qdict_put_obj(opts, "driver",
391091af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
39119a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
39129a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
39139a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
391491af7014SMax Reitz 
391591af7014SMax Reitz             bs->full_open_options = opts;
391691af7014SMax Reitz         } else {
391791af7014SMax Reitz             QDECREF(opts);
391891af7014SMax Reitz         }
391991af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
392091af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
392191af7014SMax Reitz          * so the full options QDict should be equal to the options given
392291af7014SMax Reitz          * specifically for this block device when it was opened (plus the
392391af7014SMax Reitz          * driver specification).
392491af7014SMax Reitz          * Because those options don't change, there is no need to update
392591af7014SMax Reitz          * full_open_options when it's already set. */
392691af7014SMax Reitz 
392791af7014SMax Reitz         opts = qdict_new();
392891af7014SMax Reitz         append_open_options(opts, bs);
392991af7014SMax Reitz         qdict_put_obj(opts, "driver",
393091af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
393191af7014SMax Reitz 
393291af7014SMax Reitz         if (bs->exact_filename[0]) {
393391af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
393491af7014SMax Reitz              * require this filename to be parsed), but we have to find some
393591af7014SMax Reitz              * default solution here, so just include it. If some block driver
393691af7014SMax Reitz              * does not support pure options without any filename at all or
393791af7014SMax Reitz              * needs some special format of the options QDict, it needs to
393891af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
393991af7014SMax Reitz              */
394091af7014SMax Reitz             qdict_put_obj(opts, "filename",
394191af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
394291af7014SMax Reitz         }
394391af7014SMax Reitz 
394491af7014SMax Reitz         bs->full_open_options = opts;
394591af7014SMax Reitz     }
394691af7014SMax Reitz 
394791af7014SMax Reitz     if (bs->exact_filename[0]) {
394891af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
394991af7014SMax Reitz     } else if (bs->full_open_options) {
395091af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
395191af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
395291af7014SMax Reitz                  qstring_get_str(json));
395391af7014SMax Reitz         QDECREF(json);
395491af7014SMax Reitz     }
395591af7014SMax Reitz }
3956e06018adSWen Congyang 
3957e06018adSWen Congyang /*
3958e06018adSWen Congyang  * Hot add/remove a BDS's child. So the user can take a child offline when
3959e06018adSWen Congyang  * it is broken and take a new child online
3960e06018adSWen Congyang  */
3961e06018adSWen Congyang void bdrv_add_child(BlockDriverState *parent_bs, BlockDriverState *child_bs,
3962e06018adSWen Congyang                     Error **errp)
3963e06018adSWen Congyang {
3964e06018adSWen Congyang 
3965e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_add_child) {
3966e06018adSWen Congyang         error_setg(errp, "The node %s does not support adding a child",
3967e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
3968e06018adSWen Congyang         return;
3969e06018adSWen Congyang     }
3970e06018adSWen Congyang 
3971e06018adSWen Congyang     if (!QLIST_EMPTY(&child_bs->parents)) {
3972e06018adSWen Congyang         error_setg(errp, "The node %s already has a parent",
3973e06018adSWen Congyang                    child_bs->node_name);
3974e06018adSWen Congyang         return;
3975e06018adSWen Congyang     }
3976e06018adSWen Congyang 
3977e06018adSWen Congyang     parent_bs->drv->bdrv_add_child(parent_bs, child_bs, errp);
3978e06018adSWen Congyang }
3979e06018adSWen Congyang 
3980e06018adSWen Congyang void bdrv_del_child(BlockDriverState *parent_bs, BdrvChild *child, Error **errp)
3981e06018adSWen Congyang {
3982e06018adSWen Congyang     BdrvChild *tmp;
3983e06018adSWen Congyang 
3984e06018adSWen Congyang     if (!parent_bs->drv || !parent_bs->drv->bdrv_del_child) {
3985e06018adSWen Congyang         error_setg(errp, "The node %s does not support removing a child",
3986e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs));
3987e06018adSWen Congyang         return;
3988e06018adSWen Congyang     }
3989e06018adSWen Congyang 
3990e06018adSWen Congyang     QLIST_FOREACH(tmp, &parent_bs->children, next) {
3991e06018adSWen Congyang         if (tmp == child) {
3992e06018adSWen Congyang             break;
3993e06018adSWen Congyang         }
3994e06018adSWen Congyang     }
3995e06018adSWen Congyang 
3996e06018adSWen Congyang     if (!tmp) {
3997e06018adSWen Congyang         error_setg(errp, "The node %s does not have a child named %s",
3998e06018adSWen Congyang                    bdrv_get_device_or_node_name(parent_bs),
3999e06018adSWen Congyang                    bdrv_get_device_or_node_name(child->bs));
4000e06018adSWen Congyang         return;
4001e06018adSWen Congyang     }
4002e06018adSWen Congyang 
4003e06018adSWen Congyang     parent_bs->drv->bdrv_del_child(parent_bs, child, errp);
4004e06018adSWen Congyang }
4005