xref: /openbmc/qemu/block.c (revision e6ff69bf5edfb0475903456a8c7f785635986540)
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"
41db628338SAlberto Garcia #include "block/throttle-groups.h"
42f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
43f348b6d1SVeronia Bahaa #include "qemu/id.h"
44fc01f7e7Sbellard 
4571e72a19SJuan Quintela #ifdef CONFIG_BSD
467674e7bfSbellard #include <sys/ioctl.h>
4772cf2d4fSBlue Swirl #include <sys/queue.h>
48c5e97233Sblueswir1 #ifndef __DragonFly__
497674e7bfSbellard #include <sys/disk.h>
507674e7bfSbellard #endif
51c5e97233Sblueswir1 #endif
527674e7bfSbellard 
5349dc768dSaliguori #ifdef _WIN32
5449dc768dSaliguori #include <windows.h>
5549dc768dSaliguori #endif
5649dc768dSaliguori 
571c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
581c9805a3SStefan Hajnoczi 
59dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
60dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
61dc364f4cSBenoît Canet 
622c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
632c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
642c1d04e0SMax Reitz 
658a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
668a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
67ea2384d3Sbellard 
68f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
69f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
70f3930ed0SKevin Wolf                              BlockDriverState *parent,
71ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
72f3930ed0SKevin Wolf 
73eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
74eb852011SMarkus Armbruster static int use_bdrv_whitelist;
75eb852011SMarkus Armbruster 
7664dff520SMax Reitz static void bdrv_close(BlockDriverState *bs);
7764dff520SMax Reitz 
789e0b22f4SStefan Hajnoczi #ifdef _WIN32
799e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
809e0b22f4SStefan Hajnoczi {
819e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
829e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
839e0b22f4SStefan Hajnoczi             filename[1] == ':');
849e0b22f4SStefan Hajnoczi }
859e0b22f4SStefan Hajnoczi 
869e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
879e0b22f4SStefan Hajnoczi {
889e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
899e0b22f4SStefan Hajnoczi         filename[2] == '\0')
909e0b22f4SStefan Hajnoczi         return 1;
919e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
929e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
939e0b22f4SStefan Hajnoczi         return 1;
949e0b22f4SStefan Hajnoczi     return 0;
959e0b22f4SStefan Hajnoczi }
969e0b22f4SStefan Hajnoczi #endif
979e0b22f4SStefan Hajnoczi 
98339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
99339064d5SKevin Wolf {
100339064d5SKevin Wolf     if (!bs || !bs->drv) {
101459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
102459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
103339064d5SKevin Wolf     }
104339064d5SKevin Wolf 
105339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
106339064d5SKevin Wolf }
107339064d5SKevin Wolf 
1084196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1094196d2f0SDenis V. Lunev {
1104196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
111459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
112459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1134196d2f0SDenis V. Lunev     }
1144196d2f0SDenis V. Lunev 
1154196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1164196d2f0SDenis V. Lunev }
1174196d2f0SDenis V. Lunev 
1189e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1195c98415bSMax Reitz int path_has_protocol(const char *path)
1209e0b22f4SStefan Hajnoczi {
121947995c0SPaolo Bonzini     const char *p;
122947995c0SPaolo Bonzini 
1239e0b22f4SStefan Hajnoczi #ifdef _WIN32
1249e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1259e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1269e0b22f4SStefan Hajnoczi         return 0;
1279e0b22f4SStefan Hajnoczi     }
128947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
129947995c0SPaolo Bonzini #else
130947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1319e0b22f4SStefan Hajnoczi #endif
1329e0b22f4SStefan Hajnoczi 
133947995c0SPaolo Bonzini     return *p == ':';
1349e0b22f4SStefan Hajnoczi }
1359e0b22f4SStefan Hajnoczi 
13683f64091Sbellard int path_is_absolute(const char *path)
13783f64091Sbellard {
13821664424Sbellard #ifdef _WIN32
13921664424Sbellard     /* specific case for names like: "\\.\d:" */
140f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
14121664424Sbellard         return 1;
142f53f4da9SPaolo Bonzini     }
143f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1443b9f94e1Sbellard #else
145f53f4da9SPaolo Bonzini     return (*path == '/');
1463b9f94e1Sbellard #endif
14783f64091Sbellard }
14883f64091Sbellard 
14983f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
15083f64091Sbellard    path to it by considering it is relative to base_path. URL are
15183f64091Sbellard    supported. */
15283f64091Sbellard void path_combine(char *dest, int dest_size,
15383f64091Sbellard                   const char *base_path,
15483f64091Sbellard                   const char *filename)
15583f64091Sbellard {
15683f64091Sbellard     const char *p, *p1;
15783f64091Sbellard     int len;
15883f64091Sbellard 
15983f64091Sbellard     if (dest_size <= 0)
16083f64091Sbellard         return;
16183f64091Sbellard     if (path_is_absolute(filename)) {
16283f64091Sbellard         pstrcpy(dest, dest_size, filename);
16383f64091Sbellard     } else {
16483f64091Sbellard         p = strchr(base_path, ':');
16583f64091Sbellard         if (p)
16683f64091Sbellard             p++;
16783f64091Sbellard         else
16883f64091Sbellard             p = base_path;
1693b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1703b9f94e1Sbellard #ifdef _WIN32
1713b9f94e1Sbellard         {
1723b9f94e1Sbellard             const char *p2;
1733b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1743b9f94e1Sbellard             if (!p1 || p2 > p1)
1753b9f94e1Sbellard                 p1 = p2;
1763b9f94e1Sbellard         }
1773b9f94e1Sbellard #endif
17883f64091Sbellard         if (p1)
17983f64091Sbellard             p1++;
18083f64091Sbellard         else
18183f64091Sbellard             p1 = base_path;
18283f64091Sbellard         if (p1 > p)
18383f64091Sbellard             p = p1;
18483f64091Sbellard         len = p - base_path;
18583f64091Sbellard         if (len > dest_size - 1)
18683f64091Sbellard             len = dest_size - 1;
18783f64091Sbellard         memcpy(dest, base_path, len);
18883f64091Sbellard         dest[len] = '\0';
18983f64091Sbellard         pstrcat(dest, dest_size, filename);
19083f64091Sbellard     }
19183f64091Sbellard }
19283f64091Sbellard 
1930a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
1940a82855aSMax Reitz                                                   const char *backing,
1959f07429eSMax Reitz                                                   char *dest, size_t sz,
1969f07429eSMax Reitz                                                   Error **errp)
1970a82855aSMax Reitz {
1989f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
1999f07429eSMax Reitz         path_is_absolute(backing))
2009f07429eSMax Reitz     {
2010a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2029f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2039f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2049f07429eSMax Reitz                    backed);
2050a82855aSMax Reitz     } else {
2060a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2070a82855aSMax Reitz     }
2080a82855aSMax Reitz }
2090a82855aSMax Reitz 
2109f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2119f07429eSMax Reitz                                     Error **errp)
212dc5a1371SPaolo Bonzini {
2139f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2149f07429eSMax Reitz 
2159f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2169f07429eSMax Reitz                                                  dest, sz, errp);
217dc5a1371SPaolo Bonzini }
218dc5a1371SPaolo Bonzini 
2190eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2200eb7217eSStefan Hajnoczi {
2210eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
222b2e12bc6SChristoph Hellwig 
2238a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
224ea2384d3Sbellard }
225b338082bSbellard 
2267f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
227fc01f7e7Sbellard {
2289aaf28c6SMax Reitz     return bdrv_new();
229e4e9986bSMarkus Armbruster }
230e4e9986bSMarkus Armbruster 
231e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
232e4e9986bSMarkus Armbruster {
233e4e9986bSMarkus Armbruster     BlockDriverState *bs;
234e4e9986bSMarkus Armbruster     int i;
235e4e9986bSMarkus Armbruster 
2365839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
237e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
238fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
239fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
240fbe40ff7SFam Zheng     }
241d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
242cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
243cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2449fcb0251SFam Zheng     bs->refcnt = 1;
245dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
246d7d512f6SPaolo Bonzini 
2472c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
2482c1d04e0SMax Reitz 
249b338082bSbellard     return bs;
250b338082bSbellard }
251b338082bSbellard 
252ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
253ea2384d3Sbellard {
254ea2384d3Sbellard     BlockDriver *drv1;
2558a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2568a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
257ea2384d3Sbellard             return drv1;
258ea2384d3Sbellard         }
2598a22f02aSStefan Hajnoczi     }
260ea2384d3Sbellard     return NULL;
261ea2384d3Sbellard }
262ea2384d3Sbellard 
263b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
264eb852011SMarkus Armbruster {
265b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
266b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
267b64ec4e4SFam Zheng     };
268b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
269b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
270eb852011SMarkus Armbruster     };
271eb852011SMarkus Armbruster     const char **p;
272eb852011SMarkus Armbruster 
273b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
274eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
275b64ec4e4SFam Zheng     }
276eb852011SMarkus Armbruster 
277b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
278eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
279eb852011SMarkus Armbruster             return 1;
280eb852011SMarkus Armbruster         }
281eb852011SMarkus Armbruster     }
282b64ec4e4SFam Zheng     if (read_only) {
283b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
284b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
285b64ec4e4SFam Zheng                 return 1;
286b64ec4e4SFam Zheng             }
287b64ec4e4SFam Zheng         }
288b64ec4e4SFam Zheng     }
289eb852011SMarkus Armbruster     return 0;
290eb852011SMarkus Armbruster }
291eb852011SMarkus Armbruster 
292*e6ff69bfSDaniel P. Berrange bool bdrv_uses_whitelist(void)
293*e6ff69bfSDaniel P. Berrange {
294*e6ff69bfSDaniel P. Berrange     return use_bdrv_whitelist;
295*e6ff69bfSDaniel P. Berrange }
296*e6ff69bfSDaniel P. Berrange 
2975b7e1542SZhi Yong Wu typedef struct CreateCo {
2985b7e1542SZhi Yong Wu     BlockDriver *drv;
2995b7e1542SZhi Yong Wu     char *filename;
30083d0521aSChunyan Liu     QemuOpts *opts;
3015b7e1542SZhi Yong Wu     int ret;
302cc84d90fSMax Reitz     Error *err;
3035b7e1542SZhi Yong Wu } CreateCo;
3045b7e1542SZhi Yong Wu 
3055b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3065b7e1542SZhi Yong Wu {
307cc84d90fSMax Reitz     Error *local_err = NULL;
308cc84d90fSMax Reitz     int ret;
309cc84d90fSMax Reitz 
3105b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3115b7e1542SZhi Yong Wu     assert(cco->drv);
3125b7e1542SZhi Yong Wu 
313c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
31484d18f06SMarkus Armbruster     if (local_err) {
315cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
316cc84d90fSMax Reitz     }
317cc84d90fSMax Reitz     cco->ret = ret;
3185b7e1542SZhi Yong Wu }
3195b7e1542SZhi Yong Wu 
3200e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
32183d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
322ea2384d3Sbellard {
3235b7e1542SZhi Yong Wu     int ret;
3240e7e1989SKevin Wolf 
3255b7e1542SZhi Yong Wu     Coroutine *co;
3265b7e1542SZhi Yong Wu     CreateCo cco = {
3275b7e1542SZhi Yong Wu         .drv = drv,
3285b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
32983d0521aSChunyan Liu         .opts = opts,
3305b7e1542SZhi Yong Wu         .ret = NOT_DONE,
331cc84d90fSMax Reitz         .err = NULL,
3325b7e1542SZhi Yong Wu     };
3335b7e1542SZhi Yong Wu 
334c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
335cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
33680168bffSLuiz Capitulino         ret = -ENOTSUP;
33780168bffSLuiz Capitulino         goto out;
3385b7e1542SZhi Yong Wu     }
3395b7e1542SZhi Yong Wu 
3405b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3415b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3425b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3435b7e1542SZhi Yong Wu     } else {
3445b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3455b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3465b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
347b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3485b7e1542SZhi Yong Wu         }
3495b7e1542SZhi Yong Wu     }
3505b7e1542SZhi Yong Wu 
3515b7e1542SZhi Yong Wu     ret = cco.ret;
352cc84d90fSMax Reitz     if (ret < 0) {
35384d18f06SMarkus Armbruster         if (cco.err) {
354cc84d90fSMax Reitz             error_propagate(errp, cco.err);
355cc84d90fSMax Reitz         } else {
356cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
357cc84d90fSMax Reitz         }
358cc84d90fSMax Reitz     }
3595b7e1542SZhi Yong Wu 
36080168bffSLuiz Capitulino out:
36180168bffSLuiz Capitulino     g_free(cco.filename);
3625b7e1542SZhi Yong Wu     return ret;
363ea2384d3Sbellard }
364ea2384d3Sbellard 
365c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
36684a12e66SChristoph Hellwig {
36784a12e66SChristoph Hellwig     BlockDriver *drv;
368cc84d90fSMax Reitz     Error *local_err = NULL;
369cc84d90fSMax Reitz     int ret;
37084a12e66SChristoph Hellwig 
371b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
37284a12e66SChristoph Hellwig     if (drv == NULL) {
37316905d71SStefan Hajnoczi         return -ENOENT;
37484a12e66SChristoph Hellwig     }
37584a12e66SChristoph Hellwig 
376c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
37784d18f06SMarkus Armbruster     if (local_err) {
378cc84d90fSMax Reitz         error_propagate(errp, local_err);
379cc84d90fSMax Reitz     }
380cc84d90fSMax Reitz     return ret;
38184a12e66SChristoph Hellwig }
38284a12e66SChristoph Hellwig 
383892b7de8SEkaterina Tumanova /**
384892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
385892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
386892b7de8SEkaterina Tumanova  * On failure return -errno.
387892b7de8SEkaterina Tumanova  * @bs must not be empty.
388892b7de8SEkaterina Tumanova  */
389892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
390892b7de8SEkaterina Tumanova {
391892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
392892b7de8SEkaterina Tumanova 
393892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
394892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
395892b7de8SEkaterina Tumanova     }
396892b7de8SEkaterina Tumanova 
397892b7de8SEkaterina Tumanova     return -ENOTSUP;
398892b7de8SEkaterina Tumanova }
399892b7de8SEkaterina Tumanova 
400892b7de8SEkaterina Tumanova /**
401892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
402892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
403892b7de8SEkaterina Tumanova  * On failure return -errno.
404892b7de8SEkaterina Tumanova  * @bs must not be empty.
405892b7de8SEkaterina Tumanova  */
406892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
407892b7de8SEkaterina Tumanova {
408892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
409892b7de8SEkaterina Tumanova 
410892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
411892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
412892b7de8SEkaterina Tumanova     }
413892b7de8SEkaterina Tumanova 
414892b7de8SEkaterina Tumanova     return -ENOTSUP;
415892b7de8SEkaterina Tumanova }
416892b7de8SEkaterina Tumanova 
417eba25057SJim Meyering /*
418eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
419eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
420eba25057SJim Meyering  */
421eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
422eba25057SJim Meyering {
423d5249393Sbellard #ifdef _WIN32
4243b9f94e1Sbellard     char temp_dir[MAX_PATH];
425eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
426eba25057SJim Meyering        have length MAX_PATH or greater.  */
427eba25057SJim Meyering     assert(size >= MAX_PATH);
428eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
429eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
430eba25057SJim Meyering             ? 0 : -GetLastError());
431d5249393Sbellard #else
432ea2384d3Sbellard     int fd;
4337ccfb2ebSblueswir1     const char *tmpdir;
4340badc1eeSaurel32     tmpdir = getenv("TMPDIR");
43569bef793SAmit Shah     if (!tmpdir) {
43669bef793SAmit Shah         tmpdir = "/var/tmp";
43769bef793SAmit Shah     }
438eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
439eba25057SJim Meyering         return -EOVERFLOW;
440ea2384d3Sbellard     }
441eba25057SJim Meyering     fd = mkstemp(filename);
442fe235a06SDunrong Huang     if (fd < 0) {
443fe235a06SDunrong Huang         return -errno;
444fe235a06SDunrong Huang     }
445fe235a06SDunrong Huang     if (close(fd) != 0) {
446fe235a06SDunrong Huang         unlink(filename);
447eba25057SJim Meyering         return -errno;
448eba25057SJim Meyering     }
449eba25057SJim Meyering     return 0;
450d5249393Sbellard #endif
451eba25057SJim Meyering }
452ea2384d3Sbellard 
453f3a5d3f8SChristoph Hellwig /*
454f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
455f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
456f3a5d3f8SChristoph Hellwig  */
457f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
458f3a5d3f8SChristoph Hellwig {
459508c7cb3SChristoph Hellwig     int score_max = 0, score;
460508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
461f3a5d3f8SChristoph Hellwig 
4628a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
463508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
464508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
465508c7cb3SChristoph Hellwig             if (score > score_max) {
466508c7cb3SChristoph Hellwig                 score_max = score;
467508c7cb3SChristoph Hellwig                 drv = d;
468f3a5d3f8SChristoph Hellwig             }
469508c7cb3SChristoph Hellwig         }
470f3a5d3f8SChristoph Hellwig     }
471f3a5d3f8SChristoph Hellwig 
472508c7cb3SChristoph Hellwig     return drv;
473f3a5d3f8SChristoph Hellwig }
474f3a5d3f8SChristoph Hellwig 
47598289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
476b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
477b65a5e12SMax Reitz                                 Error **errp)
47884a12e66SChristoph Hellwig {
47984a12e66SChristoph Hellwig     BlockDriver *drv1;
48084a12e66SChristoph Hellwig     char protocol[128];
48184a12e66SChristoph Hellwig     int len;
48284a12e66SChristoph Hellwig     const char *p;
48384a12e66SChristoph Hellwig 
48466f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
48566f82ceeSKevin Wolf 
48639508e7aSChristoph Hellwig     /*
48739508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
48839508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
48939508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
49039508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
49139508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
49239508e7aSChristoph Hellwig      */
49384a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
49439508e7aSChristoph Hellwig     if (drv1) {
49584a12e66SChristoph Hellwig         return drv1;
49684a12e66SChristoph Hellwig     }
49739508e7aSChristoph Hellwig 
49898289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
499ef810437SMax Reitz         return &bdrv_file;
50039508e7aSChristoph Hellwig     }
50198289620SKevin Wolf 
5029e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5039e0b22f4SStefan Hajnoczi     assert(p != NULL);
50484a12e66SChristoph Hellwig     len = p - filename;
50584a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
50684a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
50784a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
50884a12e66SChristoph Hellwig     protocol[len] = '\0';
50984a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
51084a12e66SChristoph Hellwig         if (drv1->protocol_name &&
51184a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
51284a12e66SChristoph Hellwig             return drv1;
51384a12e66SChristoph Hellwig         }
51484a12e66SChristoph Hellwig     }
515b65a5e12SMax Reitz 
516b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
51784a12e66SChristoph Hellwig     return NULL;
51884a12e66SChristoph Hellwig }
51984a12e66SChristoph Hellwig 
520c6684249SMarkus Armbruster /*
521c6684249SMarkus Armbruster  * Guess image format by probing its contents.
522c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
523c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
524c6684249SMarkus Armbruster  *
525c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5267cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5277cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
528c6684249SMarkus Armbruster  * @filename    is its filename.
529c6684249SMarkus Armbruster  *
530c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
531c6684249SMarkus Armbruster  * probing score.
532c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
533c6684249SMarkus Armbruster  */
53438f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
535c6684249SMarkus Armbruster                             const char *filename)
536c6684249SMarkus Armbruster {
537c6684249SMarkus Armbruster     int score_max = 0, score;
538c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
539c6684249SMarkus Armbruster 
540c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
541c6684249SMarkus Armbruster         if (d->bdrv_probe) {
542c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
543c6684249SMarkus Armbruster             if (score > score_max) {
544c6684249SMarkus Armbruster                 score_max = score;
545c6684249SMarkus Armbruster                 drv = d;
546c6684249SMarkus Armbruster             }
547c6684249SMarkus Armbruster         }
548c6684249SMarkus Armbruster     }
549c6684249SMarkus Armbruster 
550c6684249SMarkus Armbruster     return drv;
551c6684249SMarkus Armbruster }
552c6684249SMarkus Armbruster 
553f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
55434b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
555ea2384d3Sbellard {
556c6684249SMarkus Armbruster     BlockDriver *drv;
5577cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
558f500a6d3SKevin Wolf     int ret = 0;
559f8ea0b00SNicholas Bellinger 
56008a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
561b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
562ef810437SMax Reitz         *pdrv = &bdrv_raw;
563c98ac35dSStefan Weil         return ret;
5641a396859SNicholas A. Bellinger     }
565f8ea0b00SNicholas Bellinger 
56683f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
567ea2384d3Sbellard     if (ret < 0) {
56834b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
56934b5d2c6SMax Reitz                          "format");
570c98ac35dSStefan Weil         *pdrv = NULL;
571c98ac35dSStefan Weil         return ret;
572ea2384d3Sbellard     }
573ea2384d3Sbellard 
574c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
575c98ac35dSStefan Weil     if (!drv) {
57634b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
57734b5d2c6SMax Reitz                    "driver found");
578c98ac35dSStefan Weil         ret = -ENOENT;
579c98ac35dSStefan Weil     }
580c98ac35dSStefan Weil     *pdrv = drv;
581c98ac35dSStefan Weil     return ret;
582ea2384d3Sbellard }
583ea2384d3Sbellard 
58451762288SStefan Hajnoczi /**
58551762288SStefan Hajnoczi  * Set the current 'total_sectors' value
58665a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
58751762288SStefan Hajnoczi  */
58851762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
58951762288SStefan Hajnoczi {
59051762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
59151762288SStefan Hajnoczi 
592396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
593b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
594396759adSNicholas Bellinger         return 0;
595396759adSNicholas Bellinger 
59651762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
59751762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
59851762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
59951762288SStefan Hajnoczi         if (length < 0) {
60051762288SStefan Hajnoczi             return length;
60151762288SStefan Hajnoczi         }
6027e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
60351762288SStefan Hajnoczi     }
60451762288SStefan Hajnoczi 
60551762288SStefan Hajnoczi     bs->total_sectors = hint;
60651762288SStefan Hajnoczi     return 0;
60751762288SStefan Hajnoczi }
60851762288SStefan Hajnoczi 
609c3993cdcSStefan Hajnoczi /**
610cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
611cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
612cddff5baSKevin Wolf  */
613cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
614cddff5baSKevin Wolf                               QDict *old_options)
615cddff5baSKevin Wolf {
616cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
617cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
618cddff5baSKevin Wolf     } else {
619cddff5baSKevin Wolf         qdict_join(options, old_options, false);
620cddff5baSKevin Wolf     }
621cddff5baSKevin Wolf }
622cddff5baSKevin Wolf 
623cddff5baSKevin Wolf /**
6249e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6259e8f1835SPaolo Bonzini  *
6269e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6279e8f1835SPaolo Bonzini  */
6289e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6299e8f1835SPaolo Bonzini {
6309e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6319e8f1835SPaolo Bonzini 
6329e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6339e8f1835SPaolo Bonzini         /* do nothing */
6349e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6359e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6369e8f1835SPaolo Bonzini     } else {
6379e8f1835SPaolo Bonzini         return -1;
6389e8f1835SPaolo Bonzini     }
6399e8f1835SPaolo Bonzini 
6409e8f1835SPaolo Bonzini     return 0;
6419e8f1835SPaolo Bonzini }
6429e8f1835SPaolo Bonzini 
6439e8f1835SPaolo Bonzini /**
644c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
645c3993cdcSStefan Hajnoczi  *
646c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
647c3993cdcSStefan Hajnoczi  */
648c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
649c3993cdcSStefan Hajnoczi {
650c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
651c3993cdcSStefan Hajnoczi 
652c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
653c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
65492196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
65592196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
656c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
657c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
658c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
659c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
660c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
661c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
662c3993cdcSStefan Hajnoczi         /* this is the default */
663c3993cdcSStefan Hajnoczi     } else {
664c3993cdcSStefan Hajnoczi         return -1;
665c3993cdcSStefan Hajnoczi     }
666c3993cdcSStefan Hajnoczi 
667c3993cdcSStefan Hajnoczi     return 0;
668c3993cdcSStefan Hajnoczi }
669c3993cdcSStefan Hajnoczi 
6700b50cc88SKevin Wolf /*
67173176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
67273176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
67373176beeSKevin Wolf  * flags like a backing file)
674b1e6fc08SKevin Wolf  */
67573176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
67673176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
677b1e6fc08SKevin Wolf {
67873176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
67973176beeSKevin Wolf 
68073176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
68173176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
68273176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
68373176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
684b1e6fc08SKevin Wolf }
685b1e6fc08SKevin Wolf 
686b1e6fc08SKevin Wolf /*
6878e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
6888e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
6890b50cc88SKevin Wolf  */
6908e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
6918e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
6920b50cc88SKevin Wolf {
6938e2160e2SKevin Wolf     int flags = parent_flags;
6948e2160e2SKevin Wolf 
6950b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6960b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
6970b50cc88SKevin Wolf 
69891a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
69991a097e7SKevin Wolf      * the parent. */
70091a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
70191a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
70291a097e7SKevin Wolf 
7030b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
70491a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
70591a097e7SKevin Wolf      * corresponding parent options. */
70691a097e7SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
70791a097e7SKevin Wolf     flags |= BDRV_O_UNMAP;
7080b50cc88SKevin Wolf 
7090b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
710abb06c5aSDaniel P. Berrange     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ |
711abb06c5aSDaniel P. Berrange                BDRV_O_NO_IO);
7120b50cc88SKevin Wolf 
7138e2160e2SKevin Wolf     *child_flags = flags;
7140b50cc88SKevin Wolf }
7150b50cc88SKevin Wolf 
716f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7178e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
718f3930ed0SKevin Wolf };
719f3930ed0SKevin Wolf 
720f3930ed0SKevin Wolf /*
7218e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7228e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7238e2160e2SKevin Wolf  * flags for the parent BDS
724f3930ed0SKevin Wolf  */
7258e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7268e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
727f3930ed0SKevin Wolf {
7288e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7298e2160e2SKevin Wolf                                parent_flags, parent_options);
7308e2160e2SKevin Wolf 
731abb06c5aSDaniel P. Berrange     *child_flags &= ~(BDRV_O_PROTOCOL | BDRV_O_NO_IO);
732f3930ed0SKevin Wolf }
733f3930ed0SKevin Wolf 
734f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7358e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
736f3930ed0SKevin Wolf };
737f3930ed0SKevin Wolf 
738317fc44eSKevin Wolf /*
7398e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7408e2160e2SKevin Wolf  * given options and flags for the parent BDS
741317fc44eSKevin Wolf  */
7428e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7438e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
744317fc44eSKevin Wolf {
7458e2160e2SKevin Wolf     int flags = parent_flags;
7468e2160e2SKevin Wolf 
747b8816a43SKevin Wolf     /* The cache mode is inherited unmodified for backing files; except WCE,
748b8816a43SKevin Wolf      * which is only applied on the top level (BlockBackend) */
749b8816a43SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
75091a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
75191a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
75291a097e7SKevin Wolf 
753317fc44eSKevin Wolf     /* backing files always opened read-only */
754317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
755317fc44eSKevin Wolf 
756317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7578bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
758317fc44eSKevin Wolf 
7598e2160e2SKevin Wolf     *child_flags = flags;
760317fc44eSKevin Wolf }
761317fc44eSKevin Wolf 
762f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7638e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
764f3930ed0SKevin Wolf };
765f3930ed0SKevin Wolf 
7667b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7677b272452SKevin Wolf {
7687b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7697b272452SKevin Wolf 
7707b272452SKevin Wolf     /*
7717b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7727b272452SKevin Wolf      * image.
7737b272452SKevin Wolf      */
77420cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7757b272452SKevin Wolf 
7767b272452SKevin Wolf     /*
7777b272452SKevin Wolf      * Snapshots should be writable.
7787b272452SKevin Wolf      */
7798bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7807b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7817b272452SKevin Wolf     }
7827b272452SKevin Wolf 
7837b272452SKevin Wolf     return open_flags;
7847b272452SKevin Wolf }
7857b272452SKevin Wolf 
78691a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
78791a097e7SKevin Wolf {
78891a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
78991a097e7SKevin Wolf 
79091a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_WB));
79191a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, false)) {
79291a097e7SKevin Wolf         *flags |= BDRV_O_CACHE_WB;
79391a097e7SKevin Wolf     }
79491a097e7SKevin Wolf 
79591a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
79691a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
79791a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
79891a097e7SKevin Wolf     }
79991a097e7SKevin Wolf 
80091a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
80191a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
80291a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
80391a097e7SKevin Wolf     }
80491a097e7SKevin Wolf }
80591a097e7SKevin Wolf 
80691a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
80791a097e7SKevin Wolf {
80891a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_WB)) {
80991a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_WB,
81091a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_CACHE_WB));
81191a097e7SKevin Wolf     }
81291a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
81391a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
81491a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
81591a097e7SKevin Wolf     }
81691a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
81791a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
81891a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
81991a097e7SKevin Wolf     }
82091a097e7SKevin Wolf }
82191a097e7SKevin Wolf 
822636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8236913c0c2SBenoît Canet                                   const char *node_name,
8246913c0c2SBenoît Canet                                   Error **errp)
8256913c0c2SBenoît Canet {
82615489c76SJeff Cody     char *gen_node_name = NULL;
8276913c0c2SBenoît Canet 
82815489c76SJeff Cody     if (!node_name) {
82915489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
83015489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
83115489c76SJeff Cody         /*
83215489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
83315489c76SJeff Cody          * generated (generated names use characters not available to the user)
83415489c76SJeff Cody          */
8359aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
836636ea370SKevin Wolf         return;
8376913c0c2SBenoît Canet     }
8386913c0c2SBenoît Canet 
8390c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8407f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8410c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8420c5e94eeSBenoît Canet                    node_name);
84315489c76SJeff Cody         goto out;
8440c5e94eeSBenoît Canet     }
8450c5e94eeSBenoît Canet 
8466913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8476913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8486913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
84915489c76SJeff Cody         goto out;
8506913c0c2SBenoît Canet     }
8516913c0c2SBenoît Canet 
8526913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8536913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8546913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
85515489c76SJeff Cody out:
85615489c76SJeff Cody     g_free(gen_node_name);
8576913c0c2SBenoît Canet }
8586913c0c2SBenoît Canet 
85918edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
86018edf289SKevin Wolf     .name = "bdrv_common",
86118edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
86218edf289SKevin Wolf     .desc = {
86318edf289SKevin Wolf         {
86418edf289SKevin Wolf             .name = "node-name",
86518edf289SKevin Wolf             .type = QEMU_OPT_STRING,
86618edf289SKevin Wolf             .help = "Node name of the block device node",
86718edf289SKevin Wolf         },
86862392ebbSKevin Wolf         {
86962392ebbSKevin Wolf             .name = "driver",
87062392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
87162392ebbSKevin Wolf             .help = "Block driver to use for the node",
87262392ebbSKevin Wolf         },
87391a097e7SKevin Wolf         {
87491a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
87591a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87691a097e7SKevin Wolf             .help = "Enable writeback mode",
87791a097e7SKevin Wolf         },
87891a097e7SKevin Wolf         {
87991a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
88091a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
88191a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
88291a097e7SKevin Wolf         },
88391a097e7SKevin Wolf         {
88491a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
88591a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
88691a097e7SKevin Wolf             .help = "Ignore flush requests",
88791a097e7SKevin Wolf         },
88818edf289SKevin Wolf         { /* end of list */ }
88918edf289SKevin Wolf     },
89018edf289SKevin Wolf };
89118edf289SKevin Wolf 
892b6ce07aaSKevin Wolf /*
89357915332SKevin Wolf  * Common part for opening disk images and files
894b6ad491aSKevin Wolf  *
895b6ad491aSKevin Wolf  * Removes all processed options from *options.
89657915332SKevin Wolf  */
8979a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
89882dc8b41SKevin Wolf                             QDict *options, Error **errp)
89957915332SKevin Wolf {
90057915332SKevin Wolf     int ret, open_flags;
901035fccdfSKevin Wolf     const char *filename;
90262392ebbSKevin Wolf     const char *driver_name = NULL;
9036913c0c2SBenoît Canet     const char *node_name = NULL;
90418edf289SKevin Wolf     QemuOpts *opts;
90562392ebbSKevin Wolf     BlockDriver *drv;
90634b5d2c6SMax Reitz     Error *local_err = NULL;
90757915332SKevin Wolf 
9086405875cSPaolo Bonzini     assert(bs->file == NULL);
909707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
91057915332SKevin Wolf 
91162392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
91262392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
91362392ebbSKevin Wolf     if (local_err) {
91462392ebbSKevin Wolf         error_propagate(errp, local_err);
91562392ebbSKevin Wolf         ret = -EINVAL;
91662392ebbSKevin Wolf         goto fail_opts;
91762392ebbSKevin Wolf     }
91862392ebbSKevin Wolf 
91962392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
92062392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
92162392ebbSKevin Wolf     assert(drv != NULL);
92262392ebbSKevin Wolf 
92345673671SKevin Wolf     if (file != NULL) {
9249a4f4c31SKevin Wolf         filename = file->bs->filename;
92545673671SKevin Wolf     } else {
92645673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
92745673671SKevin Wolf     }
92845673671SKevin Wolf 
929765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
930765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
931765003dbSKevin Wolf                    drv->format_name);
93218edf289SKevin Wolf         ret = -EINVAL;
93318edf289SKevin Wolf         goto fail_opts;
93418edf289SKevin Wolf     }
93518edf289SKevin Wolf 
93682dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
93782dc8b41SKevin Wolf                            drv->format_name);
93862392ebbSKevin Wolf 
93918edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
940636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9410fb6395cSMarkus Armbruster     if (local_err) {
942636ea370SKevin Wolf         error_propagate(errp, local_err);
94318edf289SKevin Wolf         ret = -EINVAL;
94418edf289SKevin Wolf         goto fail_opts;
9455d186eb0SKevin Wolf     }
9465d186eb0SKevin Wolf 
947c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9480d51b4deSAsias He     bs->zero_beyond_eof = true;
94982dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
950b64ec4e4SFam Zheng 
951b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9528f94a6e4SKevin Wolf         error_setg(errp,
9538f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9548f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9558f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9568f94a6e4SKevin Wolf                    drv->format_name);
95718edf289SKevin Wolf         ret = -ENOTSUP;
95818edf289SKevin Wolf         goto fail_opts;
959b64ec4e4SFam Zheng     }
96057915332SKevin Wolf 
96153fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
96282dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9630ebd24e0SKevin Wolf         if (!bs->read_only) {
96453fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9650ebd24e0SKevin Wolf         } else {
9660ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
96718edf289SKevin Wolf             ret = -EINVAL;
96818edf289SKevin Wolf             goto fail_opts;
9690ebd24e0SKevin Wolf         }
97053fec9d3SStefan Hajnoczi     }
97153fec9d3SStefan Hajnoczi 
972c2ad1b0cSKevin Wolf     if (filename != NULL) {
97357915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
974c2ad1b0cSKevin Wolf     } else {
975c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
976c2ad1b0cSKevin Wolf     }
97791af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97857915332SKevin Wolf 
97957915332SKevin Wolf     bs->drv = drv;
9807267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
98157915332SKevin Wolf 
98291a097e7SKevin Wolf     /* Apply cache mode options */
98391a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
98473ac451fSKevin Wolf 
98573ac451fSKevin Wolf     if (!bs->blk && (bs->open_flags & BDRV_O_CACHE_WB) == 0) {
98673ac451fSKevin Wolf         error_setg(errp, "Can't set writethrough mode except for the root");
98773ac451fSKevin Wolf         ret = -EINVAL;
98873ac451fSKevin Wolf         goto free_and_fail;
98973ac451fSKevin Wolf     }
99073ac451fSKevin Wolf 
99191a097e7SKevin Wolf     bdrv_set_enable_write_cache(bs, bs->open_flags & BDRV_O_CACHE_WB);
992e7c63796SStefan Hajnoczi 
99366f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
99482dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
99566f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9965d186eb0SKevin Wolf         assert(file == NULL);
997030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
99834b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
999f500a6d3SKevin Wolf     } else {
10002af5ef70SKevin Wolf         if (file == NULL) {
100134b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
100234b5d2c6SMax Reitz                        "protocol level", drv->format_name);
10032af5ef70SKevin Wolf             ret = -EINVAL;
10042af5ef70SKevin Wolf             goto free_and_fail;
10052af5ef70SKevin Wolf         }
1006f500a6d3SKevin Wolf         bs->file = file;
100734b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
100866f82ceeSKevin Wolf     }
100966f82ceeSKevin Wolf 
101057915332SKevin Wolf     if (ret < 0) {
101184d18f06SMarkus Armbruster         if (local_err) {
101234b5d2c6SMax Reitz             error_propagate(errp, local_err);
10132fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
10142fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
101534b5d2c6SMax Reitz         } else {
101634b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
101734b5d2c6SMax Reitz         }
101857915332SKevin Wolf         goto free_and_fail;
101957915332SKevin Wolf     }
102057915332SKevin Wolf 
102151762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
102251762288SStefan Hajnoczi     if (ret < 0) {
102334b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
102451762288SStefan Hajnoczi         goto free_and_fail;
102557915332SKevin Wolf     }
102651762288SStefan Hajnoczi 
10273baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10283baca891SKevin Wolf     if (local_err) {
10293baca891SKevin Wolf         error_propagate(errp, local_err);
10303baca891SKevin Wolf         ret = -EINVAL;
10313baca891SKevin Wolf         goto free_and_fail;
10323baca891SKevin Wolf     }
10333baca891SKevin Wolf 
1034c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10354196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1036b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
103718edf289SKevin Wolf 
103818edf289SKevin Wolf     qemu_opts_del(opts);
103957915332SKevin Wolf     return 0;
104057915332SKevin Wolf 
104157915332SKevin Wolf free_and_fail:
104266f82ceeSKevin Wolf     bs->file = NULL;
10437267c094SAnthony Liguori     g_free(bs->opaque);
104457915332SKevin Wolf     bs->opaque = NULL;
104557915332SKevin Wolf     bs->drv = NULL;
104618edf289SKevin Wolf fail_opts:
104718edf289SKevin Wolf     qemu_opts_del(opts);
104857915332SKevin Wolf     return ret;
104957915332SKevin Wolf }
105057915332SKevin Wolf 
10515e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10525e5c4f63SKevin Wolf {
10535e5c4f63SKevin Wolf     QObject *options_obj;
10545e5c4f63SKevin Wolf     QDict *options;
10555e5c4f63SKevin Wolf     int ret;
10565e5c4f63SKevin Wolf 
10575e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10585e5c4f63SKevin Wolf     assert(ret);
10595e5c4f63SKevin Wolf 
10605e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10615e5c4f63SKevin Wolf     if (!options_obj) {
10625e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10635e5c4f63SKevin Wolf         return NULL;
10645e5c4f63SKevin Wolf     }
10655e5c4f63SKevin Wolf 
10665e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10675e5c4f63SKevin Wolf         qobject_decref(options_obj);
10685e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10695e5c4f63SKevin Wolf         return NULL;
10705e5c4f63SKevin Wolf     }
10715e5c4f63SKevin Wolf 
10725e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10735e5c4f63SKevin Wolf     qdict_flatten(options);
10745e5c4f63SKevin Wolf 
10755e5c4f63SKevin Wolf     return options;
10765e5c4f63SKevin Wolf }
10775e5c4f63SKevin Wolf 
1078de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1079de3b53f0SKevin Wolf                                 Error **errp)
1080de3b53f0SKevin Wolf {
1081de3b53f0SKevin Wolf     QDict *json_options;
1082de3b53f0SKevin Wolf     Error *local_err = NULL;
1083de3b53f0SKevin Wolf 
1084de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1085de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1086de3b53f0SKevin Wolf         return;
1087de3b53f0SKevin Wolf     }
1088de3b53f0SKevin Wolf 
1089de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1090de3b53f0SKevin Wolf     if (local_err) {
1091de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1092de3b53f0SKevin Wolf         return;
1093de3b53f0SKevin Wolf     }
1094de3b53f0SKevin Wolf 
1095de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1096de3b53f0SKevin Wolf      * specified directly */
1097de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1098de3b53f0SKevin Wolf     QDECREF(json_options);
1099de3b53f0SKevin Wolf     *pfilename = NULL;
1100de3b53f0SKevin Wolf }
1101de3b53f0SKevin Wolf 
110257915332SKevin Wolf /*
1103f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1104f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
110553a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
110653a29513SMax Reitz  * block driver has been specified explicitly.
1107f54120ffSKevin Wolf  */
1108de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1109053e1578SMax Reitz                              int *flags, Error **errp)
1110f54120ffSKevin Wolf {
1111f54120ffSKevin Wolf     const char *drvname;
111253a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1113f54120ffSKevin Wolf     bool parse_filename = false;
1114053e1578SMax Reitz     BlockDriver *drv = NULL;
1115f54120ffSKevin Wolf     Error *local_err = NULL;
1116f54120ffSKevin Wolf 
111753a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1118053e1578SMax Reitz     if (drvname) {
1119053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1120053e1578SMax Reitz         if (!drv) {
1121053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1122053e1578SMax Reitz             return -ENOENT;
1123053e1578SMax Reitz         }
112453a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
112553a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1126053e1578SMax Reitz         protocol = drv->bdrv_file_open;
112753a29513SMax Reitz     }
112853a29513SMax Reitz 
112953a29513SMax Reitz     if (protocol) {
113053a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
113153a29513SMax Reitz     } else {
113253a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
113353a29513SMax Reitz     }
113453a29513SMax Reitz 
113591a097e7SKevin Wolf     /* Translate cache options from flags into options */
113691a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
113791a097e7SKevin Wolf 
1138f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
113917b005f1SKevin Wolf     if (protocol && filename) {
1140f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1141f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1142f54120ffSKevin Wolf             parse_filename = true;
1143f54120ffSKevin Wolf         } else {
1144f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1145f54120ffSKevin Wolf                              "the same time");
1146f54120ffSKevin Wolf             return -EINVAL;
1147f54120ffSKevin Wolf         }
1148f54120ffSKevin Wolf     }
1149f54120ffSKevin Wolf 
1150f54120ffSKevin Wolf     /* Find the right block driver */
1151f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1152f54120ffSKevin Wolf 
115317b005f1SKevin Wolf     if (!drvname && protocol) {
1154f54120ffSKevin Wolf         if (filename) {
1155b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1156f54120ffSKevin Wolf             if (!drv) {
1157f54120ffSKevin Wolf                 return -EINVAL;
1158f54120ffSKevin Wolf             }
1159f54120ffSKevin Wolf 
1160f54120ffSKevin Wolf             drvname = drv->format_name;
1161f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1162f54120ffSKevin Wolf         } else {
1163f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1164f54120ffSKevin Wolf             return -EINVAL;
1165f54120ffSKevin Wolf         }
116617b005f1SKevin Wolf     }
116717b005f1SKevin Wolf 
116817b005f1SKevin Wolf     assert(drv || !protocol);
1169f54120ffSKevin Wolf 
1170f54120ffSKevin Wolf     /* Driver-specific filename parsing */
117117b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1172f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1173f54120ffSKevin Wolf         if (local_err) {
1174f54120ffSKevin Wolf             error_propagate(errp, local_err);
1175f54120ffSKevin Wolf             return -EINVAL;
1176f54120ffSKevin Wolf         }
1177f54120ffSKevin Wolf 
1178f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1179f54120ffSKevin Wolf             qdict_del(*options, "filename");
1180f54120ffSKevin Wolf         }
1181f54120ffSKevin Wolf     }
1182f54120ffSKevin Wolf 
1183f54120ffSKevin Wolf     return 0;
1184f54120ffSKevin Wolf }
1185f54120ffSKevin Wolf 
1186f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1187260fecf1SKevin Wolf                                   const char *child_name,
1188df581792SKevin Wolf                                   const BdrvChildRole *child_role)
1189df581792SKevin Wolf {
1190df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1191df581792SKevin Wolf     *child = (BdrvChild) {
1192df581792SKevin Wolf         .bs     = child_bs,
1193260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1194df581792SKevin Wolf         .role   = child_role,
1195df581792SKevin Wolf     };
1196df581792SKevin Wolf 
1197d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1198b4b059f6SKevin Wolf 
1199b4b059f6SKevin Wolf     return child;
1200df581792SKevin Wolf }
1201df581792SKevin Wolf 
1202f21d96d0SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1203f21d96d0SKevin Wolf                                     BlockDriverState *child_bs,
1204f21d96d0SKevin Wolf                                     const char *child_name,
1205f21d96d0SKevin Wolf                                     const BdrvChildRole *child_role)
1206f21d96d0SKevin Wolf {
1207f21d96d0SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role);
1208f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1209f21d96d0SKevin Wolf     return child;
1210f21d96d0SKevin Wolf }
1211f21d96d0SKevin Wolf 
12123f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
121333a60407SKevin Wolf {
1214f21d96d0SKevin Wolf     if (child->next.le_prev) {
121533a60407SKevin Wolf         QLIST_REMOVE(child, next);
1216f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1217f21d96d0SKevin Wolf     }
1218d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1219260fecf1SKevin Wolf     g_free(child->name);
122033a60407SKevin Wolf     g_free(child);
122133a60407SKevin Wolf }
122233a60407SKevin Wolf 
1223f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
122433a60407SKevin Wolf {
1225779020cbSKevin Wolf     BlockDriverState *child_bs;
1226779020cbSKevin Wolf 
1227f21d96d0SKevin Wolf     child_bs = child->bs;
1228f21d96d0SKevin Wolf     bdrv_detach_child(child);
1229f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1230f21d96d0SKevin Wolf }
1231f21d96d0SKevin Wolf 
1232f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1233f21d96d0SKevin Wolf {
1234779020cbSKevin Wolf     if (child == NULL) {
1235779020cbSKevin Wolf         return;
1236779020cbSKevin Wolf     }
123733a60407SKevin Wolf 
123833a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
123933a60407SKevin Wolf         child->bs->inherits_from = NULL;
124033a60407SKevin Wolf     }
124133a60407SKevin Wolf 
1242f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
124333a60407SKevin Wolf }
124433a60407SKevin Wolf 
12455db15a57SKevin Wolf /*
12465db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12475db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12485db15a57SKevin Wolf  */
12498d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12508d24cce1SFam Zheng {
12515db15a57SKevin Wolf     if (backing_hd) {
12525db15a57SKevin Wolf         bdrv_ref(backing_hd);
12535db15a57SKevin Wolf     }
12548d24cce1SFam Zheng 
1255760e0063SKevin Wolf     if (bs->backing) {
1256826b6ca0SFam Zheng         assert(bs->backing_blocker);
1257760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12585db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1259826b6ca0SFam Zheng     } else if (backing_hd) {
1260826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
126181e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
126281e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1263826b6ca0SFam Zheng     }
1264826b6ca0SFam Zheng 
12658d24cce1SFam Zheng     if (!backing_hd) {
1266826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1267826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1268760e0063SKevin Wolf         bs->backing = NULL;
12698d24cce1SFam Zheng         goto out;
12708d24cce1SFam Zheng     }
1271260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
12728d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
12738d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
12748d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
12758d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1276826b6ca0SFam Zheng 
1277760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1278826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1279760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1280826b6ca0SFam Zheng                     bs->backing_blocker);
12818d24cce1SFam Zheng out:
12823baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
12838d24cce1SFam Zheng }
12848d24cce1SFam Zheng 
128531ca6d07SKevin Wolf /*
128631ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
128731ca6d07SKevin Wolf  *
1288d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1289d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1290d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1291d9b7b057SKevin Wolf  * BlockdevRef.
1292d9b7b057SKevin Wolf  *
1293d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
129431ca6d07SKevin Wolf  */
1295d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1296d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12979156df12SPaolo Bonzini {
12981ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1299d9b7b057SKevin Wolf     char *bdref_key_dot;
1300d9b7b057SKevin Wolf     const char *reference = NULL;
1301317fc44eSKevin Wolf     int ret = 0;
13028d24cce1SFam Zheng     BlockDriverState *backing_hd;
1303d9b7b057SKevin Wolf     QDict *options;
1304d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
130534b5d2c6SMax Reitz     Error *local_err = NULL;
13069156df12SPaolo Bonzini 
1307760e0063SKevin Wolf     if (bs->backing != NULL) {
13081ba4b6a5SBenoît Canet         goto free_exit;
13099156df12SPaolo Bonzini     }
13109156df12SPaolo Bonzini 
131131ca6d07SKevin Wolf     /* NULL means an empty set of options */
1312d9b7b057SKevin Wolf     if (parent_options == NULL) {
1313d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1314d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
131531ca6d07SKevin Wolf     }
131631ca6d07SKevin Wolf 
13179156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1318d9b7b057SKevin Wolf 
1319d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1320d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1321d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1322d9b7b057SKevin Wolf 
1323d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1324d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13251cb6f506SKevin Wolf         backing_filename[0] = '\0';
13261cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
132731ca6d07SKevin Wolf         QDECREF(options);
13281ba4b6a5SBenoît Canet         goto free_exit;
1329dbecebddSFam Zheng     } else {
13309f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13319f07429eSMax Reitz                                        &local_err);
13329f07429eSMax Reitz         if (local_err) {
13339f07429eSMax Reitz             ret = -EINVAL;
13349f07429eSMax Reitz             error_propagate(errp, local_err);
13359f07429eSMax Reitz             QDECREF(options);
13369f07429eSMax Reitz             goto free_exit;
13379f07429eSMax Reitz         }
13389156df12SPaolo Bonzini     }
13399156df12SPaolo Bonzini 
13408ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13418ee79e70SKevin Wolf         ret = -EINVAL;
13428ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13438ee79e70SKevin Wolf         QDECREF(options);
13448ee79e70SKevin Wolf         goto free_exit;
13458ee79e70SKevin Wolf     }
13468ee79e70SKevin Wolf 
1347c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1348c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13499156df12SPaolo Bonzini     }
13509156df12SPaolo Bonzini 
1351d9b7b057SKevin Wolf     backing_hd = NULL;
1352f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1353f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1354d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1355e43bfd9cSMarkus Armbruster                             errp);
13569156df12SPaolo Bonzini     if (ret < 0) {
13579156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1358e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13591ba4b6a5SBenoît Canet         goto free_exit;
13609156df12SPaolo Bonzini     }
1361df581792SKevin Wolf 
13625db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13635db15a57SKevin Wolf      * backing_hd reference now */
13648d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13655db15a57SKevin Wolf     bdrv_unref(backing_hd);
1366d80ac658SPeter Feiner 
1367d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1368d9b7b057SKevin Wolf 
13691ba4b6a5SBenoît Canet free_exit:
13701ba4b6a5SBenoît Canet     g_free(backing_filename);
1371d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
13721ba4b6a5SBenoît Canet     return ret;
13739156df12SPaolo Bonzini }
13749156df12SPaolo Bonzini 
1375b6ce07aaSKevin Wolf /*
1376da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1377da557aacSMax Reitz  * device's options.
1378da557aacSMax Reitz  *
1379da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1380b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1381da557aacSMax Reitz  *
1382da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1383da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1384da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1385da557aacSMax Reitz  * BlockdevRef.
1386da557aacSMax Reitz  *
1387da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1388da557aacSMax Reitz  */
1389b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1390f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1391b4b059f6SKevin Wolf                            BlockDriverState* parent,
1392b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1393f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1394da557aacSMax Reitz {
1395b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1396b4b059f6SKevin Wolf     BlockDriverState *bs;
1397da557aacSMax Reitz     QDict *image_options;
1398da557aacSMax Reitz     int ret;
1399da557aacSMax Reitz     char *bdref_key_dot;
1400da557aacSMax Reitz     const char *reference;
1401da557aacSMax Reitz 
1402df581792SKevin Wolf     assert(child_role != NULL);
1403f67503e5SMax Reitz 
1404da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1405da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1406da557aacSMax Reitz     g_free(bdref_key_dot);
1407da557aacSMax Reitz 
1408da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1409da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1410b4b059f6SKevin Wolf         if (!allow_none) {
1411da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1412da557aacSMax Reitz                        bdref_key);
1413da557aacSMax Reitz         }
1414b20e61e0SMarkus Armbruster         QDECREF(image_options);
1415da557aacSMax Reitz         goto done;
1416da557aacSMax Reitz     }
1417da557aacSMax Reitz 
1418b4b059f6SKevin Wolf     bs = NULL;
1419b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1420ce343771SMax Reitz                             parent, child_role, errp);
1421df581792SKevin Wolf     if (ret < 0) {
1422df581792SKevin Wolf         goto done;
1423df581792SKevin Wolf     }
1424df581792SKevin Wolf 
1425260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1426da557aacSMax Reitz 
1427da557aacSMax Reitz done:
1428da557aacSMax Reitz     qdict_del(options, bdref_key);
1429b4b059f6SKevin Wolf     return c;
1430b4b059f6SKevin Wolf }
1431b4b059f6SKevin Wolf 
143273176beeSKevin Wolf static int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags,
143373176beeSKevin Wolf                                      QDict *snapshot_options, Error **errp)
1434b998875dSKevin Wolf {
1435b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14361ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1437b998875dSKevin Wolf     int64_t total_size;
143883d0521aSChunyan Liu     QemuOpts *opts = NULL;
1439b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1440c2e0dbbfSFam Zheng     Error *local_err = NULL;
1441b998875dSKevin Wolf     int ret;
1442b998875dSKevin Wolf 
1443b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1444b998875dSKevin Wolf        instead of opening 'filename' directly */
1445b998875dSKevin Wolf 
1446b998875dSKevin Wolf     /* Get the required size from the image */
1447f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1448f187743aSKevin Wolf     if (total_size < 0) {
14496b8aeca5SChen Gang         ret = total_size;
1450f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14511ba4b6a5SBenoît Canet         goto out;
1452f187743aSKevin Wolf     }
1453b998875dSKevin Wolf 
1454b998875dSKevin Wolf     /* Create the temporary image */
14551ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1456b998875dSKevin Wolf     if (ret < 0) {
1457b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14581ba4b6a5SBenoît Canet         goto out;
1459b998875dSKevin Wolf     }
1460b998875dSKevin Wolf 
1461ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1462c282e1fdSChunyan Liu                             &error_abort);
146339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1464e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
146583d0521aSChunyan Liu     qemu_opts_del(opts);
1466b998875dSKevin Wolf     if (ret < 0) {
1467e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1468e43bfd9cSMarkus Armbruster                       tmp_filename);
14691ba4b6a5SBenoît Canet         goto out;
1470b998875dSKevin Wolf     }
1471b998875dSKevin Wolf 
147273176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1473b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1474b998875dSKevin Wolf               qstring_from_str("file"));
1475b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1476b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1477e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1478e6641719SMax Reitz               qstring_from_str("qcow2"));
1479b998875dSKevin Wolf 
1480e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1481b998875dSKevin Wolf 
1482b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
14836ebf9aa2SMax Reitz                     flags, &local_err);
148473176beeSKevin Wolf     snapshot_options = NULL;
1485b998875dSKevin Wolf     if (ret < 0) {
1486b998875dSKevin Wolf         error_propagate(errp, local_err);
14871ba4b6a5SBenoît Canet         goto out;
1488b998875dSKevin Wolf     }
1489b998875dSKevin Wolf 
1490b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14911ba4b6a5SBenoît Canet 
14921ba4b6a5SBenoît Canet out:
149373176beeSKevin Wolf     QDECREF(snapshot_options);
14941ba4b6a5SBenoît Canet     g_free(tmp_filename);
14956b8aeca5SChen Gang     return ret;
1496b998875dSKevin Wolf }
1497b998875dSKevin Wolf 
1498da557aacSMax Reitz /*
1499b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1500de9c0cecSKevin Wolf  *
1501de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1502de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1503de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1504de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1505f67503e5SMax Reitz  *
1506f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1507f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1508ddf5636dSMax Reitz  *
1509ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1510ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1511ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1512b6ce07aaSKevin Wolf  */
1513f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1514ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1515f3930ed0SKevin Wolf                              BlockDriverState *parent,
1516ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1517ea2384d3Sbellard {
1518b6ce07aaSKevin Wolf     int ret;
15199a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15209a4f4c31SKevin Wolf     BlockDriverState *bs;
1521ce343771SMax Reitz     BlockDriver *drv = NULL;
152274fe54f2SKevin Wolf     const char *drvname;
15233e8c2e57SAlberto Garcia     const char *backing;
152434b5d2c6SMax Reitz     Error *local_err = NULL;
152573176beeSKevin Wolf     QDict *snapshot_options = NULL;
1526b1e6fc08SKevin Wolf     int snapshot_flags = 0;
152733e3963eSbellard 
1528f67503e5SMax Reitz     assert(pbs);
1529f3930ed0SKevin Wolf     assert(!child_role || !flags);
1530f3930ed0SKevin Wolf     assert(!child_role == !parent);
1531f67503e5SMax Reitz 
1532ddf5636dSMax Reitz     if (reference) {
1533ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1534ddf5636dSMax Reitz         QDECREF(options);
1535ddf5636dSMax Reitz 
1536ddf5636dSMax Reitz         if (*pbs) {
1537ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1538ddf5636dSMax Reitz                        "another block device");
1539ddf5636dSMax Reitz             return -EINVAL;
1540ddf5636dSMax Reitz         }
1541ddf5636dSMax Reitz 
1542ddf5636dSMax Reitz         if (filename || options_non_empty) {
1543ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1544ddf5636dSMax Reitz                        "additional options or a new filename");
1545ddf5636dSMax Reitz             return -EINVAL;
1546ddf5636dSMax Reitz         }
1547ddf5636dSMax Reitz 
1548ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1549ddf5636dSMax Reitz         if (!bs) {
1550ddf5636dSMax Reitz             return -ENODEV;
1551ddf5636dSMax Reitz         }
1552ddf5636dSMax Reitz         bdrv_ref(bs);
1553ddf5636dSMax Reitz         *pbs = bs;
1554ddf5636dSMax Reitz         return 0;
1555ddf5636dSMax Reitz     }
1556ddf5636dSMax Reitz 
1557f67503e5SMax Reitz     if (*pbs) {
1558f67503e5SMax Reitz         bs = *pbs;
1559f67503e5SMax Reitz     } else {
1560e4e9986bSMarkus Armbruster         bs = bdrv_new();
1561f67503e5SMax Reitz     }
1562f67503e5SMax Reitz 
1563de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1564de9c0cecSKevin Wolf     if (options == NULL) {
1565de9c0cecSKevin Wolf         options = qdict_new();
1566de9c0cecSKevin Wolf     }
1567de9c0cecSKevin Wolf 
1568145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1569de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1570de3b53f0SKevin Wolf     if (local_err) {
1571de3b53f0SKevin Wolf         ret = -EINVAL;
1572de3b53f0SKevin Wolf         goto fail;
1573de3b53f0SKevin Wolf     }
1574de3b53f0SKevin Wolf 
1575145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1576145f598eSKevin Wolf 
1577f3930ed0SKevin Wolf     if (child_role) {
1578bddcec37SKevin Wolf         bs->inherits_from = parent;
15798e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
15808e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1581f3930ed0SKevin Wolf     }
1582f3930ed0SKevin Wolf 
1583de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1584462f5bcfSKevin Wolf     if (local_err) {
1585462f5bcfSKevin Wolf         goto fail;
1586462f5bcfSKevin Wolf     }
1587462f5bcfSKevin Wolf 
158862392ebbSKevin Wolf     bs->open_flags = flags;
158962392ebbSKevin Wolf     bs->options = options;
159062392ebbSKevin Wolf     options = qdict_clone_shallow(options);
159162392ebbSKevin Wolf 
159276c591b0SKevin Wolf     /* Find the right image format driver */
159376c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
159476c591b0SKevin Wolf     if (drvname) {
159576c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
159676c591b0SKevin Wolf         if (!drv) {
159776c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
159876c591b0SKevin Wolf             ret = -EINVAL;
159976c591b0SKevin Wolf             goto fail;
160076c591b0SKevin Wolf         }
160176c591b0SKevin Wolf     }
160276c591b0SKevin Wolf 
160376c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
160476c591b0SKevin Wolf 
16053e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
16063e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16073e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16083e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16093e8c2e57SAlberto Garcia     }
16103e8c2e57SAlberto Garcia 
1611f500a6d3SKevin Wolf     /* Open image file without format layer */
1612f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1613be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1614be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1615be028adcSJeff Cody         }
1616b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
161773176beeSKevin Wolf             snapshot_options = qdict_new();
161873176beeSKevin Wolf             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
161973176beeSKevin Wolf                                        flags, options);
16208e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1621b1e6fc08SKevin Wolf         }
1622be028adcSJeff Cody 
1623f3930ed0SKevin Wolf         bs->open_flags = flags;
16241fdd6933SKevin Wolf 
16259a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16261fdd6933SKevin Wolf                                &child_file, true, &local_err);
16271fdd6933SKevin Wolf         if (local_err) {
16281fdd6933SKevin Wolf             ret = -EINVAL;
16298bfea15dSKevin Wolf             goto fail;
1630f500a6d3SKevin Wolf         }
1631f4788adcSKevin Wolf     }
1632f500a6d3SKevin Wolf 
163376c591b0SKevin Wolf     /* Image format probing */
163438f3ef57SKevin Wolf     bs->probed = !drv;
163576c591b0SKevin Wolf     if (!drv && file) {
16369a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
163717b005f1SKevin Wolf         if (ret < 0) {
163817b005f1SKevin Wolf             goto fail;
163917b005f1SKevin Wolf         }
164062392ebbSKevin Wolf         /*
164162392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
164262392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
164362392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
164462392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
164562392ebbSKevin Wolf          *
164662392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
164762392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
164862392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
164962392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
165062392ebbSKevin Wolf          */
165162392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
165262392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
165376c591b0SKevin Wolf     } else if (!drv) {
16542a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16552a05cbe4SMax Reitz         ret = -EINVAL;
16568bfea15dSKevin Wolf         goto fail;
16572a05cbe4SMax Reitz     }
1658f500a6d3SKevin Wolf 
165953a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
166053a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
166153a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
166253a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
166353a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
166453a29513SMax Reitz 
1665b6ce07aaSKevin Wolf     /* Open the image */
166682dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1667b6ce07aaSKevin Wolf     if (ret < 0) {
16688bfea15dSKevin Wolf         goto fail;
16696987307cSChristoph Hellwig     }
16706987307cSChristoph Hellwig 
16712a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16729a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1673f500a6d3SKevin Wolf         file = NULL;
1674f500a6d3SKevin Wolf     }
1675f500a6d3SKevin Wolf 
1676b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16779156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1678d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1679b6ce07aaSKevin Wolf         if (ret < 0) {
1680b6ad491aSKevin Wolf             goto close_and_fail;
1681b6ce07aaSKevin Wolf         }
1682b6ce07aaSKevin Wolf     }
1683b6ce07aaSKevin Wolf 
168491af7014SMax Reitz     bdrv_refresh_filename(bs);
168591af7014SMax Reitz 
1686b6ad491aSKevin Wolf     /* Check if any unknown options were used */
16875acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1688b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
16895acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
16905acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
16915acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
16925acd9d81SMax Reitz         } else {
1693d0e46a55SMax Reitz             error_setg(errp,
1694d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1695d0e46a55SMax Reitz                        drv->format_name, entry->key);
16965acd9d81SMax Reitz         }
1697b6ad491aSKevin Wolf 
1698b6ad491aSKevin Wolf         ret = -EINVAL;
1699b6ad491aSKevin Wolf         goto close_and_fail;
1700b6ad491aSKevin Wolf     }
1701b6ad491aSKevin Wolf 
1702b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1703a7f53e26SMarkus Armbruster         if (bs->blk) {
1704a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1705a7f53e26SMarkus Armbruster         }
1706c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1707c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1708c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1709c3adb58fSMarkus Armbruster         error_setg(errp,
1710c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1711c3adb58fSMarkus Armbruster         ret = -EBUSY;
1712c3adb58fSMarkus Armbruster         goto close_and_fail;
1713b6ce07aaSKevin Wolf     }
1714b6ce07aaSKevin Wolf 
1715c3adb58fSMarkus Armbruster     QDECREF(options);
1716f67503e5SMax Reitz     *pbs = bs;
1717dd62f1caSKevin Wolf 
1718dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1719dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1720dd62f1caSKevin Wolf     if (snapshot_flags) {
172173176beeSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, snapshot_options,
172273176beeSKevin Wolf                                         &local_err);
172373176beeSKevin Wolf         snapshot_options = NULL;
1724dd62f1caSKevin Wolf         if (local_err) {
1725dd62f1caSKevin Wolf             goto close_and_fail;
1726dd62f1caSKevin Wolf         }
1727dd62f1caSKevin Wolf     }
1728dd62f1caSKevin Wolf 
1729b6ce07aaSKevin Wolf     return 0;
1730b6ce07aaSKevin Wolf 
17318bfea15dSKevin Wolf fail:
1732f500a6d3SKevin Wolf     if (file != NULL) {
17339a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1734f500a6d3SKevin Wolf     }
173573176beeSKevin Wolf     QDECREF(snapshot_options);
1736145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1737de9c0cecSKevin Wolf     QDECREF(bs->options);
1738b6ad491aSKevin Wolf     QDECREF(options);
1739de9c0cecSKevin Wolf     bs->options = NULL;
1740f67503e5SMax Reitz     if (!*pbs) {
1741f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1742f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1743f67503e5SMax Reitz            since it has not really been opened yet. */
1744f67503e5SMax Reitz         bdrv_unref(bs);
1745f67503e5SMax Reitz     }
174684d18f06SMarkus Armbruster     if (local_err) {
174734b5d2c6SMax Reitz         error_propagate(errp, local_err);
174834b5d2c6SMax Reitz     }
1749b6ad491aSKevin Wolf     return ret;
1750de9c0cecSKevin Wolf 
1751b6ad491aSKevin Wolf close_and_fail:
1752f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1753f67503e5SMax Reitz     if (*pbs) {
1754b6ad491aSKevin Wolf         bdrv_close(bs);
1755f67503e5SMax Reitz     } else {
1756f67503e5SMax Reitz         bdrv_unref(bs);
1757f67503e5SMax Reitz     }
175873176beeSKevin Wolf     QDECREF(snapshot_options);
1759b6ad491aSKevin Wolf     QDECREF(options);
176084d18f06SMarkus Armbruster     if (local_err) {
176134b5d2c6SMax Reitz         error_propagate(errp, local_err);
176234b5d2c6SMax Reitz     }
1763b6ce07aaSKevin Wolf     return ret;
1764b6ce07aaSKevin Wolf }
1765b6ce07aaSKevin Wolf 
1766f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
17676ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1768f3930ed0SKevin Wolf {
1769f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1770ce343771SMax Reitz                              NULL, errp);
1771f3930ed0SKevin Wolf }
1772f3930ed0SKevin Wolf 
1773e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1774e971aa12SJeff Cody      bool prepared;
1775e971aa12SJeff Cody      BDRVReopenState state;
1776e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1777e971aa12SJeff Cody } BlockReopenQueueEntry;
1778e971aa12SJeff Cody 
1779e971aa12SJeff Cody /*
1780e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1781e971aa12SJeff Cody  * reopen of multiple devices.
1782e971aa12SJeff Cody  *
1783e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1784e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1785e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1786e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1787e971aa12SJeff Cody  * atomic 'set'.
1788e971aa12SJeff Cody  *
1789e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1790e971aa12SJeff Cody  *
17914d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17924d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
17934d2cb092SKevin Wolf  *
1794e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1795e971aa12SJeff Cody  *
1796e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1797e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1798e971aa12SJeff Cody  *
1799e971aa12SJeff Cody  */
180028518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
18014d2cb092SKevin Wolf                                                  BlockDriverState *bs,
180228518102SKevin Wolf                                                  QDict *options,
180328518102SKevin Wolf                                                  int flags,
180428518102SKevin Wolf                                                  const BdrvChildRole *role,
180528518102SKevin Wolf                                                  QDict *parent_options,
180628518102SKevin Wolf                                                  int parent_flags)
1807e971aa12SJeff Cody {
1808e971aa12SJeff Cody     assert(bs != NULL);
1809e971aa12SJeff Cody 
1810e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
181167251a31SKevin Wolf     BdrvChild *child;
1812145f598eSKevin Wolf     QDict *old_options, *explicit_options;
181367251a31SKevin Wolf 
1814e971aa12SJeff Cody     if (bs_queue == NULL) {
1815e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1816e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1817e971aa12SJeff Cody     }
1818e971aa12SJeff Cody 
18194d2cb092SKevin Wolf     if (!options) {
18204d2cb092SKevin Wolf         options = qdict_new();
18214d2cb092SKevin Wolf     }
18224d2cb092SKevin Wolf 
182328518102SKevin Wolf     /*
182428518102SKevin Wolf      * Precedence of options:
182528518102SKevin Wolf      * 1. Explicitly passed in options (highest)
182691a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1827145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18288e2160e2SKevin Wolf      * 4. Inherited from parent node
182928518102SKevin Wolf      * 5. Retained from effective options of bs
183028518102SKevin Wolf      */
183128518102SKevin Wolf 
183291a097e7SKevin Wolf     if (!parent_options) {
183391a097e7SKevin Wolf         /*
183491a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
183591a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
183691a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
183791a097e7SKevin Wolf          * not considered.
183891a097e7SKevin Wolf          */
183991a097e7SKevin Wolf         update_options_from_flags(options, flags);
184091a097e7SKevin Wolf     }
184191a097e7SKevin Wolf 
1842145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1843145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1844145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1845145f598eSKevin Wolf     QDECREF(old_options);
1846145f598eSKevin Wolf 
1847145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1848145f598eSKevin Wolf 
184928518102SKevin Wolf     /* Inherit from parent node */
185028518102SKevin Wolf     if (parent_options) {
185128518102SKevin Wolf         assert(!flags);
18528e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
185328518102SKevin Wolf     }
185428518102SKevin Wolf 
185528518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18564d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1857cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18584d2cb092SKevin Wolf     QDECREF(old_options);
18594d2cb092SKevin Wolf 
1860f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1861f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1862f1f25a2eSKevin Wolf 
186367251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18644c9dfe5dSKevin Wolf         QDict *new_child_options;
18654c9dfe5dSKevin Wolf         char *child_key_dot;
186667251a31SKevin Wolf 
18674c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18684c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18694c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
187067251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
187167251a31SKevin Wolf             continue;
187267251a31SKevin Wolf         }
187367251a31SKevin Wolf 
18744c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18754c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18764c9dfe5dSKevin Wolf         g_free(child_key_dot);
18774c9dfe5dSKevin Wolf 
187828518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
187928518102SKevin Wolf                                 child->role, options, flags);
1880e971aa12SJeff Cody     }
1881e971aa12SJeff Cody 
1882e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1883e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1884e971aa12SJeff Cody 
1885e971aa12SJeff Cody     bs_entry->state.bs = bs;
18864d2cb092SKevin Wolf     bs_entry->state.options = options;
1887145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1888e971aa12SJeff Cody     bs_entry->state.flags = flags;
1889e971aa12SJeff Cody 
1890e971aa12SJeff Cody     return bs_queue;
1891e971aa12SJeff Cody }
1892e971aa12SJeff Cody 
189328518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
189428518102SKevin Wolf                                     BlockDriverState *bs,
189528518102SKevin Wolf                                     QDict *options, int flags)
189628518102SKevin Wolf {
189728518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
189828518102SKevin Wolf                                    NULL, NULL, 0);
189928518102SKevin Wolf }
190028518102SKevin Wolf 
1901e971aa12SJeff Cody /*
1902e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1903e971aa12SJeff Cody  *
1904e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1905e971aa12SJeff Cody  * via bdrv_reopen_queue().
1906e971aa12SJeff Cody  *
1907e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1908e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1909e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1910e971aa12SJeff Cody  * data cleaned up.
1911e971aa12SJeff Cody  *
1912e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1913e971aa12SJeff Cody  * to all devices.
1914e971aa12SJeff Cody  *
1915e971aa12SJeff Cody  */
1916e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1917e971aa12SJeff Cody {
1918e971aa12SJeff Cody     int ret = -1;
1919e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1920e971aa12SJeff Cody     Error *local_err = NULL;
1921e971aa12SJeff Cody 
1922e971aa12SJeff Cody     assert(bs_queue != NULL);
1923e971aa12SJeff Cody 
1924e971aa12SJeff Cody     bdrv_drain_all();
1925e971aa12SJeff Cody 
1926e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1927e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1928e971aa12SJeff Cody             error_propagate(errp, local_err);
1929e971aa12SJeff Cody             goto cleanup;
1930e971aa12SJeff Cody         }
1931e971aa12SJeff Cody         bs_entry->prepared = true;
1932e971aa12SJeff Cody     }
1933e971aa12SJeff Cody 
1934e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1935e971aa12SJeff Cody      * changes
1936e971aa12SJeff Cody      */
1937e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1938e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1939e971aa12SJeff Cody     }
1940e971aa12SJeff Cody 
1941e971aa12SJeff Cody     ret = 0;
1942e971aa12SJeff Cody 
1943e971aa12SJeff Cody cleanup:
1944e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1945e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1946e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1947145f598eSKevin Wolf         } else if (ret) {
1948145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1949e971aa12SJeff Cody         }
19504d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1951e971aa12SJeff Cody         g_free(bs_entry);
1952e971aa12SJeff Cody     }
1953e971aa12SJeff Cody     g_free(bs_queue);
1954e971aa12SJeff Cody     return ret;
1955e971aa12SJeff Cody }
1956e971aa12SJeff Cody 
1957e971aa12SJeff Cody 
1958e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1959e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1960e971aa12SJeff Cody {
1961e971aa12SJeff Cody     int ret = -1;
1962e971aa12SJeff Cody     Error *local_err = NULL;
19634d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1964e971aa12SJeff Cody 
1965e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1966e971aa12SJeff Cody     if (local_err != NULL) {
1967e971aa12SJeff Cody         error_propagate(errp, local_err);
1968e971aa12SJeff Cody     }
1969e971aa12SJeff Cody     return ret;
1970e971aa12SJeff Cody }
1971e971aa12SJeff Cody 
1972e971aa12SJeff Cody 
1973e971aa12SJeff Cody /*
1974e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1975e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1976e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1977e971aa12SJeff Cody  *
1978e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1979e971aa12SJeff Cody  * flags are the new open flags
1980e971aa12SJeff Cody  * queue is the reopen queue
1981e971aa12SJeff Cody  *
1982e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1983e971aa12SJeff Cody  * as well.
1984e971aa12SJeff Cody  *
1985e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1986e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1987e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1988e971aa12SJeff Cody  *
1989e971aa12SJeff Cody  */
1990e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1991e971aa12SJeff Cody                         Error **errp)
1992e971aa12SJeff Cody {
1993e971aa12SJeff Cody     int ret = -1;
1994e971aa12SJeff Cody     Error *local_err = NULL;
1995e971aa12SJeff Cody     BlockDriver *drv;
1996ccf9dc07SKevin Wolf     QemuOpts *opts;
1997ccf9dc07SKevin Wolf     const char *value;
1998e971aa12SJeff Cody 
1999e971aa12SJeff Cody     assert(reopen_state != NULL);
2000e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
2001e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2002e971aa12SJeff Cody 
2003ccf9dc07SKevin Wolf     /* Process generic block layer options */
2004ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2005ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2006ccf9dc07SKevin Wolf     if (local_err) {
2007ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2008ccf9dc07SKevin Wolf         ret = -EINVAL;
2009ccf9dc07SKevin Wolf         goto error;
2010ccf9dc07SKevin Wolf     }
2011ccf9dc07SKevin Wolf 
201291a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
201391a097e7SKevin Wolf 
201491a097e7SKevin Wolf     /* If a guest device is attached, it owns WCE */
201591a097e7SKevin Wolf     if (reopen_state->bs->blk && blk_get_attached_dev(reopen_state->bs->blk)) {
201691a097e7SKevin Wolf         bool old_wce = bdrv_enable_write_cache(reopen_state->bs);
201791a097e7SKevin Wolf         bool new_wce = (reopen_state->flags & BDRV_O_CACHE_WB);
201891a097e7SKevin Wolf         if (old_wce != new_wce) {
201991a097e7SKevin Wolf             error_setg(errp, "Cannot change cache.writeback: Device attached");
202091a097e7SKevin Wolf             ret = -EINVAL;
202191a097e7SKevin Wolf             goto error;
202291a097e7SKevin Wolf         }
202391a097e7SKevin Wolf     }
202491a097e7SKevin Wolf 
2025ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2026ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2027ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2028ccf9dc07SKevin Wolf     if (value) {
2029ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2030ccf9dc07SKevin Wolf     }
2031ccf9dc07SKevin Wolf 
2032ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2033ccf9dc07SKevin Wolf     if (value) {
2034ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2035ccf9dc07SKevin Wolf     }
2036ccf9dc07SKevin Wolf 
2037e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2038e971aa12SJeff Cody      * to r/w */
2039e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2040e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
204181e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
204281e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2043e971aa12SJeff Cody         goto error;
2044e971aa12SJeff Cody     }
2045e971aa12SJeff Cody 
2046e971aa12SJeff Cody 
2047e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2048e971aa12SJeff Cody     if (ret) {
2049455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2050e971aa12SJeff Cody         goto error;
2051e971aa12SJeff Cody     }
2052e971aa12SJeff Cody 
2053e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2054e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2055e971aa12SJeff Cody         if (ret) {
2056e971aa12SJeff Cody             if (local_err != NULL) {
2057e971aa12SJeff Cody                 error_propagate(errp, local_err);
2058e971aa12SJeff Cody             } else {
2059d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2060e971aa12SJeff Cody                            reopen_state->bs->filename);
2061e971aa12SJeff Cody             }
2062e971aa12SJeff Cody             goto error;
2063e971aa12SJeff Cody         }
2064e971aa12SJeff Cody     } else {
2065e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2066e971aa12SJeff Cody          * handler for each supported drv. */
206781e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206881e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
206981e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2070e971aa12SJeff Cody         ret = -1;
2071e971aa12SJeff Cody         goto error;
2072e971aa12SJeff Cody     }
2073e971aa12SJeff Cody 
20744d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20754d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20764d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20774d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20784d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20794d2cb092SKevin Wolf 
20804d2cb092SKevin Wolf         do {
20814d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20824d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20834d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20844d2cb092SKevin Wolf                                                 entry->key);
20854d2cb092SKevin Wolf 
20864d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20874d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20884d2cb092SKevin Wolf                 ret = -EINVAL;
20894d2cb092SKevin Wolf                 goto error;
20904d2cb092SKevin Wolf             }
20914d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20924d2cb092SKevin Wolf     }
20934d2cb092SKevin Wolf 
2094e971aa12SJeff Cody     ret = 0;
2095e971aa12SJeff Cody 
2096e971aa12SJeff Cody error:
2097ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2098e971aa12SJeff Cody     return ret;
2099e971aa12SJeff Cody }
2100e971aa12SJeff Cody 
2101e971aa12SJeff Cody /*
2102e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2103e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2104e971aa12SJeff Cody  * the active BlockDriverState contents.
2105e971aa12SJeff Cody  */
2106e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2107e971aa12SJeff Cody {
2108e971aa12SJeff Cody     BlockDriver *drv;
2109e971aa12SJeff Cody 
2110e971aa12SJeff Cody     assert(reopen_state != NULL);
2111e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2112e971aa12SJeff Cody     assert(drv != NULL);
2113e971aa12SJeff Cody 
2114e971aa12SJeff Cody     /* If there are any driver level actions to take */
2115e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2116e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2117e971aa12SJeff Cody     }
2118e971aa12SJeff Cody 
2119e971aa12SJeff Cody     /* set BDS specific flags now */
2120145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2121145f598eSKevin Wolf 
2122145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2123e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2124e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
2125e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
2126e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2127355ef4acSKevin Wolf 
21283baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2129e971aa12SJeff Cody }
2130e971aa12SJeff Cody 
2131e971aa12SJeff Cody /*
2132e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2133e971aa12SJeff Cody  * reopen_state
2134e971aa12SJeff Cody  */
2135e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2136e971aa12SJeff Cody {
2137e971aa12SJeff Cody     BlockDriver *drv;
2138e971aa12SJeff Cody 
2139e971aa12SJeff Cody     assert(reopen_state != NULL);
2140e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2141e971aa12SJeff Cody     assert(drv != NULL);
2142e971aa12SJeff Cody 
2143e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2144e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2145e971aa12SJeff Cody     }
2146145f598eSKevin Wolf 
2147145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2148e971aa12SJeff Cody }
2149e971aa12SJeff Cody 
2150e971aa12SJeff Cody 
215164dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2152fc01f7e7Sbellard {
215333384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
215433384421SMax Reitz 
2155ca9bd24cSMax Reitz     assert(!bs->job);
215699b7e775SAlberto Garcia 
215799b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
2158a0d64a61SAlberto Garcia     if (bs->throttle_state) {
215999b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
216099b7e775SAlberto Garcia     }
216199b7e775SAlberto Garcia 
2162fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
216358fda173SStefan Hajnoczi     bdrv_flush(bs);
216453ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2165fc27291dSPaolo Bonzini 
2166c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2167c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2168c5acdc9aSMax Reitz 
2169b4d02820SMax Reitz     if (bs->blk) {
2170b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
2171b4d02820SMax Reitz     }
2172b4d02820SMax Reitz 
21733cbc002cSPaolo Bonzini     if (bs->drv) {
21746e93e7c4SKevin Wolf         BdrvChild *child, *next;
21756e93e7c4SKevin Wolf 
21769a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21779a4f4c31SKevin Wolf         bs->drv = NULL;
21789a7dedbcSKevin Wolf 
21799a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21809a7dedbcSKevin Wolf 
21819a4f4c31SKevin Wolf         if (bs->file != NULL) {
21829a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21839a4f4c31SKevin Wolf             bs->file = NULL;
21849a4f4c31SKevin Wolf         }
21859a4f4c31SKevin Wolf 
21866e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
218733a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
218833a60407SKevin Wolf              * bdrv_unref_child() here */
2189bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2190bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2191bddcec37SKevin Wolf             }
219233a60407SKevin Wolf             bdrv_detach_child(child);
21936e93e7c4SKevin Wolf         }
21946e93e7c4SKevin Wolf 
21957267c094SAnthony Liguori         g_free(bs->opaque);
2196ea2384d3Sbellard         bs->opaque = NULL;
219753fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2198a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2199a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
22006405875cSPaolo Bonzini         bs->total_sectors = 0;
22016405875cSPaolo Bonzini         bs->encrypted = 0;
22026405875cSPaolo Bonzini         bs->valid_key = 0;
22036405875cSPaolo Bonzini         bs->sg = 0;
22040d51b4deSAsias He         bs->zero_beyond_eof = false;
2205de9c0cecSKevin Wolf         QDECREF(bs->options);
2206145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2207de9c0cecSKevin Wolf         bs->options = NULL;
220891af7014SMax Reitz         QDECREF(bs->full_open_options);
220991af7014SMax Reitz         bs->full_open_options = NULL;
22109ca11154SPavel Hrdina     }
221166f82ceeSKevin Wolf 
221233384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
221333384421SMax Reitz         g_free(ban);
221433384421SMax Reitz     }
221533384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2216fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2217b338082bSbellard }
2218b338082bSbellard 
22192bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22202bc93fedSMORITA Kazutaka {
22212bc93fedSMORITA Kazutaka     BlockDriverState *bs;
2222ca9bd24cSMax Reitz     AioContext *aio_context;
22232bc93fedSMORITA Kazutaka 
2224ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2225ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2226ca9bd24cSMax Reitz     bdrv_drain_all();
2227ca9bd24cSMax Reitz 
2228ca9bd24cSMax Reitz     blk_remove_all_bs();
2229ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2230ca9bd24cSMax Reitz 
2231ca9bd24cSMax Reitz     /* Cancel all block jobs */
2232ca9bd24cSMax Reitz     while (!QTAILQ_EMPTY(&all_bdrv_states)) {
2233ca9bd24cSMax Reitz         QTAILQ_FOREACH(bs, &all_bdrv_states, bs_list) {
2234ca9bd24cSMax Reitz             aio_context = bdrv_get_aio_context(bs);
2235ed78cda3SStefan Hajnoczi 
2236ed78cda3SStefan Hajnoczi             aio_context_acquire(aio_context);
2237ca9bd24cSMax Reitz             if (bs->job) {
2238ca9bd24cSMax Reitz                 block_job_cancel_sync(bs->job);
2239ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2240ca9bd24cSMax Reitz                 break;
2241ca9bd24cSMax Reitz             }
2242ca9bd24cSMax Reitz             aio_context_release(aio_context);
2243ca9bd24cSMax Reitz         }
2244ca9bd24cSMax Reitz 
2245ca9bd24cSMax Reitz         /* All the remaining BlockDriverStates are referenced directly or
2246ca9bd24cSMax Reitz          * indirectly from block jobs, so there needs to be at least one BDS
2247ca9bd24cSMax Reitz          * directly used by a block job */
2248ca9bd24cSMax Reitz         assert(bs);
22492bc93fedSMORITA Kazutaka     }
22502bc93fedSMORITA Kazutaka }
22512bc93fedSMORITA Kazutaka 
22528e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
22534ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
22544ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
22554ddc07caSPaolo Bonzini {
22564ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
22574ddc07caSPaolo Bonzini 
22584ddc07caSPaolo Bonzini     /* dev info */
22594ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
2260dd62f1caSKevin Wolf }
2261dd62f1caSKevin Wolf 
2262dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2263dd62f1caSKevin Wolf                                        BlockDriverState *to)
2264dd62f1caSKevin Wolf {
2265dd62f1caSKevin Wolf     BdrvChild *c, *next;
2266dd62f1caSKevin Wolf 
2267f21d96d0SKevin Wolf     if (from->blk) {
2268f21d96d0SKevin Wolf         /* FIXME We bypass blk_set_bs(), so we need to make these updates
2269f21d96d0SKevin Wolf          * manually. The root problem is not in this change function, but the
2270f21d96d0SKevin Wolf          * existence of BlockDriverState.blk. */
2271f21d96d0SKevin Wolf         to->blk = from->blk;
2272f21d96d0SKevin Wolf         from->blk = NULL;
2273f21d96d0SKevin Wolf     }
2274f21d96d0SKevin Wolf 
2275dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2276dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2277dd62f1caSKevin Wolf         c->bs = to;
2278dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2279dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2280dd62f1caSKevin Wolf         bdrv_ref(to);
2281dd62f1caSKevin Wolf         bdrv_unref(from);
2282dd62f1caSKevin Wolf     }
2283dd62f1caSKevin Wolf }
2284dd62f1caSKevin Wolf 
2285dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2286dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2287dd62f1caSKevin Wolf {
2288dd62f1caSKevin Wolf     BlockDriverState tmp;
2289dd62f1caSKevin Wolf 
2290dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2291dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2292dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2293dd62f1caSKevin Wolf 
2294dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2295dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2296dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2297dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2298dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2299dd62f1caSKevin Wolf     }
2300dd62f1caSKevin Wolf }
2301dd62f1caSKevin Wolf 
23028802d1fdSJeff Cody /*
23038802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
23048802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
23058802d1fdSJeff Cody  *
23068802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
23078802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
23088802d1fdSJeff Cody  *
2309bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2310f6801b83SJeff Cody  *
23118802d1fdSJeff Cody  * This function does not create any image files.
2312dd62f1caSKevin Wolf  *
2313dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2314dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2315dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2316dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
23178802d1fdSJeff Cody  */
23188802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
23198802d1fdSJeff Cody {
2320dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2321dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
23228802d1fdSJeff Cody 
2323dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2324dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2325dd62f1caSKevin Wolf 
2326dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2327dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2328dd62f1caSKevin Wolf 
2329dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2330dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2331dd62f1caSKevin Wolf 
2332dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2333dd62f1caSKevin Wolf      * additional reference any more. */
2334dd62f1caSKevin Wolf     bdrv_unref(bs_new);
23358802d1fdSJeff Cody }
23368802d1fdSJeff Cody 
23373f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
23383f09bfbcSKevin Wolf {
23393f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
23403f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
23413f09bfbcSKevin Wolf 
23423f09bfbcSKevin Wolf     bdrv_ref(old);
23433f09bfbcSKevin Wolf 
23443f09bfbcSKevin Wolf     if (old->blk) {
23453f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
23463f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
23473f09bfbcSKevin Wolf          *
23483f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
23493f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
23503f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
23513f09bfbcSKevin Wolf         assert(!new->blk);
23523f09bfbcSKevin Wolf         swap_feature_fields(old, new);
23533f09bfbcSKevin Wolf     }
23543f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
23553f09bfbcSKevin Wolf 
23563f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
23573f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
23583f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
23593f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
23603f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
23613f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
23623f09bfbcSKevin Wolf     }
23633f09bfbcSKevin Wolf 
23643f09bfbcSKevin Wolf     bdrv_unref(old);
23653f09bfbcSKevin Wolf }
23663f09bfbcSKevin Wolf 
23674f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2368b338082bSbellard {
23693e914655SPaolo Bonzini     assert(!bs->job);
23703718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
23714f6fd349SFam Zheng     assert(!bs->refcnt);
237218846deeSMarkus Armbruster 
2373e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2374e1b5c52eSStefan Hajnoczi 
23751b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
237663eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
237763eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
237863eaaae0SKevin Wolf     }
23792c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
23802c1d04e0SMax Reitz 
23817267c094SAnthony Liguori     g_free(bs);
2382fc01f7e7Sbellard }
2383fc01f7e7Sbellard 
2384e97fc193Saliguori /*
2385e97fc193Saliguori  * Run consistency checks on an image
2386e97fc193Saliguori  *
2387e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2388a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2389e076f338SKevin Wolf  * check are stored in res.
2390e97fc193Saliguori  */
23914534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2392e97fc193Saliguori {
2393908bcd54SMax Reitz     if (bs->drv == NULL) {
2394908bcd54SMax Reitz         return -ENOMEDIUM;
2395908bcd54SMax Reitz     }
2396e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2397e97fc193Saliguori         return -ENOTSUP;
2398e97fc193Saliguori     }
2399e97fc193Saliguori 
2400e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
24014534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2402e97fc193Saliguori }
2403e97fc193Saliguori 
24048a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
24058a426614SKevin Wolf 
240633e3963eSbellard /* commit COW file into the raw image */
240733e3963eSbellard int bdrv_commit(BlockDriverState *bs)
240833e3963eSbellard {
240919cb3738Sbellard     BlockDriver *drv = bs->drv;
241072706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
24118a426614SKevin Wolf     int n, ro, open_flags;
24120bce597dSJeff Cody     int ret = 0;
241372706ea4SJeff Cody     uint8_t *buf = NULL;
241433e3963eSbellard 
241519cb3738Sbellard     if (!drv)
241619cb3738Sbellard         return -ENOMEDIUM;
241733e3963eSbellard 
2418760e0063SKevin Wolf     if (!bs->backing) {
24194dca4b63SNaphtali Sprei         return -ENOTSUP;
24204dca4b63SNaphtali Sprei     }
24214dca4b63SNaphtali Sprei 
2422bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2423760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
24242d3735d3SStefan Hajnoczi         return -EBUSY;
24252d3735d3SStefan Hajnoczi     }
24262d3735d3SStefan Hajnoczi 
2427760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2428760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
24294dca4b63SNaphtali Sprei 
24304dca4b63SNaphtali Sprei     if (ro) {
2431760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
24320bce597dSJeff Cody             return -EACCES;
24334dca4b63SNaphtali Sprei         }
2434ea2384d3Sbellard     }
2435ea2384d3Sbellard 
243672706ea4SJeff Cody     length = bdrv_getlength(bs);
243772706ea4SJeff Cody     if (length < 0) {
243872706ea4SJeff Cody         ret = length;
243972706ea4SJeff Cody         goto ro_cleanup;
244072706ea4SJeff Cody     }
244172706ea4SJeff Cody 
2442760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
244372706ea4SJeff Cody     if (backing_length < 0) {
244472706ea4SJeff Cody         ret = backing_length;
244572706ea4SJeff Cody         goto ro_cleanup;
244672706ea4SJeff Cody     }
244772706ea4SJeff Cody 
244872706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
244972706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
245072706ea4SJeff Cody      * we must return an error */
245172706ea4SJeff Cody     if (length > backing_length) {
2452760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
245372706ea4SJeff Cody         if (ret < 0) {
245472706ea4SJeff Cody             goto ro_cleanup;
245572706ea4SJeff Cody         }
245672706ea4SJeff Cody     }
245772706ea4SJeff Cody 
245872706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2459857d4f46SKevin Wolf 
2460857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2461760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2462857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2463857d4f46SKevin Wolf     if (buf == NULL) {
2464857d4f46SKevin Wolf         ret = -ENOMEM;
2465857d4f46SKevin Wolf         goto ro_cleanup;
2466857d4f46SKevin Wolf     }
24678a426614SKevin Wolf 
24688a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2469d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2470d663640cSPaolo Bonzini         if (ret < 0) {
2471d663640cSPaolo Bonzini             goto ro_cleanup;
2472d663640cSPaolo Bonzini         }
2473d663640cSPaolo Bonzini         if (ret) {
2474dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2475dabfa6ccSKevin Wolf             if (ret < 0) {
24764dca4b63SNaphtali Sprei                 goto ro_cleanup;
247733e3963eSbellard             }
247833e3963eSbellard 
2479760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2480dabfa6ccSKevin Wolf             if (ret < 0) {
24814dca4b63SNaphtali Sprei                 goto ro_cleanup;
248233e3963eSbellard             }
248333e3963eSbellard         }
248433e3963eSbellard     }
248595389c86Sbellard 
24861d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
24871d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2488dabfa6ccSKevin Wolf         if (ret < 0) {
2489dabfa6ccSKevin Wolf             goto ro_cleanup;
2490dabfa6ccSKevin Wolf         }
24911d44952fSChristoph Hellwig         bdrv_flush(bs);
24921d44952fSChristoph Hellwig     }
249395389c86Sbellard 
24943f5075aeSChristoph Hellwig     /*
24953f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24963f5075aeSChristoph Hellwig      * stable on disk.
24973f5075aeSChristoph Hellwig      */
2498760e0063SKevin Wolf     if (bs->backing) {
2499760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2500dabfa6ccSKevin Wolf     }
25014dca4b63SNaphtali Sprei 
2502dabfa6ccSKevin Wolf     ret = 0;
25034dca4b63SNaphtali Sprei ro_cleanup:
2504857d4f46SKevin Wolf     qemu_vfree(buf);
25054dca4b63SNaphtali Sprei 
25064dca4b63SNaphtali Sprei     if (ro) {
25070bce597dSJeff Cody         /* ignoring error return here */
2508760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
25094dca4b63SNaphtali Sprei     }
25104dca4b63SNaphtali Sprei 
25111d44952fSChristoph Hellwig     return ret;
251233e3963eSbellard }
251333e3963eSbellard 
2514756e6736SKevin Wolf /*
2515756e6736SKevin Wolf  * Return values:
2516756e6736SKevin Wolf  * 0        - success
2517756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2518756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2519756e6736SKevin Wolf  *            image file header
2520756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2521756e6736SKevin Wolf  */
2522756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2523756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2524756e6736SKevin Wolf {
2525756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2526469ef350SPaolo Bonzini     int ret;
2527756e6736SKevin Wolf 
25285f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25295f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25305f377794SPaolo Bonzini         return -EINVAL;
25315f377794SPaolo Bonzini     }
25325f377794SPaolo Bonzini 
2533756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2534469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2535756e6736SKevin Wolf     } else {
2536469ef350SPaolo Bonzini         ret = -ENOTSUP;
2537756e6736SKevin Wolf     }
2538469ef350SPaolo Bonzini 
2539469ef350SPaolo Bonzini     if (ret == 0) {
2540469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2541469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2542469ef350SPaolo Bonzini     }
2543469ef350SPaolo Bonzini     return ret;
2544756e6736SKevin Wolf }
2545756e6736SKevin Wolf 
25466ebdcee2SJeff Cody /*
25476ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25486ebdcee2SJeff Cody  *
25496ebdcee2SJeff Cody  * active is the current topmost image.
25506ebdcee2SJeff Cody  *
25516ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25526ebdcee2SJeff Cody  * or if active == bs.
25534caf0fcdSJeff Cody  *
25544caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25556ebdcee2SJeff Cody  */
25566ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25576ebdcee2SJeff Cody                                     BlockDriverState *bs)
25586ebdcee2SJeff Cody {
2559760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2560760e0063SKevin Wolf         active = backing_bs(active);
25616ebdcee2SJeff Cody     }
25626ebdcee2SJeff Cody 
25634caf0fcdSJeff Cody     return active;
25646ebdcee2SJeff Cody }
25656ebdcee2SJeff Cody 
25664caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25674caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25684caf0fcdSJeff Cody {
25694caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25706ebdcee2SJeff Cody }
25716ebdcee2SJeff Cody 
25726ebdcee2SJeff Cody /*
25736ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25746ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25756ebdcee2SJeff Cody  *
25766ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25776ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25786ebdcee2SJeff Cody  *
25796ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25806ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25816ebdcee2SJeff Cody  *
25826ebdcee2SJeff Cody  * to
25836ebdcee2SJeff Cody  *
25846ebdcee2SJeff Cody  * bottom <- base <- active
25856ebdcee2SJeff Cody  *
25866ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25876ebdcee2SJeff Cody  *
25886ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25896ebdcee2SJeff Cody  *
25906ebdcee2SJeff Cody  * to
25916ebdcee2SJeff Cody  *
25926ebdcee2SJeff Cody  * base <- active
25936ebdcee2SJeff Cody  *
259454e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
259554e26900SJeff Cody  * overlay image metadata.
259654e26900SJeff Cody  *
25976ebdcee2SJeff Cody  * Error conditions:
25986ebdcee2SJeff Cody  *  if active == top, that is considered an error
25996ebdcee2SJeff Cody  *
26006ebdcee2SJeff Cody  */
26016ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
260254e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
26036ebdcee2SJeff Cody {
26046ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26056ebdcee2SJeff Cody     int ret = -EIO;
26066ebdcee2SJeff Cody 
26076ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26086ebdcee2SJeff Cody         goto exit;
26096ebdcee2SJeff Cody     }
26106ebdcee2SJeff Cody 
26116ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26126ebdcee2SJeff Cody 
26136ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26146ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26156ebdcee2SJeff Cody         goto exit;
26166ebdcee2SJeff Cody     }
26176ebdcee2SJeff Cody 
2618760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
26196ebdcee2SJeff Cody      * to do, no intermediate images */
2620760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
26216ebdcee2SJeff Cody         ret = 0;
26226ebdcee2SJeff Cody         goto exit;
26236ebdcee2SJeff Cody     }
26246ebdcee2SJeff Cody 
26255db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
26265db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
26276ebdcee2SJeff Cody         goto exit;
26286ebdcee2SJeff Cody     }
26296ebdcee2SJeff Cody 
26306ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26315db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
263254e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26335db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
26346ebdcee2SJeff Cody     if (ret) {
26356ebdcee2SJeff Cody         goto exit;
26366ebdcee2SJeff Cody     }
26375db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
26386ebdcee2SJeff Cody 
26396ebdcee2SJeff Cody     ret = 0;
26406ebdcee2SJeff Cody exit:
26416ebdcee2SJeff Cody     return ret;
26426ebdcee2SJeff Cody }
26436ebdcee2SJeff Cody 
264483f64091Sbellard /**
264583f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
264683f64091Sbellard  */
264783f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
264883f64091Sbellard {
264983f64091Sbellard     BlockDriver *drv = bs->drv;
265051762288SStefan Hajnoczi     int ret;
265183f64091Sbellard     if (!drv)
265219cb3738Sbellard         return -ENOMEDIUM;
265383f64091Sbellard     if (!drv->bdrv_truncate)
265483f64091Sbellard         return -ENOTSUP;
265559f2689dSNaphtali Sprei     if (bs->read_only)
265659f2689dSNaphtali Sprei         return -EACCES;
26579c75e168SJeff Cody 
265851762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
265951762288SStefan Hajnoczi     if (ret == 0) {
266051762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2661ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2662a7f53e26SMarkus Armbruster         if (bs->blk) {
2663a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2664a7f53e26SMarkus Armbruster         }
266551762288SStefan Hajnoczi     }
266651762288SStefan Hajnoczi     return ret;
266783f64091Sbellard }
266883f64091Sbellard 
266983f64091Sbellard /**
26704a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26714a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26724a1d5e1fSFam Zheng  */
26734a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26744a1d5e1fSFam Zheng {
26754a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26764a1d5e1fSFam Zheng     if (!drv) {
26774a1d5e1fSFam Zheng         return -ENOMEDIUM;
26784a1d5e1fSFam Zheng     }
26794a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26804a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26814a1d5e1fSFam Zheng     }
26824a1d5e1fSFam Zheng     if (bs->file) {
26839a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26844a1d5e1fSFam Zheng     }
26854a1d5e1fSFam Zheng     return -ENOTSUP;
26864a1d5e1fSFam Zheng }
26874a1d5e1fSFam Zheng 
26884a1d5e1fSFam Zheng /**
268965a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
269083f64091Sbellard  */
269165a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
269283f64091Sbellard {
269383f64091Sbellard     BlockDriver *drv = bs->drv;
269465a9bb25SMarkus Armbruster 
269583f64091Sbellard     if (!drv)
269619cb3738Sbellard         return -ENOMEDIUM;
269751762288SStefan Hajnoczi 
2698b94a2610SKevin Wolf     if (drv->has_variable_length) {
2699b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2700b94a2610SKevin Wolf         if (ret < 0) {
2701b94a2610SKevin Wolf             return ret;
2702fc01f7e7Sbellard         }
270346a4e4e6SStefan Hajnoczi     }
270465a9bb25SMarkus Armbruster     return bs->total_sectors;
270565a9bb25SMarkus Armbruster }
270665a9bb25SMarkus Armbruster 
270765a9bb25SMarkus Armbruster /**
270865a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
270965a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
271065a9bb25SMarkus Armbruster  */
271165a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
271265a9bb25SMarkus Armbruster {
271365a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
271465a9bb25SMarkus Armbruster 
27154a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
271665a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
271746a4e4e6SStefan Hajnoczi }
2718fc01f7e7Sbellard 
271919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
272096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2721fc01f7e7Sbellard {
272265a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
272365a9bb25SMarkus Armbruster 
272465a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2725fc01f7e7Sbellard }
2726cf98951bSbellard 
2727b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2728b338082bSbellard {
2729b338082bSbellard     return bs->read_only;
2730b338082bSbellard }
2731b338082bSbellard 
2732985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2733985a03b0Sths {
2734985a03b0Sths     return bs->sg;
2735985a03b0Sths }
2736985a03b0Sths 
2737e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2738e900a7b7SChristoph Hellwig {
2739e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2740e900a7b7SChristoph Hellwig }
2741e900a7b7SChristoph Hellwig 
2742425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2743425b0148SPaolo Bonzini {
2744425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
274555b110f2SJeff Cody 
274655b110f2SJeff Cody     /* so a reopen() will preserve wce */
274755b110f2SJeff Cody     if (wce) {
274855b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
274955b110f2SJeff Cody     } else {
275055b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
275155b110f2SJeff Cody     }
2752425b0148SPaolo Bonzini }
2753425b0148SPaolo Bonzini 
2754ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2755ea2384d3Sbellard {
2756760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2757ea2384d3Sbellard         return 1;
2758760e0063SKevin Wolf     }
2759ea2384d3Sbellard     return bs->encrypted;
2760ea2384d3Sbellard }
2761ea2384d3Sbellard 
2762c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2763c0f4ce77Saliguori {
2764760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2765c0f4ce77Saliguori 
2766760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2767c0f4ce77Saliguori         return 1;
2768760e0063SKevin Wolf     }
2769c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2770c0f4ce77Saliguori }
2771c0f4ce77Saliguori 
2772ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2773ea2384d3Sbellard {
2774ea2384d3Sbellard     int ret;
2775760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2776760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2777ea2384d3Sbellard         if (ret < 0)
2778ea2384d3Sbellard             return ret;
2779ea2384d3Sbellard         if (!bs->encrypted)
2780ea2384d3Sbellard             return 0;
2781ea2384d3Sbellard     }
2782fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2783fd04a2aeSShahar Havivi         return -EINVAL;
2784fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2785fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2786fd04a2aeSShahar Havivi     }
2787c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2788bb5fc20fSaliguori     if (ret < 0) {
2789bb5fc20fSaliguori         bs->valid_key = 0;
2790bb5fc20fSaliguori     } else if (!bs->valid_key) {
2791bb5fc20fSaliguori         bs->valid_key = 1;
2792a7f53e26SMarkus Armbruster         if (bs->blk) {
2793bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2794a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2795a7f53e26SMarkus Armbruster         }
2796bb5fc20fSaliguori     }
2797c0f4ce77Saliguori     return ret;
2798ea2384d3Sbellard }
2799ea2384d3Sbellard 
28004d2855a3SMarkus Armbruster /*
28014d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
28024d2855a3SMarkus Armbruster  * If @key is non-null:
28034d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
28044d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
28054d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
28064d2855a3SMarkus Armbruster  * If @key is null:
28074d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
28084d2855a3SMarkus Armbruster  *     Else do nothing.
28094d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
28104d2855a3SMarkus Armbruster  */
28114d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
28124d2855a3SMarkus Armbruster {
28134d2855a3SMarkus Armbruster     if (key) {
28144d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
281581e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
281681e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
28174d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2818c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
28194d2855a3SMarkus Armbruster         }
28204d2855a3SMarkus Armbruster     } else {
28214d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2822b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2823b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
282481e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
28254d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
28264d2855a3SMarkus Armbruster         }
28274d2855a3SMarkus Armbruster     }
28284d2855a3SMarkus Armbruster }
28294d2855a3SMarkus Armbruster 
2830f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2831ea2384d3Sbellard {
2832f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2833ea2384d3Sbellard }
2834ea2384d3Sbellard 
2835ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2836ada42401SStefan Hajnoczi {
2837ada42401SStefan Hajnoczi     return strcmp(a, b);
2838ada42401SStefan Hajnoczi }
2839ada42401SStefan Hajnoczi 
2840ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2841ea2384d3Sbellard                          void *opaque)
2842ea2384d3Sbellard {
2843ea2384d3Sbellard     BlockDriver *drv;
2844e855e4fbSJeff Cody     int count = 0;
2845ada42401SStefan Hajnoczi     int i;
2846e855e4fbSJeff Cody     const char **formats = NULL;
2847ea2384d3Sbellard 
28488a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2849e855e4fbSJeff Cody         if (drv->format_name) {
2850e855e4fbSJeff Cody             bool found = false;
2851e855e4fbSJeff Cody             int i = count;
2852e855e4fbSJeff Cody             while (formats && i && !found) {
2853e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2854e855e4fbSJeff Cody             }
2855e855e4fbSJeff Cody 
2856e855e4fbSJeff Cody             if (!found) {
28575839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2858e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2859ea2384d3Sbellard             }
2860ea2384d3Sbellard         }
2861e855e4fbSJeff Cody     }
2862ada42401SStefan Hajnoczi 
2863ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2864ada42401SStefan Hajnoczi 
2865ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2866ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2867ada42401SStefan Hajnoczi     }
2868ada42401SStefan Hajnoczi 
2869e855e4fbSJeff Cody     g_free(formats);
2870e855e4fbSJeff Cody }
2871ea2384d3Sbellard 
2872dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2873dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2874dc364f4cSBenoît Canet {
2875dc364f4cSBenoît Canet     BlockDriverState *bs;
2876dc364f4cSBenoît Canet 
2877dc364f4cSBenoît Canet     assert(node_name);
2878dc364f4cSBenoît Canet 
2879dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2880dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2881dc364f4cSBenoît Canet             return bs;
2882dc364f4cSBenoît Canet         }
2883dc364f4cSBenoît Canet     }
2884dc364f4cSBenoît Canet     return NULL;
2885dc364f4cSBenoît Canet }
2886dc364f4cSBenoît Canet 
2887c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2888d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2889c13163fbSBenoît Canet {
2890c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2891c13163fbSBenoît Canet     BlockDriverState *bs;
2892c13163fbSBenoît Canet 
2893c13163fbSBenoît Canet     list = NULL;
2894c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2895d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2896d5a8ee60SAlberto Garcia         if (!info) {
2897d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2898d5a8ee60SAlberto Garcia             return NULL;
2899d5a8ee60SAlberto Garcia         }
2900c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2901d5a8ee60SAlberto Garcia         entry->value = info;
2902c13163fbSBenoît Canet         entry->next = list;
2903c13163fbSBenoît Canet         list = entry;
2904c13163fbSBenoît Canet     }
2905c13163fbSBenoît Canet 
2906c13163fbSBenoît Canet     return list;
2907c13163fbSBenoît Canet }
2908c13163fbSBenoît Canet 
290912d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
291012d3ba82SBenoît Canet                                  const char *node_name,
291112d3ba82SBenoît Canet                                  Error **errp)
291212d3ba82SBenoît Canet {
29137f06d47eSMarkus Armbruster     BlockBackend *blk;
29147f06d47eSMarkus Armbruster     BlockDriverState *bs;
291512d3ba82SBenoît Canet 
291612d3ba82SBenoît Canet     if (device) {
29177f06d47eSMarkus Armbruster         blk = blk_by_name(device);
291812d3ba82SBenoît Canet 
29197f06d47eSMarkus Armbruster         if (blk) {
29209f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
29219f4ed6fbSAlberto Garcia             if (!bs) {
29225433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
29235433c24fSMax Reitz             }
29245433c24fSMax Reitz 
29259f4ed6fbSAlberto Garcia             return bs;
292612d3ba82SBenoît Canet         }
2927dd67fa50SBenoît Canet     }
292812d3ba82SBenoît Canet 
2929dd67fa50SBenoît Canet     if (node_name) {
293012d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
293112d3ba82SBenoît Canet 
2932dd67fa50SBenoît Canet         if (bs) {
2933dd67fa50SBenoît Canet             return bs;
2934dd67fa50SBenoît Canet         }
293512d3ba82SBenoît Canet     }
293612d3ba82SBenoît Canet 
2937dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2938dd67fa50SBenoît Canet                      device ? device : "",
2939dd67fa50SBenoît Canet                      node_name ? node_name : "");
2940dd67fa50SBenoît Canet     return NULL;
294112d3ba82SBenoît Canet }
294212d3ba82SBenoît Canet 
29435a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
29445a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
29455a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
29465a6684d2SJeff Cody {
29475a6684d2SJeff Cody     while (top && top != base) {
2948760e0063SKevin Wolf         top = backing_bs(top);
29495a6684d2SJeff Cody     }
29505a6684d2SJeff Cody 
29515a6684d2SJeff Cody     return top != NULL;
29525a6684d2SJeff Cody }
29535a6684d2SJeff Cody 
295404df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
295504df765aSFam Zheng {
295604df765aSFam Zheng     if (!bs) {
295704df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
295804df765aSFam Zheng     }
295904df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
296004df765aSFam Zheng }
296104df765aSFam Zheng 
296226260580SMax Reitz /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
296326260580SMax Reitz  * the monitor or attached to a BlockBackend */
29642f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29652f399b0aSMarkus Armbruster {
296626260580SMax Reitz     if (!bs || bs->blk) {
296726260580SMax Reitz         bs = blk_next_root_bs(bs);
296826260580SMax Reitz         if (bs) {
296926260580SMax Reitz             return bs;
29702f399b0aSMarkus Armbruster         }
297126260580SMax Reitz     }
297226260580SMax Reitz 
297326260580SMax Reitz     /* Ignore all BDSs that are attached to a BlockBackend here; they have been
297426260580SMax Reitz      * handled by the above block already */
297526260580SMax Reitz     do {
297626260580SMax Reitz         bs = bdrv_next_monitor_owned(bs);
297726260580SMax Reitz     } while (bs && bs->blk);
297826260580SMax Reitz     return bs;
29792f399b0aSMarkus Armbruster }
29802f399b0aSMarkus Armbruster 
298120a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
298220a9e77dSFam Zheng {
298320a9e77dSFam Zheng     return bs->node_name;
298420a9e77dSFam Zheng }
298520a9e77dSFam Zheng 
29867f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2987bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2988ea2384d3Sbellard {
2989bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2990ea2384d3Sbellard }
2991ea2384d3Sbellard 
29929b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29939b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29949b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29959b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29969b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29979b2aa84fSAlberto Garcia {
29989b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
29999b2aa84fSAlberto Garcia }
30009b2aa84fSAlberto Garcia 
3001c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3002c8433287SMarkus Armbruster {
3003c8433287SMarkus Armbruster     return bs->open_flags;
3004c8433287SMarkus Armbruster }
3005c8433287SMarkus Armbruster 
30063ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30073ac21627SPeter Lieven {
30083ac21627SPeter Lieven     return 1;
30093ac21627SPeter Lieven }
30103ac21627SPeter Lieven 
3011f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3012f2feebbdSKevin Wolf {
3013f2feebbdSKevin Wolf     assert(bs->drv);
3014f2feebbdSKevin Wolf 
301511212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
301611212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
3017760e0063SKevin Wolf     if (bs->backing) {
301811212d8fSPaolo Bonzini         return 0;
301911212d8fSPaolo Bonzini     }
3020336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3021336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3022f2feebbdSKevin Wolf     }
3023f2feebbdSKevin Wolf 
30243ac21627SPeter Lieven     /* safe default */
30253ac21627SPeter Lieven     return 0;
3026f2feebbdSKevin Wolf }
3027f2feebbdSKevin Wolf 
30284ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
30294ce78691SPeter Lieven {
30304ce78691SPeter Lieven     BlockDriverInfo bdi;
30314ce78691SPeter Lieven 
3032760e0063SKevin Wolf     if (bs->backing) {
30334ce78691SPeter Lieven         return false;
30344ce78691SPeter Lieven     }
30354ce78691SPeter Lieven 
30364ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30374ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
30384ce78691SPeter Lieven     }
30394ce78691SPeter Lieven 
30404ce78691SPeter Lieven     return false;
30414ce78691SPeter Lieven }
30424ce78691SPeter Lieven 
30434ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
30444ce78691SPeter Lieven {
30454ce78691SPeter Lieven     BlockDriverInfo bdi;
30464ce78691SPeter Lieven 
3047760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
30484ce78691SPeter Lieven         return false;
30494ce78691SPeter Lieven     }
30504ce78691SPeter Lieven 
30514ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30524ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
30534ce78691SPeter Lieven     }
30544ce78691SPeter Lieven 
30554ce78691SPeter Lieven     return false;
30564ce78691SPeter Lieven }
30574ce78691SPeter Lieven 
3058045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3059045df330Saliguori {
3060760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
3061045df330Saliguori         return bs->backing_file;
3062045df330Saliguori     else if (bs->encrypted)
3063045df330Saliguori         return bs->filename;
3064045df330Saliguori     else
3065045df330Saliguori         return NULL;
3066045df330Saliguori }
3067045df330Saliguori 
306883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
306983f64091Sbellard                                char *filename, int filename_size)
307083f64091Sbellard {
307183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
307283f64091Sbellard }
307383f64091Sbellard 
3074faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3075faea38e7Sbellard {
3076faea38e7Sbellard     BlockDriver *drv = bs->drv;
3077faea38e7Sbellard     if (!drv)
307819cb3738Sbellard         return -ENOMEDIUM;
3079faea38e7Sbellard     if (!drv->bdrv_get_info)
3080faea38e7Sbellard         return -ENOTSUP;
3081faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3082faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3083faea38e7Sbellard }
3084faea38e7Sbellard 
3085eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3086eae041feSMax Reitz {
3087eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3088eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3089eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3090eae041feSMax Reitz     }
3091eae041feSMax Reitz     return NULL;
3092eae041feSMax Reitz }
3093eae041feSMax Reitz 
3094a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
30958b9b0cc2SKevin Wolf {
3096bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30978b9b0cc2SKevin Wolf         return;
30988b9b0cc2SKevin Wolf     }
30998b9b0cc2SKevin Wolf 
3100bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
310141c695c7SKevin Wolf }
31028b9b0cc2SKevin Wolf 
310341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
310441c695c7SKevin Wolf                           const char *tag)
310541c695c7SKevin Wolf {
310641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
31079a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
310841c695c7SKevin Wolf     }
310941c695c7SKevin Wolf 
311041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
311141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
311241c695c7SKevin Wolf     }
311341c695c7SKevin Wolf 
311441c695c7SKevin Wolf     return -ENOTSUP;
311541c695c7SKevin Wolf }
311641c695c7SKevin Wolf 
31174cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
31184cc70e93SFam Zheng {
31194cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
31209a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
31214cc70e93SFam Zheng     }
31224cc70e93SFam Zheng 
31234cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
31244cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
31254cc70e93SFam Zheng     }
31264cc70e93SFam Zheng 
31274cc70e93SFam Zheng     return -ENOTSUP;
31284cc70e93SFam Zheng }
31294cc70e93SFam Zheng 
313041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
313141c695c7SKevin Wolf {
3132938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
31339a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
313441c695c7SKevin Wolf     }
313541c695c7SKevin Wolf 
313641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
313741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
313841c695c7SKevin Wolf     }
313941c695c7SKevin Wolf 
314041c695c7SKevin Wolf     return -ENOTSUP;
314141c695c7SKevin Wolf }
314241c695c7SKevin Wolf 
314341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
314441c695c7SKevin Wolf {
314541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
31469a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
314741c695c7SKevin Wolf     }
314841c695c7SKevin Wolf 
314941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
315041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
315141c695c7SKevin Wolf     }
315241c695c7SKevin Wolf 
315341c695c7SKevin Wolf     return false;
31548b9b0cc2SKevin Wolf }
31558b9b0cc2SKevin Wolf 
3156199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3157199630b6SBlue Swirl {
3158199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3159199630b6SBlue Swirl }
3160199630b6SBlue Swirl 
3161b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3162b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3163b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3164b1b1d783SJeff Cody  * the CWD rather than the chain. */
3165e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3166e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3167e8a6bb9cSMarcelo Tosatti {
3168b1b1d783SJeff Cody     char *filename_full = NULL;
3169b1b1d783SJeff Cody     char *backing_file_full = NULL;
3170b1b1d783SJeff Cody     char *filename_tmp = NULL;
3171b1b1d783SJeff Cody     int is_protocol = 0;
3172b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3173b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3174b1b1d783SJeff Cody 
3175b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3176e8a6bb9cSMarcelo Tosatti         return NULL;
3177e8a6bb9cSMarcelo Tosatti     }
3178e8a6bb9cSMarcelo Tosatti 
3179b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3180b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3181b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3182b1b1d783SJeff Cody 
3183b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3184b1b1d783SJeff Cody 
3185760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3186b1b1d783SJeff Cody 
3187b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3188b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3189b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3190b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3191760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3192b1b1d783SJeff Cody                 break;
3193b1b1d783SJeff Cody             }
3194e8a6bb9cSMarcelo Tosatti         } else {
3195b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3196b1b1d783SJeff Cody              * image's filename path */
3197b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3198b1b1d783SJeff Cody                          backing_file);
3199b1b1d783SJeff Cody 
3200b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3201b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3202b1b1d783SJeff Cody                 continue;
3203b1b1d783SJeff Cody             }
3204b1b1d783SJeff Cody 
3205b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3206b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3207b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3208b1b1d783SJeff Cody                          curr_bs->backing_file);
3209b1b1d783SJeff Cody 
3210b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3211b1b1d783SJeff Cody                 continue;
3212b1b1d783SJeff Cody             }
3213b1b1d783SJeff Cody 
3214b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3215760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3216b1b1d783SJeff Cody                 break;
3217b1b1d783SJeff Cody             }
3218e8a6bb9cSMarcelo Tosatti         }
3219e8a6bb9cSMarcelo Tosatti     }
3220e8a6bb9cSMarcelo Tosatti 
3221b1b1d783SJeff Cody     g_free(filename_full);
3222b1b1d783SJeff Cody     g_free(backing_file_full);
3223b1b1d783SJeff Cody     g_free(filename_tmp);
3224b1b1d783SJeff Cody     return retval;
3225e8a6bb9cSMarcelo Tosatti }
3226e8a6bb9cSMarcelo Tosatti 
3227f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3228f198fd1cSBenoît Canet {
3229f198fd1cSBenoît Canet     if (!bs->drv) {
3230f198fd1cSBenoît Canet         return 0;
3231f198fd1cSBenoît Canet     }
3232f198fd1cSBenoît Canet 
3233760e0063SKevin Wolf     if (!bs->backing) {
3234f198fd1cSBenoît Canet         return 0;
3235f198fd1cSBenoît Canet     }
3236f198fd1cSBenoît Canet 
3237760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3238f198fd1cSBenoît Canet }
3239f198fd1cSBenoît Canet 
3240ea2384d3Sbellard void bdrv_init(void)
3241ea2384d3Sbellard {
32425efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3243ea2384d3Sbellard }
3244ce1a14dcSpbrook 
3245eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3246eb852011SMarkus Armbruster {
3247eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3248eb852011SMarkus Armbruster     bdrv_init();
3249eb852011SMarkus Armbruster }
3250eb852011SMarkus Armbruster 
32515a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
32520f15423cSAnthony Liguori {
32535a8a30dbSKevin Wolf     Error *local_err = NULL;
32545a8a30dbSKevin Wolf     int ret;
32555a8a30dbSKevin Wolf 
32563456a8d1SKevin Wolf     if (!bs->drv)  {
32573456a8d1SKevin Wolf         return;
32580f15423cSAnthony Liguori     }
32593456a8d1SKevin Wolf 
326004c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
32617ea2d269SAlexey Kardashevskiy         return;
32627ea2d269SAlexey Kardashevskiy     }
326304c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
32647ea2d269SAlexey Kardashevskiy 
32653456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
32665a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
32673456a8d1SKevin Wolf     } else if (bs->file) {
32689a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
32695a8a30dbSKevin Wolf     }
32705a8a30dbSKevin Wolf     if (local_err) {
327104c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32725a8a30dbSKevin Wolf         error_propagate(errp, local_err);
32735a8a30dbSKevin Wolf         return;
32743456a8d1SKevin Wolf     }
32753456a8d1SKevin Wolf 
32765a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
32775a8a30dbSKevin Wolf     if (ret < 0) {
327804c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32795a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
32805a8a30dbSKevin Wolf         return;
32815a8a30dbSKevin Wolf     }
32820f15423cSAnthony Liguori }
32830f15423cSAnthony Liguori 
32845a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
32850f15423cSAnthony Liguori {
328679720af6SMax Reitz     BlockDriverState *bs = NULL;
32875a8a30dbSKevin Wolf     Error *local_err = NULL;
32880f15423cSAnthony Liguori 
328979720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3290ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3291ed78cda3SStefan Hajnoczi 
3292ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32935a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3294ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32955a8a30dbSKevin Wolf         if (local_err) {
32965a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32975a8a30dbSKevin Wolf             return;
32985a8a30dbSKevin Wolf         }
32990f15423cSAnthony Liguori     }
33000f15423cSAnthony Liguori }
33010f15423cSAnthony Liguori 
330276b1c7feSKevin Wolf static int bdrv_inactivate(BlockDriverState *bs)
330376b1c7feSKevin Wolf {
330476b1c7feSKevin Wolf     int ret;
330576b1c7feSKevin Wolf 
330676b1c7feSKevin Wolf     if (bs->drv->bdrv_inactivate) {
330776b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
330876b1c7feSKevin Wolf         if (ret < 0) {
330976b1c7feSKevin Wolf             return ret;
331076b1c7feSKevin Wolf         }
331176b1c7feSKevin Wolf     }
331276b1c7feSKevin Wolf 
331376b1c7feSKevin Wolf     bs->open_flags |= BDRV_O_INACTIVE;
331476b1c7feSKevin Wolf     return 0;
331576b1c7feSKevin Wolf }
331676b1c7feSKevin Wolf 
331776b1c7feSKevin Wolf int bdrv_inactivate_all(void)
331876b1c7feSKevin Wolf {
331979720af6SMax Reitz     BlockDriverState *bs = NULL;
332076b1c7feSKevin Wolf     int ret;
332176b1c7feSKevin Wolf 
332279720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
332376b1c7feSKevin Wolf         AioContext *aio_context = bdrv_get_aio_context(bs);
332476b1c7feSKevin Wolf 
332576b1c7feSKevin Wolf         aio_context_acquire(aio_context);
332676b1c7feSKevin Wolf         ret = bdrv_inactivate(bs);
332776b1c7feSKevin Wolf         aio_context_release(aio_context);
332876b1c7feSKevin Wolf         if (ret < 0) {
332976b1c7feSKevin Wolf             return ret;
333076b1c7feSKevin Wolf         }
333176b1c7feSKevin Wolf     }
333276b1c7feSKevin Wolf 
333376b1c7feSKevin Wolf     return 0;
333476b1c7feSKevin Wolf }
333576b1c7feSKevin Wolf 
3336f9f05dc5SKevin Wolf /**************************************************************/
333719cb3738Sbellard /* removable device support */
333819cb3738Sbellard 
333919cb3738Sbellard /**
334019cb3738Sbellard  * Return TRUE if the media is present
334119cb3738Sbellard  */
3342e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
334319cb3738Sbellard {
334419cb3738Sbellard     BlockDriver *drv = bs->drv;
334528d7a789SMax Reitz     BdrvChild *child;
3346a1aff5bfSMarkus Armbruster 
3347e031f750SMax Reitz     if (!drv) {
3348e031f750SMax Reitz         return false;
3349e031f750SMax Reitz     }
335028d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3351a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
335219cb3738Sbellard     }
335328d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
335428d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
335528d7a789SMax Reitz             return false;
335628d7a789SMax Reitz         }
335728d7a789SMax Reitz     }
335828d7a789SMax Reitz     return true;
335928d7a789SMax Reitz }
336019cb3738Sbellard 
336119cb3738Sbellard /**
33628e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
33638e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
336419cb3738Sbellard  */
336519cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
336619cb3738Sbellard {
336719cb3738Sbellard     BlockDriver *drv = bs->drv;
336819cb3738Sbellard 
33698e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33708e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33718e49ca46SMarkus Armbruster     }
33728e49ca46SMarkus Armbruster     return -ENOTSUP;
337319cb3738Sbellard }
337419cb3738Sbellard 
337519cb3738Sbellard /**
337619cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
337719cb3738Sbellard  */
3378f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
337919cb3738Sbellard {
338019cb3738Sbellard     BlockDriver *drv = bs->drv;
3381bfb197e0SMarkus Armbruster     const char *device_name;
338219cb3738Sbellard 
3383822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3384822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
338519cb3738Sbellard     }
33866f382ed2SLuiz Capitulino 
3387bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3388bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3389bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3390a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
33916f382ed2SLuiz Capitulino     }
339219cb3738Sbellard }
339319cb3738Sbellard 
339419cb3738Sbellard /**
339519cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
339619cb3738Sbellard  * to eject it manually).
339719cb3738Sbellard  */
3398025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
339919cb3738Sbellard {
340019cb3738Sbellard     BlockDriver *drv = bs->drv;
340119cb3738Sbellard 
3402025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3403b8c6d095SStefan Hajnoczi 
3404025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3405025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
340619cb3738Sbellard     }
340719cb3738Sbellard }
3408985a03b0Sths 
34099fcb0251SFam Zheng /* Get a reference to bs */
34109fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
34119fcb0251SFam Zheng {
34129fcb0251SFam Zheng     bs->refcnt++;
34139fcb0251SFam Zheng }
34149fcb0251SFam Zheng 
34159fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
34169fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
34179fcb0251SFam Zheng  * deleted. */
34189fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
34199fcb0251SFam Zheng {
34209a4d5ca6SJeff Cody     if (!bs) {
34219a4d5ca6SJeff Cody         return;
34229a4d5ca6SJeff Cody     }
34239fcb0251SFam Zheng     assert(bs->refcnt > 0);
34249fcb0251SFam Zheng     if (--bs->refcnt == 0) {
34259fcb0251SFam Zheng         bdrv_delete(bs);
34269fcb0251SFam Zheng     }
34279fcb0251SFam Zheng }
34289fcb0251SFam Zheng 
3429fbe40ff7SFam Zheng struct BdrvOpBlocker {
3430fbe40ff7SFam Zheng     Error *reason;
3431fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3432fbe40ff7SFam Zheng };
3433fbe40ff7SFam Zheng 
3434fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3435fbe40ff7SFam Zheng {
3436fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3437fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3438fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3439fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3440fbe40ff7SFam Zheng         if (errp) {
3441e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3442e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3443e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3444fbe40ff7SFam Zheng         }
3445fbe40ff7SFam Zheng         return true;
3446fbe40ff7SFam Zheng     }
3447fbe40ff7SFam Zheng     return false;
3448fbe40ff7SFam Zheng }
3449fbe40ff7SFam Zheng 
3450fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3451fbe40ff7SFam Zheng {
3452fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3453fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3454fbe40ff7SFam Zheng 
34555839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3456fbe40ff7SFam Zheng     blocker->reason = reason;
3457fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3458fbe40ff7SFam Zheng }
3459fbe40ff7SFam Zheng 
3460fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3461fbe40ff7SFam Zheng {
3462fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3463fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3464fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3465fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3466fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3467fbe40ff7SFam Zheng             g_free(blocker);
3468fbe40ff7SFam Zheng         }
3469fbe40ff7SFam Zheng     }
3470fbe40ff7SFam Zheng }
3471fbe40ff7SFam Zheng 
3472fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3473fbe40ff7SFam Zheng {
3474fbe40ff7SFam Zheng     int i;
3475fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3476fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3477fbe40ff7SFam Zheng     }
3478fbe40ff7SFam Zheng }
3479fbe40ff7SFam Zheng 
3480fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3481fbe40ff7SFam Zheng {
3482fbe40ff7SFam Zheng     int i;
3483fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3484fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3485fbe40ff7SFam Zheng     }
3486fbe40ff7SFam Zheng }
3487fbe40ff7SFam Zheng 
3488fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3489fbe40ff7SFam Zheng {
3490fbe40ff7SFam Zheng     int i;
3491fbe40ff7SFam Zheng 
3492fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3493fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3494fbe40ff7SFam Zheng             return false;
3495fbe40ff7SFam Zheng         }
3496fbe40ff7SFam Zheng     }
3497fbe40ff7SFam Zheng     return true;
3498fbe40ff7SFam Zheng }
3499fbe40ff7SFam Zheng 
3500d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3501f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3502f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3503f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3504f88e1a42SJes Sorensen {
350583d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
350683d0521aSChunyan Liu     QemuOpts *opts = NULL;
350783d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
350883d0521aSChunyan Liu     int64_t size;
3509f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3510cc84d90fSMax Reitz     Error *local_err = NULL;
3511f88e1a42SJes Sorensen     int ret = 0;
3512f88e1a42SJes Sorensen 
3513f88e1a42SJes Sorensen     /* Find driver and parse its options */
3514f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3515f88e1a42SJes Sorensen     if (!drv) {
351671c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3517d92ada22SLuiz Capitulino         return;
3518f88e1a42SJes Sorensen     }
3519f88e1a42SJes Sorensen 
3520b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3521f88e1a42SJes Sorensen     if (!proto_drv) {
3522d92ada22SLuiz Capitulino         return;
3523f88e1a42SJes Sorensen     }
3524f88e1a42SJes Sorensen 
3525c6149724SMax Reitz     if (!drv->create_opts) {
3526c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3527c6149724SMax Reitz                    drv->format_name);
3528c6149724SMax Reitz         return;
3529c6149724SMax Reitz     }
3530c6149724SMax Reitz 
3531c6149724SMax Reitz     if (!proto_drv->create_opts) {
3532c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3533c6149724SMax Reitz                    proto_drv->format_name);
3534c6149724SMax Reitz         return;
3535c6149724SMax Reitz     }
3536c6149724SMax Reitz 
3537c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3538c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3539f88e1a42SJes Sorensen 
3540f88e1a42SJes Sorensen     /* Create parameter list with default values */
354183d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
354239101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3543f88e1a42SJes Sorensen 
3544f88e1a42SJes Sorensen     /* Parse -o options */
3545f88e1a42SJes Sorensen     if (options) {
3546dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3547dc523cd3SMarkus Armbruster         if (local_err) {
3548dc523cd3SMarkus Armbruster             error_report_err(local_err);
3549dc523cd3SMarkus Armbruster             local_err = NULL;
355083d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3551f88e1a42SJes Sorensen             goto out;
3552f88e1a42SJes Sorensen         }
3553f88e1a42SJes Sorensen     }
3554f88e1a42SJes Sorensen 
3555f88e1a42SJes Sorensen     if (base_filename) {
3556f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35576be4194bSMarkus Armbruster         if (local_err) {
355871c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
355971c79813SLuiz Capitulino                        fmt);
3560f88e1a42SJes Sorensen             goto out;
3561f88e1a42SJes Sorensen         }
3562f88e1a42SJes Sorensen     }
3563f88e1a42SJes Sorensen 
3564f88e1a42SJes Sorensen     if (base_fmt) {
3565f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35666be4194bSMarkus Armbruster         if (local_err) {
356771c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
356871c79813SLuiz Capitulino                              "format '%s'", fmt);
3569f88e1a42SJes Sorensen             goto out;
3570f88e1a42SJes Sorensen         }
3571f88e1a42SJes Sorensen     }
3572f88e1a42SJes Sorensen 
357383d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
357483d0521aSChunyan Liu     if (backing_file) {
357583d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
357671c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
357771c79813SLuiz Capitulino                              "same filename as the backing file");
3578792da93aSJes Sorensen             goto out;
3579792da93aSJes Sorensen         }
3580792da93aSJes Sorensen     }
3581792da93aSJes Sorensen 
358283d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3583f88e1a42SJes Sorensen 
3584f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3585f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
358683d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
358783d0521aSChunyan Liu     if (size == -1) {
358883d0521aSChunyan Liu         if (backing_file) {
358966f6b814SMax Reitz             BlockDriverState *bs;
359029168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
359152bf1e72SMarkus Armbruster             int64_t size;
359263090dacSPaolo Bonzini             int back_flags;
3593e6641719SMax Reitz             QDict *backing_options = NULL;
359463090dacSPaolo Bonzini 
359529168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
359629168018SMax Reitz                                                          full_backing, PATH_MAX,
359729168018SMax Reitz                                                          &local_err);
359829168018SMax Reitz             if (local_err) {
359929168018SMax Reitz                 g_free(full_backing);
360029168018SMax Reitz                 goto out;
360129168018SMax Reitz             }
360229168018SMax Reitz 
360363090dacSPaolo Bonzini             /* backing files always opened read-only */
360463090dacSPaolo Bonzini             back_flags =
360563090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3606f88e1a42SJes Sorensen 
3607e6641719SMax Reitz             if (backing_fmt) {
3608e6641719SMax Reitz                 backing_options = qdict_new();
3609e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3610e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3611e6641719SMax Reitz             }
3612e6641719SMax Reitz 
3613f67503e5SMax Reitz             bs = NULL;
3614e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
36156ebf9aa2SMax Reitz                             back_flags, &local_err);
361629168018SMax Reitz             g_free(full_backing);
3617f88e1a42SJes Sorensen             if (ret < 0) {
3618f88e1a42SJes Sorensen                 goto out;
3619f88e1a42SJes Sorensen             }
362052bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
362152bf1e72SMarkus Armbruster             if (size < 0) {
362252bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
362352bf1e72SMarkus Armbruster                                  backing_file);
362452bf1e72SMarkus Armbruster                 bdrv_unref(bs);
362552bf1e72SMarkus Armbruster                 goto out;
362652bf1e72SMarkus Armbruster             }
3627f88e1a42SJes Sorensen 
362839101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
362966f6b814SMax Reitz 
363066f6b814SMax Reitz             bdrv_unref(bs);
3631f88e1a42SJes Sorensen         } else {
363271c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3633f88e1a42SJes Sorensen             goto out;
3634f88e1a42SJes Sorensen         }
3635f88e1a42SJes Sorensen     }
3636f88e1a42SJes Sorensen 
3637f382d43aSMiroslav Rezanina     if (!quiet) {
3638f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
363943c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3640f88e1a42SJes Sorensen         puts("");
3641f382d43aSMiroslav Rezanina     }
364283d0521aSChunyan Liu 
3643c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
364483d0521aSChunyan Liu 
3645cc84d90fSMax Reitz     if (ret == -EFBIG) {
3646cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3647cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3648cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3649f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
365083d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3651f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3652f3f4d2c0SKevin Wolf         }
3653cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3654cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3655cc84d90fSMax Reitz         error_free(local_err);
3656cc84d90fSMax Reitz         local_err = NULL;
3657f88e1a42SJes Sorensen     }
3658f88e1a42SJes Sorensen 
3659f88e1a42SJes Sorensen out:
366083d0521aSChunyan Liu     qemu_opts_del(opts);
366183d0521aSChunyan Liu     qemu_opts_free(create_opts);
366284d18f06SMarkus Armbruster     if (local_err) {
3663cc84d90fSMax Reitz         error_propagate(errp, local_err);
3664cc84d90fSMax Reitz     }
3665f88e1a42SJes Sorensen }
366685d126f3SStefan Hajnoczi 
366785d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
366885d126f3SStefan Hajnoczi {
3669dcd04228SStefan Hajnoczi     return bs->aio_context;
3670dcd04228SStefan Hajnoczi }
3671dcd04228SStefan Hajnoczi 
3672dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3673dcd04228SStefan Hajnoczi {
367433384421SMax Reitz     BdrvAioNotifier *baf;
367533384421SMax Reitz 
3676dcd04228SStefan Hajnoczi     if (!bs->drv) {
3677dcd04228SStefan Hajnoczi         return;
3678dcd04228SStefan Hajnoczi     }
3679dcd04228SStefan Hajnoczi 
368033384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
368133384421SMax Reitz         baf->detach_aio_context(baf->opaque);
368233384421SMax Reitz     }
368333384421SMax Reitz 
3684a0d64a61SAlberto Garcia     if (bs->throttle_state) {
36850e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
368613af91ebSStefan Hajnoczi     }
3687dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3688dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3689dcd04228SStefan Hajnoczi     }
3690dcd04228SStefan Hajnoczi     if (bs->file) {
36919a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3692dcd04228SStefan Hajnoczi     }
3693760e0063SKevin Wolf     if (bs->backing) {
3694760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3695dcd04228SStefan Hajnoczi     }
3696dcd04228SStefan Hajnoczi 
3697dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3698dcd04228SStefan Hajnoczi }
3699dcd04228SStefan Hajnoczi 
3700dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3701dcd04228SStefan Hajnoczi                              AioContext *new_context)
3702dcd04228SStefan Hajnoczi {
370333384421SMax Reitz     BdrvAioNotifier *ban;
370433384421SMax Reitz 
3705dcd04228SStefan Hajnoczi     if (!bs->drv) {
3706dcd04228SStefan Hajnoczi         return;
3707dcd04228SStefan Hajnoczi     }
3708dcd04228SStefan Hajnoczi 
3709dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3710dcd04228SStefan Hajnoczi 
3711760e0063SKevin Wolf     if (bs->backing) {
3712760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3713dcd04228SStefan Hajnoczi     }
3714dcd04228SStefan Hajnoczi     if (bs->file) {
37159a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3716dcd04228SStefan Hajnoczi     }
3717dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3718dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3719dcd04228SStefan Hajnoczi     }
3720a0d64a61SAlberto Garcia     if (bs->throttle_state) {
37210e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
372213af91ebSStefan Hajnoczi     }
372333384421SMax Reitz 
372433384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
372533384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
372633384421SMax Reitz     }
3727dcd04228SStefan Hajnoczi }
3728dcd04228SStefan Hajnoczi 
3729dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3730dcd04228SStefan Hajnoczi {
373153ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3732dcd04228SStefan Hajnoczi 
3733dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3734dcd04228SStefan Hajnoczi 
3735dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3736dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3737dcd04228SStefan Hajnoczi      */
3738dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3739dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3740dcd04228SStefan Hajnoczi     aio_context_release(new_context);
374185d126f3SStefan Hajnoczi }
3742d616b224SStefan Hajnoczi 
374333384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
374433384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
374533384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
374633384421SMax Reitz {
374733384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
374833384421SMax Reitz     *ban = (BdrvAioNotifier){
374933384421SMax Reitz         .attached_aio_context = attached_aio_context,
375033384421SMax Reitz         .detach_aio_context   = detach_aio_context,
375133384421SMax Reitz         .opaque               = opaque
375233384421SMax Reitz     };
375333384421SMax Reitz 
375433384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
375533384421SMax Reitz }
375633384421SMax Reitz 
375733384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
375833384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
375933384421SMax Reitz                                                                    void *),
376033384421SMax Reitz                                       void (*detach_aio_context)(void *),
376133384421SMax Reitz                                       void *opaque)
376233384421SMax Reitz {
376333384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
376433384421SMax Reitz 
376533384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
376633384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
376733384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
376833384421SMax Reitz             ban->opaque               == opaque)
376933384421SMax Reitz         {
377033384421SMax Reitz             QLIST_REMOVE(ban, list);
377133384421SMax Reitz             g_free(ban);
377233384421SMax Reitz 
377333384421SMax Reitz             return;
377433384421SMax Reitz         }
377533384421SMax Reitz     }
377633384421SMax Reitz 
377733384421SMax Reitz     abort();
377833384421SMax Reitz }
377933384421SMax Reitz 
378077485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
37818b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
37826f176b48SMax Reitz {
3783c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
37846f176b48SMax Reitz         return -ENOTSUP;
37856f176b48SMax Reitz     }
37868b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
37876f176b48SMax Reitz }
3788f6186f49SBenoît Canet 
3789b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3790b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3791b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3792b5042a36SBenoît Canet  * node graph.
3793212a5a8fSBenoît Canet  */
3794212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3795212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3796f6186f49SBenoît Canet {
3797b5042a36SBenoît Canet     /* return false if basic checks fails */
3798b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3799b5042a36SBenoît Canet         return false;
3800b5042a36SBenoît Canet     }
3801b5042a36SBenoît Canet 
3802b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3803b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3804b5042a36SBenoît Canet      */
3805b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3806b5042a36SBenoît Canet         return bs == candidate;
3807b5042a36SBenoît Canet     }
3808b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3809b5042a36SBenoît Canet 
3810b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3811b5042a36SBenoît Canet      * the node graph.
3812b5042a36SBenoît Canet      */
3813b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3814212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3815212a5a8fSBenoît Canet     }
3816212a5a8fSBenoît Canet 
3817b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3818b5042a36SBenoît Canet      */
3819b5042a36SBenoît Canet     return false;
3820212a5a8fSBenoît Canet }
3821212a5a8fSBenoît Canet 
3822212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3823212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3824212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3825212a5a8fSBenoît Canet  */
3826212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3827212a5a8fSBenoît Canet {
382879720af6SMax Reitz     BlockDriverState *bs = NULL;
3829212a5a8fSBenoît Canet 
3830212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
383179720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3832212a5a8fSBenoît Canet         bool perm;
3833212a5a8fSBenoît Canet 
3834b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3835e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3836212a5a8fSBenoît Canet 
3837212a5a8fSBenoît Canet         /* candidate is the first non filter */
3838212a5a8fSBenoît Canet         if (perm) {
3839212a5a8fSBenoît Canet             return true;
3840212a5a8fSBenoît Canet         }
3841212a5a8fSBenoît Canet     }
3842212a5a8fSBenoît Canet 
3843212a5a8fSBenoît Canet     return false;
3844f6186f49SBenoît Canet }
384509158f00SBenoît Canet 
3846e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3847e12f3784SWen Congyang                                         const char *node_name, Error **errp)
384809158f00SBenoît Canet {
384909158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38505a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38515a7e7a0bSStefan Hajnoczi 
385209158f00SBenoît Canet     if (!to_replace_bs) {
385309158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
385409158f00SBenoît Canet         return NULL;
385509158f00SBenoît Canet     }
385609158f00SBenoît Canet 
38575a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38585a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38595a7e7a0bSStefan Hajnoczi 
386009158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38615a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38625a7e7a0bSStefan Hajnoczi         goto out;
386309158f00SBenoît Canet     }
386409158f00SBenoît Canet 
386509158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
386609158f00SBenoît Canet      * most non filter in order to prevent data corruption.
386709158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
386809158f00SBenoît Canet      * blocked by the backing blockers.
386909158f00SBenoît Canet      */
3870e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
387109158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
38725a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38735a7e7a0bSStefan Hajnoczi         goto out;
387409158f00SBenoît Canet     }
387509158f00SBenoît Canet 
38765a7e7a0bSStefan Hajnoczi out:
38775a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
387809158f00SBenoît Canet     return to_replace_bs;
387909158f00SBenoît Canet }
3880448ad91dSMing Lei 
388191af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
388291af7014SMax Reitz {
388391af7014SMax Reitz     const QDictEntry *entry;
38849e700c1aSKevin Wolf     QemuOptDesc *desc;
3885260fecf1SKevin Wolf     BdrvChild *child;
388691af7014SMax Reitz     bool found_any = false;
3887260fecf1SKevin Wolf     const char *p;
388891af7014SMax Reitz 
388991af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
389091af7014SMax Reitz          entry = qdict_next(bs->options, entry))
389191af7014SMax Reitz     {
3892260fecf1SKevin Wolf         /* Exclude options for children */
3893260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3894260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3895260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3896260fecf1SKevin Wolf             {
3897260fecf1SKevin Wolf                 break;
3898260fecf1SKevin Wolf             }
3899260fecf1SKevin Wolf         }
3900260fecf1SKevin Wolf         if (child) {
39019e700c1aSKevin Wolf             continue;
39029e700c1aSKevin Wolf         }
39039e700c1aSKevin Wolf 
39049e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
39059e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
39069e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
39079e700c1aSKevin Wolf                 break;
39089e700c1aSKevin Wolf             }
39099e700c1aSKevin Wolf         }
39109e700c1aSKevin Wolf         if (desc->name) {
39119e700c1aSKevin Wolf             continue;
39129e700c1aSKevin Wolf         }
39139e700c1aSKevin Wolf 
391491af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
391591af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
391691af7014SMax Reitz         found_any = true;
391791af7014SMax Reitz     }
391891af7014SMax Reitz 
391991af7014SMax Reitz     return found_any;
392091af7014SMax Reitz }
392191af7014SMax Reitz 
392291af7014SMax Reitz /* Updates the following BDS fields:
392391af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
392491af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
392591af7014SMax Reitz  *                    other options; so reading and writing must return the same
392691af7014SMax Reitz  *                    results, but caching etc. may be different)
392791af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
392891af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
392991af7014SMax Reitz  *                       equalling the given one
393091af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
393191af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
393291af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
393391af7014SMax Reitz  */
393491af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
393591af7014SMax Reitz {
393691af7014SMax Reitz     BlockDriver *drv = bs->drv;
393791af7014SMax Reitz     QDict *opts;
393891af7014SMax Reitz 
393991af7014SMax Reitz     if (!drv) {
394091af7014SMax Reitz         return;
394191af7014SMax Reitz     }
394291af7014SMax Reitz 
394391af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
394491af7014SMax Reitz      * refresh that first */
394591af7014SMax Reitz     if (bs->file) {
39469a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
394791af7014SMax Reitz     }
394891af7014SMax Reitz 
394991af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
395091af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
395191af7014SMax Reitz          * information before refreshing it */
395291af7014SMax Reitz         bs->exact_filename[0] = '\0';
395391af7014SMax Reitz         if (bs->full_open_options) {
395491af7014SMax Reitz             QDECREF(bs->full_open_options);
395591af7014SMax Reitz             bs->full_open_options = NULL;
395691af7014SMax Reitz         }
395791af7014SMax Reitz 
39584cdd01d3SKevin Wolf         opts = qdict_new();
39594cdd01d3SKevin Wolf         append_open_options(opts, bs);
39604cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
39614cdd01d3SKevin Wolf         QDECREF(opts);
396291af7014SMax Reitz     } else if (bs->file) {
396391af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
396491af7014SMax Reitz         bool has_open_options;
396591af7014SMax Reitz 
396691af7014SMax Reitz         bs->exact_filename[0] = '\0';
396791af7014SMax Reitz         if (bs->full_open_options) {
396891af7014SMax Reitz             QDECREF(bs->full_open_options);
396991af7014SMax Reitz             bs->full_open_options = NULL;
397091af7014SMax Reitz         }
397191af7014SMax Reitz 
397291af7014SMax Reitz         opts = qdict_new();
397391af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
397491af7014SMax Reitz 
397591af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
397691af7014SMax Reitz          * the underlying file should suffice for this one as well */
39779a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
39789a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
397991af7014SMax Reitz         }
398091af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
398191af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
398291af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
398391af7014SMax Reitz          * contain a representation of the filename, therefore the following
398491af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
39859a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
398691af7014SMax Reitz             qdict_put_obj(opts, "driver",
398791af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
39889a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
39899a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
39909a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
399191af7014SMax Reitz 
399291af7014SMax Reitz             bs->full_open_options = opts;
399391af7014SMax Reitz         } else {
399491af7014SMax Reitz             QDECREF(opts);
399591af7014SMax Reitz         }
399691af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
399791af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
399891af7014SMax Reitz          * so the full options QDict should be equal to the options given
399991af7014SMax Reitz          * specifically for this block device when it was opened (plus the
400091af7014SMax Reitz          * driver specification).
400191af7014SMax Reitz          * Because those options don't change, there is no need to update
400291af7014SMax Reitz          * full_open_options when it's already set. */
400391af7014SMax Reitz 
400491af7014SMax Reitz         opts = qdict_new();
400591af7014SMax Reitz         append_open_options(opts, bs);
400691af7014SMax Reitz         qdict_put_obj(opts, "driver",
400791af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
400891af7014SMax Reitz 
400991af7014SMax Reitz         if (bs->exact_filename[0]) {
401091af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
401191af7014SMax Reitz              * require this filename to be parsed), but we have to find some
401291af7014SMax Reitz              * default solution here, so just include it. If some block driver
401391af7014SMax Reitz              * does not support pure options without any filename at all or
401491af7014SMax Reitz              * needs some special format of the options QDict, it needs to
401591af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
401691af7014SMax Reitz              */
401791af7014SMax Reitz             qdict_put_obj(opts, "filename",
401891af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
401991af7014SMax Reitz         }
402091af7014SMax Reitz 
402191af7014SMax Reitz         bs->full_open_options = opts;
402291af7014SMax Reitz     }
402391af7014SMax Reitz 
402491af7014SMax Reitz     if (bs->exact_filename[0]) {
402591af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
402691af7014SMax Reitz     } else if (bs->full_open_options) {
402791af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
402891af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
402991af7014SMax Reitz                  qstring_get_str(json));
403091af7014SMax Reitz         QDECREF(json);
403191af7014SMax Reitz     }
403291af7014SMax Reitz }
4033