xref: /openbmc/qemu/block.c (revision 62392ebb09fc6e87626aa151a616f24c4e921493)
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  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
27737e150eSPaolo Bonzini #include "block/block_int.h"
28737e150eSPaolo Bonzini #include "block/blockjob.h"
29d49b6836SMarkus Armbruster #include "qemu/error-report.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
31cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.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"
42fc01f7e7Sbellard 
4371e72a19SJuan Quintela #ifdef CONFIG_BSD
447674e7bfSbellard #include <sys/types.h>
457674e7bfSbellard #include <sys/stat.h>
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 
579bd2b08fSJohn Snow /**
589bd2b08fSJohn Snow  * A BdrvDirtyBitmap can be in three possible states:
599bd2b08fSJohn Snow  * (1) successor is NULL and disabled is false: full r/w mode
609bd2b08fSJohn Snow  * (2) successor is NULL and disabled is true: read only mode ("disabled")
619bd2b08fSJohn Snow  * (3) successor is set: frozen mode.
629bd2b08fSJohn Snow  *     A frozen bitmap cannot be renamed, deleted, anonymized, cleared, set,
639bd2b08fSJohn Snow  *     or enabled. A frozen bitmap can only abdicate() or reclaim().
649bd2b08fSJohn Snow  */
65e4654d2dSFam Zheng struct BdrvDirtyBitmap {
66aa0c7ca5SJohn Snow     HBitmap *bitmap;            /* Dirty sector bitmap implementation */
67aa0c7ca5SJohn Snow     BdrvDirtyBitmap *successor; /* Anonymous child; implies frozen status */
68aa0c7ca5SJohn Snow     char *name;                 /* Optional non-empty unique ID */
69aa0c7ca5SJohn Snow     int64_t size;               /* Size of the bitmap (Number of sectors) */
70aa0c7ca5SJohn Snow     bool disabled;              /* Bitmap is read-only */
71e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
72e4654d2dSFam Zheng };
73e4654d2dSFam Zheng 
741c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
751c9805a3SStefan Hajnoczi 
76c69a4dd8SMax Reitz struct BdrvStates bdrv_states = QTAILQ_HEAD_INITIALIZER(bdrv_states);
777ee930d0Sblueswir1 
78dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
79dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
80dc364f4cSBenoît Canet 
818a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
828a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
83ea2384d3Sbellard 
84f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
85f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
86f3930ed0SKevin Wolf                              BlockDriverState *parent,
87ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
88f3930ed0SKevin Wolf 
89ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs);
90eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
91eb852011SMarkus Armbruster static int use_bdrv_whitelist;
92eb852011SMarkus Armbruster 
939e0b22f4SStefan Hajnoczi #ifdef _WIN32
949e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
959e0b22f4SStefan Hajnoczi {
969e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
979e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
989e0b22f4SStefan Hajnoczi             filename[1] == ':');
999e0b22f4SStefan Hajnoczi }
1009e0b22f4SStefan Hajnoczi 
1019e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1029e0b22f4SStefan Hajnoczi {
1039e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1049e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1059e0b22f4SStefan Hajnoczi         return 1;
1069e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1079e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1089e0b22f4SStefan Hajnoczi         return 1;
1099e0b22f4SStefan Hajnoczi     return 0;
1109e0b22f4SStefan Hajnoczi }
1119e0b22f4SStefan Hajnoczi #endif
1129e0b22f4SStefan Hajnoczi 
113339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
114339064d5SKevin Wolf {
115339064d5SKevin Wolf     if (!bs || !bs->drv) {
116459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
117459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
118339064d5SKevin Wolf     }
119339064d5SKevin Wolf 
120339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
121339064d5SKevin Wolf }
122339064d5SKevin Wolf 
1234196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1244196d2f0SDenis V. Lunev {
1254196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
126459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
127459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1284196d2f0SDenis V. Lunev     }
1294196d2f0SDenis V. Lunev 
1304196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1314196d2f0SDenis V. Lunev }
1324196d2f0SDenis V. Lunev 
1339e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1345c98415bSMax Reitz int path_has_protocol(const char *path)
1359e0b22f4SStefan Hajnoczi {
136947995c0SPaolo Bonzini     const char *p;
137947995c0SPaolo Bonzini 
1389e0b22f4SStefan Hajnoczi #ifdef _WIN32
1399e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1409e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1419e0b22f4SStefan Hajnoczi         return 0;
1429e0b22f4SStefan Hajnoczi     }
143947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
144947995c0SPaolo Bonzini #else
145947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1469e0b22f4SStefan Hajnoczi #endif
1479e0b22f4SStefan Hajnoczi 
148947995c0SPaolo Bonzini     return *p == ':';
1499e0b22f4SStefan Hajnoczi }
1509e0b22f4SStefan Hajnoczi 
15183f64091Sbellard int path_is_absolute(const char *path)
15283f64091Sbellard {
15321664424Sbellard #ifdef _WIN32
15421664424Sbellard     /* specific case for names like: "\\.\d:" */
155f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
15621664424Sbellard         return 1;
157f53f4da9SPaolo Bonzini     }
158f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1593b9f94e1Sbellard #else
160f53f4da9SPaolo Bonzini     return (*path == '/');
1613b9f94e1Sbellard #endif
16283f64091Sbellard }
16383f64091Sbellard 
16483f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
16583f64091Sbellard    path to it by considering it is relative to base_path. URL are
16683f64091Sbellard    supported. */
16783f64091Sbellard void path_combine(char *dest, int dest_size,
16883f64091Sbellard                   const char *base_path,
16983f64091Sbellard                   const char *filename)
17083f64091Sbellard {
17183f64091Sbellard     const char *p, *p1;
17283f64091Sbellard     int len;
17383f64091Sbellard 
17483f64091Sbellard     if (dest_size <= 0)
17583f64091Sbellard         return;
17683f64091Sbellard     if (path_is_absolute(filename)) {
17783f64091Sbellard         pstrcpy(dest, dest_size, filename);
17883f64091Sbellard     } else {
17983f64091Sbellard         p = strchr(base_path, ':');
18083f64091Sbellard         if (p)
18183f64091Sbellard             p++;
18283f64091Sbellard         else
18383f64091Sbellard             p = base_path;
1843b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1853b9f94e1Sbellard #ifdef _WIN32
1863b9f94e1Sbellard         {
1873b9f94e1Sbellard             const char *p2;
1883b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1893b9f94e1Sbellard             if (!p1 || p2 > p1)
1903b9f94e1Sbellard                 p1 = p2;
1913b9f94e1Sbellard         }
1923b9f94e1Sbellard #endif
19383f64091Sbellard         if (p1)
19483f64091Sbellard             p1++;
19583f64091Sbellard         else
19683f64091Sbellard             p1 = base_path;
19783f64091Sbellard         if (p1 > p)
19883f64091Sbellard             p = p1;
19983f64091Sbellard         len = p - base_path;
20083f64091Sbellard         if (len > dest_size - 1)
20183f64091Sbellard             len = dest_size - 1;
20283f64091Sbellard         memcpy(dest, base_path, len);
20383f64091Sbellard         dest[len] = '\0';
20483f64091Sbellard         pstrcat(dest, dest_size, filename);
20583f64091Sbellard     }
20683f64091Sbellard }
20783f64091Sbellard 
2080a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
2090a82855aSMax Reitz                                                   const char *backing,
2109f07429eSMax Reitz                                                   char *dest, size_t sz,
2119f07429eSMax Reitz                                                   Error **errp)
2120a82855aSMax Reitz {
2139f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2149f07429eSMax Reitz         path_is_absolute(backing))
2159f07429eSMax Reitz     {
2160a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2179f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2189f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2199f07429eSMax Reitz                    backed);
2200a82855aSMax Reitz     } else {
2210a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2220a82855aSMax Reitz     }
2230a82855aSMax Reitz }
2240a82855aSMax Reitz 
2259f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2269f07429eSMax Reitz                                     Error **errp)
227dc5a1371SPaolo Bonzini {
2289f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2299f07429eSMax Reitz 
2309f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2319f07429eSMax Reitz                                                  dest, sz, errp);
232dc5a1371SPaolo Bonzini }
233dc5a1371SPaolo Bonzini 
2340eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2350eb7217eSStefan Hajnoczi {
2360eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
237b2e12bc6SChristoph Hellwig 
2388a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
239ea2384d3Sbellard }
240b338082bSbellard 
2417f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
242fc01f7e7Sbellard {
2437f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
244e4e9986bSMarkus Armbruster 
245e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
246e4e9986bSMarkus Armbruster     return bs;
247e4e9986bSMarkus Armbruster }
248e4e9986bSMarkus Armbruster 
249e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
250e4e9986bSMarkus Armbruster {
251e4e9986bSMarkus Armbruster     BlockDriverState *bs;
252e4e9986bSMarkus Armbruster     int i;
253e4e9986bSMarkus Armbruster 
2545839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
255e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
256fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
257fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
258fbe40ff7SFam Zheng     }
259d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
260d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
261cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
262cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2639fcb0251SFam Zheng     bs->refcnt = 1;
264dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
265d7d512f6SPaolo Bonzini 
266b338082bSbellard     return bs;
267b338082bSbellard }
268b338082bSbellard 
269d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
270d7d512f6SPaolo Bonzini {
271d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
272d7d512f6SPaolo Bonzini }
273d7d512f6SPaolo Bonzini 
274ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
275ea2384d3Sbellard {
276ea2384d3Sbellard     BlockDriver *drv1;
2778a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2788a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
279ea2384d3Sbellard             return drv1;
280ea2384d3Sbellard         }
2818a22f02aSStefan Hajnoczi     }
282ea2384d3Sbellard     return NULL;
283ea2384d3Sbellard }
284ea2384d3Sbellard 
285b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
286eb852011SMarkus Armbruster {
287b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
288b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
289b64ec4e4SFam Zheng     };
290b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
291b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
292eb852011SMarkus Armbruster     };
293eb852011SMarkus Armbruster     const char **p;
294eb852011SMarkus Armbruster 
295b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
296eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
297b64ec4e4SFam Zheng     }
298eb852011SMarkus Armbruster 
299b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
300eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
301eb852011SMarkus Armbruster             return 1;
302eb852011SMarkus Armbruster         }
303eb852011SMarkus Armbruster     }
304b64ec4e4SFam Zheng     if (read_only) {
305b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
306b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
307b64ec4e4SFam Zheng                 return 1;
308b64ec4e4SFam Zheng             }
309b64ec4e4SFam Zheng         }
310b64ec4e4SFam Zheng     }
311eb852011SMarkus Armbruster     return 0;
312eb852011SMarkus Armbruster }
313eb852011SMarkus Armbruster 
3145b7e1542SZhi Yong Wu typedef struct CreateCo {
3155b7e1542SZhi Yong Wu     BlockDriver *drv;
3165b7e1542SZhi Yong Wu     char *filename;
31783d0521aSChunyan Liu     QemuOpts *opts;
3185b7e1542SZhi Yong Wu     int ret;
319cc84d90fSMax Reitz     Error *err;
3205b7e1542SZhi Yong Wu } CreateCo;
3215b7e1542SZhi Yong Wu 
3225b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3235b7e1542SZhi Yong Wu {
324cc84d90fSMax Reitz     Error *local_err = NULL;
325cc84d90fSMax Reitz     int ret;
326cc84d90fSMax Reitz 
3275b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3285b7e1542SZhi Yong Wu     assert(cco->drv);
3295b7e1542SZhi Yong Wu 
330c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
33184d18f06SMarkus Armbruster     if (local_err) {
332cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
333cc84d90fSMax Reitz     }
334cc84d90fSMax Reitz     cco->ret = ret;
3355b7e1542SZhi Yong Wu }
3365b7e1542SZhi Yong Wu 
3370e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
33883d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
339ea2384d3Sbellard {
3405b7e1542SZhi Yong Wu     int ret;
3410e7e1989SKevin Wolf 
3425b7e1542SZhi Yong Wu     Coroutine *co;
3435b7e1542SZhi Yong Wu     CreateCo cco = {
3445b7e1542SZhi Yong Wu         .drv = drv,
3455b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
34683d0521aSChunyan Liu         .opts = opts,
3475b7e1542SZhi Yong Wu         .ret = NOT_DONE,
348cc84d90fSMax Reitz         .err = NULL,
3495b7e1542SZhi Yong Wu     };
3505b7e1542SZhi Yong Wu 
351c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
352cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35380168bffSLuiz Capitulino         ret = -ENOTSUP;
35480168bffSLuiz Capitulino         goto out;
3555b7e1542SZhi Yong Wu     }
3565b7e1542SZhi Yong Wu 
3575b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3585b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3595b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3605b7e1542SZhi Yong Wu     } else {
3615b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3625b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3635b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
364b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3655b7e1542SZhi Yong Wu         }
3665b7e1542SZhi Yong Wu     }
3675b7e1542SZhi Yong Wu 
3685b7e1542SZhi Yong Wu     ret = cco.ret;
369cc84d90fSMax Reitz     if (ret < 0) {
37084d18f06SMarkus Armbruster         if (cco.err) {
371cc84d90fSMax Reitz             error_propagate(errp, cco.err);
372cc84d90fSMax Reitz         } else {
373cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
374cc84d90fSMax Reitz         }
375cc84d90fSMax Reitz     }
3765b7e1542SZhi Yong Wu 
37780168bffSLuiz Capitulino out:
37880168bffSLuiz Capitulino     g_free(cco.filename);
3795b7e1542SZhi Yong Wu     return ret;
380ea2384d3Sbellard }
381ea2384d3Sbellard 
382c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38384a12e66SChristoph Hellwig {
38484a12e66SChristoph Hellwig     BlockDriver *drv;
385cc84d90fSMax Reitz     Error *local_err = NULL;
386cc84d90fSMax Reitz     int ret;
38784a12e66SChristoph Hellwig 
388b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
38984a12e66SChristoph Hellwig     if (drv == NULL) {
39016905d71SStefan Hajnoczi         return -ENOENT;
39184a12e66SChristoph Hellwig     }
39284a12e66SChristoph Hellwig 
393c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
39484d18f06SMarkus Armbruster     if (local_err) {
395cc84d90fSMax Reitz         error_propagate(errp, local_err);
396cc84d90fSMax Reitz     }
397cc84d90fSMax Reitz     return ret;
39884a12e66SChristoph Hellwig }
39984a12e66SChristoph Hellwig 
400892b7de8SEkaterina Tumanova /**
401892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
402892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
403892b7de8SEkaterina Tumanova  * On failure return -errno.
404892b7de8SEkaterina Tumanova  * @bs must not be empty.
405892b7de8SEkaterina Tumanova  */
406892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
407892b7de8SEkaterina Tumanova {
408892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
409892b7de8SEkaterina Tumanova 
410892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
411892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
412892b7de8SEkaterina Tumanova     }
413892b7de8SEkaterina Tumanova 
414892b7de8SEkaterina Tumanova     return -ENOTSUP;
415892b7de8SEkaterina Tumanova }
416892b7de8SEkaterina Tumanova 
417892b7de8SEkaterina Tumanova /**
418892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
419892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
420892b7de8SEkaterina Tumanova  * On failure return -errno.
421892b7de8SEkaterina Tumanova  * @bs must not be empty.
422892b7de8SEkaterina Tumanova  */
423892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
424892b7de8SEkaterina Tumanova {
425892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
426892b7de8SEkaterina Tumanova 
427892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
428892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
429892b7de8SEkaterina Tumanova     }
430892b7de8SEkaterina Tumanova 
431892b7de8SEkaterina Tumanova     return -ENOTSUP;
432892b7de8SEkaterina Tumanova }
433892b7de8SEkaterina Tumanova 
434eba25057SJim Meyering /*
435eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
436eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
437eba25057SJim Meyering  */
438eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
439eba25057SJim Meyering {
440d5249393Sbellard #ifdef _WIN32
4413b9f94e1Sbellard     char temp_dir[MAX_PATH];
442eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
443eba25057SJim Meyering        have length MAX_PATH or greater.  */
444eba25057SJim Meyering     assert(size >= MAX_PATH);
445eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
446eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
447eba25057SJim Meyering             ? 0 : -GetLastError());
448d5249393Sbellard #else
449ea2384d3Sbellard     int fd;
4507ccfb2ebSblueswir1     const char *tmpdir;
4510badc1eeSaurel32     tmpdir = getenv("TMPDIR");
45269bef793SAmit Shah     if (!tmpdir) {
45369bef793SAmit Shah         tmpdir = "/var/tmp";
45469bef793SAmit Shah     }
455eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
456eba25057SJim Meyering         return -EOVERFLOW;
457ea2384d3Sbellard     }
458eba25057SJim Meyering     fd = mkstemp(filename);
459fe235a06SDunrong Huang     if (fd < 0) {
460fe235a06SDunrong Huang         return -errno;
461fe235a06SDunrong Huang     }
462fe235a06SDunrong Huang     if (close(fd) != 0) {
463fe235a06SDunrong Huang         unlink(filename);
464eba25057SJim Meyering         return -errno;
465eba25057SJim Meyering     }
466eba25057SJim Meyering     return 0;
467d5249393Sbellard #endif
468eba25057SJim Meyering }
469ea2384d3Sbellard 
470f3a5d3f8SChristoph Hellwig /*
471f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
472f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
473f3a5d3f8SChristoph Hellwig  */
474f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
475f3a5d3f8SChristoph Hellwig {
476508c7cb3SChristoph Hellwig     int score_max = 0, score;
477508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
478f3a5d3f8SChristoph Hellwig 
4798a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
480508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
481508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
482508c7cb3SChristoph Hellwig             if (score > score_max) {
483508c7cb3SChristoph Hellwig                 score_max = score;
484508c7cb3SChristoph Hellwig                 drv = d;
485f3a5d3f8SChristoph Hellwig             }
486508c7cb3SChristoph Hellwig         }
487f3a5d3f8SChristoph Hellwig     }
488f3a5d3f8SChristoph Hellwig 
489508c7cb3SChristoph Hellwig     return drv;
490f3a5d3f8SChristoph Hellwig }
491f3a5d3f8SChristoph Hellwig 
49298289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
493b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
494b65a5e12SMax Reitz                                 Error **errp)
49584a12e66SChristoph Hellwig {
49684a12e66SChristoph Hellwig     BlockDriver *drv1;
49784a12e66SChristoph Hellwig     char protocol[128];
49884a12e66SChristoph Hellwig     int len;
49984a12e66SChristoph Hellwig     const char *p;
50084a12e66SChristoph Hellwig 
50166f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
50266f82ceeSKevin Wolf 
50339508e7aSChristoph Hellwig     /*
50439508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
50539508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
50639508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
50739508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
50839508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
50939508e7aSChristoph Hellwig      */
51084a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
51139508e7aSChristoph Hellwig     if (drv1) {
51284a12e66SChristoph Hellwig         return drv1;
51384a12e66SChristoph Hellwig     }
51439508e7aSChristoph Hellwig 
51598289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
516ef810437SMax Reitz         return &bdrv_file;
51739508e7aSChristoph Hellwig     }
51898289620SKevin Wolf 
5199e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5209e0b22f4SStefan Hajnoczi     assert(p != NULL);
52184a12e66SChristoph Hellwig     len = p - filename;
52284a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
52384a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
52484a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
52584a12e66SChristoph Hellwig     protocol[len] = '\0';
52684a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
52784a12e66SChristoph Hellwig         if (drv1->protocol_name &&
52884a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
52984a12e66SChristoph Hellwig             return drv1;
53084a12e66SChristoph Hellwig         }
53184a12e66SChristoph Hellwig     }
532b65a5e12SMax Reitz 
533b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
53484a12e66SChristoph Hellwig     return NULL;
53584a12e66SChristoph Hellwig }
53684a12e66SChristoph Hellwig 
537c6684249SMarkus Armbruster /*
538c6684249SMarkus Armbruster  * Guess image format by probing its contents.
539c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
540c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
541c6684249SMarkus Armbruster  *
542c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5437cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5447cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
545c6684249SMarkus Armbruster  * @filename    is its filename.
546c6684249SMarkus Armbruster  *
547c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
548c6684249SMarkus Armbruster  * probing score.
549c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
550c6684249SMarkus Armbruster  */
55138f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
552c6684249SMarkus Armbruster                             const char *filename)
553c6684249SMarkus Armbruster {
554c6684249SMarkus Armbruster     int score_max = 0, score;
555c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
556c6684249SMarkus Armbruster 
557c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
558c6684249SMarkus Armbruster         if (d->bdrv_probe) {
559c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
560c6684249SMarkus Armbruster             if (score > score_max) {
561c6684249SMarkus Armbruster                 score_max = score;
562c6684249SMarkus Armbruster                 drv = d;
563c6684249SMarkus Armbruster             }
564c6684249SMarkus Armbruster         }
565c6684249SMarkus Armbruster     }
566c6684249SMarkus Armbruster 
567c6684249SMarkus Armbruster     return drv;
568c6684249SMarkus Armbruster }
569c6684249SMarkus Armbruster 
570f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
57134b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
572ea2384d3Sbellard {
573c6684249SMarkus Armbruster     BlockDriver *drv;
5747cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
575f500a6d3SKevin Wolf     int ret = 0;
576f8ea0b00SNicholas Bellinger 
57708a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
578b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
579ef810437SMax Reitz         *pdrv = &bdrv_raw;
580c98ac35dSStefan Weil         return ret;
5811a396859SNicholas A. Bellinger     }
582f8ea0b00SNicholas Bellinger 
58383f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
584ea2384d3Sbellard     if (ret < 0) {
58534b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
58634b5d2c6SMax Reitz                          "format");
587c98ac35dSStefan Weil         *pdrv = NULL;
588c98ac35dSStefan Weil         return ret;
589ea2384d3Sbellard     }
590ea2384d3Sbellard 
591c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
592c98ac35dSStefan Weil     if (!drv) {
59334b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
59434b5d2c6SMax Reitz                    "driver found");
595c98ac35dSStefan Weil         ret = -ENOENT;
596c98ac35dSStefan Weil     }
597c98ac35dSStefan Weil     *pdrv = drv;
598c98ac35dSStefan Weil     return ret;
599ea2384d3Sbellard }
600ea2384d3Sbellard 
60151762288SStefan Hajnoczi /**
60251762288SStefan Hajnoczi  * Set the current 'total_sectors' value
60365a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
60451762288SStefan Hajnoczi  */
60551762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
60651762288SStefan Hajnoczi {
60751762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
60851762288SStefan Hajnoczi 
609396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
610b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
611396759adSNicholas Bellinger         return 0;
612396759adSNicholas Bellinger 
61351762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
61451762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
61551762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
61651762288SStefan Hajnoczi         if (length < 0) {
61751762288SStefan Hajnoczi             return length;
61851762288SStefan Hajnoczi         }
6197e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
62051762288SStefan Hajnoczi     }
62151762288SStefan Hajnoczi 
62251762288SStefan Hajnoczi     bs->total_sectors = hint;
62351762288SStefan Hajnoczi     return 0;
62451762288SStefan Hajnoczi }
62551762288SStefan Hajnoczi 
626c3993cdcSStefan Hajnoczi /**
627cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
628cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
629cddff5baSKevin Wolf  */
630cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
631cddff5baSKevin Wolf                               QDict *old_options)
632cddff5baSKevin Wolf {
633cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
634cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
635cddff5baSKevin Wolf     } else {
636cddff5baSKevin Wolf         qdict_join(options, old_options, false);
637cddff5baSKevin Wolf     }
638cddff5baSKevin Wolf }
639cddff5baSKevin Wolf 
640cddff5baSKevin Wolf /**
6419e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6429e8f1835SPaolo Bonzini  *
6439e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6449e8f1835SPaolo Bonzini  */
6459e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6469e8f1835SPaolo Bonzini {
6479e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6489e8f1835SPaolo Bonzini 
6499e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6509e8f1835SPaolo Bonzini         /* do nothing */
6519e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6529e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6539e8f1835SPaolo Bonzini     } else {
6549e8f1835SPaolo Bonzini         return -1;
6559e8f1835SPaolo Bonzini     }
6569e8f1835SPaolo Bonzini 
6579e8f1835SPaolo Bonzini     return 0;
6589e8f1835SPaolo Bonzini }
6599e8f1835SPaolo Bonzini 
6609e8f1835SPaolo Bonzini /**
661c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
662c3993cdcSStefan Hajnoczi  *
663c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
664c3993cdcSStefan Hajnoczi  */
665c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
666c3993cdcSStefan Hajnoczi {
667c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
668c3993cdcSStefan Hajnoczi 
669c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
670c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
67192196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
67292196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
673c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
674c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
675c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
676c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
677c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
678c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
679c3993cdcSStefan Hajnoczi         /* this is the default */
680c3993cdcSStefan Hajnoczi     } else {
681c3993cdcSStefan Hajnoczi         return -1;
682c3993cdcSStefan Hajnoczi     }
683c3993cdcSStefan Hajnoczi 
684c3993cdcSStefan Hajnoczi     return 0;
685c3993cdcSStefan Hajnoczi }
686c3993cdcSStefan Hajnoczi 
6870b50cc88SKevin Wolf /*
688b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
689b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
690b1e6fc08SKevin Wolf  * like a backing file)
691b1e6fc08SKevin Wolf  */
692b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
693b1e6fc08SKevin Wolf {
694b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
695b1e6fc08SKevin Wolf }
696b1e6fc08SKevin Wolf 
697b1e6fc08SKevin Wolf /*
698f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if a protocol driver is expected,
699f3930ed0SKevin Wolf  * based on the given flags for the parent BDS
7000b50cc88SKevin Wolf  */
7010b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
7020b50cc88SKevin Wolf {
7030b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7040b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7050b50cc88SKevin Wolf 
7060b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
7070b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
7080b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
7090b50cc88SKevin Wolf 
7100b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
7115669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
7120b50cc88SKevin Wolf 
7130b50cc88SKevin Wolf     return flags;
7140b50cc88SKevin Wolf }
7150b50cc88SKevin Wolf 
716f3930ed0SKevin Wolf const BdrvChildRole child_file = {
717f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_flags,
718f3930ed0SKevin Wolf };
719f3930ed0SKevin Wolf 
720f3930ed0SKevin Wolf /*
721f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if the use of formats (and not
722f3930ed0SKevin Wolf  * only protocols) is permitted for it, based on the given flags for the parent
723f3930ed0SKevin Wolf  * BDS
724f3930ed0SKevin Wolf  */
725f3930ed0SKevin Wolf static int bdrv_inherited_fmt_flags(int parent_flags)
726f3930ed0SKevin Wolf {
727f3930ed0SKevin Wolf     int flags = child_file.inherit_flags(parent_flags);
728f3930ed0SKevin Wolf     return flags & ~BDRV_O_PROTOCOL;
729f3930ed0SKevin Wolf }
730f3930ed0SKevin Wolf 
731f3930ed0SKevin Wolf const BdrvChildRole child_format = {
732f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_fmt_flags,
733f3930ed0SKevin Wolf };
734f3930ed0SKevin Wolf 
735317fc44eSKevin Wolf /*
736760e0063SKevin Wolf  * Returns the flags that bs->backing should get, based on the given flags
737317fc44eSKevin Wolf  * for the parent BDS
738317fc44eSKevin Wolf  */
739317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
740317fc44eSKevin Wolf {
741317fc44eSKevin Wolf     /* backing files always opened read-only */
742317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
743317fc44eSKevin Wolf 
744317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7458bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
746317fc44eSKevin Wolf 
747317fc44eSKevin Wolf     return flags;
748317fc44eSKevin Wolf }
749317fc44eSKevin Wolf 
750f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
751f3930ed0SKevin Wolf     .inherit_flags = bdrv_backing_flags,
752f3930ed0SKevin Wolf };
753f3930ed0SKevin Wolf 
7547b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7557b272452SKevin Wolf {
7567b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7577b272452SKevin Wolf 
7587b272452SKevin Wolf     /*
7597b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7607b272452SKevin Wolf      * image.
7617b272452SKevin Wolf      */
76220cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7637b272452SKevin Wolf 
7647b272452SKevin Wolf     /*
7657b272452SKevin Wolf      * Snapshots should be writable.
7667b272452SKevin Wolf      */
7678bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7687b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7697b272452SKevin Wolf     }
7707b272452SKevin Wolf 
7717b272452SKevin Wolf     return open_flags;
7727b272452SKevin Wolf }
7737b272452SKevin Wolf 
774636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
7756913c0c2SBenoît Canet                                   const char *node_name,
7766913c0c2SBenoît Canet                                   Error **errp)
7776913c0c2SBenoît Canet {
77815489c76SJeff Cody     char *gen_node_name = NULL;
7796913c0c2SBenoît Canet 
78015489c76SJeff Cody     if (!node_name) {
78115489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
78215489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
78315489c76SJeff Cody         /*
78415489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
78515489c76SJeff Cody          * generated (generated names use characters not available to the user)
78615489c76SJeff Cody          */
7879aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
788636ea370SKevin Wolf         return;
7896913c0c2SBenoît Canet     }
7906913c0c2SBenoît Canet 
7910c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
7927f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
7930c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
7940c5e94eeSBenoît Canet                    node_name);
79515489c76SJeff Cody         goto out;
7960c5e94eeSBenoît Canet     }
7970c5e94eeSBenoît Canet 
7986913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
7996913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8006913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
80115489c76SJeff Cody         goto out;
8026913c0c2SBenoît Canet     }
8036913c0c2SBenoît Canet 
8046913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8056913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8066913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
80715489c76SJeff Cody out:
80815489c76SJeff Cody     g_free(gen_node_name);
8096913c0c2SBenoît Canet }
8106913c0c2SBenoît Canet 
81118edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
81218edf289SKevin Wolf     .name = "bdrv_common",
81318edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
81418edf289SKevin Wolf     .desc = {
81518edf289SKevin Wolf         {
81618edf289SKevin Wolf             .name = "node-name",
81718edf289SKevin Wolf             .type = QEMU_OPT_STRING,
81818edf289SKevin Wolf             .help = "Node name of the block device node",
81918edf289SKevin Wolf         },
820*62392ebbSKevin Wolf         {
821*62392ebbSKevin Wolf             .name = "driver",
822*62392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
823*62392ebbSKevin Wolf             .help = "Block driver to use for the node",
824*62392ebbSKevin Wolf         },
82518edf289SKevin Wolf         { /* end of list */ }
82618edf289SKevin Wolf     },
82718edf289SKevin Wolf };
82818edf289SKevin Wolf 
829b6ce07aaSKevin Wolf /*
83057915332SKevin Wolf  * Common part for opening disk images and files
831b6ad491aSKevin Wolf  *
832b6ad491aSKevin Wolf  * Removes all processed options from *options.
83357915332SKevin Wolf  */
8349a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
835*62392ebbSKevin Wolf                             QDict *options, int flags, Error **errp)
83657915332SKevin Wolf {
83757915332SKevin Wolf     int ret, open_flags;
838035fccdfSKevin Wolf     const char *filename;
839*62392ebbSKevin Wolf     const char *driver_name = NULL;
8406913c0c2SBenoît Canet     const char *node_name = NULL;
84118edf289SKevin Wolf     QemuOpts *opts;
842*62392ebbSKevin Wolf     BlockDriver *drv;
84334b5d2c6SMax Reitz     Error *local_err = NULL;
84457915332SKevin Wolf 
8456405875cSPaolo Bonzini     assert(bs->file == NULL);
846707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
84757915332SKevin Wolf 
848*62392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
849*62392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
850*62392ebbSKevin Wolf     if (local_err) {
851*62392ebbSKevin Wolf         error_propagate(errp, local_err);
852*62392ebbSKevin Wolf         ret = -EINVAL;
853*62392ebbSKevin Wolf         goto fail_opts;
854*62392ebbSKevin Wolf     }
855*62392ebbSKevin Wolf 
856*62392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
857*62392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
858*62392ebbSKevin Wolf     assert(drv != NULL);
859*62392ebbSKevin Wolf 
86045673671SKevin Wolf     if (file != NULL) {
8619a4f4c31SKevin Wolf         filename = file->bs->filename;
86245673671SKevin Wolf     } else {
86345673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
86445673671SKevin Wolf     }
86545673671SKevin Wolf 
866765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
867765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
868765003dbSKevin Wolf                    drv->format_name);
86918edf289SKevin Wolf         ret = -EINVAL;
87018edf289SKevin Wolf         goto fail_opts;
87118edf289SKevin Wolf     }
87218edf289SKevin Wolf 
873*62392ebbSKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
874*62392ebbSKevin Wolf 
87518edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
876636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8770fb6395cSMarkus Armbruster     if (local_err) {
878636ea370SKevin Wolf         error_propagate(errp, local_err);
87918edf289SKevin Wolf         ret = -EINVAL;
88018edf289SKevin Wolf         goto fail_opts;
8815d186eb0SKevin Wolf     }
8825d186eb0SKevin Wolf 
883c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8840d51b4deSAsias He     bs->zero_beyond_eof = true;
885b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
886b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
887b64ec4e4SFam Zheng 
888b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8898f94a6e4SKevin Wolf         error_setg(errp,
8908f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8918f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8928f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8938f94a6e4SKevin Wolf                    drv->format_name);
89418edf289SKevin Wolf         ret = -ENOTSUP;
89518edf289SKevin Wolf         goto fail_opts;
896b64ec4e4SFam Zheng     }
89757915332SKevin Wolf 
89853fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8990ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
9000ebd24e0SKevin Wolf         if (!bs->read_only) {
90153fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9020ebd24e0SKevin Wolf         } else {
9030ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
90418edf289SKevin Wolf             ret = -EINVAL;
90518edf289SKevin Wolf             goto fail_opts;
9060ebd24e0SKevin Wolf         }
90753fec9d3SStefan Hajnoczi     }
90853fec9d3SStefan Hajnoczi 
909c2ad1b0cSKevin Wolf     if (filename != NULL) {
91057915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
911c2ad1b0cSKevin Wolf     } else {
912c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
913c2ad1b0cSKevin Wolf     }
91491af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
91557915332SKevin Wolf 
91657915332SKevin Wolf     bs->drv = drv;
9177267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
91857915332SKevin Wolf 
91903f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
920e7c63796SStefan Hajnoczi 
92166f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
92266f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9235d186eb0SKevin Wolf         assert(file == NULL);
924030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
92534b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
926f500a6d3SKevin Wolf     } else {
9272af5ef70SKevin Wolf         if (file == NULL) {
92834b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
92934b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9302af5ef70SKevin Wolf             ret = -EINVAL;
9312af5ef70SKevin Wolf             goto free_and_fail;
9322af5ef70SKevin Wolf         }
933f500a6d3SKevin Wolf         bs->file = file;
93434b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
93566f82ceeSKevin Wolf     }
93666f82ceeSKevin Wolf 
93757915332SKevin Wolf     if (ret < 0) {
93884d18f06SMarkus Armbruster         if (local_err) {
93934b5d2c6SMax Reitz             error_propagate(errp, local_err);
9402fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9412fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
94234b5d2c6SMax Reitz         } else {
94334b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
94434b5d2c6SMax Reitz         }
94557915332SKevin Wolf         goto free_and_fail;
94657915332SKevin Wolf     }
94757915332SKevin Wolf 
948a1f688f4SMarkus Armbruster     if (bs->encrypted) {
949a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
950a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
951a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
952a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
953a1f688f4SMarkus Armbruster     }
954a1f688f4SMarkus Armbruster 
95551762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
95651762288SStefan Hajnoczi     if (ret < 0) {
95734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
95851762288SStefan Hajnoczi         goto free_and_fail;
95957915332SKevin Wolf     }
96051762288SStefan Hajnoczi 
9613baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
9623baca891SKevin Wolf     if (local_err) {
9633baca891SKevin Wolf         error_propagate(errp, local_err);
9643baca891SKevin Wolf         ret = -EINVAL;
9653baca891SKevin Wolf         goto free_and_fail;
9663baca891SKevin Wolf     }
9673baca891SKevin Wolf 
968c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9694196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
970b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
97118edf289SKevin Wolf 
97218edf289SKevin Wolf     qemu_opts_del(opts);
97357915332SKevin Wolf     return 0;
97457915332SKevin Wolf 
97557915332SKevin Wolf free_and_fail:
97666f82ceeSKevin Wolf     bs->file = NULL;
9777267c094SAnthony Liguori     g_free(bs->opaque);
97857915332SKevin Wolf     bs->opaque = NULL;
97957915332SKevin Wolf     bs->drv = NULL;
98018edf289SKevin Wolf fail_opts:
98118edf289SKevin Wolf     qemu_opts_del(opts);
98257915332SKevin Wolf     return ret;
98357915332SKevin Wolf }
98457915332SKevin Wolf 
9855e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9865e5c4f63SKevin Wolf {
9875e5c4f63SKevin Wolf     QObject *options_obj;
9885e5c4f63SKevin Wolf     QDict *options;
9895e5c4f63SKevin Wolf     int ret;
9905e5c4f63SKevin Wolf 
9915e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
9925e5c4f63SKevin Wolf     assert(ret);
9935e5c4f63SKevin Wolf 
9945e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
9955e5c4f63SKevin Wolf     if (!options_obj) {
9965e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
9975e5c4f63SKevin Wolf         return NULL;
9985e5c4f63SKevin Wolf     }
9995e5c4f63SKevin Wolf 
10005e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10015e5c4f63SKevin Wolf         qobject_decref(options_obj);
10025e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10035e5c4f63SKevin Wolf         return NULL;
10045e5c4f63SKevin Wolf     }
10055e5c4f63SKevin Wolf 
10065e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10075e5c4f63SKevin Wolf     qdict_flatten(options);
10085e5c4f63SKevin Wolf 
10095e5c4f63SKevin Wolf     return options;
10105e5c4f63SKevin Wolf }
10115e5c4f63SKevin Wolf 
101257915332SKevin Wolf /*
1013f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1014f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
101553a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
101653a29513SMax Reitz  * block driver has been specified explicitly.
1017f54120ffSKevin Wolf  */
101853a29513SMax Reitz static int bdrv_fill_options(QDict **options, const char **pfilename,
1019053e1578SMax Reitz                              int *flags, Error **errp)
1020f54120ffSKevin Wolf {
10215e5c4f63SKevin Wolf     const char *filename = *pfilename;
1022f54120ffSKevin Wolf     const char *drvname;
102353a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1024f54120ffSKevin Wolf     bool parse_filename = false;
1025053e1578SMax Reitz     BlockDriver *drv = NULL;
1026f54120ffSKevin Wolf     Error *local_err = NULL;
1027f54120ffSKevin Wolf 
10285e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10295e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10305e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10315e5c4f63SKevin Wolf         if (local_err) {
10325e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10335e5c4f63SKevin Wolf             return -EINVAL;
10345e5c4f63SKevin Wolf         }
10355e5c4f63SKevin Wolf 
10365e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10375e5c4f63SKevin Wolf          * specified directly */
10385e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10395e5c4f63SKevin Wolf         QDECREF(json_options);
10405e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10415e5c4f63SKevin Wolf     }
10425e5c4f63SKevin Wolf 
104353a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1044053e1578SMax Reitz     if (drvname) {
1045053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1046053e1578SMax Reitz         if (!drv) {
1047053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1048053e1578SMax Reitz             return -ENOENT;
1049053e1578SMax Reitz         }
105053a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
105153a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1052053e1578SMax Reitz         protocol = drv->bdrv_file_open;
105353a29513SMax Reitz     }
105453a29513SMax Reitz 
105553a29513SMax Reitz     if (protocol) {
105653a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
105753a29513SMax Reitz     } else {
105853a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
105953a29513SMax Reitz     }
106053a29513SMax Reitz 
1061f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
106217b005f1SKevin Wolf     if (protocol && filename) {
1063f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1064f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1065f54120ffSKevin Wolf             parse_filename = true;
1066f54120ffSKevin Wolf         } else {
1067f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1068f54120ffSKevin Wolf                              "the same time");
1069f54120ffSKevin Wolf             return -EINVAL;
1070f54120ffSKevin Wolf         }
1071f54120ffSKevin Wolf     }
1072f54120ffSKevin Wolf 
1073f54120ffSKevin Wolf     /* Find the right block driver */
1074f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1075f54120ffSKevin Wolf 
107617b005f1SKevin Wolf     if (!drvname && protocol) {
1077f54120ffSKevin Wolf         if (filename) {
1078b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1079f54120ffSKevin Wolf             if (!drv) {
1080f54120ffSKevin Wolf                 return -EINVAL;
1081f54120ffSKevin Wolf             }
1082f54120ffSKevin Wolf 
1083f54120ffSKevin Wolf             drvname = drv->format_name;
1084f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1085f54120ffSKevin Wolf         } else {
1086f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1087f54120ffSKevin Wolf             return -EINVAL;
1088f54120ffSKevin Wolf         }
108917b005f1SKevin Wolf     }
109017b005f1SKevin Wolf 
109117b005f1SKevin Wolf     assert(drv || !protocol);
1092f54120ffSKevin Wolf 
1093f54120ffSKevin Wolf     /* Driver-specific filename parsing */
109417b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1095f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1096f54120ffSKevin Wolf         if (local_err) {
1097f54120ffSKevin Wolf             error_propagate(errp, local_err);
1098f54120ffSKevin Wolf             return -EINVAL;
1099f54120ffSKevin Wolf         }
1100f54120ffSKevin Wolf 
1101f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1102f54120ffSKevin Wolf             qdict_del(*options, "filename");
1103f54120ffSKevin Wolf         }
1104f54120ffSKevin Wolf     }
1105f54120ffSKevin Wolf 
1106d44f928aSMax Reitz     if (runstate_check(RUN_STATE_INMIGRATE)) {
1107d44f928aSMax Reitz         *flags |= BDRV_O_INCOMING;
1108d44f928aSMax Reitz     }
1109d44f928aSMax Reitz 
1110f54120ffSKevin Wolf     return 0;
1111f54120ffSKevin Wolf }
1112f54120ffSKevin Wolf 
1113b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1114df581792SKevin Wolf                                     BlockDriverState *child_bs,
1115260fecf1SKevin Wolf                                     const char *child_name,
1116df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1117df581792SKevin Wolf {
1118df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1119df581792SKevin Wolf     *child = (BdrvChild) {
1120df581792SKevin Wolf         .bs     = child_bs,
1121260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1122df581792SKevin Wolf         .role   = child_role,
1123df581792SKevin Wolf     };
1124df581792SKevin Wolf 
1125df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1126d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1127b4b059f6SKevin Wolf 
1128b4b059f6SKevin Wolf     return child;
1129df581792SKevin Wolf }
1130df581792SKevin Wolf 
11313f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
113233a60407SKevin Wolf {
113333a60407SKevin Wolf     QLIST_REMOVE(child, next);
1134d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1135260fecf1SKevin Wolf     g_free(child->name);
113633a60407SKevin Wolf     g_free(child);
113733a60407SKevin Wolf }
113833a60407SKevin Wolf 
113933a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
114033a60407SKevin Wolf {
1141779020cbSKevin Wolf     BlockDriverState *child_bs;
1142779020cbSKevin Wolf 
1143779020cbSKevin Wolf     if (child == NULL) {
1144779020cbSKevin Wolf         return;
1145779020cbSKevin Wolf     }
114633a60407SKevin Wolf 
114733a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
114833a60407SKevin Wolf         child->bs->inherits_from = NULL;
114933a60407SKevin Wolf     }
115033a60407SKevin Wolf 
1151779020cbSKevin Wolf     child_bs = child->bs;
115233a60407SKevin Wolf     bdrv_detach_child(child);
115333a60407SKevin Wolf     bdrv_unref(child_bs);
115433a60407SKevin Wolf }
115533a60407SKevin Wolf 
11565db15a57SKevin Wolf /*
11575db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
11585db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
11595db15a57SKevin Wolf  */
11608d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11618d24cce1SFam Zheng {
11625db15a57SKevin Wolf     if (backing_hd) {
11635db15a57SKevin Wolf         bdrv_ref(backing_hd);
11645db15a57SKevin Wolf     }
11658d24cce1SFam Zheng 
1166760e0063SKevin Wolf     if (bs->backing) {
1167826b6ca0SFam Zheng         assert(bs->backing_blocker);
1168760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
11695db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1170826b6ca0SFam Zheng     } else if (backing_hd) {
1171826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
117281e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
117381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1174826b6ca0SFam Zheng     }
1175826b6ca0SFam Zheng 
11768d24cce1SFam Zheng     if (!backing_hd) {
1177826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1178826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1179760e0063SKevin Wolf         bs->backing = NULL;
11808d24cce1SFam Zheng         goto out;
11818d24cce1SFam Zheng     }
1182260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
11838d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11848d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11858d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11868d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1187826b6ca0SFam Zheng 
1188760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1189826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1190760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1191826b6ca0SFam Zheng                     bs->backing_blocker);
11928d24cce1SFam Zheng out:
11933baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11948d24cce1SFam Zheng }
11958d24cce1SFam Zheng 
119631ca6d07SKevin Wolf /*
119731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
119831ca6d07SKevin Wolf  *
1199d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1200d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1201d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1202d9b7b057SKevin Wolf  * BlockdevRef.
1203d9b7b057SKevin Wolf  *
1204d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
120531ca6d07SKevin Wolf  */
1206d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1207d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12089156df12SPaolo Bonzini {
12091ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1210d9b7b057SKevin Wolf     char *bdref_key_dot;
1211d9b7b057SKevin Wolf     const char *reference = NULL;
1212317fc44eSKevin Wolf     int ret = 0;
12138d24cce1SFam Zheng     BlockDriverState *backing_hd;
1214d9b7b057SKevin Wolf     QDict *options;
1215d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
121634b5d2c6SMax Reitz     Error *local_err = NULL;
12179156df12SPaolo Bonzini 
1218760e0063SKevin Wolf     if (bs->backing != NULL) {
12191ba4b6a5SBenoît Canet         goto free_exit;
12209156df12SPaolo Bonzini     }
12219156df12SPaolo Bonzini 
122231ca6d07SKevin Wolf     /* NULL means an empty set of options */
1223d9b7b057SKevin Wolf     if (parent_options == NULL) {
1224d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1225d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
122631ca6d07SKevin Wolf     }
122731ca6d07SKevin Wolf 
12289156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1229d9b7b057SKevin Wolf 
1230d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1231d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1232d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1233d9b7b057SKevin Wolf 
1234d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1235d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
12361cb6f506SKevin Wolf         backing_filename[0] = '\0';
12371cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
123831ca6d07SKevin Wolf         QDECREF(options);
12391ba4b6a5SBenoît Canet         goto free_exit;
1240dbecebddSFam Zheng     } else {
12419f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
12429f07429eSMax Reitz                                        &local_err);
12439f07429eSMax Reitz         if (local_err) {
12449f07429eSMax Reitz             ret = -EINVAL;
12459f07429eSMax Reitz             error_propagate(errp, local_err);
12469f07429eSMax Reitz             QDECREF(options);
12479f07429eSMax Reitz             goto free_exit;
12489f07429eSMax Reitz         }
12499156df12SPaolo Bonzini     }
12509156df12SPaolo Bonzini 
12518ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12528ee79e70SKevin Wolf         ret = -EINVAL;
12538ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12548ee79e70SKevin Wolf         QDECREF(options);
12558ee79e70SKevin Wolf         goto free_exit;
12568ee79e70SKevin Wolf     }
12578ee79e70SKevin Wolf 
1258c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1259c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
12609156df12SPaolo Bonzini     }
12619156df12SPaolo Bonzini 
1262d9b7b057SKevin Wolf     backing_hd = NULL;
1263f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1264f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1265d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1266d9b7b057SKevin Wolf                             &local_err);
12679156df12SPaolo Bonzini     if (ret < 0) {
12689156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1269b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1270b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1271b04b6b6eSFam Zheng         error_free(local_err);
12721ba4b6a5SBenoît Canet         goto free_exit;
12739156df12SPaolo Bonzini     }
1274df581792SKevin Wolf 
12755db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
12765db15a57SKevin Wolf      * backing_hd reference now */
12778d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
12785db15a57SKevin Wolf     bdrv_unref(backing_hd);
1279d80ac658SPeter Feiner 
1280d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1281d9b7b057SKevin Wolf 
12821ba4b6a5SBenoît Canet free_exit:
12831ba4b6a5SBenoît Canet     g_free(backing_filename);
1284d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
12851ba4b6a5SBenoît Canet     return ret;
12869156df12SPaolo Bonzini }
12879156df12SPaolo Bonzini 
1288b6ce07aaSKevin Wolf /*
1289da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1290da557aacSMax Reitz  * device's options.
1291da557aacSMax Reitz  *
1292da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1293b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1294da557aacSMax Reitz  *
1295da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1296da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1297da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1298da557aacSMax Reitz  * BlockdevRef.
1299da557aacSMax Reitz  *
1300da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1301da557aacSMax Reitz  */
1302b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1303f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1304b4b059f6SKevin Wolf                            BlockDriverState* parent,
1305b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1306f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1307da557aacSMax Reitz {
1308b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1309b4b059f6SKevin Wolf     BlockDriverState *bs;
1310da557aacSMax Reitz     QDict *image_options;
1311da557aacSMax Reitz     int ret;
1312da557aacSMax Reitz     char *bdref_key_dot;
1313da557aacSMax Reitz     const char *reference;
1314da557aacSMax Reitz 
1315df581792SKevin Wolf     assert(child_role != NULL);
1316f67503e5SMax Reitz 
1317da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1318da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1319da557aacSMax Reitz     g_free(bdref_key_dot);
1320da557aacSMax Reitz 
1321da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1322da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1323b4b059f6SKevin Wolf         if (!allow_none) {
1324da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1325da557aacSMax Reitz                        bdref_key);
1326da557aacSMax Reitz         }
1327b20e61e0SMarkus Armbruster         QDECREF(image_options);
1328da557aacSMax Reitz         goto done;
1329da557aacSMax Reitz     }
1330da557aacSMax Reitz 
1331b4b059f6SKevin Wolf     bs = NULL;
1332b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1333ce343771SMax Reitz                             parent, child_role, errp);
1334df581792SKevin Wolf     if (ret < 0) {
1335df581792SKevin Wolf         goto done;
1336df581792SKevin Wolf     }
1337df581792SKevin Wolf 
1338260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1339da557aacSMax Reitz 
1340da557aacSMax Reitz done:
1341da557aacSMax Reitz     qdict_del(options, bdref_key);
1342b4b059f6SKevin Wolf     return c;
1343b4b059f6SKevin Wolf }
1344b4b059f6SKevin Wolf 
13456b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1346b998875dSKevin Wolf {
1347b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
13481ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1349b998875dSKevin Wolf     int64_t total_size;
135083d0521aSChunyan Liu     QemuOpts *opts = NULL;
1351b998875dSKevin Wolf     QDict *snapshot_options;
1352b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1353c2e0dbbfSFam Zheng     Error *local_err = NULL;
1354b998875dSKevin Wolf     int ret;
1355b998875dSKevin Wolf 
1356b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1357b998875dSKevin Wolf        instead of opening 'filename' directly */
1358b998875dSKevin Wolf 
1359b998875dSKevin Wolf     /* Get the required size from the image */
1360f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1361f187743aSKevin Wolf     if (total_size < 0) {
13626b8aeca5SChen Gang         ret = total_size;
1363f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13641ba4b6a5SBenoît Canet         goto out;
1365f187743aSKevin Wolf     }
1366b998875dSKevin Wolf 
1367b998875dSKevin Wolf     /* Create the temporary image */
13681ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1369b998875dSKevin Wolf     if (ret < 0) {
1370b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13711ba4b6a5SBenoît Canet         goto out;
1372b998875dSKevin Wolf     }
1373b998875dSKevin Wolf 
1374ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1375c282e1fdSChunyan Liu                             &error_abort);
137639101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1377ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
137883d0521aSChunyan Liu     qemu_opts_del(opts);
1379b998875dSKevin Wolf     if (ret < 0) {
1380b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1381b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1382b998875dSKevin Wolf                          error_get_pretty(local_err));
1383b998875dSKevin Wolf         error_free(local_err);
13841ba4b6a5SBenoît Canet         goto out;
1385b998875dSKevin Wolf     }
1386b998875dSKevin Wolf 
1387b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1388b998875dSKevin Wolf     snapshot_options = qdict_new();
1389b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1390b998875dSKevin Wolf               qstring_from_str("file"));
1391b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1392b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1393e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1394e6641719SMax Reitz               qstring_from_str("qcow2"));
1395b998875dSKevin Wolf 
1396e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1397b998875dSKevin Wolf 
1398b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
13996ebf9aa2SMax Reitz                     flags, &local_err);
1400b998875dSKevin Wolf     if (ret < 0) {
1401b998875dSKevin Wolf         error_propagate(errp, local_err);
14021ba4b6a5SBenoît Canet         goto out;
1403b998875dSKevin Wolf     }
1404b998875dSKevin Wolf 
1405b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14061ba4b6a5SBenoît Canet 
14071ba4b6a5SBenoît Canet out:
14081ba4b6a5SBenoît Canet     g_free(tmp_filename);
14096b8aeca5SChen Gang     return ret;
1410b998875dSKevin Wolf }
1411b998875dSKevin Wolf 
1412da557aacSMax Reitz /*
1413b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1414de9c0cecSKevin Wolf  *
1415de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1416de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1417de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1418de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1419f67503e5SMax Reitz  *
1420f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1421f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1422ddf5636dSMax Reitz  *
1423ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1424ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1425ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1426b6ce07aaSKevin Wolf  */
1427f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1428ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1429f3930ed0SKevin Wolf                              BlockDriverState *parent,
1430ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1431ea2384d3Sbellard {
1432b6ce07aaSKevin Wolf     int ret;
14339a4f4c31SKevin Wolf     BdrvChild *file = NULL;
14349a4f4c31SKevin Wolf     BlockDriverState *bs;
1435ce343771SMax Reitz     BlockDriver *drv = NULL;
143674fe54f2SKevin Wolf     const char *drvname;
14373e8c2e57SAlberto Garcia     const char *backing;
143834b5d2c6SMax Reitz     Error *local_err = NULL;
1439b1e6fc08SKevin Wolf     int snapshot_flags = 0;
144033e3963eSbellard 
1441f67503e5SMax Reitz     assert(pbs);
1442f3930ed0SKevin Wolf     assert(!child_role || !flags);
1443f3930ed0SKevin Wolf     assert(!child_role == !parent);
1444f67503e5SMax Reitz 
1445ddf5636dSMax Reitz     if (reference) {
1446ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1447ddf5636dSMax Reitz         QDECREF(options);
1448ddf5636dSMax Reitz 
1449ddf5636dSMax Reitz         if (*pbs) {
1450ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1451ddf5636dSMax Reitz                        "another block device");
1452ddf5636dSMax Reitz             return -EINVAL;
1453ddf5636dSMax Reitz         }
1454ddf5636dSMax Reitz 
1455ddf5636dSMax Reitz         if (filename || options_non_empty) {
1456ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1457ddf5636dSMax Reitz                        "additional options or a new filename");
1458ddf5636dSMax Reitz             return -EINVAL;
1459ddf5636dSMax Reitz         }
1460ddf5636dSMax Reitz 
1461ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1462ddf5636dSMax Reitz         if (!bs) {
1463ddf5636dSMax Reitz             return -ENODEV;
1464ddf5636dSMax Reitz         }
1465ddf5636dSMax Reitz         bdrv_ref(bs);
1466ddf5636dSMax Reitz         *pbs = bs;
1467ddf5636dSMax Reitz         return 0;
1468ddf5636dSMax Reitz     }
1469ddf5636dSMax Reitz 
1470f67503e5SMax Reitz     if (*pbs) {
1471f67503e5SMax Reitz         bs = *pbs;
1472f67503e5SMax Reitz     } else {
1473e4e9986bSMarkus Armbruster         bs = bdrv_new();
1474f67503e5SMax Reitz     }
1475f67503e5SMax Reitz 
1476de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1477de9c0cecSKevin Wolf     if (options == NULL) {
1478de9c0cecSKevin Wolf         options = qdict_new();
1479de9c0cecSKevin Wolf     }
1480de9c0cecSKevin Wolf 
1481f3930ed0SKevin Wolf     if (child_role) {
1482bddcec37SKevin Wolf         bs->inherits_from = parent;
1483f3930ed0SKevin Wolf         flags = child_role->inherit_flags(parent->open_flags);
1484f3930ed0SKevin Wolf     }
1485f3930ed0SKevin Wolf 
1486053e1578SMax Reitz     ret = bdrv_fill_options(&options, &filename, &flags, &local_err);
1487462f5bcfSKevin Wolf     if (local_err) {
1488462f5bcfSKevin Wolf         goto fail;
1489462f5bcfSKevin Wolf     }
1490462f5bcfSKevin Wolf 
1491*62392ebbSKevin Wolf     bs->open_flags = flags;
1492*62392ebbSKevin Wolf     bs->options = options;
1493*62392ebbSKevin Wolf     options = qdict_clone_shallow(options);
1494*62392ebbSKevin Wolf 
149576c591b0SKevin Wolf     /* Find the right image format driver */
149676c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
149776c591b0SKevin Wolf     if (drvname) {
149876c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
149976c591b0SKevin Wolf         if (!drv) {
150076c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
150176c591b0SKevin Wolf             ret = -EINVAL;
150276c591b0SKevin Wolf             goto fail;
150376c591b0SKevin Wolf         }
150476c591b0SKevin Wolf     }
150576c591b0SKevin Wolf 
150676c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
150776c591b0SKevin Wolf 
15083e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
15093e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
15103e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
15113e8c2e57SAlberto Garcia         qdict_del(options, "backing");
15123e8c2e57SAlberto Garcia     }
15133e8c2e57SAlberto Garcia 
1514f500a6d3SKevin Wolf     /* Open image file without format layer */
1515f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1516be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1517be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1518be028adcSJeff Cody         }
1519b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1520b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1521b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1522b1e6fc08SKevin Wolf         }
1523be028adcSJeff Cody 
1524f3930ed0SKevin Wolf         bs->open_flags = flags;
15251fdd6933SKevin Wolf 
15269a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
15271fdd6933SKevin Wolf                                &child_file, true, &local_err);
15281fdd6933SKevin Wolf         if (local_err) {
15291fdd6933SKevin Wolf             ret = -EINVAL;
15308bfea15dSKevin Wolf             goto fail;
1531f500a6d3SKevin Wolf         }
1532f4788adcSKevin Wolf     }
1533f500a6d3SKevin Wolf 
153476c591b0SKevin Wolf     /* Image format probing */
153538f3ef57SKevin Wolf     bs->probed = !drv;
153676c591b0SKevin Wolf     if (!drv && file) {
15379a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
153817b005f1SKevin Wolf         if (ret < 0) {
153917b005f1SKevin Wolf             goto fail;
154017b005f1SKevin Wolf         }
1541*62392ebbSKevin Wolf         /*
1542*62392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
1543*62392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
1544*62392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
1545*62392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
1546*62392ebbSKevin Wolf          *
1547*62392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
1548*62392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
1549*62392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
1550*62392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
1551*62392ebbSKevin Wolf          */
1552*62392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
1553*62392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
155476c591b0SKevin Wolf     } else if (!drv) {
15552a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
15562a05cbe4SMax Reitz         ret = -EINVAL;
15578bfea15dSKevin Wolf         goto fail;
15582a05cbe4SMax Reitz     }
1559f500a6d3SKevin Wolf 
156053a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
156153a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
156253a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
156353a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
156453a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
156553a29513SMax Reitz 
1566b6ce07aaSKevin Wolf     /* Open the image */
1567*62392ebbSKevin Wolf     ret = bdrv_open_common(bs, file, options, flags, &local_err);
1568b6ce07aaSKevin Wolf     if (ret < 0) {
15698bfea15dSKevin Wolf         goto fail;
15706987307cSChristoph Hellwig     }
15716987307cSChristoph Hellwig 
15722a05cbe4SMax Reitz     if (file && (bs->file != file)) {
15739a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1574f500a6d3SKevin Wolf         file = NULL;
1575f500a6d3SKevin Wolf     }
1576f500a6d3SKevin Wolf 
1577b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
15789156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1579d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1580b6ce07aaSKevin Wolf         if (ret < 0) {
1581b6ad491aSKevin Wolf             goto close_and_fail;
1582b6ce07aaSKevin Wolf         }
1583b6ce07aaSKevin Wolf     }
1584b6ce07aaSKevin Wolf 
158591af7014SMax Reitz     bdrv_refresh_filename(bs);
158691af7014SMax Reitz 
1587b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15885acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1589b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15905acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15915acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15925acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15935acd9d81SMax Reitz         } else {
159434b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15955acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1596bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
15975acd9d81SMax Reitz         }
1598b6ad491aSKevin Wolf 
1599b6ad491aSKevin Wolf         ret = -EINVAL;
1600b6ad491aSKevin Wolf         goto close_and_fail;
1601b6ad491aSKevin Wolf     }
1602b6ad491aSKevin Wolf 
1603b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1604a7f53e26SMarkus Armbruster         if (bs->blk) {
1605a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1606a7f53e26SMarkus Armbruster         }
1607c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1608c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1609c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1610c3adb58fSMarkus Armbruster         error_setg(errp,
1611c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1612c3adb58fSMarkus Armbruster         ret = -EBUSY;
1613c3adb58fSMarkus Armbruster         goto close_and_fail;
1614b6ce07aaSKevin Wolf     }
1615b6ce07aaSKevin Wolf 
1616c3adb58fSMarkus Armbruster     QDECREF(options);
1617f67503e5SMax Reitz     *pbs = bs;
1618dd62f1caSKevin Wolf 
1619dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1620dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1621dd62f1caSKevin Wolf     if (snapshot_flags) {
1622dd62f1caSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1623dd62f1caSKevin Wolf         if (local_err) {
1624dd62f1caSKevin Wolf             goto close_and_fail;
1625dd62f1caSKevin Wolf         }
1626dd62f1caSKevin Wolf     }
1627dd62f1caSKevin Wolf 
1628b6ce07aaSKevin Wolf     return 0;
1629b6ce07aaSKevin Wolf 
16308bfea15dSKevin Wolf fail:
1631f500a6d3SKevin Wolf     if (file != NULL) {
16329a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1633f500a6d3SKevin Wolf     }
1634de9c0cecSKevin Wolf     QDECREF(bs->options);
1635b6ad491aSKevin Wolf     QDECREF(options);
1636de9c0cecSKevin Wolf     bs->options = NULL;
1637f67503e5SMax Reitz     if (!*pbs) {
1638f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1639f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1640f67503e5SMax Reitz            since it has not really been opened yet. */
1641f67503e5SMax Reitz         bdrv_unref(bs);
1642f67503e5SMax Reitz     }
164384d18f06SMarkus Armbruster     if (local_err) {
164434b5d2c6SMax Reitz         error_propagate(errp, local_err);
164534b5d2c6SMax Reitz     }
1646b6ad491aSKevin Wolf     return ret;
1647de9c0cecSKevin Wolf 
1648b6ad491aSKevin Wolf close_and_fail:
1649f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1650f67503e5SMax Reitz     if (*pbs) {
1651b6ad491aSKevin Wolf         bdrv_close(bs);
1652f67503e5SMax Reitz     } else {
1653f67503e5SMax Reitz         bdrv_unref(bs);
1654f67503e5SMax Reitz     }
1655b6ad491aSKevin Wolf     QDECREF(options);
165684d18f06SMarkus Armbruster     if (local_err) {
165734b5d2c6SMax Reitz         error_propagate(errp, local_err);
165834b5d2c6SMax Reitz     }
1659b6ce07aaSKevin Wolf     return ret;
1660b6ce07aaSKevin Wolf }
1661b6ce07aaSKevin Wolf 
1662f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
16636ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1664f3930ed0SKevin Wolf {
1665f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1666ce343771SMax Reitz                              NULL, errp);
1667f3930ed0SKevin Wolf }
1668f3930ed0SKevin Wolf 
1669e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1670e971aa12SJeff Cody      bool prepared;
1671e971aa12SJeff Cody      BDRVReopenState state;
1672e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1673e971aa12SJeff Cody } BlockReopenQueueEntry;
1674e971aa12SJeff Cody 
1675e971aa12SJeff Cody /*
1676e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1677e971aa12SJeff Cody  * reopen of multiple devices.
1678e971aa12SJeff Cody  *
1679e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1680e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1681e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1682e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1683e971aa12SJeff Cody  * atomic 'set'.
1684e971aa12SJeff Cody  *
1685e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1686e971aa12SJeff Cody  *
16874d2cb092SKevin Wolf  * options contains the changed options for the associated bs
16884d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
16894d2cb092SKevin Wolf  *
1690e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1691e971aa12SJeff Cody  *
1692e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1693e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1694e971aa12SJeff Cody  *
1695e971aa12SJeff Cody  */
1696e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
16974d2cb092SKevin Wolf                                     BlockDriverState *bs,
16984d2cb092SKevin Wolf                                     QDict *options, int flags)
1699e971aa12SJeff Cody {
1700e971aa12SJeff Cody     assert(bs != NULL);
1701e971aa12SJeff Cody 
1702e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
170367251a31SKevin Wolf     BdrvChild *child;
17044d2cb092SKevin Wolf     QDict *old_options;
170567251a31SKevin Wolf 
1706e971aa12SJeff Cody     if (bs_queue == NULL) {
1707e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1708e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1709e971aa12SJeff Cody     }
1710e971aa12SJeff Cody 
17114d2cb092SKevin Wolf     if (!options) {
17124d2cb092SKevin Wolf         options = qdict_new();
17134d2cb092SKevin Wolf     }
17144d2cb092SKevin Wolf 
17154d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1716cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
17174d2cb092SKevin Wolf     QDECREF(old_options);
17184d2cb092SKevin Wolf 
1719f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1720f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1721f1f25a2eSKevin Wolf 
172267251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
172367251a31SKevin Wolf         int child_flags;
172467251a31SKevin Wolf 
172567251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
172667251a31SKevin Wolf             continue;
172767251a31SKevin Wolf         }
172867251a31SKevin Wolf 
172967251a31SKevin Wolf         child_flags = child->role->inherit_flags(flags);
17304d2cb092SKevin Wolf         /* TODO Pass down child flags (backing.*, extents.*, ...) */
17314d2cb092SKevin Wolf         bdrv_reopen_queue(bs_queue, child->bs, NULL, child_flags);
1732e971aa12SJeff Cody     }
1733e971aa12SJeff Cody 
1734e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1735e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1736e971aa12SJeff Cody 
1737e971aa12SJeff Cody     bs_entry->state.bs = bs;
17384d2cb092SKevin Wolf     bs_entry->state.options = options;
1739e971aa12SJeff Cody     bs_entry->state.flags = flags;
1740e971aa12SJeff Cody 
1741e971aa12SJeff Cody     return bs_queue;
1742e971aa12SJeff Cody }
1743e971aa12SJeff Cody 
1744e971aa12SJeff Cody /*
1745e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1746e971aa12SJeff Cody  *
1747e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1748e971aa12SJeff Cody  * via bdrv_reopen_queue().
1749e971aa12SJeff Cody  *
1750e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1751e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1752e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1753e971aa12SJeff Cody  * data cleaned up.
1754e971aa12SJeff Cody  *
1755e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1756e971aa12SJeff Cody  * to all devices.
1757e971aa12SJeff Cody  *
1758e971aa12SJeff Cody  */
1759e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1760e971aa12SJeff Cody {
1761e971aa12SJeff Cody     int ret = -1;
1762e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1763e971aa12SJeff Cody     Error *local_err = NULL;
1764e971aa12SJeff Cody 
1765e971aa12SJeff Cody     assert(bs_queue != NULL);
1766e971aa12SJeff Cody 
1767e971aa12SJeff Cody     bdrv_drain_all();
1768e971aa12SJeff Cody 
1769e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1770e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1771e971aa12SJeff Cody             error_propagate(errp, local_err);
1772e971aa12SJeff Cody             goto cleanup;
1773e971aa12SJeff Cody         }
1774e971aa12SJeff Cody         bs_entry->prepared = true;
1775e971aa12SJeff Cody     }
1776e971aa12SJeff Cody 
1777e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1778e971aa12SJeff Cody      * changes
1779e971aa12SJeff Cody      */
1780e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1781e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1782e971aa12SJeff Cody     }
1783e971aa12SJeff Cody 
1784e971aa12SJeff Cody     ret = 0;
1785e971aa12SJeff Cody 
1786e971aa12SJeff Cody cleanup:
1787e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1788e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1789e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1790e971aa12SJeff Cody         }
17914d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1792e971aa12SJeff Cody         g_free(bs_entry);
1793e971aa12SJeff Cody     }
1794e971aa12SJeff Cody     g_free(bs_queue);
1795e971aa12SJeff Cody     return ret;
1796e971aa12SJeff Cody }
1797e971aa12SJeff Cody 
1798e971aa12SJeff Cody 
1799e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1800e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1801e971aa12SJeff Cody {
1802e971aa12SJeff Cody     int ret = -1;
1803e971aa12SJeff Cody     Error *local_err = NULL;
18044d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1805e971aa12SJeff Cody 
1806e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1807e971aa12SJeff Cody     if (local_err != NULL) {
1808e971aa12SJeff Cody         error_propagate(errp, local_err);
1809e971aa12SJeff Cody     }
1810e971aa12SJeff Cody     return ret;
1811e971aa12SJeff Cody }
1812e971aa12SJeff Cody 
1813e971aa12SJeff Cody 
1814e971aa12SJeff Cody /*
1815e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1816e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1817e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1818e971aa12SJeff Cody  *
1819e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1820e971aa12SJeff Cody  * flags are the new open flags
1821e971aa12SJeff Cody  * queue is the reopen queue
1822e971aa12SJeff Cody  *
1823e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1824e971aa12SJeff Cody  * as well.
1825e971aa12SJeff Cody  *
1826e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1827e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1828e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1829e971aa12SJeff Cody  *
1830e971aa12SJeff Cody  */
1831e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1832e971aa12SJeff Cody                         Error **errp)
1833e971aa12SJeff Cody {
1834e971aa12SJeff Cody     int ret = -1;
1835e971aa12SJeff Cody     Error *local_err = NULL;
1836e971aa12SJeff Cody     BlockDriver *drv;
1837e971aa12SJeff Cody 
1838e971aa12SJeff Cody     assert(reopen_state != NULL);
1839e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1840e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1841e971aa12SJeff Cody 
1842e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1843e971aa12SJeff Cody      * to r/w */
1844e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1845e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
184681e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
184781e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1848e971aa12SJeff Cody         goto error;
1849e971aa12SJeff Cody     }
1850e971aa12SJeff Cody 
1851e971aa12SJeff Cody 
1852e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1853e971aa12SJeff Cody     if (ret) {
1854455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
1855e971aa12SJeff Cody         goto error;
1856e971aa12SJeff Cody     }
1857e971aa12SJeff Cody 
1858e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1859e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1860e971aa12SJeff Cody         if (ret) {
1861e971aa12SJeff Cody             if (local_err != NULL) {
1862e971aa12SJeff Cody                 error_propagate(errp, local_err);
1863e971aa12SJeff Cody             } else {
1864d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1865e971aa12SJeff Cody                            reopen_state->bs->filename);
1866e971aa12SJeff Cody             }
1867e971aa12SJeff Cody             goto error;
1868e971aa12SJeff Cody         }
1869e971aa12SJeff Cody     } else {
1870e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1871e971aa12SJeff Cody          * handler for each supported drv. */
187281e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
187381e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
187481e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1875e971aa12SJeff Cody         ret = -1;
1876e971aa12SJeff Cody         goto error;
1877e971aa12SJeff Cody     }
1878e971aa12SJeff Cody 
18794d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
18804d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
18814d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
18824d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
18834d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
18844d2cb092SKevin Wolf 
18854d2cb092SKevin Wolf         do {
18864d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
18874d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
18884d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
18894d2cb092SKevin Wolf                                                 entry->key);
18904d2cb092SKevin Wolf 
18914d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
18924d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
18934d2cb092SKevin Wolf                 ret = -EINVAL;
18944d2cb092SKevin Wolf                 goto error;
18954d2cb092SKevin Wolf             }
18964d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
18974d2cb092SKevin Wolf     }
18984d2cb092SKevin Wolf 
1899e971aa12SJeff Cody     ret = 0;
1900e971aa12SJeff Cody 
1901e971aa12SJeff Cody error:
1902e971aa12SJeff Cody     return ret;
1903e971aa12SJeff Cody }
1904e971aa12SJeff Cody 
1905e971aa12SJeff Cody /*
1906e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1907e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1908e971aa12SJeff Cody  * the active BlockDriverState contents.
1909e971aa12SJeff Cody  */
1910e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1911e971aa12SJeff Cody {
1912e971aa12SJeff Cody     BlockDriver *drv;
1913e971aa12SJeff Cody 
1914e971aa12SJeff Cody     assert(reopen_state != NULL);
1915e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1916e971aa12SJeff Cody     assert(drv != NULL);
1917e971aa12SJeff Cody 
1918e971aa12SJeff Cody     /* If there are any driver level actions to take */
1919e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1920e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1921e971aa12SJeff Cody     }
1922e971aa12SJeff Cody 
1923e971aa12SJeff Cody     /* set BDS specific flags now */
1924e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1925e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1926e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1927e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1928355ef4acSKevin Wolf 
19293baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1930e971aa12SJeff Cody }
1931e971aa12SJeff Cody 
1932e971aa12SJeff Cody /*
1933e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1934e971aa12SJeff Cody  * reopen_state
1935e971aa12SJeff Cody  */
1936e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1937e971aa12SJeff Cody {
1938e971aa12SJeff Cody     BlockDriver *drv;
1939e971aa12SJeff Cody 
1940e971aa12SJeff Cody     assert(reopen_state != NULL);
1941e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1942e971aa12SJeff Cody     assert(drv != NULL);
1943e971aa12SJeff Cody 
1944e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1945e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1946e971aa12SJeff Cody     }
1947e971aa12SJeff Cody }
1948e971aa12SJeff Cody 
1949e971aa12SJeff Cody 
1950fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1951fc01f7e7Sbellard {
195233384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
195333384421SMax Reitz 
19543e914655SPaolo Bonzini     if (bs->job) {
19553e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
19563e914655SPaolo Bonzini     }
195799b7e775SAlberto Garcia 
195899b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
1959a0d64a61SAlberto Garcia     if (bs->throttle_state) {
196099b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
196199b7e775SAlberto Garcia     }
196299b7e775SAlberto Garcia 
196353ec73e2SFam Zheng     bdrv_drain(bs); /* complete I/O */
196458fda173SStefan Hajnoczi     bdrv_flush(bs);
196553ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
1966d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
19677094f12fSKevin Wolf 
1968b4d02820SMax Reitz     if (bs->blk) {
1969b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
1970b4d02820SMax Reitz     }
1971b4d02820SMax Reitz 
19723cbc002cSPaolo Bonzini     if (bs->drv) {
19736e93e7c4SKevin Wolf         BdrvChild *child, *next;
19746e93e7c4SKevin Wolf 
19759a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
19769a4f4c31SKevin Wolf         bs->drv = NULL;
19779a7dedbcSKevin Wolf 
19789a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
19799a7dedbcSKevin Wolf 
19809a4f4c31SKevin Wolf         if (bs->file != NULL) {
19819a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
19829a4f4c31SKevin Wolf             bs->file = NULL;
19839a4f4c31SKevin Wolf         }
19849a4f4c31SKevin Wolf 
19856e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
198633a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
198733a60407SKevin Wolf              * bdrv_unref_child() here */
1988bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
1989bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
1990bddcec37SKevin Wolf             }
199133a60407SKevin Wolf             bdrv_detach_child(child);
19926e93e7c4SKevin Wolf         }
19936e93e7c4SKevin Wolf 
19947267c094SAnthony Liguori         g_free(bs->opaque);
1995ea2384d3Sbellard         bs->opaque = NULL;
199653fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1997a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1998a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
19996405875cSPaolo Bonzini         bs->total_sectors = 0;
20006405875cSPaolo Bonzini         bs->encrypted = 0;
20016405875cSPaolo Bonzini         bs->valid_key = 0;
20026405875cSPaolo Bonzini         bs->sg = 0;
20030d51b4deSAsias He         bs->zero_beyond_eof = false;
2004de9c0cecSKevin Wolf         QDECREF(bs->options);
2005de9c0cecSKevin Wolf         bs->options = NULL;
200691af7014SMax Reitz         QDECREF(bs->full_open_options);
200791af7014SMax Reitz         bs->full_open_options = NULL;
20089ca11154SPavel Hrdina     }
200966f82ceeSKevin Wolf 
201033384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
201133384421SMax Reitz         g_free(ban);
201233384421SMax Reitz     }
201333384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2014b338082bSbellard }
2015b338082bSbellard 
20162bc93fedSMORITA Kazutaka void bdrv_close_all(void)
20172bc93fedSMORITA Kazutaka {
20182bc93fedSMORITA Kazutaka     BlockDriverState *bs;
20192bc93fedSMORITA Kazutaka 
2020dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2021ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2022ed78cda3SStefan Hajnoczi 
2023ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
20242bc93fedSMORITA Kazutaka         bdrv_close(bs);
2025ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
20262bc93fedSMORITA Kazutaka     }
20272bc93fedSMORITA Kazutaka }
20282bc93fedSMORITA Kazutaka 
2029dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
2030dc364f4cSBenoît Canet  * graph_bdrv_state list.
2031d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
2032d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
2033d22b2f41SRyan Harper {
2034bfb197e0SMarkus Armbruster     /*
2035bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
2036bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
2037bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
2038bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
2039bfb197e0SMarkus Armbruster      * resetting it to null on remove.
2040bfb197e0SMarkus Armbruster      */
2041bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
2042dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2043bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
2044d22b2f41SRyan Harper     }
2045dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
2046dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2047dc364f4cSBenoît Canet     }
2048dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
2049d22b2f41SRyan Harper }
2050d22b2f41SRyan Harper 
20518e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
20524ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
20534ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
20544ddc07caSPaolo Bonzini {
20554ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
20564ddc07caSPaolo Bonzini 
20574ddc07caSPaolo Bonzini     /* dev info */
20584ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
20594ddc07caSPaolo Bonzini 
20604ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
20614ddc07caSPaolo Bonzini 
2062dd62f1caSKevin Wolf     /* dirty bitmap */
2063dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2064dd62f1caSKevin Wolf }
2065dd62f1caSKevin Wolf 
2066dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2067dd62f1caSKevin Wolf                                        BlockDriverState *to)
2068dd62f1caSKevin Wolf {
2069dd62f1caSKevin Wolf     BdrvChild *c, *next;
2070dd62f1caSKevin Wolf 
2071dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2072dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2073dd62f1caSKevin Wolf         c->bs = to;
2074dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2075dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2076dd62f1caSKevin Wolf         bdrv_ref(to);
2077dd62f1caSKevin Wolf         bdrv_unref(from);
2078dd62f1caSKevin Wolf     }
2079dd62f1caSKevin Wolf     if (from->blk) {
2080dd62f1caSKevin Wolf         blk_set_bs(from->blk, to);
2081dd62f1caSKevin Wolf         if (!to->device_list.tqe_prev) {
2082dd62f1caSKevin Wolf             QTAILQ_INSERT_BEFORE(from, to, device_list);
2083dd62f1caSKevin Wolf         }
2084dd62f1caSKevin Wolf         QTAILQ_REMOVE(&bdrv_states, from, device_list);
2085dd62f1caSKevin Wolf     }
2086dd62f1caSKevin Wolf }
2087dd62f1caSKevin Wolf 
2088dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2089dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2090dd62f1caSKevin Wolf {
2091dd62f1caSKevin Wolf     BlockDriverState tmp;
2092dd62f1caSKevin Wolf 
2093dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2094dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2095dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2096dd62f1caSKevin Wolf 
2097dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2098dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2099dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2100dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2101dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2102dd62f1caSKevin Wolf     }
2103dd62f1caSKevin Wolf }
2104dd62f1caSKevin Wolf 
21058802d1fdSJeff Cody /*
21068802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
21078802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
21088802d1fdSJeff Cody  *
21098802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
21108802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
21118802d1fdSJeff Cody  *
2112bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2113f6801b83SJeff Cody  *
21148802d1fdSJeff Cody  * This function does not create any image files.
2115dd62f1caSKevin Wolf  *
2116dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2117dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2118dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2119dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
21208802d1fdSJeff Cody  */
21218802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
21228802d1fdSJeff Cody {
2123dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2124dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
21258802d1fdSJeff Cody 
2126dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2127dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2128dd62f1caSKevin Wolf 
2129dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2130dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2131dd62f1caSKevin Wolf 
2132dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2133dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2134dd62f1caSKevin Wolf 
2135dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2136dd62f1caSKevin Wolf      * additional reference any more. */
2137dd62f1caSKevin Wolf     bdrv_unref(bs_new);
21388802d1fdSJeff Cody }
21398802d1fdSJeff Cody 
21403f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
21413f09bfbcSKevin Wolf {
21423f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
21433f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
21443f09bfbcSKevin Wolf 
21453f09bfbcSKevin Wolf     bdrv_ref(old);
21463f09bfbcSKevin Wolf 
21473f09bfbcSKevin Wolf     if (old->blk) {
21483f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
21493f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
21503f09bfbcSKevin Wolf          *
21513f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
21523f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
21533f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
21543f09bfbcSKevin Wolf         assert(!new->blk);
21553f09bfbcSKevin Wolf         swap_feature_fields(old, new);
21563f09bfbcSKevin Wolf     }
21573f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
21583f09bfbcSKevin Wolf 
21593f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
21603f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
21613f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
21623f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
21633f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
21643f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
21653f09bfbcSKevin Wolf     }
21663f09bfbcSKevin Wolf 
21673f09bfbcSKevin Wolf     bdrv_unref(old);
21683f09bfbcSKevin Wolf }
21693f09bfbcSKevin Wolf 
21704f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2171b338082bSbellard {
21723e914655SPaolo Bonzini     assert(!bs->job);
21733718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21744f6fd349SFam Zheng     assert(!bs->refcnt);
2175e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
217618846deeSMarkus Armbruster 
2177e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2178e1b5c52eSStefan Hajnoczi 
21791b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2180d22b2f41SRyan Harper     bdrv_make_anon(bs);
218134c6f050Saurel32 
21827267c094SAnthony Liguori     g_free(bs);
2183fc01f7e7Sbellard }
2184fc01f7e7Sbellard 
2185e97fc193Saliguori /*
2186e97fc193Saliguori  * Run consistency checks on an image
2187e97fc193Saliguori  *
2188e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2189a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2190e076f338SKevin Wolf  * check are stored in res.
2191e97fc193Saliguori  */
21924534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2193e97fc193Saliguori {
2194908bcd54SMax Reitz     if (bs->drv == NULL) {
2195908bcd54SMax Reitz         return -ENOMEDIUM;
2196908bcd54SMax Reitz     }
2197e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2198e97fc193Saliguori         return -ENOTSUP;
2199e97fc193Saliguori     }
2200e97fc193Saliguori 
2201e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
22024534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2203e97fc193Saliguori }
2204e97fc193Saliguori 
22058a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
22068a426614SKevin Wolf 
220733e3963eSbellard /* commit COW file into the raw image */
220833e3963eSbellard int bdrv_commit(BlockDriverState *bs)
220933e3963eSbellard {
221019cb3738Sbellard     BlockDriver *drv = bs->drv;
221172706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
22128a426614SKevin Wolf     int n, ro, open_flags;
22130bce597dSJeff Cody     int ret = 0;
221472706ea4SJeff Cody     uint8_t *buf = NULL;
221533e3963eSbellard 
221619cb3738Sbellard     if (!drv)
221719cb3738Sbellard         return -ENOMEDIUM;
221833e3963eSbellard 
2219760e0063SKevin Wolf     if (!bs->backing) {
22204dca4b63SNaphtali Sprei         return -ENOTSUP;
22214dca4b63SNaphtali Sprei     }
22224dca4b63SNaphtali Sprei 
2223bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2224760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
22252d3735d3SStefan Hajnoczi         return -EBUSY;
22262d3735d3SStefan Hajnoczi     }
22272d3735d3SStefan Hajnoczi 
2228760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2229760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
22304dca4b63SNaphtali Sprei 
22314dca4b63SNaphtali Sprei     if (ro) {
2232760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
22330bce597dSJeff Cody             return -EACCES;
22344dca4b63SNaphtali Sprei         }
2235ea2384d3Sbellard     }
2236ea2384d3Sbellard 
223772706ea4SJeff Cody     length = bdrv_getlength(bs);
223872706ea4SJeff Cody     if (length < 0) {
223972706ea4SJeff Cody         ret = length;
224072706ea4SJeff Cody         goto ro_cleanup;
224172706ea4SJeff Cody     }
224272706ea4SJeff Cody 
2243760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
224472706ea4SJeff Cody     if (backing_length < 0) {
224572706ea4SJeff Cody         ret = backing_length;
224672706ea4SJeff Cody         goto ro_cleanup;
224772706ea4SJeff Cody     }
224872706ea4SJeff Cody 
224972706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
225072706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
225172706ea4SJeff Cody      * we must return an error */
225272706ea4SJeff Cody     if (length > backing_length) {
2253760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
225472706ea4SJeff Cody         if (ret < 0) {
225572706ea4SJeff Cody             goto ro_cleanup;
225672706ea4SJeff Cody         }
225772706ea4SJeff Cody     }
225872706ea4SJeff Cody 
225972706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2260857d4f46SKevin Wolf 
2261857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2262760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2263857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2264857d4f46SKevin Wolf     if (buf == NULL) {
2265857d4f46SKevin Wolf         ret = -ENOMEM;
2266857d4f46SKevin Wolf         goto ro_cleanup;
2267857d4f46SKevin Wolf     }
22688a426614SKevin Wolf 
22698a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2270d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2271d663640cSPaolo Bonzini         if (ret < 0) {
2272d663640cSPaolo Bonzini             goto ro_cleanup;
2273d663640cSPaolo Bonzini         }
2274d663640cSPaolo Bonzini         if (ret) {
2275dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2276dabfa6ccSKevin Wolf             if (ret < 0) {
22774dca4b63SNaphtali Sprei                 goto ro_cleanup;
227833e3963eSbellard             }
227933e3963eSbellard 
2280760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2281dabfa6ccSKevin Wolf             if (ret < 0) {
22824dca4b63SNaphtali Sprei                 goto ro_cleanup;
228333e3963eSbellard             }
228433e3963eSbellard         }
228533e3963eSbellard     }
228695389c86Sbellard 
22871d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22881d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2289dabfa6ccSKevin Wolf         if (ret < 0) {
2290dabfa6ccSKevin Wolf             goto ro_cleanup;
2291dabfa6ccSKevin Wolf         }
22921d44952fSChristoph Hellwig         bdrv_flush(bs);
22931d44952fSChristoph Hellwig     }
229495389c86Sbellard 
22953f5075aeSChristoph Hellwig     /*
22963f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22973f5075aeSChristoph Hellwig      * stable on disk.
22983f5075aeSChristoph Hellwig      */
2299760e0063SKevin Wolf     if (bs->backing) {
2300760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2301dabfa6ccSKevin Wolf     }
23024dca4b63SNaphtali Sprei 
2303dabfa6ccSKevin Wolf     ret = 0;
23044dca4b63SNaphtali Sprei ro_cleanup:
2305857d4f46SKevin Wolf     qemu_vfree(buf);
23064dca4b63SNaphtali Sprei 
23074dca4b63SNaphtali Sprei     if (ro) {
23080bce597dSJeff Cody         /* ignoring error return here */
2309760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
23104dca4b63SNaphtali Sprei     }
23114dca4b63SNaphtali Sprei 
23121d44952fSChristoph Hellwig     return ret;
231333e3963eSbellard }
231433e3963eSbellard 
2315e8877497SStefan Hajnoczi int bdrv_commit_all(void)
23166ab4b5abSMarkus Armbruster {
23176ab4b5abSMarkus Armbruster     BlockDriverState *bs;
23186ab4b5abSMarkus Armbruster 
2319dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2320ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2321ed78cda3SStefan Hajnoczi 
2322ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2323760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2324e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2325e8877497SStefan Hajnoczi             if (ret < 0) {
2326ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2327e8877497SStefan Hajnoczi                 return ret;
23286ab4b5abSMarkus Armbruster             }
23296ab4b5abSMarkus Armbruster         }
2330ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2331272d2d8eSJeff Cody     }
2332e8877497SStefan Hajnoczi     return 0;
2333e8877497SStefan Hajnoczi }
23346ab4b5abSMarkus Armbruster 
2335756e6736SKevin Wolf /*
2336756e6736SKevin Wolf  * Return values:
2337756e6736SKevin Wolf  * 0        - success
2338756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2339756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2340756e6736SKevin Wolf  *            image file header
2341756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2342756e6736SKevin Wolf  */
2343756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2344756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2345756e6736SKevin Wolf {
2346756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2347469ef350SPaolo Bonzini     int ret;
2348756e6736SKevin Wolf 
23495f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23505f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23515f377794SPaolo Bonzini         return -EINVAL;
23525f377794SPaolo Bonzini     }
23535f377794SPaolo Bonzini 
2354756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2355469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2356756e6736SKevin Wolf     } else {
2357469ef350SPaolo Bonzini         ret = -ENOTSUP;
2358756e6736SKevin Wolf     }
2359469ef350SPaolo Bonzini 
2360469ef350SPaolo Bonzini     if (ret == 0) {
2361469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2362469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2363469ef350SPaolo Bonzini     }
2364469ef350SPaolo Bonzini     return ret;
2365756e6736SKevin Wolf }
2366756e6736SKevin Wolf 
23676ebdcee2SJeff Cody /*
23686ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23696ebdcee2SJeff Cody  *
23706ebdcee2SJeff Cody  * active is the current topmost image.
23716ebdcee2SJeff Cody  *
23726ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23736ebdcee2SJeff Cody  * or if active == bs.
23744caf0fcdSJeff Cody  *
23754caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
23766ebdcee2SJeff Cody  */
23776ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23786ebdcee2SJeff Cody                                     BlockDriverState *bs)
23796ebdcee2SJeff Cody {
2380760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2381760e0063SKevin Wolf         active = backing_bs(active);
23826ebdcee2SJeff Cody     }
23836ebdcee2SJeff Cody 
23844caf0fcdSJeff Cody     return active;
23856ebdcee2SJeff Cody }
23866ebdcee2SJeff Cody 
23874caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
23884caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
23894caf0fcdSJeff Cody {
23904caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
23916ebdcee2SJeff Cody }
23926ebdcee2SJeff Cody 
23936ebdcee2SJeff Cody /*
23946ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23956ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23966ebdcee2SJeff Cody  *
23976ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23986ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23996ebdcee2SJeff Cody  *
24006ebdcee2SJeff Cody  * E.g., this will convert the following chain:
24016ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
24026ebdcee2SJeff Cody  *
24036ebdcee2SJeff Cody  * to
24046ebdcee2SJeff Cody  *
24056ebdcee2SJeff Cody  * bottom <- base <- active
24066ebdcee2SJeff Cody  *
24076ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24086ebdcee2SJeff Cody  *
24096ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24106ebdcee2SJeff Cody  *
24116ebdcee2SJeff Cody  * to
24126ebdcee2SJeff Cody  *
24136ebdcee2SJeff Cody  * base <- active
24146ebdcee2SJeff Cody  *
241554e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
241654e26900SJeff Cody  * overlay image metadata.
241754e26900SJeff Cody  *
24186ebdcee2SJeff Cody  * Error conditions:
24196ebdcee2SJeff Cody  *  if active == top, that is considered an error
24206ebdcee2SJeff Cody  *
24216ebdcee2SJeff Cody  */
24226ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
242354e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
24246ebdcee2SJeff Cody {
24256ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24266ebdcee2SJeff Cody     int ret = -EIO;
24276ebdcee2SJeff Cody 
24286ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24296ebdcee2SJeff Cody         goto exit;
24306ebdcee2SJeff Cody     }
24316ebdcee2SJeff Cody 
24326ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24336ebdcee2SJeff Cody 
24346ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24356ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24366ebdcee2SJeff Cody         goto exit;
24376ebdcee2SJeff Cody     }
24386ebdcee2SJeff Cody 
2439760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
24406ebdcee2SJeff Cody      * to do, no intermediate images */
2441760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
24426ebdcee2SJeff Cody         ret = 0;
24436ebdcee2SJeff Cody         goto exit;
24446ebdcee2SJeff Cody     }
24456ebdcee2SJeff Cody 
24465db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
24475db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
24486ebdcee2SJeff Cody         goto exit;
24496ebdcee2SJeff Cody     }
24506ebdcee2SJeff Cody 
24516ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
24525db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
245354e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
24545db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
24556ebdcee2SJeff Cody     if (ret) {
24566ebdcee2SJeff Cody         goto exit;
24576ebdcee2SJeff Cody     }
24585db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
24596ebdcee2SJeff Cody 
24606ebdcee2SJeff Cody     ret = 0;
24616ebdcee2SJeff Cody exit:
24626ebdcee2SJeff Cody     return ret;
24636ebdcee2SJeff Cody }
24646ebdcee2SJeff Cody 
246583f64091Sbellard /**
246683f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
246783f64091Sbellard  */
246883f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
246983f64091Sbellard {
247083f64091Sbellard     BlockDriver *drv = bs->drv;
247151762288SStefan Hajnoczi     int ret;
247283f64091Sbellard     if (!drv)
247319cb3738Sbellard         return -ENOMEDIUM;
247483f64091Sbellard     if (!drv->bdrv_truncate)
247583f64091Sbellard         return -ENOTSUP;
247659f2689dSNaphtali Sprei     if (bs->read_only)
247759f2689dSNaphtali Sprei         return -EACCES;
24789c75e168SJeff Cody 
247951762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
248051762288SStefan Hajnoczi     if (ret == 0) {
248151762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2482ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2483a7f53e26SMarkus Armbruster         if (bs->blk) {
2484a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2485a7f53e26SMarkus Armbruster         }
248651762288SStefan Hajnoczi     }
248751762288SStefan Hajnoczi     return ret;
248883f64091Sbellard }
248983f64091Sbellard 
249083f64091Sbellard /**
24914a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
24924a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
24934a1d5e1fSFam Zheng  */
24944a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
24954a1d5e1fSFam Zheng {
24964a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
24974a1d5e1fSFam Zheng     if (!drv) {
24984a1d5e1fSFam Zheng         return -ENOMEDIUM;
24994a1d5e1fSFam Zheng     }
25004a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
25014a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
25024a1d5e1fSFam Zheng     }
25034a1d5e1fSFam Zheng     if (bs->file) {
25049a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
25054a1d5e1fSFam Zheng     }
25064a1d5e1fSFam Zheng     return -ENOTSUP;
25074a1d5e1fSFam Zheng }
25084a1d5e1fSFam Zheng 
25094a1d5e1fSFam Zheng /**
251065a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
251183f64091Sbellard  */
251265a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
251383f64091Sbellard {
251483f64091Sbellard     BlockDriver *drv = bs->drv;
251565a9bb25SMarkus Armbruster 
251683f64091Sbellard     if (!drv)
251719cb3738Sbellard         return -ENOMEDIUM;
251851762288SStefan Hajnoczi 
2519b94a2610SKevin Wolf     if (drv->has_variable_length) {
2520b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2521b94a2610SKevin Wolf         if (ret < 0) {
2522b94a2610SKevin Wolf             return ret;
2523fc01f7e7Sbellard         }
252446a4e4e6SStefan Hajnoczi     }
252565a9bb25SMarkus Armbruster     return bs->total_sectors;
252665a9bb25SMarkus Armbruster }
252765a9bb25SMarkus Armbruster 
252865a9bb25SMarkus Armbruster /**
252965a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
253065a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
253165a9bb25SMarkus Armbruster  */
253265a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
253365a9bb25SMarkus Armbruster {
253465a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
253565a9bb25SMarkus Armbruster 
25364a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
253765a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
253846a4e4e6SStefan Hajnoczi }
2539fc01f7e7Sbellard 
254019cb3738Sbellard /* return 0 as number of sectors if no device present or error */
254196b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2542fc01f7e7Sbellard {
254365a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
254465a9bb25SMarkus Armbruster 
254565a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2546fc01f7e7Sbellard }
2547cf98951bSbellard 
2548b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2549b338082bSbellard {
2550b338082bSbellard     return bs->read_only;
2551b338082bSbellard }
2552b338082bSbellard 
2553985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2554985a03b0Sths {
2555985a03b0Sths     return bs->sg;
2556985a03b0Sths }
2557985a03b0Sths 
2558e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2559e900a7b7SChristoph Hellwig {
2560e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2561e900a7b7SChristoph Hellwig }
2562e900a7b7SChristoph Hellwig 
2563425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2564425b0148SPaolo Bonzini {
2565425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
256655b110f2SJeff Cody 
256755b110f2SJeff Cody     /* so a reopen() will preserve wce */
256855b110f2SJeff Cody     if (wce) {
256955b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
257055b110f2SJeff Cody     } else {
257155b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
257255b110f2SJeff Cody     }
2573425b0148SPaolo Bonzini }
2574425b0148SPaolo Bonzini 
2575ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2576ea2384d3Sbellard {
2577760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2578ea2384d3Sbellard         return 1;
2579760e0063SKevin Wolf     }
2580ea2384d3Sbellard     return bs->encrypted;
2581ea2384d3Sbellard }
2582ea2384d3Sbellard 
2583c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2584c0f4ce77Saliguori {
2585760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2586c0f4ce77Saliguori 
2587760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2588c0f4ce77Saliguori         return 1;
2589760e0063SKevin Wolf     }
2590c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2591c0f4ce77Saliguori }
2592c0f4ce77Saliguori 
2593ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2594ea2384d3Sbellard {
2595ea2384d3Sbellard     int ret;
2596760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2597760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2598ea2384d3Sbellard         if (ret < 0)
2599ea2384d3Sbellard             return ret;
2600ea2384d3Sbellard         if (!bs->encrypted)
2601ea2384d3Sbellard             return 0;
2602ea2384d3Sbellard     }
2603fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2604fd04a2aeSShahar Havivi         return -EINVAL;
2605fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2606fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2607fd04a2aeSShahar Havivi     }
2608c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2609bb5fc20fSaliguori     if (ret < 0) {
2610bb5fc20fSaliguori         bs->valid_key = 0;
2611bb5fc20fSaliguori     } else if (!bs->valid_key) {
2612bb5fc20fSaliguori         bs->valid_key = 1;
2613a7f53e26SMarkus Armbruster         if (bs->blk) {
2614bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2615a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2616a7f53e26SMarkus Armbruster         }
2617bb5fc20fSaliguori     }
2618c0f4ce77Saliguori     return ret;
2619ea2384d3Sbellard }
2620ea2384d3Sbellard 
26214d2855a3SMarkus Armbruster /*
26224d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
26234d2855a3SMarkus Armbruster  * If @key is non-null:
26244d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
26254d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
26264d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
26274d2855a3SMarkus Armbruster  * If @key is null:
26284d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
26294d2855a3SMarkus Armbruster  *     Else do nothing.
26304d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
26314d2855a3SMarkus Armbruster  */
26324d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
26334d2855a3SMarkus Armbruster {
26344d2855a3SMarkus Armbruster     if (key) {
26354d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
263681e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
263781e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
26384d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2639c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
26404d2855a3SMarkus Armbruster         }
26414d2855a3SMarkus Armbruster     } else {
26424d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2643b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2644b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
264581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
26464d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
26474d2855a3SMarkus Armbruster         }
26484d2855a3SMarkus Armbruster     }
26494d2855a3SMarkus Armbruster }
26504d2855a3SMarkus Armbruster 
2651f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2652ea2384d3Sbellard {
2653f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2654ea2384d3Sbellard }
2655ea2384d3Sbellard 
2656ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2657ada42401SStefan Hajnoczi {
2658ada42401SStefan Hajnoczi     return strcmp(a, b);
2659ada42401SStefan Hajnoczi }
2660ada42401SStefan Hajnoczi 
2661ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2662ea2384d3Sbellard                          void *opaque)
2663ea2384d3Sbellard {
2664ea2384d3Sbellard     BlockDriver *drv;
2665e855e4fbSJeff Cody     int count = 0;
2666ada42401SStefan Hajnoczi     int i;
2667e855e4fbSJeff Cody     const char **formats = NULL;
2668ea2384d3Sbellard 
26698a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2670e855e4fbSJeff Cody         if (drv->format_name) {
2671e855e4fbSJeff Cody             bool found = false;
2672e855e4fbSJeff Cody             int i = count;
2673e855e4fbSJeff Cody             while (formats && i && !found) {
2674e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2675e855e4fbSJeff Cody             }
2676e855e4fbSJeff Cody 
2677e855e4fbSJeff Cody             if (!found) {
26785839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2679e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2680ea2384d3Sbellard             }
2681ea2384d3Sbellard         }
2682e855e4fbSJeff Cody     }
2683ada42401SStefan Hajnoczi 
2684ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2685ada42401SStefan Hajnoczi 
2686ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2687ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2688ada42401SStefan Hajnoczi     }
2689ada42401SStefan Hajnoczi 
2690e855e4fbSJeff Cody     g_free(formats);
2691e855e4fbSJeff Cody }
2692ea2384d3Sbellard 
2693dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2694dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2695dc364f4cSBenoît Canet {
2696dc364f4cSBenoît Canet     BlockDriverState *bs;
2697dc364f4cSBenoît Canet 
2698dc364f4cSBenoît Canet     assert(node_name);
2699dc364f4cSBenoît Canet 
2700dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2701dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2702dc364f4cSBenoît Canet             return bs;
2703dc364f4cSBenoît Canet         }
2704dc364f4cSBenoît Canet     }
2705dc364f4cSBenoît Canet     return NULL;
2706dc364f4cSBenoît Canet }
2707dc364f4cSBenoît Canet 
2708c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2709d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2710c13163fbSBenoît Canet {
2711c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2712c13163fbSBenoît Canet     BlockDriverState *bs;
2713c13163fbSBenoît Canet 
2714c13163fbSBenoît Canet     list = NULL;
2715c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2716d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2717d5a8ee60SAlberto Garcia         if (!info) {
2718d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2719d5a8ee60SAlberto Garcia             return NULL;
2720d5a8ee60SAlberto Garcia         }
2721c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2722d5a8ee60SAlberto Garcia         entry->value = info;
2723c13163fbSBenoît Canet         entry->next = list;
2724c13163fbSBenoît Canet         list = entry;
2725c13163fbSBenoît Canet     }
2726c13163fbSBenoît Canet 
2727c13163fbSBenoît Canet     return list;
2728c13163fbSBenoît Canet }
2729c13163fbSBenoît Canet 
273012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
273112d3ba82SBenoît Canet                                  const char *node_name,
273212d3ba82SBenoît Canet                                  Error **errp)
273312d3ba82SBenoît Canet {
27347f06d47eSMarkus Armbruster     BlockBackend *blk;
27357f06d47eSMarkus Armbruster     BlockDriverState *bs;
273612d3ba82SBenoît Canet 
273712d3ba82SBenoît Canet     if (device) {
27387f06d47eSMarkus Armbruster         blk = blk_by_name(device);
273912d3ba82SBenoît Canet 
27407f06d47eSMarkus Armbruster         if (blk) {
27419f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
27429f4ed6fbSAlberto Garcia             if (!bs) {
27435433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
27445433c24fSMax Reitz             }
27455433c24fSMax Reitz 
27469f4ed6fbSAlberto Garcia             return bs;
274712d3ba82SBenoît Canet         }
2748dd67fa50SBenoît Canet     }
274912d3ba82SBenoît Canet 
2750dd67fa50SBenoît Canet     if (node_name) {
275112d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
275212d3ba82SBenoît Canet 
2753dd67fa50SBenoît Canet         if (bs) {
2754dd67fa50SBenoît Canet             return bs;
2755dd67fa50SBenoît Canet         }
275612d3ba82SBenoît Canet     }
275712d3ba82SBenoît Canet 
2758dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2759dd67fa50SBenoît Canet                      device ? device : "",
2760dd67fa50SBenoît Canet                      node_name ? node_name : "");
2761dd67fa50SBenoît Canet     return NULL;
276212d3ba82SBenoît Canet }
276312d3ba82SBenoît Canet 
27645a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
27655a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
27665a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
27675a6684d2SJeff Cody {
27685a6684d2SJeff Cody     while (top && top != base) {
2769760e0063SKevin Wolf         top = backing_bs(top);
27705a6684d2SJeff Cody     }
27715a6684d2SJeff Cody 
27725a6684d2SJeff Cody     return top != NULL;
27735a6684d2SJeff Cody }
27745a6684d2SJeff Cody 
277504df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
277604df765aSFam Zheng {
277704df765aSFam Zheng     if (!bs) {
277804df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
277904df765aSFam Zheng     }
278004df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
278104df765aSFam Zheng }
278204df765aSFam Zheng 
27832f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
27842f399b0aSMarkus Armbruster {
27852f399b0aSMarkus Armbruster     if (!bs) {
27862f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
27872f399b0aSMarkus Armbruster     }
2788dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
27892f399b0aSMarkus Armbruster }
27902f399b0aSMarkus Armbruster 
279120a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
279220a9e77dSFam Zheng {
279320a9e77dSFam Zheng     return bs->node_name;
279420a9e77dSFam Zheng }
279520a9e77dSFam Zheng 
27967f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2797bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2798ea2384d3Sbellard {
2799bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2800ea2384d3Sbellard }
2801ea2384d3Sbellard 
28029b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
28039b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
28049b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
28059b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
28069b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
28079b2aa84fSAlberto Garcia {
28089b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
28099b2aa84fSAlberto Garcia }
28109b2aa84fSAlberto Garcia 
2811c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2812c8433287SMarkus Armbruster {
2813c8433287SMarkus Armbruster     return bs->open_flags;
2814c8433287SMarkus Armbruster }
2815c8433287SMarkus Armbruster 
28163ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
28173ac21627SPeter Lieven {
28183ac21627SPeter Lieven     return 1;
28193ac21627SPeter Lieven }
28203ac21627SPeter Lieven 
2821f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2822f2feebbdSKevin Wolf {
2823f2feebbdSKevin Wolf     assert(bs->drv);
2824f2feebbdSKevin Wolf 
282511212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
282611212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2827760e0063SKevin Wolf     if (bs->backing) {
282811212d8fSPaolo Bonzini         return 0;
282911212d8fSPaolo Bonzini     }
2830336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2831336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2832f2feebbdSKevin Wolf     }
2833f2feebbdSKevin Wolf 
28343ac21627SPeter Lieven     /* safe default */
28353ac21627SPeter Lieven     return 0;
2836f2feebbdSKevin Wolf }
2837f2feebbdSKevin Wolf 
28384ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
28394ce78691SPeter Lieven {
28404ce78691SPeter Lieven     BlockDriverInfo bdi;
28414ce78691SPeter Lieven 
2842760e0063SKevin Wolf     if (bs->backing) {
28434ce78691SPeter Lieven         return false;
28444ce78691SPeter Lieven     }
28454ce78691SPeter Lieven 
28464ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28474ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
28484ce78691SPeter Lieven     }
28494ce78691SPeter Lieven 
28504ce78691SPeter Lieven     return false;
28514ce78691SPeter Lieven }
28524ce78691SPeter Lieven 
28534ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
28544ce78691SPeter Lieven {
28554ce78691SPeter Lieven     BlockDriverInfo bdi;
28564ce78691SPeter Lieven 
2857760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
28584ce78691SPeter Lieven         return false;
28594ce78691SPeter Lieven     }
28604ce78691SPeter Lieven 
28614ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28624ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
28634ce78691SPeter Lieven     }
28644ce78691SPeter Lieven 
28654ce78691SPeter Lieven     return false;
28664ce78691SPeter Lieven }
28674ce78691SPeter Lieven 
2868045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2869045df330Saliguori {
2870760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2871045df330Saliguori         return bs->backing_file;
2872045df330Saliguori     else if (bs->encrypted)
2873045df330Saliguori         return bs->filename;
2874045df330Saliguori     else
2875045df330Saliguori         return NULL;
2876045df330Saliguori }
2877045df330Saliguori 
287883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
287983f64091Sbellard                                char *filename, int filename_size)
288083f64091Sbellard {
288183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
288283f64091Sbellard }
288383f64091Sbellard 
2884faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2885faea38e7Sbellard {
2886faea38e7Sbellard     BlockDriver *drv = bs->drv;
2887faea38e7Sbellard     if (!drv)
288819cb3738Sbellard         return -ENOMEDIUM;
2889faea38e7Sbellard     if (!drv->bdrv_get_info)
2890faea38e7Sbellard         return -ENOTSUP;
2891faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2892faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2893faea38e7Sbellard }
2894faea38e7Sbellard 
2895eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2896eae041feSMax Reitz {
2897eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2898eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2899eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2900eae041feSMax Reitz     }
2901eae041feSMax Reitz     return NULL;
2902eae041feSMax Reitz }
2903eae041feSMax Reitz 
2904a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
29058b9b0cc2SKevin Wolf {
2906bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
29078b9b0cc2SKevin Wolf         return;
29088b9b0cc2SKevin Wolf     }
29098b9b0cc2SKevin Wolf 
2910bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
291141c695c7SKevin Wolf }
29128b9b0cc2SKevin Wolf 
291341c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
291441c695c7SKevin Wolf                           const char *tag)
291541c695c7SKevin Wolf {
291641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
29179a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
291841c695c7SKevin Wolf     }
291941c695c7SKevin Wolf 
292041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
292141c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
292241c695c7SKevin Wolf     }
292341c695c7SKevin Wolf 
292441c695c7SKevin Wolf     return -ENOTSUP;
292541c695c7SKevin Wolf }
292641c695c7SKevin Wolf 
29274cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
29284cc70e93SFam Zheng {
29294cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
29309a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
29314cc70e93SFam Zheng     }
29324cc70e93SFam Zheng 
29334cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
29344cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
29354cc70e93SFam Zheng     }
29364cc70e93SFam Zheng 
29374cc70e93SFam Zheng     return -ENOTSUP;
29384cc70e93SFam Zheng }
29394cc70e93SFam Zheng 
294041c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
294141c695c7SKevin Wolf {
2942938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
29439a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
294441c695c7SKevin Wolf     }
294541c695c7SKevin Wolf 
294641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
294741c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
294841c695c7SKevin Wolf     }
294941c695c7SKevin Wolf 
295041c695c7SKevin Wolf     return -ENOTSUP;
295141c695c7SKevin Wolf }
295241c695c7SKevin Wolf 
295341c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
295441c695c7SKevin Wolf {
295541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
29569a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
295741c695c7SKevin Wolf     }
295841c695c7SKevin Wolf 
295941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
296041c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
296141c695c7SKevin Wolf     }
296241c695c7SKevin Wolf 
296341c695c7SKevin Wolf     return false;
29648b9b0cc2SKevin Wolf }
29658b9b0cc2SKevin Wolf 
2966199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2967199630b6SBlue Swirl {
2968199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2969199630b6SBlue Swirl }
2970199630b6SBlue Swirl 
2971b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
2972b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
2973b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
2974b1b1d783SJeff Cody  * the CWD rather than the chain. */
2975e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2976e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2977e8a6bb9cSMarcelo Tosatti {
2978b1b1d783SJeff Cody     char *filename_full = NULL;
2979b1b1d783SJeff Cody     char *backing_file_full = NULL;
2980b1b1d783SJeff Cody     char *filename_tmp = NULL;
2981b1b1d783SJeff Cody     int is_protocol = 0;
2982b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
2983b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
2984b1b1d783SJeff Cody 
2985b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
2986e8a6bb9cSMarcelo Tosatti         return NULL;
2987e8a6bb9cSMarcelo Tosatti     }
2988e8a6bb9cSMarcelo Tosatti 
2989b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
2990b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
2991b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
2992b1b1d783SJeff Cody 
2993b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
2994b1b1d783SJeff Cody 
2995760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
2996b1b1d783SJeff Cody 
2997b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
2998b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
2999b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3000b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3001760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3002b1b1d783SJeff Cody                 break;
3003b1b1d783SJeff Cody             }
3004e8a6bb9cSMarcelo Tosatti         } else {
3005b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3006b1b1d783SJeff Cody              * image's filename path */
3007b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3008b1b1d783SJeff Cody                          backing_file);
3009b1b1d783SJeff Cody 
3010b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3011b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3012b1b1d783SJeff Cody                 continue;
3013b1b1d783SJeff Cody             }
3014b1b1d783SJeff Cody 
3015b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3016b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3017b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3018b1b1d783SJeff Cody                          curr_bs->backing_file);
3019b1b1d783SJeff Cody 
3020b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3021b1b1d783SJeff Cody                 continue;
3022b1b1d783SJeff Cody             }
3023b1b1d783SJeff Cody 
3024b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3025760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3026b1b1d783SJeff Cody                 break;
3027b1b1d783SJeff Cody             }
3028e8a6bb9cSMarcelo Tosatti         }
3029e8a6bb9cSMarcelo Tosatti     }
3030e8a6bb9cSMarcelo Tosatti 
3031b1b1d783SJeff Cody     g_free(filename_full);
3032b1b1d783SJeff Cody     g_free(backing_file_full);
3033b1b1d783SJeff Cody     g_free(filename_tmp);
3034b1b1d783SJeff Cody     return retval;
3035e8a6bb9cSMarcelo Tosatti }
3036e8a6bb9cSMarcelo Tosatti 
3037f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3038f198fd1cSBenoît Canet {
3039f198fd1cSBenoît Canet     if (!bs->drv) {
3040f198fd1cSBenoît Canet         return 0;
3041f198fd1cSBenoît Canet     }
3042f198fd1cSBenoît Canet 
3043760e0063SKevin Wolf     if (!bs->backing) {
3044f198fd1cSBenoît Canet         return 0;
3045f198fd1cSBenoît Canet     }
3046f198fd1cSBenoît Canet 
3047760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3048f198fd1cSBenoît Canet }
3049f198fd1cSBenoît Canet 
3050ea2384d3Sbellard void bdrv_init(void)
3051ea2384d3Sbellard {
30525efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3053ea2384d3Sbellard }
3054ce1a14dcSpbrook 
3055eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3056eb852011SMarkus Armbruster {
3057eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3058eb852011SMarkus Armbruster     bdrv_init();
3059eb852011SMarkus Armbruster }
3060eb852011SMarkus Armbruster 
30615a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
30620f15423cSAnthony Liguori {
30635a8a30dbSKevin Wolf     Error *local_err = NULL;
30645a8a30dbSKevin Wolf     int ret;
30655a8a30dbSKevin Wolf 
30663456a8d1SKevin Wolf     if (!bs->drv)  {
30673456a8d1SKevin Wolf         return;
30680f15423cSAnthony Liguori     }
30693456a8d1SKevin Wolf 
30707ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
30717ea2d269SAlexey Kardashevskiy         return;
30727ea2d269SAlexey Kardashevskiy     }
30737ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
30747ea2d269SAlexey Kardashevskiy 
30753456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
30765a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
30773456a8d1SKevin Wolf     } else if (bs->file) {
30789a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
30795a8a30dbSKevin Wolf     }
30805a8a30dbSKevin Wolf     if (local_err) {
30815a8a30dbSKevin Wolf         error_propagate(errp, local_err);
30825a8a30dbSKevin Wolf         return;
30833456a8d1SKevin Wolf     }
30843456a8d1SKevin Wolf 
30855a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
30865a8a30dbSKevin Wolf     if (ret < 0) {
30875a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
30885a8a30dbSKevin Wolf         return;
30895a8a30dbSKevin Wolf     }
30900f15423cSAnthony Liguori }
30910f15423cSAnthony Liguori 
30925a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
30930f15423cSAnthony Liguori {
30940f15423cSAnthony Liguori     BlockDriverState *bs;
30955a8a30dbSKevin Wolf     Error *local_err = NULL;
30960f15423cSAnthony Liguori 
3097dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3098ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3099ed78cda3SStefan Hajnoczi 
3100ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
31015a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3102ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
31035a8a30dbSKevin Wolf         if (local_err) {
31045a8a30dbSKevin Wolf             error_propagate(errp, local_err);
31055a8a30dbSKevin Wolf             return;
31065a8a30dbSKevin Wolf         }
31070f15423cSAnthony Liguori     }
31080f15423cSAnthony Liguori }
31090f15423cSAnthony Liguori 
3110f9f05dc5SKevin Wolf /**************************************************************/
311119cb3738Sbellard /* removable device support */
311219cb3738Sbellard 
311319cb3738Sbellard /**
311419cb3738Sbellard  * Return TRUE if the media is present
311519cb3738Sbellard  */
3116e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
311719cb3738Sbellard {
311819cb3738Sbellard     BlockDriver *drv = bs->drv;
311928d7a789SMax Reitz     BdrvChild *child;
3120a1aff5bfSMarkus Armbruster 
3121e031f750SMax Reitz     if (!drv) {
3122e031f750SMax Reitz         return false;
3123e031f750SMax Reitz     }
312428d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3125a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
312619cb3738Sbellard     }
312728d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
312828d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
312928d7a789SMax Reitz             return false;
313028d7a789SMax Reitz         }
313128d7a789SMax Reitz     }
313228d7a789SMax Reitz     return true;
313328d7a789SMax Reitz }
313419cb3738Sbellard 
313519cb3738Sbellard /**
31368e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
31378e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
313819cb3738Sbellard  */
313919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
314019cb3738Sbellard {
314119cb3738Sbellard     BlockDriver *drv = bs->drv;
314219cb3738Sbellard 
31438e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
31448e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
31458e49ca46SMarkus Armbruster     }
31468e49ca46SMarkus Armbruster     return -ENOTSUP;
314719cb3738Sbellard }
314819cb3738Sbellard 
314919cb3738Sbellard /**
315019cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
315119cb3738Sbellard  */
3152f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
315319cb3738Sbellard {
315419cb3738Sbellard     BlockDriver *drv = bs->drv;
3155bfb197e0SMarkus Armbruster     const char *device_name;
315619cb3738Sbellard 
3157822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3158822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
315919cb3738Sbellard     }
31606f382ed2SLuiz Capitulino 
3161bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3162bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3163bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3164a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
31656f382ed2SLuiz Capitulino     }
316619cb3738Sbellard }
316719cb3738Sbellard 
316819cb3738Sbellard /**
316919cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
317019cb3738Sbellard  * to eject it manually).
317119cb3738Sbellard  */
3172025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
317319cb3738Sbellard {
317419cb3738Sbellard     BlockDriver *drv = bs->drv;
317519cb3738Sbellard 
3176025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3177b8c6d095SStefan Hajnoczi 
3178025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3179025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
318019cb3738Sbellard     }
318119cb3738Sbellard }
3182985a03b0Sths 
31830db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
31840db6e54aSFam Zheng {
31850db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
31860db6e54aSFam Zheng 
31870db6e54aSFam Zheng     assert(name);
31880db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
31890db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
31900db6e54aSFam Zheng             return bm;
31910db6e54aSFam Zheng         }
31920db6e54aSFam Zheng     }
31930db6e54aSFam Zheng     return NULL;
31940db6e54aSFam Zheng }
31950db6e54aSFam Zheng 
319620dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
31970db6e54aSFam Zheng {
31989bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
31990db6e54aSFam Zheng     g_free(bitmap->name);
32000db6e54aSFam Zheng     bitmap->name = NULL;
32010db6e54aSFam Zheng }
32020db6e54aSFam Zheng 
32030db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
32045fba6c0eSJohn Snow                                           uint32_t granularity,
32050db6e54aSFam Zheng                                           const char *name,
3206b8afb520SFam Zheng                                           Error **errp)
32077cd1e32aSlirans@il.ibm.com {
32087cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3209e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
32105fba6c0eSJohn Snow     uint32_t sector_granularity;
3211a55eb92cSJan Kiszka 
321250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
321350717e94SPaolo Bonzini 
32140db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
32150db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
32160db6e54aSFam Zheng         return NULL;
32170db6e54aSFam Zheng     }
32185fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
32195fba6c0eSJohn Snow     assert(sector_granularity);
322057322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3221b8afb520SFam Zheng     if (bitmap_size < 0) {
3222b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3223b8afb520SFam Zheng         errno = -bitmap_size;
3224b8afb520SFam Zheng         return NULL;
3225b8afb520SFam Zheng     }
32265839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
32275fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3228e74e6b78SJohn Snow     bitmap->size = bitmap_size;
32290db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3230b8e6fb75SJohn Snow     bitmap->disabled = false;
3231e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3232e4654d2dSFam Zheng     return bitmap;
3233e4654d2dSFam Zheng }
3234e4654d2dSFam Zheng 
32359bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
32369bd2b08fSJohn Snow {
32379bd2b08fSJohn Snow     return bitmap->successor;
32389bd2b08fSJohn Snow }
32399bd2b08fSJohn Snow 
3240b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3241b8e6fb75SJohn Snow {
32429bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
32439bd2b08fSJohn Snow }
32449bd2b08fSJohn Snow 
32459abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
32469abe3bdcSJohn Snow {
32479abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
32489abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
32499abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
32509abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
32519abe3bdcSJohn Snow     } else {
32529abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
32539abe3bdcSJohn Snow     }
32549abe3bdcSJohn Snow }
32559abe3bdcSJohn Snow 
32569bd2b08fSJohn Snow /**
32579bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
32589bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
32599bd2b08fSJohn Snow  */
32609bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
32619bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
32629bd2b08fSJohn Snow {
32639bd2b08fSJohn Snow     uint64_t granularity;
32649bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
32659bd2b08fSJohn Snow 
32669bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
32679bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
32689bd2b08fSJohn Snow                    "currently frozen");
32699bd2b08fSJohn Snow         return -1;
32709bd2b08fSJohn Snow     }
32719bd2b08fSJohn Snow     assert(!bitmap->successor);
32729bd2b08fSJohn Snow 
32739bd2b08fSJohn Snow     /* Create an anonymous successor */
32749bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
32759bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
32769bd2b08fSJohn Snow     if (!child) {
32779bd2b08fSJohn Snow         return -1;
32789bd2b08fSJohn Snow     }
32799bd2b08fSJohn Snow 
32809bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
32819bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
32829bd2b08fSJohn Snow 
32839bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
32849bd2b08fSJohn Snow     bitmap->successor = child;
32859bd2b08fSJohn Snow     return 0;
32869bd2b08fSJohn Snow }
32879bd2b08fSJohn Snow 
32889bd2b08fSJohn Snow /**
32899bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
32909bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
32919bd2b08fSJohn Snow  */
32929bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
32939bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
32949bd2b08fSJohn Snow                                             Error **errp)
32959bd2b08fSJohn Snow {
32969bd2b08fSJohn Snow     char *name;
32979bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
32989bd2b08fSJohn Snow 
32999bd2b08fSJohn Snow     if (successor == NULL) {
33009bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
33019bd2b08fSJohn Snow                    "there's no successor present");
33029bd2b08fSJohn Snow         return NULL;
33039bd2b08fSJohn Snow     }
33049bd2b08fSJohn Snow 
33059bd2b08fSJohn Snow     name = bitmap->name;
33069bd2b08fSJohn Snow     bitmap->name = NULL;
33079bd2b08fSJohn Snow     successor->name = name;
33089bd2b08fSJohn Snow     bitmap->successor = NULL;
33099bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
33109bd2b08fSJohn Snow 
33119bd2b08fSJohn Snow     return successor;
33129bd2b08fSJohn Snow }
33139bd2b08fSJohn Snow 
33149bd2b08fSJohn Snow /**
33159bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
33169bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
33179bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
33189bd2b08fSJohn Snow  */
33199bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
33209bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
33219bd2b08fSJohn Snow                                            Error **errp)
33229bd2b08fSJohn Snow {
33239bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
33249bd2b08fSJohn Snow 
33259bd2b08fSJohn Snow     if (!successor) {
33269bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
33279bd2b08fSJohn Snow         return NULL;
33289bd2b08fSJohn Snow     }
33299bd2b08fSJohn Snow 
33309bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
33319bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
33329bd2b08fSJohn Snow         return NULL;
33339bd2b08fSJohn Snow     }
33349bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
33359bd2b08fSJohn Snow     parent->successor = NULL;
33369bd2b08fSJohn Snow 
33379bd2b08fSJohn Snow     return parent;
3338b8e6fb75SJohn Snow }
3339b8e6fb75SJohn Snow 
3340ce1ffea8SJohn Snow /**
3341ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3342ce1ffea8SJohn Snow  */
3343ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3344ce1ffea8SJohn Snow {
3345ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3346ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3347ce1ffea8SJohn Snow 
3348ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
334906207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3350ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
33515270b6a0SJohn Snow         bitmap->size = size;
3352ce1ffea8SJohn Snow     }
3353ce1ffea8SJohn Snow }
3354ce1ffea8SJohn Snow 
3355e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3356e4654d2dSFam Zheng {
3357e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3358e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3359e4654d2dSFam Zheng         if (bm == bitmap) {
33609bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3361e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3362e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
33630db6e54aSFam Zheng             g_free(bitmap->name);
3364e4654d2dSFam Zheng             g_free(bitmap);
3365e4654d2dSFam Zheng             return;
33667cd1e32aSlirans@il.ibm.com         }
33677cd1e32aSlirans@il.ibm.com     }
33687cd1e32aSlirans@il.ibm.com }
33697cd1e32aSlirans@il.ibm.com 
3370b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3371b8e6fb75SJohn Snow {
33729bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3373b8e6fb75SJohn Snow     bitmap->disabled = true;
3374b8e6fb75SJohn Snow }
3375b8e6fb75SJohn Snow 
3376b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3377b8e6fb75SJohn Snow {
33789bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3379b8e6fb75SJohn Snow     bitmap->disabled = false;
3380b8e6fb75SJohn Snow }
3381b8e6fb75SJohn Snow 
338221b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
338321b56835SFam Zheng {
338421b56835SFam Zheng     BdrvDirtyBitmap *bm;
338521b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
338621b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
338721b56835SFam Zheng 
338821b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
33895839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
33905839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
339120dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3392592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
33930db6e54aSFam Zheng         info->has_name = !!bm->name;
33940db6e54aSFam Zheng         info->name = g_strdup(bm->name);
33959abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
339621b56835SFam Zheng         entry->value = info;
339721b56835SFam Zheng         *plist = entry;
339821b56835SFam Zheng         plist = &entry->next;
339921b56835SFam Zheng     }
340021b56835SFam Zheng 
340121b56835SFam Zheng     return list;
340221b56835SFam Zheng }
340321b56835SFam Zheng 
3404e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
34057cd1e32aSlirans@il.ibm.com {
3406e4654d2dSFam Zheng     if (bitmap) {
3407e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
34087cd1e32aSlirans@il.ibm.com     } else {
34097cd1e32aSlirans@il.ibm.com         return 0;
34107cd1e32aSlirans@il.ibm.com     }
34117cd1e32aSlirans@il.ibm.com }
34127cd1e32aSlirans@il.ibm.com 
3413341ebc2fSJohn Snow /**
3414341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3415341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3416341ebc2fSJohn Snow  * is no cluster size information available.
3417341ebc2fSJohn Snow  */
3418341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3419341ebc2fSJohn Snow {
3420341ebc2fSJohn Snow     BlockDriverInfo bdi;
3421341ebc2fSJohn Snow     uint32_t granularity;
3422341ebc2fSJohn Snow 
3423341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3424341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3425341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3426341ebc2fSJohn Snow     } else {
3427341ebc2fSJohn Snow         granularity = 65536;
3428341ebc2fSJohn Snow     }
3429341ebc2fSJohn Snow 
3430341ebc2fSJohn Snow     return granularity;
3431341ebc2fSJohn Snow }
3432341ebc2fSJohn Snow 
3433592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3434592fdd02SJohn Snow {
3435592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3436592fdd02SJohn Snow }
3437592fdd02SJohn Snow 
343820dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
34391755da16SPaolo Bonzini {
3440e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
34411755da16SPaolo Bonzini }
34421755da16SPaolo Bonzini 
344320dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3444c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3445c4237dfaSVladimir Sementsov-Ogievskiy {
3446b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3447c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3448c4237dfaSVladimir Sementsov-Ogievskiy }
3449c4237dfaSVladimir Sementsov-Ogievskiy 
345020dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3451c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3452c4237dfaSVladimir Sementsov-Ogievskiy {
3453b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3454c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3455c4237dfaSVladimir Sementsov-Ogievskiy }
3456c4237dfaSVladimir Sementsov-Ogievskiy 
3457df9a681dSFam Zheng void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out)
3458e74e6b78SJohn Snow {
3459e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3460df9a681dSFam Zheng     if (!out) {
3461c6a8c328SWen Congyang         hbitmap_reset_all(bitmap->bitmap);
3462df9a681dSFam Zheng     } else {
3463df9a681dSFam Zheng         HBitmap *backup = bitmap->bitmap;
3464df9a681dSFam Zheng         bitmap->bitmap = hbitmap_alloc(bitmap->size,
3465df9a681dSFam Zheng                                        hbitmap_granularity(backup));
3466df9a681dSFam Zheng         *out = backup;
3467df9a681dSFam Zheng     }
3468df9a681dSFam Zheng }
3469df9a681dSFam Zheng 
3470df9a681dSFam Zheng void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in)
3471df9a681dSFam Zheng {
3472df9a681dSFam Zheng     HBitmap *tmp = bitmap->bitmap;
3473df9a681dSFam Zheng     assert(bdrv_dirty_bitmap_enabled(bitmap));
3474df9a681dSFam Zheng     bitmap->bitmap = in;
3475df9a681dSFam Zheng     hbitmap_free(tmp);
3476e74e6b78SJohn Snow }
3477e74e6b78SJohn Snow 
3478e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
34791755da16SPaolo Bonzini                     int nr_sectors)
34801755da16SPaolo Bonzini {
3481e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3482e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3483b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3484b8e6fb75SJohn Snow             continue;
3485b8e6fb75SJohn Snow         }
3486e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3487e4654d2dSFam Zheng     }
34881755da16SPaolo Bonzini }
34891755da16SPaolo Bonzini 
3490d58d8453SJohn Snow /**
3491d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3492d58d8453SJohn Snow  */
3493d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3494d58d8453SJohn Snow {
3495d58d8453SJohn Snow     assert(hbi->hb);
3496d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3497d58d8453SJohn Snow }
3498d58d8453SJohn Snow 
349920dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3500aaa0eb75SLiran Schour {
3501e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3502aaa0eb75SLiran Schour }
3503f88e1a42SJes Sorensen 
35049fcb0251SFam Zheng /* Get a reference to bs */
35059fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
35069fcb0251SFam Zheng {
35079fcb0251SFam Zheng     bs->refcnt++;
35089fcb0251SFam Zheng }
35099fcb0251SFam Zheng 
35109fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
35119fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
35129fcb0251SFam Zheng  * deleted. */
35139fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
35149fcb0251SFam Zheng {
35159a4d5ca6SJeff Cody     if (!bs) {
35169a4d5ca6SJeff Cody         return;
35179a4d5ca6SJeff Cody     }
35189fcb0251SFam Zheng     assert(bs->refcnt > 0);
35199fcb0251SFam Zheng     if (--bs->refcnt == 0) {
35209fcb0251SFam Zheng         bdrv_delete(bs);
35219fcb0251SFam Zheng     }
35229fcb0251SFam Zheng }
35239fcb0251SFam Zheng 
3524fbe40ff7SFam Zheng struct BdrvOpBlocker {
3525fbe40ff7SFam Zheng     Error *reason;
3526fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3527fbe40ff7SFam Zheng };
3528fbe40ff7SFam Zheng 
3529fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3530fbe40ff7SFam Zheng {
3531fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3532fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3533fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3534fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3535fbe40ff7SFam Zheng         if (errp) {
353681e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
353781e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3538bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3539fbe40ff7SFam Zheng         }
3540fbe40ff7SFam Zheng         return true;
3541fbe40ff7SFam Zheng     }
3542fbe40ff7SFam Zheng     return false;
3543fbe40ff7SFam Zheng }
3544fbe40ff7SFam Zheng 
3545fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3546fbe40ff7SFam Zheng {
3547fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3548fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3549fbe40ff7SFam Zheng 
35505839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3551fbe40ff7SFam Zheng     blocker->reason = reason;
3552fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3553fbe40ff7SFam Zheng }
3554fbe40ff7SFam Zheng 
3555fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3556fbe40ff7SFam Zheng {
3557fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3558fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3559fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3560fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3561fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3562fbe40ff7SFam Zheng             g_free(blocker);
3563fbe40ff7SFam Zheng         }
3564fbe40ff7SFam Zheng     }
3565fbe40ff7SFam Zheng }
3566fbe40ff7SFam Zheng 
3567fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3568fbe40ff7SFam Zheng {
3569fbe40ff7SFam Zheng     int i;
3570fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3571fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3572fbe40ff7SFam Zheng     }
3573fbe40ff7SFam Zheng }
3574fbe40ff7SFam Zheng 
3575fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3576fbe40ff7SFam Zheng {
3577fbe40ff7SFam Zheng     int i;
3578fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3579fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3580fbe40ff7SFam Zheng     }
3581fbe40ff7SFam Zheng }
3582fbe40ff7SFam Zheng 
3583fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3584fbe40ff7SFam Zheng {
3585fbe40ff7SFam Zheng     int i;
3586fbe40ff7SFam Zheng 
3587fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3588fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3589fbe40ff7SFam Zheng             return false;
3590fbe40ff7SFam Zheng         }
3591fbe40ff7SFam Zheng     }
3592fbe40ff7SFam Zheng     return true;
3593fbe40ff7SFam Zheng }
3594fbe40ff7SFam Zheng 
3595d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3596f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3597f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3598f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3599f88e1a42SJes Sorensen {
360083d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
360183d0521aSChunyan Liu     QemuOpts *opts = NULL;
360283d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
360383d0521aSChunyan Liu     int64_t size;
3604f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3605cc84d90fSMax Reitz     Error *local_err = NULL;
3606f88e1a42SJes Sorensen     int ret = 0;
3607f88e1a42SJes Sorensen 
3608f88e1a42SJes Sorensen     /* Find driver and parse its options */
3609f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3610f88e1a42SJes Sorensen     if (!drv) {
361171c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3612d92ada22SLuiz Capitulino         return;
3613f88e1a42SJes Sorensen     }
3614f88e1a42SJes Sorensen 
3615b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3616f88e1a42SJes Sorensen     if (!proto_drv) {
3617d92ada22SLuiz Capitulino         return;
3618f88e1a42SJes Sorensen     }
3619f88e1a42SJes Sorensen 
3620c6149724SMax Reitz     if (!drv->create_opts) {
3621c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3622c6149724SMax Reitz                    drv->format_name);
3623c6149724SMax Reitz         return;
3624c6149724SMax Reitz     }
3625c6149724SMax Reitz 
3626c6149724SMax Reitz     if (!proto_drv->create_opts) {
3627c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3628c6149724SMax Reitz                    proto_drv->format_name);
3629c6149724SMax Reitz         return;
3630c6149724SMax Reitz     }
3631c6149724SMax Reitz 
3632c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3633c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3634f88e1a42SJes Sorensen 
3635f88e1a42SJes Sorensen     /* Create parameter list with default values */
363683d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
363739101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3638f88e1a42SJes Sorensen 
3639f88e1a42SJes Sorensen     /* Parse -o options */
3640f88e1a42SJes Sorensen     if (options) {
3641dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3642dc523cd3SMarkus Armbruster         if (local_err) {
3643dc523cd3SMarkus Armbruster             error_report_err(local_err);
3644dc523cd3SMarkus Armbruster             local_err = NULL;
364583d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3646f88e1a42SJes Sorensen             goto out;
3647f88e1a42SJes Sorensen         }
3648f88e1a42SJes Sorensen     }
3649f88e1a42SJes Sorensen 
3650f88e1a42SJes Sorensen     if (base_filename) {
3651f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
36526be4194bSMarkus Armbruster         if (local_err) {
365371c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
365471c79813SLuiz Capitulino                        fmt);
3655f88e1a42SJes Sorensen             goto out;
3656f88e1a42SJes Sorensen         }
3657f88e1a42SJes Sorensen     }
3658f88e1a42SJes Sorensen 
3659f88e1a42SJes Sorensen     if (base_fmt) {
3660f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
36616be4194bSMarkus Armbruster         if (local_err) {
366271c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
366371c79813SLuiz Capitulino                              "format '%s'", fmt);
3664f88e1a42SJes Sorensen             goto out;
3665f88e1a42SJes Sorensen         }
3666f88e1a42SJes Sorensen     }
3667f88e1a42SJes Sorensen 
366883d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
366983d0521aSChunyan Liu     if (backing_file) {
367083d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
367171c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
367271c79813SLuiz Capitulino                              "same filename as the backing file");
3673792da93aSJes Sorensen             goto out;
3674792da93aSJes Sorensen         }
3675792da93aSJes Sorensen     }
3676792da93aSJes Sorensen 
367783d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3678f88e1a42SJes Sorensen 
3679f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3680f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
368183d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
368283d0521aSChunyan Liu     if (size == -1) {
368383d0521aSChunyan Liu         if (backing_file) {
368466f6b814SMax Reitz             BlockDriverState *bs;
368529168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
368652bf1e72SMarkus Armbruster             int64_t size;
368763090dacSPaolo Bonzini             int back_flags;
3688e6641719SMax Reitz             QDict *backing_options = NULL;
368963090dacSPaolo Bonzini 
369029168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
369129168018SMax Reitz                                                          full_backing, PATH_MAX,
369229168018SMax Reitz                                                          &local_err);
369329168018SMax Reitz             if (local_err) {
369429168018SMax Reitz                 g_free(full_backing);
369529168018SMax Reitz                 goto out;
369629168018SMax Reitz             }
369729168018SMax Reitz 
369863090dacSPaolo Bonzini             /* backing files always opened read-only */
369963090dacSPaolo Bonzini             back_flags =
370063090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3701f88e1a42SJes Sorensen 
3702e6641719SMax Reitz             if (backing_fmt) {
3703e6641719SMax Reitz                 backing_options = qdict_new();
3704e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3705e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3706e6641719SMax Reitz             }
3707e6641719SMax Reitz 
3708f67503e5SMax Reitz             bs = NULL;
3709e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
37106ebf9aa2SMax Reitz                             back_flags, &local_err);
371129168018SMax Reitz             g_free(full_backing);
3712f88e1a42SJes Sorensen             if (ret < 0) {
3713f88e1a42SJes Sorensen                 goto out;
3714f88e1a42SJes Sorensen             }
371552bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
371652bf1e72SMarkus Armbruster             if (size < 0) {
371752bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
371852bf1e72SMarkus Armbruster                                  backing_file);
371952bf1e72SMarkus Armbruster                 bdrv_unref(bs);
372052bf1e72SMarkus Armbruster                 goto out;
372152bf1e72SMarkus Armbruster             }
3722f88e1a42SJes Sorensen 
372339101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
372466f6b814SMax Reitz 
372566f6b814SMax Reitz             bdrv_unref(bs);
3726f88e1a42SJes Sorensen         } else {
372771c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3728f88e1a42SJes Sorensen             goto out;
3729f88e1a42SJes Sorensen         }
3730f88e1a42SJes Sorensen     }
3731f88e1a42SJes Sorensen 
3732f382d43aSMiroslav Rezanina     if (!quiet) {
3733f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
373443c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3735f88e1a42SJes Sorensen         puts("");
3736f382d43aSMiroslav Rezanina     }
373783d0521aSChunyan Liu 
3738c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
373983d0521aSChunyan Liu 
3740cc84d90fSMax Reitz     if (ret == -EFBIG) {
3741cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3742cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3743cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3744f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
374583d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3746f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3747f3f4d2c0SKevin Wolf         }
3748cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3749cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3750cc84d90fSMax Reitz         error_free(local_err);
3751cc84d90fSMax Reitz         local_err = NULL;
3752f88e1a42SJes Sorensen     }
3753f88e1a42SJes Sorensen 
3754f88e1a42SJes Sorensen out:
375583d0521aSChunyan Liu     qemu_opts_del(opts);
375683d0521aSChunyan Liu     qemu_opts_free(create_opts);
375784d18f06SMarkus Armbruster     if (local_err) {
3758cc84d90fSMax Reitz         error_propagate(errp, local_err);
3759cc84d90fSMax Reitz     }
3760f88e1a42SJes Sorensen }
376185d126f3SStefan Hajnoczi 
376285d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
376385d126f3SStefan Hajnoczi {
3764dcd04228SStefan Hajnoczi     return bs->aio_context;
3765dcd04228SStefan Hajnoczi }
3766dcd04228SStefan Hajnoczi 
3767dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3768dcd04228SStefan Hajnoczi {
376933384421SMax Reitz     BdrvAioNotifier *baf;
377033384421SMax Reitz 
3771dcd04228SStefan Hajnoczi     if (!bs->drv) {
3772dcd04228SStefan Hajnoczi         return;
3773dcd04228SStefan Hajnoczi     }
3774dcd04228SStefan Hajnoczi 
377533384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
377633384421SMax Reitz         baf->detach_aio_context(baf->opaque);
377733384421SMax Reitz     }
377833384421SMax Reitz 
3779a0d64a61SAlberto Garcia     if (bs->throttle_state) {
37800e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
378113af91ebSStefan Hajnoczi     }
3782dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3783dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3784dcd04228SStefan Hajnoczi     }
3785dcd04228SStefan Hajnoczi     if (bs->file) {
37869a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3787dcd04228SStefan Hajnoczi     }
3788760e0063SKevin Wolf     if (bs->backing) {
3789760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3790dcd04228SStefan Hajnoczi     }
3791dcd04228SStefan Hajnoczi 
3792dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3793dcd04228SStefan Hajnoczi }
3794dcd04228SStefan Hajnoczi 
3795dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3796dcd04228SStefan Hajnoczi                              AioContext *new_context)
3797dcd04228SStefan Hajnoczi {
379833384421SMax Reitz     BdrvAioNotifier *ban;
379933384421SMax Reitz 
3800dcd04228SStefan Hajnoczi     if (!bs->drv) {
3801dcd04228SStefan Hajnoczi         return;
3802dcd04228SStefan Hajnoczi     }
3803dcd04228SStefan Hajnoczi 
3804dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3805dcd04228SStefan Hajnoczi 
3806760e0063SKevin Wolf     if (bs->backing) {
3807760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3808dcd04228SStefan Hajnoczi     }
3809dcd04228SStefan Hajnoczi     if (bs->file) {
38109a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3811dcd04228SStefan Hajnoczi     }
3812dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3813dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3814dcd04228SStefan Hajnoczi     }
3815a0d64a61SAlberto Garcia     if (bs->throttle_state) {
38160e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
381713af91ebSStefan Hajnoczi     }
381833384421SMax Reitz 
381933384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
382033384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
382133384421SMax Reitz     }
3822dcd04228SStefan Hajnoczi }
3823dcd04228SStefan Hajnoczi 
3824dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3825dcd04228SStefan Hajnoczi {
382653ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3827dcd04228SStefan Hajnoczi 
3828dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3829dcd04228SStefan Hajnoczi 
3830dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3831dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3832dcd04228SStefan Hajnoczi      */
3833dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3834dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3835dcd04228SStefan Hajnoczi     aio_context_release(new_context);
383685d126f3SStefan Hajnoczi }
3837d616b224SStefan Hajnoczi 
383833384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
383933384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
384033384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
384133384421SMax Reitz {
384233384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
384333384421SMax Reitz     *ban = (BdrvAioNotifier){
384433384421SMax Reitz         .attached_aio_context = attached_aio_context,
384533384421SMax Reitz         .detach_aio_context   = detach_aio_context,
384633384421SMax Reitz         .opaque               = opaque
384733384421SMax Reitz     };
384833384421SMax Reitz 
384933384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
385033384421SMax Reitz }
385133384421SMax Reitz 
385233384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
385333384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
385433384421SMax Reitz                                                                    void *),
385533384421SMax Reitz                                       void (*detach_aio_context)(void *),
385633384421SMax Reitz                                       void *opaque)
385733384421SMax Reitz {
385833384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
385933384421SMax Reitz 
386033384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
386133384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
386233384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
386333384421SMax Reitz             ban->opaque               == opaque)
386433384421SMax Reitz         {
386533384421SMax Reitz             QLIST_REMOVE(ban, list);
386633384421SMax Reitz             g_free(ban);
386733384421SMax Reitz 
386833384421SMax Reitz             return;
386933384421SMax Reitz         }
387033384421SMax Reitz     }
387133384421SMax Reitz 
387233384421SMax Reitz     abort();
387333384421SMax Reitz }
387433384421SMax Reitz 
387577485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
387677485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
38776f176b48SMax Reitz {
3878c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
38796f176b48SMax Reitz         return -ENOTSUP;
38806f176b48SMax Reitz     }
388177485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
38826f176b48SMax Reitz }
3883f6186f49SBenoît Canet 
3884b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3885b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3886b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3887b5042a36SBenoît Canet  * node graph.
3888212a5a8fSBenoît Canet  */
3889212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3890212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3891f6186f49SBenoît Canet {
3892b5042a36SBenoît Canet     /* return false if basic checks fails */
3893b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3894b5042a36SBenoît Canet         return false;
3895b5042a36SBenoît Canet     }
3896b5042a36SBenoît Canet 
3897b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3898b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3899b5042a36SBenoît Canet      */
3900b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3901b5042a36SBenoît Canet         return bs == candidate;
3902b5042a36SBenoît Canet     }
3903b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3904b5042a36SBenoît Canet 
3905b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3906b5042a36SBenoît Canet      * the node graph.
3907b5042a36SBenoît Canet      */
3908b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3909212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3910212a5a8fSBenoît Canet     }
3911212a5a8fSBenoît Canet 
3912b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3913b5042a36SBenoît Canet      */
3914b5042a36SBenoît Canet     return false;
3915212a5a8fSBenoît Canet }
3916212a5a8fSBenoît Canet 
3917212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3918212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3919212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3920212a5a8fSBenoît Canet  */
3921212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3922212a5a8fSBenoît Canet {
3923212a5a8fSBenoît Canet     BlockDriverState *bs;
3924212a5a8fSBenoît Canet 
3925212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
3926212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3927212a5a8fSBenoît Canet         bool perm;
3928212a5a8fSBenoît Canet 
3929b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3930e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3931212a5a8fSBenoît Canet 
3932212a5a8fSBenoît Canet         /* candidate is the first non filter */
3933212a5a8fSBenoît Canet         if (perm) {
3934212a5a8fSBenoît Canet             return true;
3935212a5a8fSBenoît Canet         }
3936212a5a8fSBenoît Canet     }
3937212a5a8fSBenoît Canet 
3938212a5a8fSBenoît Canet     return false;
3939f6186f49SBenoît Canet }
394009158f00SBenoît Canet 
3941e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3942e12f3784SWen Congyang                                         const char *node_name, Error **errp)
394309158f00SBenoît Canet {
394409158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
39455a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
39465a7e7a0bSStefan Hajnoczi 
394709158f00SBenoît Canet     if (!to_replace_bs) {
394809158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
394909158f00SBenoît Canet         return NULL;
395009158f00SBenoît Canet     }
395109158f00SBenoît Canet 
39525a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
39535a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
39545a7e7a0bSStefan Hajnoczi 
395509158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
39565a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
39575a7e7a0bSStefan Hajnoczi         goto out;
395809158f00SBenoît Canet     }
395909158f00SBenoît Canet 
396009158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
396109158f00SBenoît Canet      * most non filter in order to prevent data corruption.
396209158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
396309158f00SBenoît Canet      * blocked by the backing blockers.
396409158f00SBenoît Canet      */
3965e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
396609158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
39675a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
39685a7e7a0bSStefan Hajnoczi         goto out;
396909158f00SBenoît Canet     }
397009158f00SBenoît Canet 
39715a7e7a0bSStefan Hajnoczi out:
39725a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
397309158f00SBenoît Canet     return to_replace_bs;
397409158f00SBenoît Canet }
3975448ad91dSMing Lei 
397691af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
397791af7014SMax Reitz {
397891af7014SMax Reitz     const QDictEntry *entry;
39799e700c1aSKevin Wolf     QemuOptDesc *desc;
3980260fecf1SKevin Wolf     BdrvChild *child;
398191af7014SMax Reitz     bool found_any = false;
3982260fecf1SKevin Wolf     const char *p;
398391af7014SMax Reitz 
398491af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
398591af7014SMax Reitz          entry = qdict_next(bs->options, entry))
398691af7014SMax Reitz     {
3987260fecf1SKevin Wolf         /* Exclude options for children */
3988260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3989260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3990260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3991260fecf1SKevin Wolf             {
3992260fecf1SKevin Wolf                 break;
3993260fecf1SKevin Wolf             }
3994260fecf1SKevin Wolf         }
3995260fecf1SKevin Wolf         if (child) {
39969e700c1aSKevin Wolf             continue;
39979e700c1aSKevin Wolf         }
39989e700c1aSKevin Wolf 
39999e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
40009e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
40019e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
40029e700c1aSKevin Wolf                 break;
40039e700c1aSKevin Wolf             }
40049e700c1aSKevin Wolf         }
40059e700c1aSKevin Wolf         if (desc->name) {
40069e700c1aSKevin Wolf             continue;
40079e700c1aSKevin Wolf         }
40089e700c1aSKevin Wolf 
400991af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
401091af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
401191af7014SMax Reitz         found_any = true;
401291af7014SMax Reitz     }
401391af7014SMax Reitz 
401491af7014SMax Reitz     return found_any;
401591af7014SMax Reitz }
401691af7014SMax Reitz 
401791af7014SMax Reitz /* Updates the following BDS fields:
401891af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
401991af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
402091af7014SMax Reitz  *                    other options; so reading and writing must return the same
402191af7014SMax Reitz  *                    results, but caching etc. may be different)
402291af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
402391af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
402491af7014SMax Reitz  *                       equalling the given one
402591af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
402691af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
402791af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
402891af7014SMax Reitz  */
402991af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
403091af7014SMax Reitz {
403191af7014SMax Reitz     BlockDriver *drv = bs->drv;
403291af7014SMax Reitz     QDict *opts;
403391af7014SMax Reitz 
403491af7014SMax Reitz     if (!drv) {
403591af7014SMax Reitz         return;
403691af7014SMax Reitz     }
403791af7014SMax Reitz 
403891af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
403991af7014SMax Reitz      * refresh that first */
404091af7014SMax Reitz     if (bs->file) {
40419a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
404291af7014SMax Reitz     }
404391af7014SMax Reitz 
404491af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
404591af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
404691af7014SMax Reitz          * information before refreshing it */
404791af7014SMax Reitz         bs->exact_filename[0] = '\0';
404891af7014SMax Reitz         if (bs->full_open_options) {
404991af7014SMax Reitz             QDECREF(bs->full_open_options);
405091af7014SMax Reitz             bs->full_open_options = NULL;
405191af7014SMax Reitz         }
405291af7014SMax Reitz 
40534cdd01d3SKevin Wolf         opts = qdict_new();
40544cdd01d3SKevin Wolf         append_open_options(opts, bs);
40554cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
40564cdd01d3SKevin Wolf         QDECREF(opts);
405791af7014SMax Reitz     } else if (bs->file) {
405891af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
405991af7014SMax Reitz         bool has_open_options;
406091af7014SMax Reitz 
406191af7014SMax Reitz         bs->exact_filename[0] = '\0';
406291af7014SMax Reitz         if (bs->full_open_options) {
406391af7014SMax Reitz             QDECREF(bs->full_open_options);
406491af7014SMax Reitz             bs->full_open_options = NULL;
406591af7014SMax Reitz         }
406691af7014SMax Reitz 
406791af7014SMax Reitz         opts = qdict_new();
406891af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
406991af7014SMax Reitz 
407091af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
407191af7014SMax Reitz          * the underlying file should suffice for this one as well */
40729a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
40739a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
407491af7014SMax Reitz         }
407591af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
407691af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
407791af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
407891af7014SMax Reitz          * contain a representation of the filename, therefore the following
407991af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
40809a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
408191af7014SMax Reitz             qdict_put_obj(opts, "driver",
408291af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
40839a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
40849a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
40859a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
408691af7014SMax Reitz 
408791af7014SMax Reitz             bs->full_open_options = opts;
408891af7014SMax Reitz         } else {
408991af7014SMax Reitz             QDECREF(opts);
409091af7014SMax Reitz         }
409191af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
409291af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
409391af7014SMax Reitz          * so the full options QDict should be equal to the options given
409491af7014SMax Reitz          * specifically for this block device when it was opened (plus the
409591af7014SMax Reitz          * driver specification).
409691af7014SMax Reitz          * Because those options don't change, there is no need to update
409791af7014SMax Reitz          * full_open_options when it's already set. */
409891af7014SMax Reitz 
409991af7014SMax Reitz         opts = qdict_new();
410091af7014SMax Reitz         append_open_options(opts, bs);
410191af7014SMax Reitz         qdict_put_obj(opts, "driver",
410291af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
410391af7014SMax Reitz 
410491af7014SMax Reitz         if (bs->exact_filename[0]) {
410591af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
410691af7014SMax Reitz              * require this filename to be parsed), but we have to find some
410791af7014SMax Reitz              * default solution here, so just include it. If some block driver
410891af7014SMax Reitz              * does not support pure options without any filename at all or
410991af7014SMax Reitz              * needs some special format of the options QDict, it needs to
411091af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
411191af7014SMax Reitz              */
411291af7014SMax Reitz             qdict_put_obj(opts, "filename",
411391af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
411491af7014SMax Reitz         }
411591af7014SMax Reitz 
411691af7014SMax Reitz         bs->full_open_options = opts;
411791af7014SMax Reitz     }
411891af7014SMax Reitz 
411991af7014SMax Reitz     if (bs->exact_filename[0]) {
412091af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
412191af7014SMax Reitz     } else if (bs->full_open_options) {
412291af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
412391af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
412491af7014SMax Reitz                  qstring_get_str(json));
412591af7014SMax Reitz         QDECREF(json);
412691af7014SMax Reitz     }
412791af7014SMax Reitz }
4128