xref: /openbmc/qemu/block.c (revision ccf9dc07b5c8f3b927d53e9ef8c712c2973d79c7)
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 /*
6988e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
6998e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
7000b50cc88SKevin Wolf  */
7018e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
7028e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
7030b50cc88SKevin Wolf {
7048e2160e2SKevin Wolf     int flags = parent_flags;
7058e2160e2SKevin Wolf 
7060b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7070b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7080b50cc88SKevin Wolf 
7090b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
7100b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
7110b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
7120b50cc88SKevin Wolf 
7130b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
7145669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
7150b50cc88SKevin Wolf 
7168e2160e2SKevin Wolf     *child_flags = flags;
7170b50cc88SKevin Wolf }
7180b50cc88SKevin Wolf 
719f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7208e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
721f3930ed0SKevin Wolf };
722f3930ed0SKevin Wolf 
723f3930ed0SKevin Wolf /*
7248e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7258e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7268e2160e2SKevin Wolf  * flags for the parent BDS
727f3930ed0SKevin Wolf  */
7288e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7298e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
730f3930ed0SKevin Wolf {
7318e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7328e2160e2SKevin Wolf                                parent_flags, parent_options);
7338e2160e2SKevin Wolf 
7348e2160e2SKevin Wolf     *child_flags &= ~BDRV_O_PROTOCOL;
735f3930ed0SKevin Wolf }
736f3930ed0SKevin Wolf 
737f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7388e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
739f3930ed0SKevin Wolf };
740f3930ed0SKevin Wolf 
741317fc44eSKevin Wolf /*
7428e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7438e2160e2SKevin Wolf  * given options and flags for the parent BDS
744317fc44eSKevin Wolf  */
7458e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7468e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
747317fc44eSKevin Wolf {
7488e2160e2SKevin Wolf     int flags = parent_flags;
7498e2160e2SKevin Wolf 
750317fc44eSKevin Wolf     /* backing files always opened read-only */
751317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
752317fc44eSKevin Wolf 
753317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7548bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
755317fc44eSKevin Wolf 
7568e2160e2SKevin Wolf     *child_flags = flags;
757317fc44eSKevin Wolf }
758317fc44eSKevin Wolf 
759f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7608e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
761f3930ed0SKevin Wolf };
762f3930ed0SKevin Wolf 
7637b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7647b272452SKevin Wolf {
7657b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7667b272452SKevin Wolf 
7677b272452SKevin Wolf     /*
7687b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7697b272452SKevin Wolf      * image.
7707b272452SKevin Wolf      */
77120cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7727b272452SKevin Wolf 
7737b272452SKevin Wolf     /*
7747b272452SKevin Wolf      * Snapshots should be writable.
7757b272452SKevin Wolf      */
7768bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7777b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7787b272452SKevin Wolf     }
7797b272452SKevin Wolf 
7807b272452SKevin Wolf     return open_flags;
7817b272452SKevin Wolf }
7827b272452SKevin Wolf 
783636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
7846913c0c2SBenoît Canet                                   const char *node_name,
7856913c0c2SBenoît Canet                                   Error **errp)
7866913c0c2SBenoît Canet {
78715489c76SJeff Cody     char *gen_node_name = NULL;
7886913c0c2SBenoît Canet 
78915489c76SJeff Cody     if (!node_name) {
79015489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
79115489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
79215489c76SJeff Cody         /*
79315489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
79415489c76SJeff Cody          * generated (generated names use characters not available to the user)
79515489c76SJeff Cody          */
7969aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
797636ea370SKevin Wolf         return;
7986913c0c2SBenoît Canet     }
7996913c0c2SBenoît Canet 
8000c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8017f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8020c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8030c5e94eeSBenoît Canet                    node_name);
80415489c76SJeff Cody         goto out;
8050c5e94eeSBenoît Canet     }
8060c5e94eeSBenoît Canet 
8076913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8086913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8096913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
81015489c76SJeff Cody         goto out;
8116913c0c2SBenoît Canet     }
8126913c0c2SBenoît Canet 
8136913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8146913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8156913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
81615489c76SJeff Cody out:
81715489c76SJeff Cody     g_free(gen_node_name);
8186913c0c2SBenoît Canet }
8196913c0c2SBenoît Canet 
82018edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
82118edf289SKevin Wolf     .name = "bdrv_common",
82218edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
82318edf289SKevin Wolf     .desc = {
82418edf289SKevin Wolf         {
82518edf289SKevin Wolf             .name = "node-name",
82618edf289SKevin Wolf             .type = QEMU_OPT_STRING,
82718edf289SKevin Wolf             .help = "Node name of the block device node",
82818edf289SKevin Wolf         },
82962392ebbSKevin Wolf         {
83062392ebbSKevin Wolf             .name = "driver",
83162392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
83262392ebbSKevin Wolf             .help = "Block driver to use for the node",
83362392ebbSKevin Wolf         },
83418edf289SKevin Wolf         { /* end of list */ }
83518edf289SKevin Wolf     },
83618edf289SKevin Wolf };
83718edf289SKevin Wolf 
838b6ce07aaSKevin Wolf /*
83957915332SKevin Wolf  * Common part for opening disk images and files
840b6ad491aSKevin Wolf  *
841b6ad491aSKevin Wolf  * Removes all processed options from *options.
84257915332SKevin Wolf  */
8439a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
84462392ebbSKevin Wolf                             QDict *options, int flags, Error **errp)
84557915332SKevin Wolf {
84657915332SKevin Wolf     int ret, open_flags;
847035fccdfSKevin Wolf     const char *filename;
84862392ebbSKevin Wolf     const char *driver_name = NULL;
8496913c0c2SBenoît Canet     const char *node_name = NULL;
85018edf289SKevin Wolf     QemuOpts *opts;
85162392ebbSKevin Wolf     BlockDriver *drv;
85234b5d2c6SMax Reitz     Error *local_err = NULL;
85357915332SKevin Wolf 
8546405875cSPaolo Bonzini     assert(bs->file == NULL);
855707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
85657915332SKevin Wolf 
85762392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
85862392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
85962392ebbSKevin Wolf     if (local_err) {
86062392ebbSKevin Wolf         error_propagate(errp, local_err);
86162392ebbSKevin Wolf         ret = -EINVAL;
86262392ebbSKevin Wolf         goto fail_opts;
86362392ebbSKevin Wolf     }
86462392ebbSKevin Wolf 
86562392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
86662392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
86762392ebbSKevin Wolf     assert(drv != NULL);
86862392ebbSKevin Wolf 
86945673671SKevin Wolf     if (file != NULL) {
8709a4f4c31SKevin Wolf         filename = file->bs->filename;
87145673671SKevin Wolf     } else {
87245673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
87345673671SKevin Wolf     }
87445673671SKevin Wolf 
875765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
876765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
877765003dbSKevin Wolf                    drv->format_name);
87818edf289SKevin Wolf         ret = -EINVAL;
87918edf289SKevin Wolf         goto fail_opts;
88018edf289SKevin Wolf     }
88118edf289SKevin Wolf 
88262392ebbSKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
88362392ebbSKevin Wolf 
88418edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
885636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8860fb6395cSMarkus Armbruster     if (local_err) {
887636ea370SKevin Wolf         error_propagate(errp, local_err);
88818edf289SKevin Wolf         ret = -EINVAL;
88918edf289SKevin Wolf         goto fail_opts;
8905d186eb0SKevin Wolf     }
8915d186eb0SKevin Wolf 
892c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8930d51b4deSAsias He     bs->zero_beyond_eof = true;
894b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
895b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
896b64ec4e4SFam Zheng 
897b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8988f94a6e4SKevin Wolf         error_setg(errp,
8998f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9008f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9018f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9028f94a6e4SKevin Wolf                    drv->format_name);
90318edf289SKevin Wolf         ret = -ENOTSUP;
90418edf289SKevin Wolf         goto fail_opts;
905b64ec4e4SFam Zheng     }
90657915332SKevin Wolf 
90753fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
9080ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
9090ebd24e0SKevin Wolf         if (!bs->read_only) {
91053fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9110ebd24e0SKevin Wolf         } else {
9120ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
91318edf289SKevin Wolf             ret = -EINVAL;
91418edf289SKevin Wolf             goto fail_opts;
9150ebd24e0SKevin Wolf         }
91653fec9d3SStefan Hajnoczi     }
91753fec9d3SStefan Hajnoczi 
918c2ad1b0cSKevin Wolf     if (filename != NULL) {
91957915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
920c2ad1b0cSKevin Wolf     } else {
921c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
922c2ad1b0cSKevin Wolf     }
92391af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
92457915332SKevin Wolf 
92557915332SKevin Wolf     bs->drv = drv;
9267267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
92757915332SKevin Wolf 
92803f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
929e7c63796SStefan Hajnoczi 
93066f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
93166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9325d186eb0SKevin Wolf         assert(file == NULL);
933030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
93434b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
935f500a6d3SKevin Wolf     } else {
9362af5ef70SKevin Wolf         if (file == NULL) {
93734b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
93834b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9392af5ef70SKevin Wolf             ret = -EINVAL;
9402af5ef70SKevin Wolf             goto free_and_fail;
9412af5ef70SKevin Wolf         }
942f500a6d3SKevin Wolf         bs->file = file;
94334b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
94466f82ceeSKevin Wolf     }
94566f82ceeSKevin Wolf 
94657915332SKevin Wolf     if (ret < 0) {
94784d18f06SMarkus Armbruster         if (local_err) {
94834b5d2c6SMax Reitz             error_propagate(errp, local_err);
9492fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9502fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
95134b5d2c6SMax Reitz         } else {
95234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
95334b5d2c6SMax Reitz         }
95457915332SKevin Wolf         goto free_and_fail;
95557915332SKevin Wolf     }
95657915332SKevin Wolf 
957a1f688f4SMarkus Armbruster     if (bs->encrypted) {
958a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
959a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
960a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
961a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
962a1f688f4SMarkus Armbruster     }
963a1f688f4SMarkus Armbruster 
96451762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
96551762288SStefan Hajnoczi     if (ret < 0) {
96634b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
96751762288SStefan Hajnoczi         goto free_and_fail;
96857915332SKevin Wolf     }
96951762288SStefan Hajnoczi 
9703baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
9713baca891SKevin Wolf     if (local_err) {
9723baca891SKevin Wolf         error_propagate(errp, local_err);
9733baca891SKevin Wolf         ret = -EINVAL;
9743baca891SKevin Wolf         goto free_and_fail;
9753baca891SKevin Wolf     }
9763baca891SKevin Wolf 
977c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9784196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
979b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
98018edf289SKevin Wolf 
98118edf289SKevin Wolf     qemu_opts_del(opts);
98257915332SKevin Wolf     return 0;
98357915332SKevin Wolf 
98457915332SKevin Wolf free_and_fail:
98566f82ceeSKevin Wolf     bs->file = NULL;
9867267c094SAnthony Liguori     g_free(bs->opaque);
98757915332SKevin Wolf     bs->opaque = NULL;
98857915332SKevin Wolf     bs->drv = NULL;
98918edf289SKevin Wolf fail_opts:
99018edf289SKevin Wolf     qemu_opts_del(opts);
99157915332SKevin Wolf     return ret;
99257915332SKevin Wolf }
99357915332SKevin Wolf 
9945e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9955e5c4f63SKevin Wolf {
9965e5c4f63SKevin Wolf     QObject *options_obj;
9975e5c4f63SKevin Wolf     QDict *options;
9985e5c4f63SKevin Wolf     int ret;
9995e5c4f63SKevin Wolf 
10005e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10015e5c4f63SKevin Wolf     assert(ret);
10025e5c4f63SKevin Wolf 
10035e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10045e5c4f63SKevin Wolf     if (!options_obj) {
10055e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10065e5c4f63SKevin Wolf         return NULL;
10075e5c4f63SKevin Wolf     }
10085e5c4f63SKevin Wolf 
10095e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10105e5c4f63SKevin Wolf         qobject_decref(options_obj);
10115e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10125e5c4f63SKevin Wolf         return NULL;
10135e5c4f63SKevin Wolf     }
10145e5c4f63SKevin Wolf 
10155e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10165e5c4f63SKevin Wolf     qdict_flatten(options);
10175e5c4f63SKevin Wolf 
10185e5c4f63SKevin Wolf     return options;
10195e5c4f63SKevin Wolf }
10205e5c4f63SKevin Wolf 
1021de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1022de3b53f0SKevin Wolf                                 Error **errp)
1023de3b53f0SKevin Wolf {
1024de3b53f0SKevin Wolf     QDict *json_options;
1025de3b53f0SKevin Wolf     Error *local_err = NULL;
1026de3b53f0SKevin Wolf 
1027de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1028de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1029de3b53f0SKevin Wolf         return;
1030de3b53f0SKevin Wolf     }
1031de3b53f0SKevin Wolf 
1032de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1033de3b53f0SKevin Wolf     if (local_err) {
1034de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1035de3b53f0SKevin Wolf         return;
1036de3b53f0SKevin Wolf     }
1037de3b53f0SKevin Wolf 
1038de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1039de3b53f0SKevin Wolf      * specified directly */
1040de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1041de3b53f0SKevin Wolf     QDECREF(json_options);
1042de3b53f0SKevin Wolf     *pfilename = NULL;
1043de3b53f0SKevin Wolf }
1044de3b53f0SKevin Wolf 
104557915332SKevin Wolf /*
1046f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1047f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
104853a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
104953a29513SMax Reitz  * block driver has been specified explicitly.
1050f54120ffSKevin Wolf  */
1051de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1052053e1578SMax Reitz                              int *flags, Error **errp)
1053f54120ffSKevin Wolf {
1054f54120ffSKevin Wolf     const char *drvname;
105553a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1056f54120ffSKevin Wolf     bool parse_filename = false;
1057053e1578SMax Reitz     BlockDriver *drv = NULL;
1058f54120ffSKevin Wolf     Error *local_err = NULL;
1059f54120ffSKevin Wolf 
106053a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1061053e1578SMax Reitz     if (drvname) {
1062053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1063053e1578SMax Reitz         if (!drv) {
1064053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1065053e1578SMax Reitz             return -ENOENT;
1066053e1578SMax Reitz         }
106753a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
106853a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1069053e1578SMax Reitz         protocol = drv->bdrv_file_open;
107053a29513SMax Reitz     }
107153a29513SMax Reitz 
107253a29513SMax Reitz     if (protocol) {
107353a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
107453a29513SMax Reitz     } else {
107553a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
107653a29513SMax Reitz     }
107753a29513SMax Reitz 
1078f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
107917b005f1SKevin Wolf     if (protocol && filename) {
1080f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1081f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1082f54120ffSKevin Wolf             parse_filename = true;
1083f54120ffSKevin Wolf         } else {
1084f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1085f54120ffSKevin Wolf                              "the same time");
1086f54120ffSKevin Wolf             return -EINVAL;
1087f54120ffSKevin Wolf         }
1088f54120ffSKevin Wolf     }
1089f54120ffSKevin Wolf 
1090f54120ffSKevin Wolf     /* Find the right block driver */
1091f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1092f54120ffSKevin Wolf 
109317b005f1SKevin Wolf     if (!drvname && protocol) {
1094f54120ffSKevin Wolf         if (filename) {
1095b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1096f54120ffSKevin Wolf             if (!drv) {
1097f54120ffSKevin Wolf                 return -EINVAL;
1098f54120ffSKevin Wolf             }
1099f54120ffSKevin Wolf 
1100f54120ffSKevin Wolf             drvname = drv->format_name;
1101f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1102f54120ffSKevin Wolf         } else {
1103f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1104f54120ffSKevin Wolf             return -EINVAL;
1105f54120ffSKevin Wolf         }
110617b005f1SKevin Wolf     }
110717b005f1SKevin Wolf 
110817b005f1SKevin Wolf     assert(drv || !protocol);
1109f54120ffSKevin Wolf 
1110f54120ffSKevin Wolf     /* Driver-specific filename parsing */
111117b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1112f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1113f54120ffSKevin Wolf         if (local_err) {
1114f54120ffSKevin Wolf             error_propagate(errp, local_err);
1115f54120ffSKevin Wolf             return -EINVAL;
1116f54120ffSKevin Wolf         }
1117f54120ffSKevin Wolf 
1118f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1119f54120ffSKevin Wolf             qdict_del(*options, "filename");
1120f54120ffSKevin Wolf         }
1121f54120ffSKevin Wolf     }
1122f54120ffSKevin Wolf 
1123d44f928aSMax Reitz     if (runstate_check(RUN_STATE_INMIGRATE)) {
1124d44f928aSMax Reitz         *flags |= BDRV_O_INCOMING;
1125d44f928aSMax Reitz     }
1126d44f928aSMax Reitz 
1127f54120ffSKevin Wolf     return 0;
1128f54120ffSKevin Wolf }
1129f54120ffSKevin Wolf 
1130b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1131df581792SKevin Wolf                                     BlockDriverState *child_bs,
1132260fecf1SKevin Wolf                                     const char *child_name,
1133df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1134df581792SKevin Wolf {
1135df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1136df581792SKevin Wolf     *child = (BdrvChild) {
1137df581792SKevin Wolf         .bs     = child_bs,
1138260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1139df581792SKevin Wolf         .role   = child_role,
1140df581792SKevin Wolf     };
1141df581792SKevin Wolf 
1142df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1143d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1144b4b059f6SKevin Wolf 
1145b4b059f6SKevin Wolf     return child;
1146df581792SKevin Wolf }
1147df581792SKevin Wolf 
11483f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
114933a60407SKevin Wolf {
115033a60407SKevin Wolf     QLIST_REMOVE(child, next);
1151d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1152260fecf1SKevin Wolf     g_free(child->name);
115333a60407SKevin Wolf     g_free(child);
115433a60407SKevin Wolf }
115533a60407SKevin Wolf 
115633a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
115733a60407SKevin Wolf {
1158779020cbSKevin Wolf     BlockDriverState *child_bs;
1159779020cbSKevin Wolf 
1160779020cbSKevin Wolf     if (child == NULL) {
1161779020cbSKevin Wolf         return;
1162779020cbSKevin Wolf     }
116333a60407SKevin Wolf 
116433a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
116533a60407SKevin Wolf         child->bs->inherits_from = NULL;
116633a60407SKevin Wolf     }
116733a60407SKevin Wolf 
1168779020cbSKevin Wolf     child_bs = child->bs;
116933a60407SKevin Wolf     bdrv_detach_child(child);
117033a60407SKevin Wolf     bdrv_unref(child_bs);
117133a60407SKevin Wolf }
117233a60407SKevin Wolf 
11735db15a57SKevin Wolf /*
11745db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
11755db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
11765db15a57SKevin Wolf  */
11778d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11788d24cce1SFam Zheng {
11795db15a57SKevin Wolf     if (backing_hd) {
11805db15a57SKevin Wolf         bdrv_ref(backing_hd);
11815db15a57SKevin Wolf     }
11828d24cce1SFam Zheng 
1183760e0063SKevin Wolf     if (bs->backing) {
1184826b6ca0SFam Zheng         assert(bs->backing_blocker);
1185760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
11865db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1187826b6ca0SFam Zheng     } else if (backing_hd) {
1188826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
118981e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
119081e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1191826b6ca0SFam Zheng     }
1192826b6ca0SFam Zheng 
11938d24cce1SFam Zheng     if (!backing_hd) {
1194826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1195826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1196760e0063SKevin Wolf         bs->backing = NULL;
11978d24cce1SFam Zheng         goto out;
11988d24cce1SFam Zheng     }
1199260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
12008d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
12018d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
12028d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
12038d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1204826b6ca0SFam Zheng 
1205760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1206826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1207760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1208826b6ca0SFam Zheng                     bs->backing_blocker);
12098d24cce1SFam Zheng out:
12103baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
12118d24cce1SFam Zheng }
12128d24cce1SFam Zheng 
121331ca6d07SKevin Wolf /*
121431ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
121531ca6d07SKevin Wolf  *
1216d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1217d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1218d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1219d9b7b057SKevin Wolf  * BlockdevRef.
1220d9b7b057SKevin Wolf  *
1221d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
122231ca6d07SKevin Wolf  */
1223d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1224d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12259156df12SPaolo Bonzini {
12261ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1227d9b7b057SKevin Wolf     char *bdref_key_dot;
1228d9b7b057SKevin Wolf     const char *reference = NULL;
1229317fc44eSKevin Wolf     int ret = 0;
12308d24cce1SFam Zheng     BlockDriverState *backing_hd;
1231d9b7b057SKevin Wolf     QDict *options;
1232d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
123334b5d2c6SMax Reitz     Error *local_err = NULL;
12349156df12SPaolo Bonzini 
1235760e0063SKevin Wolf     if (bs->backing != NULL) {
12361ba4b6a5SBenoît Canet         goto free_exit;
12379156df12SPaolo Bonzini     }
12389156df12SPaolo Bonzini 
123931ca6d07SKevin Wolf     /* NULL means an empty set of options */
1240d9b7b057SKevin Wolf     if (parent_options == NULL) {
1241d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1242d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
124331ca6d07SKevin Wolf     }
124431ca6d07SKevin Wolf 
12459156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1246d9b7b057SKevin Wolf 
1247d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1248d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1249d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1250d9b7b057SKevin Wolf 
1251d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1252d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
12531cb6f506SKevin Wolf         backing_filename[0] = '\0';
12541cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
125531ca6d07SKevin Wolf         QDECREF(options);
12561ba4b6a5SBenoît Canet         goto free_exit;
1257dbecebddSFam Zheng     } else {
12589f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
12599f07429eSMax Reitz                                        &local_err);
12609f07429eSMax Reitz         if (local_err) {
12619f07429eSMax Reitz             ret = -EINVAL;
12629f07429eSMax Reitz             error_propagate(errp, local_err);
12639f07429eSMax Reitz             QDECREF(options);
12649f07429eSMax Reitz             goto free_exit;
12659f07429eSMax Reitz         }
12669156df12SPaolo Bonzini     }
12679156df12SPaolo Bonzini 
12688ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12698ee79e70SKevin Wolf         ret = -EINVAL;
12708ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12718ee79e70SKevin Wolf         QDECREF(options);
12728ee79e70SKevin Wolf         goto free_exit;
12738ee79e70SKevin Wolf     }
12748ee79e70SKevin Wolf 
1275c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1276c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
12779156df12SPaolo Bonzini     }
12789156df12SPaolo Bonzini 
1279d9b7b057SKevin Wolf     backing_hd = NULL;
1280f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1281f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1282d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1283d9b7b057SKevin Wolf                             &local_err);
12849156df12SPaolo Bonzini     if (ret < 0) {
12859156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1286b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1287b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1288b04b6b6eSFam Zheng         error_free(local_err);
12891ba4b6a5SBenoît Canet         goto free_exit;
12909156df12SPaolo Bonzini     }
1291df581792SKevin Wolf 
12925db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
12935db15a57SKevin Wolf      * backing_hd reference now */
12948d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
12955db15a57SKevin Wolf     bdrv_unref(backing_hd);
1296d80ac658SPeter Feiner 
1297d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1298d9b7b057SKevin Wolf 
12991ba4b6a5SBenoît Canet free_exit:
13001ba4b6a5SBenoît Canet     g_free(backing_filename);
1301d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
13021ba4b6a5SBenoît Canet     return ret;
13039156df12SPaolo Bonzini }
13049156df12SPaolo Bonzini 
1305b6ce07aaSKevin Wolf /*
1306da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1307da557aacSMax Reitz  * device's options.
1308da557aacSMax Reitz  *
1309da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1310b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1311da557aacSMax Reitz  *
1312da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1313da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1314da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1315da557aacSMax Reitz  * BlockdevRef.
1316da557aacSMax Reitz  *
1317da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1318da557aacSMax Reitz  */
1319b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1320f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1321b4b059f6SKevin Wolf                            BlockDriverState* parent,
1322b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1323f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1324da557aacSMax Reitz {
1325b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1326b4b059f6SKevin Wolf     BlockDriverState *bs;
1327da557aacSMax Reitz     QDict *image_options;
1328da557aacSMax Reitz     int ret;
1329da557aacSMax Reitz     char *bdref_key_dot;
1330da557aacSMax Reitz     const char *reference;
1331da557aacSMax Reitz 
1332df581792SKevin Wolf     assert(child_role != NULL);
1333f67503e5SMax Reitz 
1334da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1335da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1336da557aacSMax Reitz     g_free(bdref_key_dot);
1337da557aacSMax Reitz 
1338da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1339da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1340b4b059f6SKevin Wolf         if (!allow_none) {
1341da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1342da557aacSMax Reitz                        bdref_key);
1343da557aacSMax Reitz         }
1344b20e61e0SMarkus Armbruster         QDECREF(image_options);
1345da557aacSMax Reitz         goto done;
1346da557aacSMax Reitz     }
1347da557aacSMax Reitz 
1348b4b059f6SKevin Wolf     bs = NULL;
1349b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1350ce343771SMax Reitz                             parent, child_role, errp);
1351df581792SKevin Wolf     if (ret < 0) {
1352df581792SKevin Wolf         goto done;
1353df581792SKevin Wolf     }
1354df581792SKevin Wolf 
1355260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1356da557aacSMax Reitz 
1357da557aacSMax Reitz done:
1358da557aacSMax Reitz     qdict_del(options, bdref_key);
1359b4b059f6SKevin Wolf     return c;
1360b4b059f6SKevin Wolf }
1361b4b059f6SKevin Wolf 
13626b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1363b998875dSKevin Wolf {
1364b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
13651ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1366b998875dSKevin Wolf     int64_t total_size;
136783d0521aSChunyan Liu     QemuOpts *opts = NULL;
1368b998875dSKevin Wolf     QDict *snapshot_options;
1369b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1370c2e0dbbfSFam Zheng     Error *local_err = NULL;
1371b998875dSKevin Wolf     int ret;
1372b998875dSKevin Wolf 
1373b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1374b998875dSKevin Wolf        instead of opening 'filename' directly */
1375b998875dSKevin Wolf 
1376b998875dSKevin Wolf     /* Get the required size from the image */
1377f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1378f187743aSKevin Wolf     if (total_size < 0) {
13796b8aeca5SChen Gang         ret = total_size;
1380f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13811ba4b6a5SBenoît Canet         goto out;
1382f187743aSKevin Wolf     }
1383b998875dSKevin Wolf 
1384b998875dSKevin Wolf     /* Create the temporary image */
13851ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1386b998875dSKevin Wolf     if (ret < 0) {
1387b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13881ba4b6a5SBenoît Canet         goto out;
1389b998875dSKevin Wolf     }
1390b998875dSKevin Wolf 
1391ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1392c282e1fdSChunyan Liu                             &error_abort);
139339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1394ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
139583d0521aSChunyan Liu     qemu_opts_del(opts);
1396b998875dSKevin Wolf     if (ret < 0) {
1397b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1398b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1399b998875dSKevin Wolf                          error_get_pretty(local_err));
1400b998875dSKevin Wolf         error_free(local_err);
14011ba4b6a5SBenoît Canet         goto out;
1402b998875dSKevin Wolf     }
1403b998875dSKevin Wolf 
1404b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1405b998875dSKevin Wolf     snapshot_options = qdict_new();
1406b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1407b998875dSKevin Wolf               qstring_from_str("file"));
1408b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1409b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1410e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1411e6641719SMax Reitz               qstring_from_str("qcow2"));
1412b998875dSKevin Wolf 
1413e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1414b998875dSKevin Wolf 
1415b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
14166ebf9aa2SMax Reitz                     flags, &local_err);
1417b998875dSKevin Wolf     if (ret < 0) {
1418b998875dSKevin Wolf         error_propagate(errp, local_err);
14191ba4b6a5SBenoît Canet         goto out;
1420b998875dSKevin Wolf     }
1421b998875dSKevin Wolf 
1422b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14231ba4b6a5SBenoît Canet 
14241ba4b6a5SBenoît Canet out:
14251ba4b6a5SBenoît Canet     g_free(tmp_filename);
14266b8aeca5SChen Gang     return ret;
1427b998875dSKevin Wolf }
1428b998875dSKevin Wolf 
1429da557aacSMax Reitz /*
1430b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1431de9c0cecSKevin Wolf  *
1432de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1433de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1434de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1435de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1436f67503e5SMax Reitz  *
1437f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1438f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1439ddf5636dSMax Reitz  *
1440ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1441ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1442ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1443b6ce07aaSKevin Wolf  */
1444f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1445ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1446f3930ed0SKevin Wolf                              BlockDriverState *parent,
1447ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1448ea2384d3Sbellard {
1449b6ce07aaSKevin Wolf     int ret;
14509a4f4c31SKevin Wolf     BdrvChild *file = NULL;
14519a4f4c31SKevin Wolf     BlockDriverState *bs;
1452ce343771SMax Reitz     BlockDriver *drv = NULL;
145374fe54f2SKevin Wolf     const char *drvname;
14543e8c2e57SAlberto Garcia     const char *backing;
145534b5d2c6SMax Reitz     Error *local_err = NULL;
1456b1e6fc08SKevin Wolf     int snapshot_flags = 0;
145733e3963eSbellard 
1458f67503e5SMax Reitz     assert(pbs);
1459f3930ed0SKevin Wolf     assert(!child_role || !flags);
1460f3930ed0SKevin Wolf     assert(!child_role == !parent);
1461f67503e5SMax Reitz 
1462ddf5636dSMax Reitz     if (reference) {
1463ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1464ddf5636dSMax Reitz         QDECREF(options);
1465ddf5636dSMax Reitz 
1466ddf5636dSMax Reitz         if (*pbs) {
1467ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1468ddf5636dSMax Reitz                        "another block device");
1469ddf5636dSMax Reitz             return -EINVAL;
1470ddf5636dSMax Reitz         }
1471ddf5636dSMax Reitz 
1472ddf5636dSMax Reitz         if (filename || options_non_empty) {
1473ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1474ddf5636dSMax Reitz                        "additional options or a new filename");
1475ddf5636dSMax Reitz             return -EINVAL;
1476ddf5636dSMax Reitz         }
1477ddf5636dSMax Reitz 
1478ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1479ddf5636dSMax Reitz         if (!bs) {
1480ddf5636dSMax Reitz             return -ENODEV;
1481ddf5636dSMax Reitz         }
1482ddf5636dSMax Reitz         bdrv_ref(bs);
1483ddf5636dSMax Reitz         *pbs = bs;
1484ddf5636dSMax Reitz         return 0;
1485ddf5636dSMax Reitz     }
1486ddf5636dSMax Reitz 
1487f67503e5SMax Reitz     if (*pbs) {
1488f67503e5SMax Reitz         bs = *pbs;
1489f67503e5SMax Reitz     } else {
1490e4e9986bSMarkus Armbruster         bs = bdrv_new();
1491f67503e5SMax Reitz     }
1492f67503e5SMax Reitz 
1493de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1494de9c0cecSKevin Wolf     if (options == NULL) {
1495de9c0cecSKevin Wolf         options = qdict_new();
1496de9c0cecSKevin Wolf     }
1497de9c0cecSKevin Wolf 
1498145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1499de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1500de3b53f0SKevin Wolf     if (local_err) {
1501de3b53f0SKevin Wolf         ret = -EINVAL;
1502de3b53f0SKevin Wolf         goto fail;
1503de3b53f0SKevin Wolf     }
1504de3b53f0SKevin Wolf 
1505145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1506145f598eSKevin Wolf 
1507f3930ed0SKevin Wolf     if (child_role) {
1508bddcec37SKevin Wolf         bs->inherits_from = parent;
15098e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
15108e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1511f3930ed0SKevin Wolf     }
1512f3930ed0SKevin Wolf 
1513de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1514462f5bcfSKevin Wolf     if (local_err) {
1515462f5bcfSKevin Wolf         goto fail;
1516462f5bcfSKevin Wolf     }
1517462f5bcfSKevin Wolf 
151862392ebbSKevin Wolf     bs->open_flags = flags;
151962392ebbSKevin Wolf     bs->options = options;
152062392ebbSKevin Wolf     options = qdict_clone_shallow(options);
152162392ebbSKevin Wolf 
152276c591b0SKevin Wolf     /* Find the right image format driver */
152376c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
152476c591b0SKevin Wolf     if (drvname) {
152576c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
152676c591b0SKevin Wolf         if (!drv) {
152776c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
152876c591b0SKevin Wolf             ret = -EINVAL;
152976c591b0SKevin Wolf             goto fail;
153076c591b0SKevin Wolf         }
153176c591b0SKevin Wolf     }
153276c591b0SKevin Wolf 
153376c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
153476c591b0SKevin Wolf 
15353e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
15363e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
15373e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
15383e8c2e57SAlberto Garcia         qdict_del(options, "backing");
15393e8c2e57SAlberto Garcia     }
15403e8c2e57SAlberto Garcia 
1541f500a6d3SKevin Wolf     /* Open image file without format layer */
1542f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1543be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1544be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1545be028adcSJeff Cody         }
1546b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1547b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
15488e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1549b1e6fc08SKevin Wolf         }
1550be028adcSJeff Cody 
1551f3930ed0SKevin Wolf         bs->open_flags = flags;
15521fdd6933SKevin Wolf 
15539a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
15541fdd6933SKevin Wolf                                &child_file, true, &local_err);
15551fdd6933SKevin Wolf         if (local_err) {
15561fdd6933SKevin Wolf             ret = -EINVAL;
15578bfea15dSKevin Wolf             goto fail;
1558f500a6d3SKevin Wolf         }
1559f4788adcSKevin Wolf     }
1560f500a6d3SKevin Wolf 
156176c591b0SKevin Wolf     /* Image format probing */
156238f3ef57SKevin Wolf     bs->probed = !drv;
156376c591b0SKevin Wolf     if (!drv && file) {
15649a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
156517b005f1SKevin Wolf         if (ret < 0) {
156617b005f1SKevin Wolf             goto fail;
156717b005f1SKevin Wolf         }
156862392ebbSKevin Wolf         /*
156962392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
157062392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
157162392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
157262392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
157362392ebbSKevin Wolf          *
157462392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
157562392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
157662392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
157762392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
157862392ebbSKevin Wolf          */
157962392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
158062392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
158176c591b0SKevin Wolf     } else if (!drv) {
15822a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
15832a05cbe4SMax Reitz         ret = -EINVAL;
15848bfea15dSKevin Wolf         goto fail;
15852a05cbe4SMax Reitz     }
1586f500a6d3SKevin Wolf 
158753a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
158853a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
158953a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
159053a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
159153a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
159253a29513SMax Reitz 
1593b6ce07aaSKevin Wolf     /* Open the image */
159462392ebbSKevin Wolf     ret = bdrv_open_common(bs, file, options, flags, &local_err);
1595b6ce07aaSKevin Wolf     if (ret < 0) {
15968bfea15dSKevin Wolf         goto fail;
15976987307cSChristoph Hellwig     }
15986987307cSChristoph Hellwig 
15992a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16009a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1601f500a6d3SKevin Wolf         file = NULL;
1602f500a6d3SKevin Wolf     }
1603f500a6d3SKevin Wolf 
1604b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16059156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1606d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1607b6ce07aaSKevin Wolf         if (ret < 0) {
1608b6ad491aSKevin Wolf             goto close_and_fail;
1609b6ce07aaSKevin Wolf         }
1610b6ce07aaSKevin Wolf     }
1611b6ce07aaSKevin Wolf 
161291af7014SMax Reitz     bdrv_refresh_filename(bs);
161391af7014SMax Reitz 
1614b6ad491aSKevin Wolf     /* Check if any unknown options were used */
16155acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1616b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
16175acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
16185acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
16195acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
16205acd9d81SMax Reitz         } else {
162134b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
16225acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1623bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
16245acd9d81SMax Reitz         }
1625b6ad491aSKevin Wolf 
1626b6ad491aSKevin Wolf         ret = -EINVAL;
1627b6ad491aSKevin Wolf         goto close_and_fail;
1628b6ad491aSKevin Wolf     }
1629b6ad491aSKevin Wolf 
1630b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1631a7f53e26SMarkus Armbruster         if (bs->blk) {
1632a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1633a7f53e26SMarkus Armbruster         }
1634c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1635c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1636c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1637c3adb58fSMarkus Armbruster         error_setg(errp,
1638c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1639c3adb58fSMarkus Armbruster         ret = -EBUSY;
1640c3adb58fSMarkus Armbruster         goto close_and_fail;
1641b6ce07aaSKevin Wolf     }
1642b6ce07aaSKevin Wolf 
1643c3adb58fSMarkus Armbruster     QDECREF(options);
1644f67503e5SMax Reitz     *pbs = bs;
1645dd62f1caSKevin Wolf 
1646dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1647dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1648dd62f1caSKevin Wolf     if (snapshot_flags) {
1649dd62f1caSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1650dd62f1caSKevin Wolf         if (local_err) {
1651dd62f1caSKevin Wolf             goto close_and_fail;
1652dd62f1caSKevin Wolf         }
1653dd62f1caSKevin Wolf     }
1654dd62f1caSKevin Wolf 
1655b6ce07aaSKevin Wolf     return 0;
1656b6ce07aaSKevin Wolf 
16578bfea15dSKevin Wolf fail:
1658f500a6d3SKevin Wolf     if (file != NULL) {
16599a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1660f500a6d3SKevin Wolf     }
1661145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1662de9c0cecSKevin Wolf     QDECREF(bs->options);
1663b6ad491aSKevin Wolf     QDECREF(options);
1664de9c0cecSKevin Wolf     bs->options = NULL;
1665f67503e5SMax Reitz     if (!*pbs) {
1666f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1667f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1668f67503e5SMax Reitz            since it has not really been opened yet. */
1669f67503e5SMax Reitz         bdrv_unref(bs);
1670f67503e5SMax Reitz     }
167184d18f06SMarkus Armbruster     if (local_err) {
167234b5d2c6SMax Reitz         error_propagate(errp, local_err);
167334b5d2c6SMax Reitz     }
1674b6ad491aSKevin Wolf     return ret;
1675de9c0cecSKevin Wolf 
1676b6ad491aSKevin Wolf close_and_fail:
1677f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1678f67503e5SMax Reitz     if (*pbs) {
1679b6ad491aSKevin Wolf         bdrv_close(bs);
1680f67503e5SMax Reitz     } else {
1681f67503e5SMax Reitz         bdrv_unref(bs);
1682f67503e5SMax Reitz     }
1683b6ad491aSKevin Wolf     QDECREF(options);
168484d18f06SMarkus Armbruster     if (local_err) {
168534b5d2c6SMax Reitz         error_propagate(errp, local_err);
168634b5d2c6SMax Reitz     }
1687b6ce07aaSKevin Wolf     return ret;
1688b6ce07aaSKevin Wolf }
1689b6ce07aaSKevin Wolf 
1690f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
16916ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1692f3930ed0SKevin Wolf {
1693f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1694ce343771SMax Reitz                              NULL, errp);
1695f3930ed0SKevin Wolf }
1696f3930ed0SKevin Wolf 
1697e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1698e971aa12SJeff Cody      bool prepared;
1699e971aa12SJeff Cody      BDRVReopenState state;
1700e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1701e971aa12SJeff Cody } BlockReopenQueueEntry;
1702e971aa12SJeff Cody 
1703e971aa12SJeff Cody /*
1704e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1705e971aa12SJeff Cody  * reopen of multiple devices.
1706e971aa12SJeff Cody  *
1707e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1708e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1709e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1710e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1711e971aa12SJeff Cody  * atomic 'set'.
1712e971aa12SJeff Cody  *
1713e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1714e971aa12SJeff Cody  *
17154d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17164d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
17174d2cb092SKevin Wolf  *
1718e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1719e971aa12SJeff Cody  *
1720e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1721e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1722e971aa12SJeff Cody  *
1723e971aa12SJeff Cody  */
172428518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
17254d2cb092SKevin Wolf                                                  BlockDriverState *bs,
172628518102SKevin Wolf                                                  QDict *options,
172728518102SKevin Wolf                                                  int flags,
172828518102SKevin Wolf                                                  const BdrvChildRole *role,
172928518102SKevin Wolf                                                  QDict *parent_options,
173028518102SKevin Wolf                                                  int parent_flags)
1731e971aa12SJeff Cody {
1732e971aa12SJeff Cody     assert(bs != NULL);
1733e971aa12SJeff Cody 
1734e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
173567251a31SKevin Wolf     BdrvChild *child;
1736145f598eSKevin Wolf     QDict *old_options, *explicit_options;
173767251a31SKevin Wolf 
1738e971aa12SJeff Cody     if (bs_queue == NULL) {
1739e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1740e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1741e971aa12SJeff Cody     }
1742e971aa12SJeff Cody 
17434d2cb092SKevin Wolf     if (!options) {
17444d2cb092SKevin Wolf         options = qdict_new();
17454d2cb092SKevin Wolf     }
17464d2cb092SKevin Wolf 
174728518102SKevin Wolf     /*
174828518102SKevin Wolf      * Precedence of options:
174928518102SKevin Wolf      * 1. Explicitly passed in options (highest)
175028518102SKevin Wolf      * 2. TODO Set in flags (only for top level)
1751145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
17528e2160e2SKevin Wolf      * 4. Inherited from parent node
175328518102SKevin Wolf      * 5. Retained from effective options of bs
175428518102SKevin Wolf      */
175528518102SKevin Wolf 
1756145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1757145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1758145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1759145f598eSKevin Wolf     QDECREF(old_options);
1760145f598eSKevin Wolf 
1761145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1762145f598eSKevin Wolf 
176328518102SKevin Wolf     /* Inherit from parent node */
176428518102SKevin Wolf     if (parent_options) {
176528518102SKevin Wolf         assert(!flags);
17668e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
176728518102SKevin Wolf     }
176828518102SKevin Wolf 
176928518102SKevin Wolf     /* Old values are used for options that aren't set yet */
17704d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1771cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
17724d2cb092SKevin Wolf     QDECREF(old_options);
17734d2cb092SKevin Wolf 
1774f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1775f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1776f1f25a2eSKevin Wolf 
177767251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
17784c9dfe5dSKevin Wolf         QDict *new_child_options;
17794c9dfe5dSKevin Wolf         char *child_key_dot;
178067251a31SKevin Wolf 
17814c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
17824c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
17834c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
178467251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
178567251a31SKevin Wolf             continue;
178667251a31SKevin Wolf         }
178767251a31SKevin Wolf 
17884c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
17894c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
17904c9dfe5dSKevin Wolf         g_free(child_key_dot);
17914c9dfe5dSKevin Wolf 
179228518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
179328518102SKevin Wolf                                 child->role, options, flags);
1794e971aa12SJeff Cody     }
1795e971aa12SJeff Cody 
1796e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1797e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1798e971aa12SJeff Cody 
1799e971aa12SJeff Cody     bs_entry->state.bs = bs;
18004d2cb092SKevin Wolf     bs_entry->state.options = options;
1801145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1802e971aa12SJeff Cody     bs_entry->state.flags = flags;
1803e971aa12SJeff Cody 
1804e971aa12SJeff Cody     return bs_queue;
1805e971aa12SJeff Cody }
1806e971aa12SJeff Cody 
180728518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
180828518102SKevin Wolf                                     BlockDriverState *bs,
180928518102SKevin Wolf                                     QDict *options, int flags)
181028518102SKevin Wolf {
181128518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
181228518102SKevin Wolf                                    NULL, NULL, 0);
181328518102SKevin Wolf }
181428518102SKevin Wolf 
1815e971aa12SJeff Cody /*
1816e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1817e971aa12SJeff Cody  *
1818e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1819e971aa12SJeff Cody  * via bdrv_reopen_queue().
1820e971aa12SJeff Cody  *
1821e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1822e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1823e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1824e971aa12SJeff Cody  * data cleaned up.
1825e971aa12SJeff Cody  *
1826e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1827e971aa12SJeff Cody  * to all devices.
1828e971aa12SJeff Cody  *
1829e971aa12SJeff Cody  */
1830e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1831e971aa12SJeff Cody {
1832e971aa12SJeff Cody     int ret = -1;
1833e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1834e971aa12SJeff Cody     Error *local_err = NULL;
1835e971aa12SJeff Cody 
1836e971aa12SJeff Cody     assert(bs_queue != NULL);
1837e971aa12SJeff Cody 
1838e971aa12SJeff Cody     bdrv_drain_all();
1839e971aa12SJeff Cody 
1840e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1841e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1842e971aa12SJeff Cody             error_propagate(errp, local_err);
1843e971aa12SJeff Cody             goto cleanup;
1844e971aa12SJeff Cody         }
1845e971aa12SJeff Cody         bs_entry->prepared = true;
1846e971aa12SJeff Cody     }
1847e971aa12SJeff Cody 
1848e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1849e971aa12SJeff Cody      * changes
1850e971aa12SJeff Cody      */
1851e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1852e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1853e971aa12SJeff Cody     }
1854e971aa12SJeff Cody 
1855e971aa12SJeff Cody     ret = 0;
1856e971aa12SJeff Cody 
1857e971aa12SJeff Cody cleanup:
1858e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1859e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1860e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1861145f598eSKevin Wolf         } else if (ret) {
1862145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1863e971aa12SJeff Cody         }
18644d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1865e971aa12SJeff Cody         g_free(bs_entry);
1866e971aa12SJeff Cody     }
1867e971aa12SJeff Cody     g_free(bs_queue);
1868e971aa12SJeff Cody     return ret;
1869e971aa12SJeff Cody }
1870e971aa12SJeff Cody 
1871e971aa12SJeff Cody 
1872e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1873e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1874e971aa12SJeff Cody {
1875e971aa12SJeff Cody     int ret = -1;
1876e971aa12SJeff Cody     Error *local_err = NULL;
18774d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1878e971aa12SJeff Cody 
1879e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1880e971aa12SJeff Cody     if (local_err != NULL) {
1881e971aa12SJeff Cody         error_propagate(errp, local_err);
1882e971aa12SJeff Cody     }
1883e971aa12SJeff Cody     return ret;
1884e971aa12SJeff Cody }
1885e971aa12SJeff Cody 
1886e971aa12SJeff Cody 
1887e971aa12SJeff Cody /*
1888e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1889e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1890e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1891e971aa12SJeff Cody  *
1892e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1893e971aa12SJeff Cody  * flags are the new open flags
1894e971aa12SJeff Cody  * queue is the reopen queue
1895e971aa12SJeff Cody  *
1896e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1897e971aa12SJeff Cody  * as well.
1898e971aa12SJeff Cody  *
1899e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1900e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1901e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1902e971aa12SJeff Cody  *
1903e971aa12SJeff Cody  */
1904e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1905e971aa12SJeff Cody                         Error **errp)
1906e971aa12SJeff Cody {
1907e971aa12SJeff Cody     int ret = -1;
1908e971aa12SJeff Cody     Error *local_err = NULL;
1909e971aa12SJeff Cody     BlockDriver *drv;
1910*ccf9dc07SKevin Wolf     QemuOpts *opts;
1911*ccf9dc07SKevin Wolf     const char *value;
1912e971aa12SJeff Cody 
1913e971aa12SJeff Cody     assert(reopen_state != NULL);
1914e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1915e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1916e971aa12SJeff Cody 
1917*ccf9dc07SKevin Wolf     /* Process generic block layer options */
1918*ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1919*ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
1920*ccf9dc07SKevin Wolf     if (local_err) {
1921*ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
1922*ccf9dc07SKevin Wolf         ret = -EINVAL;
1923*ccf9dc07SKevin Wolf         goto error;
1924*ccf9dc07SKevin Wolf     }
1925*ccf9dc07SKevin Wolf 
1926*ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
1927*ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
1928*ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
1929*ccf9dc07SKevin Wolf     if (value) {
1930*ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
1931*ccf9dc07SKevin Wolf     }
1932*ccf9dc07SKevin Wolf 
1933*ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
1934*ccf9dc07SKevin Wolf     if (value) {
1935*ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
1936*ccf9dc07SKevin Wolf     }
1937*ccf9dc07SKevin Wolf 
1938e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1939e971aa12SJeff Cody      * to r/w */
1940e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1941e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
194281e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
194381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1944e971aa12SJeff Cody         goto error;
1945e971aa12SJeff Cody     }
1946e971aa12SJeff Cody 
1947e971aa12SJeff Cody 
1948e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1949e971aa12SJeff Cody     if (ret) {
1950455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
1951e971aa12SJeff Cody         goto error;
1952e971aa12SJeff Cody     }
1953e971aa12SJeff Cody 
1954e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1955e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1956e971aa12SJeff Cody         if (ret) {
1957e971aa12SJeff Cody             if (local_err != NULL) {
1958e971aa12SJeff Cody                 error_propagate(errp, local_err);
1959e971aa12SJeff Cody             } else {
1960d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1961e971aa12SJeff Cody                            reopen_state->bs->filename);
1962e971aa12SJeff Cody             }
1963e971aa12SJeff Cody             goto error;
1964e971aa12SJeff Cody         }
1965e971aa12SJeff Cody     } else {
1966e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1967e971aa12SJeff Cody          * handler for each supported drv. */
196881e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
196981e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
197081e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1971e971aa12SJeff Cody         ret = -1;
1972e971aa12SJeff Cody         goto error;
1973e971aa12SJeff Cody     }
1974e971aa12SJeff Cody 
19754d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
19764d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
19774d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
19784d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
19794d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
19804d2cb092SKevin Wolf 
19814d2cb092SKevin Wolf         do {
19824d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
19834d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
19844d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
19854d2cb092SKevin Wolf                                                 entry->key);
19864d2cb092SKevin Wolf 
19874d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
19884d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
19894d2cb092SKevin Wolf                 ret = -EINVAL;
19904d2cb092SKevin Wolf                 goto error;
19914d2cb092SKevin Wolf             }
19924d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
19934d2cb092SKevin Wolf     }
19944d2cb092SKevin Wolf 
1995e971aa12SJeff Cody     ret = 0;
1996e971aa12SJeff Cody 
1997e971aa12SJeff Cody error:
1998*ccf9dc07SKevin Wolf     qemu_opts_del(opts);
1999e971aa12SJeff Cody     return ret;
2000e971aa12SJeff Cody }
2001e971aa12SJeff Cody 
2002e971aa12SJeff Cody /*
2003e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2004e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2005e971aa12SJeff Cody  * the active BlockDriverState contents.
2006e971aa12SJeff Cody  */
2007e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2008e971aa12SJeff Cody {
2009e971aa12SJeff Cody     BlockDriver *drv;
2010e971aa12SJeff Cody 
2011e971aa12SJeff Cody     assert(reopen_state != NULL);
2012e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2013e971aa12SJeff Cody     assert(drv != NULL);
2014e971aa12SJeff Cody 
2015e971aa12SJeff Cody     /* If there are any driver level actions to take */
2016e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2017e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2018e971aa12SJeff Cody     }
2019e971aa12SJeff Cody 
2020e971aa12SJeff Cody     /* set BDS specific flags now */
2021145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2022145f598eSKevin Wolf 
2023145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2024e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2025e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
2026e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
2027e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2028355ef4acSKevin Wolf 
20293baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2030e971aa12SJeff Cody }
2031e971aa12SJeff Cody 
2032e971aa12SJeff Cody /*
2033e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2034e971aa12SJeff Cody  * reopen_state
2035e971aa12SJeff Cody  */
2036e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2037e971aa12SJeff Cody {
2038e971aa12SJeff Cody     BlockDriver *drv;
2039e971aa12SJeff Cody 
2040e971aa12SJeff Cody     assert(reopen_state != NULL);
2041e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2042e971aa12SJeff Cody     assert(drv != NULL);
2043e971aa12SJeff Cody 
2044e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2045e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2046e971aa12SJeff Cody     }
2047145f598eSKevin Wolf 
2048145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2049e971aa12SJeff Cody }
2050e971aa12SJeff Cody 
2051e971aa12SJeff Cody 
2052fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
2053fc01f7e7Sbellard {
205433384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
205533384421SMax Reitz 
20563e914655SPaolo Bonzini     if (bs->job) {
20573e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
20583e914655SPaolo Bonzini     }
205999b7e775SAlberto Garcia 
206099b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
2061a0d64a61SAlberto Garcia     if (bs->throttle_state) {
206299b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
206399b7e775SAlberto Garcia     }
206499b7e775SAlberto Garcia 
206553ec73e2SFam Zheng     bdrv_drain(bs); /* complete I/O */
206658fda173SStefan Hajnoczi     bdrv_flush(bs);
206753ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2068d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
20697094f12fSKevin Wolf 
2070b4d02820SMax Reitz     if (bs->blk) {
2071b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
2072b4d02820SMax Reitz     }
2073b4d02820SMax Reitz 
20743cbc002cSPaolo Bonzini     if (bs->drv) {
20756e93e7c4SKevin Wolf         BdrvChild *child, *next;
20766e93e7c4SKevin Wolf 
20779a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
20789a4f4c31SKevin Wolf         bs->drv = NULL;
20799a7dedbcSKevin Wolf 
20809a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
20819a7dedbcSKevin Wolf 
20829a4f4c31SKevin Wolf         if (bs->file != NULL) {
20839a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
20849a4f4c31SKevin Wolf             bs->file = NULL;
20859a4f4c31SKevin Wolf         }
20869a4f4c31SKevin Wolf 
20876e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
208833a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
208933a60407SKevin Wolf              * bdrv_unref_child() here */
2090bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2091bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2092bddcec37SKevin Wolf             }
209333a60407SKevin Wolf             bdrv_detach_child(child);
20946e93e7c4SKevin Wolf         }
20956e93e7c4SKevin Wolf 
20967267c094SAnthony Liguori         g_free(bs->opaque);
2097ea2384d3Sbellard         bs->opaque = NULL;
209853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2099a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2100a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
21016405875cSPaolo Bonzini         bs->total_sectors = 0;
21026405875cSPaolo Bonzini         bs->encrypted = 0;
21036405875cSPaolo Bonzini         bs->valid_key = 0;
21046405875cSPaolo Bonzini         bs->sg = 0;
21050d51b4deSAsias He         bs->zero_beyond_eof = false;
2106de9c0cecSKevin Wolf         QDECREF(bs->options);
2107145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2108de9c0cecSKevin Wolf         bs->options = NULL;
210991af7014SMax Reitz         QDECREF(bs->full_open_options);
211091af7014SMax Reitz         bs->full_open_options = NULL;
21119ca11154SPavel Hrdina     }
211266f82ceeSKevin Wolf 
211333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
211433384421SMax Reitz         g_free(ban);
211533384421SMax Reitz     }
211633384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2117b338082bSbellard }
2118b338082bSbellard 
21192bc93fedSMORITA Kazutaka void bdrv_close_all(void)
21202bc93fedSMORITA Kazutaka {
21212bc93fedSMORITA Kazutaka     BlockDriverState *bs;
21222bc93fedSMORITA Kazutaka 
2123dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2124ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2125ed78cda3SStefan Hajnoczi 
2126ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
21272bc93fedSMORITA Kazutaka         bdrv_close(bs);
2128ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
21292bc93fedSMORITA Kazutaka     }
21302bc93fedSMORITA Kazutaka }
21312bc93fedSMORITA Kazutaka 
2132dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
2133dc364f4cSBenoît Canet  * graph_bdrv_state list.
2134d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
2135d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
2136d22b2f41SRyan Harper {
2137bfb197e0SMarkus Armbruster     /*
2138bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
2139bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
2140bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
2141bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
2142bfb197e0SMarkus Armbruster      * resetting it to null on remove.
2143bfb197e0SMarkus Armbruster      */
2144bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
2145dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2146bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
2147d22b2f41SRyan Harper     }
2148dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
2149dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2150dc364f4cSBenoît Canet     }
2151dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
2152d22b2f41SRyan Harper }
2153d22b2f41SRyan Harper 
21548e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
21554ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
21564ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
21574ddc07caSPaolo Bonzini {
21584ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
21594ddc07caSPaolo Bonzini 
21604ddc07caSPaolo Bonzini     /* dev info */
21614ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
21624ddc07caSPaolo Bonzini 
21634ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
21644ddc07caSPaolo Bonzini 
2165dd62f1caSKevin Wolf     /* dirty bitmap */
2166dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2167dd62f1caSKevin Wolf }
2168dd62f1caSKevin Wolf 
2169dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2170dd62f1caSKevin Wolf                                        BlockDriverState *to)
2171dd62f1caSKevin Wolf {
2172dd62f1caSKevin Wolf     BdrvChild *c, *next;
2173dd62f1caSKevin Wolf 
2174dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2175dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2176dd62f1caSKevin Wolf         c->bs = to;
2177dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2178dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2179dd62f1caSKevin Wolf         bdrv_ref(to);
2180dd62f1caSKevin Wolf         bdrv_unref(from);
2181dd62f1caSKevin Wolf     }
2182dd62f1caSKevin Wolf     if (from->blk) {
2183dd62f1caSKevin Wolf         blk_set_bs(from->blk, to);
2184dd62f1caSKevin Wolf         if (!to->device_list.tqe_prev) {
2185dd62f1caSKevin Wolf             QTAILQ_INSERT_BEFORE(from, to, device_list);
2186dd62f1caSKevin Wolf         }
2187dd62f1caSKevin Wolf         QTAILQ_REMOVE(&bdrv_states, from, device_list);
2188dd62f1caSKevin Wolf     }
2189dd62f1caSKevin Wolf }
2190dd62f1caSKevin Wolf 
2191dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2192dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2193dd62f1caSKevin Wolf {
2194dd62f1caSKevin Wolf     BlockDriverState tmp;
2195dd62f1caSKevin Wolf 
2196dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2197dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2198dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2199dd62f1caSKevin Wolf 
2200dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2201dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2202dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2203dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2204dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2205dd62f1caSKevin Wolf     }
2206dd62f1caSKevin Wolf }
2207dd62f1caSKevin Wolf 
22088802d1fdSJeff Cody /*
22098802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
22108802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
22118802d1fdSJeff Cody  *
22128802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
22138802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
22148802d1fdSJeff Cody  *
2215bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2216f6801b83SJeff Cody  *
22178802d1fdSJeff Cody  * This function does not create any image files.
2218dd62f1caSKevin Wolf  *
2219dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2220dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2221dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2222dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
22238802d1fdSJeff Cody  */
22248802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
22258802d1fdSJeff Cody {
2226dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2227dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
22288802d1fdSJeff Cody 
2229dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2230dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2231dd62f1caSKevin Wolf 
2232dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2233dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2234dd62f1caSKevin Wolf 
2235dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2236dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2237dd62f1caSKevin Wolf 
2238dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2239dd62f1caSKevin Wolf      * additional reference any more. */
2240dd62f1caSKevin Wolf     bdrv_unref(bs_new);
22418802d1fdSJeff Cody }
22428802d1fdSJeff Cody 
22433f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
22443f09bfbcSKevin Wolf {
22453f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
22463f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
22473f09bfbcSKevin Wolf 
22483f09bfbcSKevin Wolf     bdrv_ref(old);
22493f09bfbcSKevin Wolf 
22503f09bfbcSKevin Wolf     if (old->blk) {
22513f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
22523f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
22533f09bfbcSKevin Wolf          *
22543f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
22553f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
22563f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
22573f09bfbcSKevin Wolf         assert(!new->blk);
22583f09bfbcSKevin Wolf         swap_feature_fields(old, new);
22593f09bfbcSKevin Wolf     }
22603f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
22613f09bfbcSKevin Wolf 
22623f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
22633f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
22643f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
22653f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
22663f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
22673f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
22683f09bfbcSKevin Wolf     }
22693f09bfbcSKevin Wolf 
22703f09bfbcSKevin Wolf     bdrv_unref(old);
22713f09bfbcSKevin Wolf }
22723f09bfbcSKevin Wolf 
22734f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2274b338082bSbellard {
22753e914655SPaolo Bonzini     assert(!bs->job);
22763718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
22774f6fd349SFam Zheng     assert(!bs->refcnt);
2278e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
227918846deeSMarkus Armbruster 
2280e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2281e1b5c52eSStefan Hajnoczi 
22821b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2283d22b2f41SRyan Harper     bdrv_make_anon(bs);
228434c6f050Saurel32 
22857267c094SAnthony Liguori     g_free(bs);
2286fc01f7e7Sbellard }
2287fc01f7e7Sbellard 
2288e97fc193Saliguori /*
2289e97fc193Saliguori  * Run consistency checks on an image
2290e97fc193Saliguori  *
2291e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2292a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2293e076f338SKevin Wolf  * check are stored in res.
2294e97fc193Saliguori  */
22954534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2296e97fc193Saliguori {
2297908bcd54SMax Reitz     if (bs->drv == NULL) {
2298908bcd54SMax Reitz         return -ENOMEDIUM;
2299908bcd54SMax Reitz     }
2300e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2301e97fc193Saliguori         return -ENOTSUP;
2302e97fc193Saliguori     }
2303e97fc193Saliguori 
2304e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
23054534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2306e97fc193Saliguori }
2307e97fc193Saliguori 
23088a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
23098a426614SKevin Wolf 
231033e3963eSbellard /* commit COW file into the raw image */
231133e3963eSbellard int bdrv_commit(BlockDriverState *bs)
231233e3963eSbellard {
231319cb3738Sbellard     BlockDriver *drv = bs->drv;
231472706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
23158a426614SKevin Wolf     int n, ro, open_flags;
23160bce597dSJeff Cody     int ret = 0;
231772706ea4SJeff Cody     uint8_t *buf = NULL;
231833e3963eSbellard 
231919cb3738Sbellard     if (!drv)
232019cb3738Sbellard         return -ENOMEDIUM;
232133e3963eSbellard 
2322760e0063SKevin Wolf     if (!bs->backing) {
23234dca4b63SNaphtali Sprei         return -ENOTSUP;
23244dca4b63SNaphtali Sprei     }
23254dca4b63SNaphtali Sprei 
2326bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2327760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
23282d3735d3SStefan Hajnoczi         return -EBUSY;
23292d3735d3SStefan Hajnoczi     }
23302d3735d3SStefan Hajnoczi 
2331760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2332760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
23334dca4b63SNaphtali Sprei 
23344dca4b63SNaphtali Sprei     if (ro) {
2335760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
23360bce597dSJeff Cody             return -EACCES;
23374dca4b63SNaphtali Sprei         }
2338ea2384d3Sbellard     }
2339ea2384d3Sbellard 
234072706ea4SJeff Cody     length = bdrv_getlength(bs);
234172706ea4SJeff Cody     if (length < 0) {
234272706ea4SJeff Cody         ret = length;
234372706ea4SJeff Cody         goto ro_cleanup;
234472706ea4SJeff Cody     }
234572706ea4SJeff Cody 
2346760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
234772706ea4SJeff Cody     if (backing_length < 0) {
234872706ea4SJeff Cody         ret = backing_length;
234972706ea4SJeff Cody         goto ro_cleanup;
235072706ea4SJeff Cody     }
235172706ea4SJeff Cody 
235272706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
235372706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
235472706ea4SJeff Cody      * we must return an error */
235572706ea4SJeff Cody     if (length > backing_length) {
2356760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
235772706ea4SJeff Cody         if (ret < 0) {
235872706ea4SJeff Cody             goto ro_cleanup;
235972706ea4SJeff Cody         }
236072706ea4SJeff Cody     }
236172706ea4SJeff Cody 
236272706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2363857d4f46SKevin Wolf 
2364857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2365760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2366857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2367857d4f46SKevin Wolf     if (buf == NULL) {
2368857d4f46SKevin Wolf         ret = -ENOMEM;
2369857d4f46SKevin Wolf         goto ro_cleanup;
2370857d4f46SKevin Wolf     }
23718a426614SKevin Wolf 
23728a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2373d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2374d663640cSPaolo Bonzini         if (ret < 0) {
2375d663640cSPaolo Bonzini             goto ro_cleanup;
2376d663640cSPaolo Bonzini         }
2377d663640cSPaolo Bonzini         if (ret) {
2378dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2379dabfa6ccSKevin Wolf             if (ret < 0) {
23804dca4b63SNaphtali Sprei                 goto ro_cleanup;
238133e3963eSbellard             }
238233e3963eSbellard 
2383760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2384dabfa6ccSKevin Wolf             if (ret < 0) {
23854dca4b63SNaphtali Sprei                 goto ro_cleanup;
238633e3963eSbellard             }
238733e3963eSbellard         }
238833e3963eSbellard     }
238995389c86Sbellard 
23901d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
23911d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2392dabfa6ccSKevin Wolf         if (ret < 0) {
2393dabfa6ccSKevin Wolf             goto ro_cleanup;
2394dabfa6ccSKevin Wolf         }
23951d44952fSChristoph Hellwig         bdrv_flush(bs);
23961d44952fSChristoph Hellwig     }
239795389c86Sbellard 
23983f5075aeSChristoph Hellwig     /*
23993f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24003f5075aeSChristoph Hellwig      * stable on disk.
24013f5075aeSChristoph Hellwig      */
2402760e0063SKevin Wolf     if (bs->backing) {
2403760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2404dabfa6ccSKevin Wolf     }
24054dca4b63SNaphtali Sprei 
2406dabfa6ccSKevin Wolf     ret = 0;
24074dca4b63SNaphtali Sprei ro_cleanup:
2408857d4f46SKevin Wolf     qemu_vfree(buf);
24094dca4b63SNaphtali Sprei 
24104dca4b63SNaphtali Sprei     if (ro) {
24110bce597dSJeff Cody         /* ignoring error return here */
2412760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
24134dca4b63SNaphtali Sprei     }
24144dca4b63SNaphtali Sprei 
24151d44952fSChristoph Hellwig     return ret;
241633e3963eSbellard }
241733e3963eSbellard 
2418e8877497SStefan Hajnoczi int bdrv_commit_all(void)
24196ab4b5abSMarkus Armbruster {
24206ab4b5abSMarkus Armbruster     BlockDriverState *bs;
24216ab4b5abSMarkus Armbruster 
2422dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2423ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2424ed78cda3SStefan Hajnoczi 
2425ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2426760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2427e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2428e8877497SStefan Hajnoczi             if (ret < 0) {
2429ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2430e8877497SStefan Hajnoczi                 return ret;
24316ab4b5abSMarkus Armbruster             }
24326ab4b5abSMarkus Armbruster         }
2433ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2434272d2d8eSJeff Cody     }
2435e8877497SStefan Hajnoczi     return 0;
2436e8877497SStefan Hajnoczi }
24376ab4b5abSMarkus Armbruster 
2438756e6736SKevin Wolf /*
2439756e6736SKevin Wolf  * Return values:
2440756e6736SKevin Wolf  * 0        - success
2441756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2442756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2443756e6736SKevin Wolf  *            image file header
2444756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2445756e6736SKevin Wolf  */
2446756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2447756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2448756e6736SKevin Wolf {
2449756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2450469ef350SPaolo Bonzini     int ret;
2451756e6736SKevin Wolf 
24525f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
24535f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
24545f377794SPaolo Bonzini         return -EINVAL;
24555f377794SPaolo Bonzini     }
24565f377794SPaolo Bonzini 
2457756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2458469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2459756e6736SKevin Wolf     } else {
2460469ef350SPaolo Bonzini         ret = -ENOTSUP;
2461756e6736SKevin Wolf     }
2462469ef350SPaolo Bonzini 
2463469ef350SPaolo Bonzini     if (ret == 0) {
2464469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2465469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2466469ef350SPaolo Bonzini     }
2467469ef350SPaolo Bonzini     return ret;
2468756e6736SKevin Wolf }
2469756e6736SKevin Wolf 
24706ebdcee2SJeff Cody /*
24716ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
24726ebdcee2SJeff Cody  *
24736ebdcee2SJeff Cody  * active is the current topmost image.
24746ebdcee2SJeff Cody  *
24756ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
24766ebdcee2SJeff Cody  * or if active == bs.
24774caf0fcdSJeff Cody  *
24784caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
24796ebdcee2SJeff Cody  */
24806ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
24816ebdcee2SJeff Cody                                     BlockDriverState *bs)
24826ebdcee2SJeff Cody {
2483760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2484760e0063SKevin Wolf         active = backing_bs(active);
24856ebdcee2SJeff Cody     }
24866ebdcee2SJeff Cody 
24874caf0fcdSJeff Cody     return active;
24886ebdcee2SJeff Cody }
24896ebdcee2SJeff Cody 
24904caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
24914caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
24924caf0fcdSJeff Cody {
24934caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
24946ebdcee2SJeff Cody }
24956ebdcee2SJeff Cody 
24966ebdcee2SJeff Cody /*
24976ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
24986ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
24996ebdcee2SJeff Cody  *
25006ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25016ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25026ebdcee2SJeff Cody  *
25036ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25046ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25056ebdcee2SJeff Cody  *
25066ebdcee2SJeff Cody  * to
25076ebdcee2SJeff Cody  *
25086ebdcee2SJeff Cody  * bottom <- base <- active
25096ebdcee2SJeff Cody  *
25106ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25116ebdcee2SJeff Cody  *
25126ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25136ebdcee2SJeff Cody  *
25146ebdcee2SJeff Cody  * to
25156ebdcee2SJeff Cody  *
25166ebdcee2SJeff Cody  * base <- active
25176ebdcee2SJeff Cody  *
251854e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
251954e26900SJeff Cody  * overlay image metadata.
252054e26900SJeff Cody  *
25216ebdcee2SJeff Cody  * Error conditions:
25226ebdcee2SJeff Cody  *  if active == top, that is considered an error
25236ebdcee2SJeff Cody  *
25246ebdcee2SJeff Cody  */
25256ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
252654e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
25276ebdcee2SJeff Cody {
25286ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
25296ebdcee2SJeff Cody     int ret = -EIO;
25306ebdcee2SJeff Cody 
25316ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
25326ebdcee2SJeff Cody         goto exit;
25336ebdcee2SJeff Cody     }
25346ebdcee2SJeff Cody 
25356ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
25366ebdcee2SJeff Cody 
25376ebdcee2SJeff Cody     if (new_top_bs == NULL) {
25386ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
25396ebdcee2SJeff Cody         goto exit;
25406ebdcee2SJeff Cody     }
25416ebdcee2SJeff Cody 
2542760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
25436ebdcee2SJeff Cody      * to do, no intermediate images */
2544760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
25456ebdcee2SJeff Cody         ret = 0;
25466ebdcee2SJeff Cody         goto exit;
25476ebdcee2SJeff Cody     }
25486ebdcee2SJeff Cody 
25495db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
25505db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
25516ebdcee2SJeff Cody         goto exit;
25526ebdcee2SJeff Cody     }
25536ebdcee2SJeff Cody 
25546ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
25555db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
255654e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
25575db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
25586ebdcee2SJeff Cody     if (ret) {
25596ebdcee2SJeff Cody         goto exit;
25606ebdcee2SJeff Cody     }
25615db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
25626ebdcee2SJeff Cody 
25636ebdcee2SJeff Cody     ret = 0;
25646ebdcee2SJeff Cody exit:
25656ebdcee2SJeff Cody     return ret;
25666ebdcee2SJeff Cody }
25676ebdcee2SJeff Cody 
256883f64091Sbellard /**
256983f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
257083f64091Sbellard  */
257183f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
257283f64091Sbellard {
257383f64091Sbellard     BlockDriver *drv = bs->drv;
257451762288SStefan Hajnoczi     int ret;
257583f64091Sbellard     if (!drv)
257619cb3738Sbellard         return -ENOMEDIUM;
257783f64091Sbellard     if (!drv->bdrv_truncate)
257883f64091Sbellard         return -ENOTSUP;
257959f2689dSNaphtali Sprei     if (bs->read_only)
258059f2689dSNaphtali Sprei         return -EACCES;
25819c75e168SJeff Cody 
258251762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
258351762288SStefan Hajnoczi     if (ret == 0) {
258451762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2585ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2586a7f53e26SMarkus Armbruster         if (bs->blk) {
2587a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2588a7f53e26SMarkus Armbruster         }
258951762288SStefan Hajnoczi     }
259051762288SStefan Hajnoczi     return ret;
259183f64091Sbellard }
259283f64091Sbellard 
259383f64091Sbellard /**
25944a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
25954a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
25964a1d5e1fSFam Zheng  */
25974a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
25984a1d5e1fSFam Zheng {
25994a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26004a1d5e1fSFam Zheng     if (!drv) {
26014a1d5e1fSFam Zheng         return -ENOMEDIUM;
26024a1d5e1fSFam Zheng     }
26034a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26044a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26054a1d5e1fSFam Zheng     }
26064a1d5e1fSFam Zheng     if (bs->file) {
26079a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26084a1d5e1fSFam Zheng     }
26094a1d5e1fSFam Zheng     return -ENOTSUP;
26104a1d5e1fSFam Zheng }
26114a1d5e1fSFam Zheng 
26124a1d5e1fSFam Zheng /**
261365a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
261483f64091Sbellard  */
261565a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
261683f64091Sbellard {
261783f64091Sbellard     BlockDriver *drv = bs->drv;
261865a9bb25SMarkus Armbruster 
261983f64091Sbellard     if (!drv)
262019cb3738Sbellard         return -ENOMEDIUM;
262151762288SStefan Hajnoczi 
2622b94a2610SKevin Wolf     if (drv->has_variable_length) {
2623b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2624b94a2610SKevin Wolf         if (ret < 0) {
2625b94a2610SKevin Wolf             return ret;
2626fc01f7e7Sbellard         }
262746a4e4e6SStefan Hajnoczi     }
262865a9bb25SMarkus Armbruster     return bs->total_sectors;
262965a9bb25SMarkus Armbruster }
263065a9bb25SMarkus Armbruster 
263165a9bb25SMarkus Armbruster /**
263265a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
263365a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
263465a9bb25SMarkus Armbruster  */
263565a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
263665a9bb25SMarkus Armbruster {
263765a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
263865a9bb25SMarkus Armbruster 
26394a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
264065a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
264146a4e4e6SStefan Hajnoczi }
2642fc01f7e7Sbellard 
264319cb3738Sbellard /* return 0 as number of sectors if no device present or error */
264496b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2645fc01f7e7Sbellard {
264665a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
264765a9bb25SMarkus Armbruster 
264865a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2649fc01f7e7Sbellard }
2650cf98951bSbellard 
2651b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2652b338082bSbellard {
2653b338082bSbellard     return bs->read_only;
2654b338082bSbellard }
2655b338082bSbellard 
2656985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2657985a03b0Sths {
2658985a03b0Sths     return bs->sg;
2659985a03b0Sths }
2660985a03b0Sths 
2661e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2662e900a7b7SChristoph Hellwig {
2663e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2664e900a7b7SChristoph Hellwig }
2665e900a7b7SChristoph Hellwig 
2666425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2667425b0148SPaolo Bonzini {
2668425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
266955b110f2SJeff Cody 
267055b110f2SJeff Cody     /* so a reopen() will preserve wce */
267155b110f2SJeff Cody     if (wce) {
267255b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
267355b110f2SJeff Cody     } else {
267455b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
267555b110f2SJeff Cody     }
2676425b0148SPaolo Bonzini }
2677425b0148SPaolo Bonzini 
2678ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2679ea2384d3Sbellard {
2680760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2681ea2384d3Sbellard         return 1;
2682760e0063SKevin Wolf     }
2683ea2384d3Sbellard     return bs->encrypted;
2684ea2384d3Sbellard }
2685ea2384d3Sbellard 
2686c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2687c0f4ce77Saliguori {
2688760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2689c0f4ce77Saliguori 
2690760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2691c0f4ce77Saliguori         return 1;
2692760e0063SKevin Wolf     }
2693c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2694c0f4ce77Saliguori }
2695c0f4ce77Saliguori 
2696ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2697ea2384d3Sbellard {
2698ea2384d3Sbellard     int ret;
2699760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2700760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2701ea2384d3Sbellard         if (ret < 0)
2702ea2384d3Sbellard             return ret;
2703ea2384d3Sbellard         if (!bs->encrypted)
2704ea2384d3Sbellard             return 0;
2705ea2384d3Sbellard     }
2706fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2707fd04a2aeSShahar Havivi         return -EINVAL;
2708fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2709fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2710fd04a2aeSShahar Havivi     }
2711c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2712bb5fc20fSaliguori     if (ret < 0) {
2713bb5fc20fSaliguori         bs->valid_key = 0;
2714bb5fc20fSaliguori     } else if (!bs->valid_key) {
2715bb5fc20fSaliguori         bs->valid_key = 1;
2716a7f53e26SMarkus Armbruster         if (bs->blk) {
2717bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2718a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2719a7f53e26SMarkus Armbruster         }
2720bb5fc20fSaliguori     }
2721c0f4ce77Saliguori     return ret;
2722ea2384d3Sbellard }
2723ea2384d3Sbellard 
27244d2855a3SMarkus Armbruster /*
27254d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
27264d2855a3SMarkus Armbruster  * If @key is non-null:
27274d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
27284d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
27294d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
27304d2855a3SMarkus Armbruster  * If @key is null:
27314d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
27324d2855a3SMarkus Armbruster  *     Else do nothing.
27334d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
27344d2855a3SMarkus Armbruster  */
27354d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
27364d2855a3SMarkus Armbruster {
27374d2855a3SMarkus Armbruster     if (key) {
27384d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
273981e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
274081e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
27414d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2742c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
27434d2855a3SMarkus Armbruster         }
27444d2855a3SMarkus Armbruster     } else {
27454d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2746b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2747b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
274881e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
27494d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
27504d2855a3SMarkus Armbruster         }
27514d2855a3SMarkus Armbruster     }
27524d2855a3SMarkus Armbruster }
27534d2855a3SMarkus Armbruster 
2754f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2755ea2384d3Sbellard {
2756f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2757ea2384d3Sbellard }
2758ea2384d3Sbellard 
2759ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2760ada42401SStefan Hajnoczi {
2761ada42401SStefan Hajnoczi     return strcmp(a, b);
2762ada42401SStefan Hajnoczi }
2763ada42401SStefan Hajnoczi 
2764ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2765ea2384d3Sbellard                          void *opaque)
2766ea2384d3Sbellard {
2767ea2384d3Sbellard     BlockDriver *drv;
2768e855e4fbSJeff Cody     int count = 0;
2769ada42401SStefan Hajnoczi     int i;
2770e855e4fbSJeff Cody     const char **formats = NULL;
2771ea2384d3Sbellard 
27728a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2773e855e4fbSJeff Cody         if (drv->format_name) {
2774e855e4fbSJeff Cody             bool found = false;
2775e855e4fbSJeff Cody             int i = count;
2776e855e4fbSJeff Cody             while (formats && i && !found) {
2777e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2778e855e4fbSJeff Cody             }
2779e855e4fbSJeff Cody 
2780e855e4fbSJeff Cody             if (!found) {
27815839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2782e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2783ea2384d3Sbellard             }
2784ea2384d3Sbellard         }
2785e855e4fbSJeff Cody     }
2786ada42401SStefan Hajnoczi 
2787ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2788ada42401SStefan Hajnoczi 
2789ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2790ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2791ada42401SStefan Hajnoczi     }
2792ada42401SStefan Hajnoczi 
2793e855e4fbSJeff Cody     g_free(formats);
2794e855e4fbSJeff Cody }
2795ea2384d3Sbellard 
2796dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2797dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2798dc364f4cSBenoît Canet {
2799dc364f4cSBenoît Canet     BlockDriverState *bs;
2800dc364f4cSBenoît Canet 
2801dc364f4cSBenoît Canet     assert(node_name);
2802dc364f4cSBenoît Canet 
2803dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2804dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2805dc364f4cSBenoît Canet             return bs;
2806dc364f4cSBenoît Canet         }
2807dc364f4cSBenoît Canet     }
2808dc364f4cSBenoît Canet     return NULL;
2809dc364f4cSBenoît Canet }
2810dc364f4cSBenoît Canet 
2811c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2812d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2813c13163fbSBenoît Canet {
2814c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2815c13163fbSBenoît Canet     BlockDriverState *bs;
2816c13163fbSBenoît Canet 
2817c13163fbSBenoît Canet     list = NULL;
2818c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2819d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2820d5a8ee60SAlberto Garcia         if (!info) {
2821d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2822d5a8ee60SAlberto Garcia             return NULL;
2823d5a8ee60SAlberto Garcia         }
2824c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2825d5a8ee60SAlberto Garcia         entry->value = info;
2826c13163fbSBenoît Canet         entry->next = list;
2827c13163fbSBenoît Canet         list = entry;
2828c13163fbSBenoît Canet     }
2829c13163fbSBenoît Canet 
2830c13163fbSBenoît Canet     return list;
2831c13163fbSBenoît Canet }
2832c13163fbSBenoît Canet 
283312d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
283412d3ba82SBenoît Canet                                  const char *node_name,
283512d3ba82SBenoît Canet                                  Error **errp)
283612d3ba82SBenoît Canet {
28377f06d47eSMarkus Armbruster     BlockBackend *blk;
28387f06d47eSMarkus Armbruster     BlockDriverState *bs;
283912d3ba82SBenoît Canet 
284012d3ba82SBenoît Canet     if (device) {
28417f06d47eSMarkus Armbruster         blk = blk_by_name(device);
284212d3ba82SBenoît Canet 
28437f06d47eSMarkus Armbruster         if (blk) {
28449f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
28459f4ed6fbSAlberto Garcia             if (!bs) {
28465433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
28475433c24fSMax Reitz             }
28485433c24fSMax Reitz 
28499f4ed6fbSAlberto Garcia             return bs;
285012d3ba82SBenoît Canet         }
2851dd67fa50SBenoît Canet     }
285212d3ba82SBenoît Canet 
2853dd67fa50SBenoît Canet     if (node_name) {
285412d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
285512d3ba82SBenoît Canet 
2856dd67fa50SBenoît Canet         if (bs) {
2857dd67fa50SBenoît Canet             return bs;
2858dd67fa50SBenoît Canet         }
285912d3ba82SBenoît Canet     }
286012d3ba82SBenoît Canet 
2861dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2862dd67fa50SBenoît Canet                      device ? device : "",
2863dd67fa50SBenoît Canet                      node_name ? node_name : "");
2864dd67fa50SBenoît Canet     return NULL;
286512d3ba82SBenoît Canet }
286612d3ba82SBenoît Canet 
28675a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
28685a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
28695a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
28705a6684d2SJeff Cody {
28715a6684d2SJeff Cody     while (top && top != base) {
2872760e0063SKevin Wolf         top = backing_bs(top);
28735a6684d2SJeff Cody     }
28745a6684d2SJeff Cody 
28755a6684d2SJeff Cody     return top != NULL;
28765a6684d2SJeff Cody }
28775a6684d2SJeff Cody 
287804df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
287904df765aSFam Zheng {
288004df765aSFam Zheng     if (!bs) {
288104df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
288204df765aSFam Zheng     }
288304df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
288404df765aSFam Zheng }
288504df765aSFam Zheng 
28862f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
28872f399b0aSMarkus Armbruster {
28882f399b0aSMarkus Armbruster     if (!bs) {
28892f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
28902f399b0aSMarkus Armbruster     }
2891dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
28922f399b0aSMarkus Armbruster }
28932f399b0aSMarkus Armbruster 
289420a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
289520a9e77dSFam Zheng {
289620a9e77dSFam Zheng     return bs->node_name;
289720a9e77dSFam Zheng }
289820a9e77dSFam Zheng 
28997f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2900bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2901ea2384d3Sbellard {
2902bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2903ea2384d3Sbellard }
2904ea2384d3Sbellard 
29059b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29069b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29079b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29089b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29099b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29109b2aa84fSAlberto Garcia {
29119b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
29129b2aa84fSAlberto Garcia }
29139b2aa84fSAlberto Garcia 
2914c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2915c8433287SMarkus Armbruster {
2916c8433287SMarkus Armbruster     return bs->open_flags;
2917c8433287SMarkus Armbruster }
2918c8433287SMarkus Armbruster 
29193ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
29203ac21627SPeter Lieven {
29213ac21627SPeter Lieven     return 1;
29223ac21627SPeter Lieven }
29233ac21627SPeter Lieven 
2924f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2925f2feebbdSKevin Wolf {
2926f2feebbdSKevin Wolf     assert(bs->drv);
2927f2feebbdSKevin Wolf 
292811212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
292911212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2930760e0063SKevin Wolf     if (bs->backing) {
293111212d8fSPaolo Bonzini         return 0;
293211212d8fSPaolo Bonzini     }
2933336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2934336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2935f2feebbdSKevin Wolf     }
2936f2feebbdSKevin Wolf 
29373ac21627SPeter Lieven     /* safe default */
29383ac21627SPeter Lieven     return 0;
2939f2feebbdSKevin Wolf }
2940f2feebbdSKevin Wolf 
29414ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
29424ce78691SPeter Lieven {
29434ce78691SPeter Lieven     BlockDriverInfo bdi;
29444ce78691SPeter Lieven 
2945760e0063SKevin Wolf     if (bs->backing) {
29464ce78691SPeter Lieven         return false;
29474ce78691SPeter Lieven     }
29484ce78691SPeter Lieven 
29494ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29504ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
29514ce78691SPeter Lieven     }
29524ce78691SPeter Lieven 
29534ce78691SPeter Lieven     return false;
29544ce78691SPeter Lieven }
29554ce78691SPeter Lieven 
29564ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
29574ce78691SPeter Lieven {
29584ce78691SPeter Lieven     BlockDriverInfo bdi;
29594ce78691SPeter Lieven 
2960760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
29614ce78691SPeter Lieven         return false;
29624ce78691SPeter Lieven     }
29634ce78691SPeter Lieven 
29644ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29654ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
29664ce78691SPeter Lieven     }
29674ce78691SPeter Lieven 
29684ce78691SPeter Lieven     return false;
29694ce78691SPeter Lieven }
29704ce78691SPeter Lieven 
2971045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2972045df330Saliguori {
2973760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2974045df330Saliguori         return bs->backing_file;
2975045df330Saliguori     else if (bs->encrypted)
2976045df330Saliguori         return bs->filename;
2977045df330Saliguori     else
2978045df330Saliguori         return NULL;
2979045df330Saliguori }
2980045df330Saliguori 
298183f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
298283f64091Sbellard                                char *filename, int filename_size)
298383f64091Sbellard {
298483f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
298583f64091Sbellard }
298683f64091Sbellard 
2987faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2988faea38e7Sbellard {
2989faea38e7Sbellard     BlockDriver *drv = bs->drv;
2990faea38e7Sbellard     if (!drv)
299119cb3738Sbellard         return -ENOMEDIUM;
2992faea38e7Sbellard     if (!drv->bdrv_get_info)
2993faea38e7Sbellard         return -ENOTSUP;
2994faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2995faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2996faea38e7Sbellard }
2997faea38e7Sbellard 
2998eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2999eae041feSMax Reitz {
3000eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3001eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3002eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3003eae041feSMax Reitz     }
3004eae041feSMax Reitz     return NULL;
3005eae041feSMax Reitz }
3006eae041feSMax Reitz 
3007a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
30088b9b0cc2SKevin Wolf {
3009bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30108b9b0cc2SKevin Wolf         return;
30118b9b0cc2SKevin Wolf     }
30128b9b0cc2SKevin Wolf 
3013bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
301441c695c7SKevin Wolf }
30158b9b0cc2SKevin Wolf 
301641c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
301741c695c7SKevin Wolf                           const char *tag)
301841c695c7SKevin Wolf {
301941c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
30209a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
302141c695c7SKevin Wolf     }
302241c695c7SKevin Wolf 
302341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
302441c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
302541c695c7SKevin Wolf     }
302641c695c7SKevin Wolf 
302741c695c7SKevin Wolf     return -ENOTSUP;
302841c695c7SKevin Wolf }
302941c695c7SKevin Wolf 
30304cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
30314cc70e93SFam Zheng {
30324cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
30339a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
30344cc70e93SFam Zheng     }
30354cc70e93SFam Zheng 
30364cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
30374cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
30384cc70e93SFam Zheng     }
30394cc70e93SFam Zheng 
30404cc70e93SFam Zheng     return -ENOTSUP;
30414cc70e93SFam Zheng }
30424cc70e93SFam Zheng 
304341c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
304441c695c7SKevin Wolf {
3045938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
30469a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
304741c695c7SKevin Wolf     }
304841c695c7SKevin Wolf 
304941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
305041c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
305141c695c7SKevin Wolf     }
305241c695c7SKevin Wolf 
305341c695c7SKevin Wolf     return -ENOTSUP;
305441c695c7SKevin Wolf }
305541c695c7SKevin Wolf 
305641c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
305741c695c7SKevin Wolf {
305841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
30599a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
306041c695c7SKevin Wolf     }
306141c695c7SKevin Wolf 
306241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
306341c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
306441c695c7SKevin Wolf     }
306541c695c7SKevin Wolf 
306641c695c7SKevin Wolf     return false;
30678b9b0cc2SKevin Wolf }
30688b9b0cc2SKevin Wolf 
3069199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3070199630b6SBlue Swirl {
3071199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3072199630b6SBlue Swirl }
3073199630b6SBlue Swirl 
3074b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3075b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3076b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3077b1b1d783SJeff Cody  * the CWD rather than the chain. */
3078e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3079e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3080e8a6bb9cSMarcelo Tosatti {
3081b1b1d783SJeff Cody     char *filename_full = NULL;
3082b1b1d783SJeff Cody     char *backing_file_full = NULL;
3083b1b1d783SJeff Cody     char *filename_tmp = NULL;
3084b1b1d783SJeff Cody     int is_protocol = 0;
3085b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3086b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3087b1b1d783SJeff Cody 
3088b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3089e8a6bb9cSMarcelo Tosatti         return NULL;
3090e8a6bb9cSMarcelo Tosatti     }
3091e8a6bb9cSMarcelo Tosatti 
3092b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3093b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3094b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3095b1b1d783SJeff Cody 
3096b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3097b1b1d783SJeff Cody 
3098760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3099b1b1d783SJeff Cody 
3100b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3101b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3102b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3103b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3104760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3105b1b1d783SJeff Cody                 break;
3106b1b1d783SJeff Cody             }
3107e8a6bb9cSMarcelo Tosatti         } else {
3108b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3109b1b1d783SJeff Cody              * image's filename path */
3110b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3111b1b1d783SJeff Cody                          backing_file);
3112b1b1d783SJeff Cody 
3113b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3114b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3115b1b1d783SJeff Cody                 continue;
3116b1b1d783SJeff Cody             }
3117b1b1d783SJeff Cody 
3118b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3119b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3120b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3121b1b1d783SJeff Cody                          curr_bs->backing_file);
3122b1b1d783SJeff Cody 
3123b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3124b1b1d783SJeff Cody                 continue;
3125b1b1d783SJeff Cody             }
3126b1b1d783SJeff Cody 
3127b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3128760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3129b1b1d783SJeff Cody                 break;
3130b1b1d783SJeff Cody             }
3131e8a6bb9cSMarcelo Tosatti         }
3132e8a6bb9cSMarcelo Tosatti     }
3133e8a6bb9cSMarcelo Tosatti 
3134b1b1d783SJeff Cody     g_free(filename_full);
3135b1b1d783SJeff Cody     g_free(backing_file_full);
3136b1b1d783SJeff Cody     g_free(filename_tmp);
3137b1b1d783SJeff Cody     return retval;
3138e8a6bb9cSMarcelo Tosatti }
3139e8a6bb9cSMarcelo Tosatti 
3140f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3141f198fd1cSBenoît Canet {
3142f198fd1cSBenoît Canet     if (!bs->drv) {
3143f198fd1cSBenoît Canet         return 0;
3144f198fd1cSBenoît Canet     }
3145f198fd1cSBenoît Canet 
3146760e0063SKevin Wolf     if (!bs->backing) {
3147f198fd1cSBenoît Canet         return 0;
3148f198fd1cSBenoît Canet     }
3149f198fd1cSBenoît Canet 
3150760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3151f198fd1cSBenoît Canet }
3152f198fd1cSBenoît Canet 
3153ea2384d3Sbellard void bdrv_init(void)
3154ea2384d3Sbellard {
31555efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3156ea2384d3Sbellard }
3157ce1a14dcSpbrook 
3158eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3159eb852011SMarkus Armbruster {
3160eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3161eb852011SMarkus Armbruster     bdrv_init();
3162eb852011SMarkus Armbruster }
3163eb852011SMarkus Armbruster 
31645a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
31650f15423cSAnthony Liguori {
31665a8a30dbSKevin Wolf     Error *local_err = NULL;
31675a8a30dbSKevin Wolf     int ret;
31685a8a30dbSKevin Wolf 
31693456a8d1SKevin Wolf     if (!bs->drv)  {
31703456a8d1SKevin Wolf         return;
31710f15423cSAnthony Liguori     }
31723456a8d1SKevin Wolf 
31737ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
31747ea2d269SAlexey Kardashevskiy         return;
31757ea2d269SAlexey Kardashevskiy     }
31767ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
31777ea2d269SAlexey Kardashevskiy 
31783456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
31795a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
31803456a8d1SKevin Wolf     } else if (bs->file) {
31819a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
31825a8a30dbSKevin Wolf     }
31835a8a30dbSKevin Wolf     if (local_err) {
31845a8a30dbSKevin Wolf         error_propagate(errp, local_err);
31855a8a30dbSKevin Wolf         return;
31863456a8d1SKevin Wolf     }
31873456a8d1SKevin Wolf 
31885a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
31895a8a30dbSKevin Wolf     if (ret < 0) {
31905a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
31915a8a30dbSKevin Wolf         return;
31925a8a30dbSKevin Wolf     }
31930f15423cSAnthony Liguori }
31940f15423cSAnthony Liguori 
31955a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
31960f15423cSAnthony Liguori {
31970f15423cSAnthony Liguori     BlockDriverState *bs;
31985a8a30dbSKevin Wolf     Error *local_err = NULL;
31990f15423cSAnthony Liguori 
3200dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3201ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3202ed78cda3SStefan Hajnoczi 
3203ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32045a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3205ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32065a8a30dbSKevin Wolf         if (local_err) {
32075a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32085a8a30dbSKevin Wolf             return;
32095a8a30dbSKevin Wolf         }
32100f15423cSAnthony Liguori     }
32110f15423cSAnthony Liguori }
32120f15423cSAnthony Liguori 
3213f9f05dc5SKevin Wolf /**************************************************************/
321419cb3738Sbellard /* removable device support */
321519cb3738Sbellard 
321619cb3738Sbellard /**
321719cb3738Sbellard  * Return TRUE if the media is present
321819cb3738Sbellard  */
3219e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
322019cb3738Sbellard {
322119cb3738Sbellard     BlockDriver *drv = bs->drv;
322228d7a789SMax Reitz     BdrvChild *child;
3223a1aff5bfSMarkus Armbruster 
3224e031f750SMax Reitz     if (!drv) {
3225e031f750SMax Reitz         return false;
3226e031f750SMax Reitz     }
322728d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3228a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
322919cb3738Sbellard     }
323028d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
323128d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
323228d7a789SMax Reitz             return false;
323328d7a789SMax Reitz         }
323428d7a789SMax Reitz     }
323528d7a789SMax Reitz     return true;
323628d7a789SMax Reitz }
323719cb3738Sbellard 
323819cb3738Sbellard /**
32398e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
32408e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
324119cb3738Sbellard  */
324219cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
324319cb3738Sbellard {
324419cb3738Sbellard     BlockDriver *drv = bs->drv;
324519cb3738Sbellard 
32468e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
32478e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
32488e49ca46SMarkus Armbruster     }
32498e49ca46SMarkus Armbruster     return -ENOTSUP;
325019cb3738Sbellard }
325119cb3738Sbellard 
325219cb3738Sbellard /**
325319cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
325419cb3738Sbellard  */
3255f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
325619cb3738Sbellard {
325719cb3738Sbellard     BlockDriver *drv = bs->drv;
3258bfb197e0SMarkus Armbruster     const char *device_name;
325919cb3738Sbellard 
3260822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3261822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
326219cb3738Sbellard     }
32636f382ed2SLuiz Capitulino 
3264bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3265bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3266bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3267a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
32686f382ed2SLuiz Capitulino     }
326919cb3738Sbellard }
327019cb3738Sbellard 
327119cb3738Sbellard /**
327219cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
327319cb3738Sbellard  * to eject it manually).
327419cb3738Sbellard  */
3275025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
327619cb3738Sbellard {
327719cb3738Sbellard     BlockDriver *drv = bs->drv;
327819cb3738Sbellard 
3279025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3280b8c6d095SStefan Hajnoczi 
3281025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3282025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
328319cb3738Sbellard     }
328419cb3738Sbellard }
3285985a03b0Sths 
32860db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
32870db6e54aSFam Zheng {
32880db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
32890db6e54aSFam Zheng 
32900db6e54aSFam Zheng     assert(name);
32910db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
32920db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
32930db6e54aSFam Zheng             return bm;
32940db6e54aSFam Zheng         }
32950db6e54aSFam Zheng     }
32960db6e54aSFam Zheng     return NULL;
32970db6e54aSFam Zheng }
32980db6e54aSFam Zheng 
329920dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
33000db6e54aSFam Zheng {
33019bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
33020db6e54aSFam Zheng     g_free(bitmap->name);
33030db6e54aSFam Zheng     bitmap->name = NULL;
33040db6e54aSFam Zheng }
33050db6e54aSFam Zheng 
33060db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
33075fba6c0eSJohn Snow                                           uint32_t granularity,
33080db6e54aSFam Zheng                                           const char *name,
3309b8afb520SFam Zheng                                           Error **errp)
33107cd1e32aSlirans@il.ibm.com {
33117cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3312e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
33135fba6c0eSJohn Snow     uint32_t sector_granularity;
3314a55eb92cSJan Kiszka 
331550717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
331650717e94SPaolo Bonzini 
33170db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
33180db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
33190db6e54aSFam Zheng         return NULL;
33200db6e54aSFam Zheng     }
33215fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
33225fba6c0eSJohn Snow     assert(sector_granularity);
332357322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3324b8afb520SFam Zheng     if (bitmap_size < 0) {
3325b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3326b8afb520SFam Zheng         errno = -bitmap_size;
3327b8afb520SFam Zheng         return NULL;
3328b8afb520SFam Zheng     }
33295839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
33305fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3331e74e6b78SJohn Snow     bitmap->size = bitmap_size;
33320db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3333b8e6fb75SJohn Snow     bitmap->disabled = false;
3334e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3335e4654d2dSFam Zheng     return bitmap;
3336e4654d2dSFam Zheng }
3337e4654d2dSFam Zheng 
33389bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
33399bd2b08fSJohn Snow {
33409bd2b08fSJohn Snow     return bitmap->successor;
33419bd2b08fSJohn Snow }
33429bd2b08fSJohn Snow 
3343b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3344b8e6fb75SJohn Snow {
33459bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
33469bd2b08fSJohn Snow }
33479bd2b08fSJohn Snow 
33489abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
33499abe3bdcSJohn Snow {
33509abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
33519abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
33529abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
33539abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
33549abe3bdcSJohn Snow     } else {
33559abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
33569abe3bdcSJohn Snow     }
33579abe3bdcSJohn Snow }
33589abe3bdcSJohn Snow 
33599bd2b08fSJohn Snow /**
33609bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
33619bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
33629bd2b08fSJohn Snow  */
33639bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
33649bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
33659bd2b08fSJohn Snow {
33669bd2b08fSJohn Snow     uint64_t granularity;
33679bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
33689bd2b08fSJohn Snow 
33699bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
33709bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
33719bd2b08fSJohn Snow                    "currently frozen");
33729bd2b08fSJohn Snow         return -1;
33739bd2b08fSJohn Snow     }
33749bd2b08fSJohn Snow     assert(!bitmap->successor);
33759bd2b08fSJohn Snow 
33769bd2b08fSJohn Snow     /* Create an anonymous successor */
33779bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
33789bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
33799bd2b08fSJohn Snow     if (!child) {
33809bd2b08fSJohn Snow         return -1;
33819bd2b08fSJohn Snow     }
33829bd2b08fSJohn Snow 
33839bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
33849bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
33859bd2b08fSJohn Snow 
33869bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
33879bd2b08fSJohn Snow     bitmap->successor = child;
33889bd2b08fSJohn Snow     return 0;
33899bd2b08fSJohn Snow }
33909bd2b08fSJohn Snow 
33919bd2b08fSJohn Snow /**
33929bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
33939bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
33949bd2b08fSJohn Snow  */
33959bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
33969bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
33979bd2b08fSJohn Snow                                             Error **errp)
33989bd2b08fSJohn Snow {
33999bd2b08fSJohn Snow     char *name;
34009bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
34019bd2b08fSJohn Snow 
34029bd2b08fSJohn Snow     if (successor == NULL) {
34039bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
34049bd2b08fSJohn Snow                    "there's no successor present");
34059bd2b08fSJohn Snow         return NULL;
34069bd2b08fSJohn Snow     }
34079bd2b08fSJohn Snow 
34089bd2b08fSJohn Snow     name = bitmap->name;
34099bd2b08fSJohn Snow     bitmap->name = NULL;
34109bd2b08fSJohn Snow     successor->name = name;
34119bd2b08fSJohn Snow     bitmap->successor = NULL;
34129bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
34139bd2b08fSJohn Snow 
34149bd2b08fSJohn Snow     return successor;
34159bd2b08fSJohn Snow }
34169bd2b08fSJohn Snow 
34179bd2b08fSJohn Snow /**
34189bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
34199bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
34209bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
34219bd2b08fSJohn Snow  */
34229bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
34239bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
34249bd2b08fSJohn Snow                                            Error **errp)
34259bd2b08fSJohn Snow {
34269bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
34279bd2b08fSJohn Snow 
34289bd2b08fSJohn Snow     if (!successor) {
34299bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
34309bd2b08fSJohn Snow         return NULL;
34319bd2b08fSJohn Snow     }
34329bd2b08fSJohn Snow 
34339bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
34349bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
34359bd2b08fSJohn Snow         return NULL;
34369bd2b08fSJohn Snow     }
34379bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
34389bd2b08fSJohn Snow     parent->successor = NULL;
34399bd2b08fSJohn Snow 
34409bd2b08fSJohn Snow     return parent;
3441b8e6fb75SJohn Snow }
3442b8e6fb75SJohn Snow 
3443ce1ffea8SJohn Snow /**
3444ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3445ce1ffea8SJohn Snow  */
3446ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3447ce1ffea8SJohn Snow {
3448ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3449ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3450ce1ffea8SJohn Snow 
3451ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
345206207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3453ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
34545270b6a0SJohn Snow         bitmap->size = size;
3455ce1ffea8SJohn Snow     }
3456ce1ffea8SJohn Snow }
3457ce1ffea8SJohn Snow 
3458e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3459e4654d2dSFam Zheng {
3460e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3461e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3462e4654d2dSFam Zheng         if (bm == bitmap) {
34639bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3464e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3465e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
34660db6e54aSFam Zheng             g_free(bitmap->name);
3467e4654d2dSFam Zheng             g_free(bitmap);
3468e4654d2dSFam Zheng             return;
34697cd1e32aSlirans@il.ibm.com         }
34707cd1e32aSlirans@il.ibm.com     }
34717cd1e32aSlirans@il.ibm.com }
34727cd1e32aSlirans@il.ibm.com 
3473b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3474b8e6fb75SJohn Snow {
34759bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3476b8e6fb75SJohn Snow     bitmap->disabled = true;
3477b8e6fb75SJohn Snow }
3478b8e6fb75SJohn Snow 
3479b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3480b8e6fb75SJohn Snow {
34819bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3482b8e6fb75SJohn Snow     bitmap->disabled = false;
3483b8e6fb75SJohn Snow }
3484b8e6fb75SJohn Snow 
348521b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
348621b56835SFam Zheng {
348721b56835SFam Zheng     BdrvDirtyBitmap *bm;
348821b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
348921b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
349021b56835SFam Zheng 
349121b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
34925839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
34935839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
349420dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3495592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
34960db6e54aSFam Zheng         info->has_name = !!bm->name;
34970db6e54aSFam Zheng         info->name = g_strdup(bm->name);
34989abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
349921b56835SFam Zheng         entry->value = info;
350021b56835SFam Zheng         *plist = entry;
350121b56835SFam Zheng         plist = &entry->next;
350221b56835SFam Zheng     }
350321b56835SFam Zheng 
350421b56835SFam Zheng     return list;
350521b56835SFam Zheng }
350621b56835SFam Zheng 
3507e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
35087cd1e32aSlirans@il.ibm.com {
3509e4654d2dSFam Zheng     if (bitmap) {
3510e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
35117cd1e32aSlirans@il.ibm.com     } else {
35127cd1e32aSlirans@il.ibm.com         return 0;
35137cd1e32aSlirans@il.ibm.com     }
35147cd1e32aSlirans@il.ibm.com }
35157cd1e32aSlirans@il.ibm.com 
3516341ebc2fSJohn Snow /**
3517341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3518341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3519341ebc2fSJohn Snow  * is no cluster size information available.
3520341ebc2fSJohn Snow  */
3521341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3522341ebc2fSJohn Snow {
3523341ebc2fSJohn Snow     BlockDriverInfo bdi;
3524341ebc2fSJohn Snow     uint32_t granularity;
3525341ebc2fSJohn Snow 
3526341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3527341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3528341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3529341ebc2fSJohn Snow     } else {
3530341ebc2fSJohn Snow         granularity = 65536;
3531341ebc2fSJohn Snow     }
3532341ebc2fSJohn Snow 
3533341ebc2fSJohn Snow     return granularity;
3534341ebc2fSJohn Snow }
3535341ebc2fSJohn Snow 
3536592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3537592fdd02SJohn Snow {
3538592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3539592fdd02SJohn Snow }
3540592fdd02SJohn Snow 
354120dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
35421755da16SPaolo Bonzini {
3543e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
35441755da16SPaolo Bonzini }
35451755da16SPaolo Bonzini 
354620dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3547c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3548c4237dfaSVladimir Sementsov-Ogievskiy {
3549b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3550c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3551c4237dfaSVladimir Sementsov-Ogievskiy }
3552c4237dfaSVladimir Sementsov-Ogievskiy 
355320dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3554c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3555c4237dfaSVladimir Sementsov-Ogievskiy {
3556b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3557c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3558c4237dfaSVladimir Sementsov-Ogievskiy }
3559c4237dfaSVladimir Sementsov-Ogievskiy 
3560df9a681dSFam Zheng void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out)
3561e74e6b78SJohn Snow {
3562e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3563df9a681dSFam Zheng     if (!out) {
3564c6a8c328SWen Congyang         hbitmap_reset_all(bitmap->bitmap);
3565df9a681dSFam Zheng     } else {
3566df9a681dSFam Zheng         HBitmap *backup = bitmap->bitmap;
3567df9a681dSFam Zheng         bitmap->bitmap = hbitmap_alloc(bitmap->size,
3568df9a681dSFam Zheng                                        hbitmap_granularity(backup));
3569df9a681dSFam Zheng         *out = backup;
3570df9a681dSFam Zheng     }
3571df9a681dSFam Zheng }
3572df9a681dSFam Zheng 
3573df9a681dSFam Zheng void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in)
3574df9a681dSFam Zheng {
3575df9a681dSFam Zheng     HBitmap *tmp = bitmap->bitmap;
3576df9a681dSFam Zheng     assert(bdrv_dirty_bitmap_enabled(bitmap));
3577df9a681dSFam Zheng     bitmap->bitmap = in;
3578df9a681dSFam Zheng     hbitmap_free(tmp);
3579e74e6b78SJohn Snow }
3580e74e6b78SJohn Snow 
3581e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
35821755da16SPaolo Bonzini                     int nr_sectors)
35831755da16SPaolo Bonzini {
3584e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3585e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3586b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3587b8e6fb75SJohn Snow             continue;
3588b8e6fb75SJohn Snow         }
3589e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3590e4654d2dSFam Zheng     }
35911755da16SPaolo Bonzini }
35921755da16SPaolo Bonzini 
3593d58d8453SJohn Snow /**
3594d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3595d58d8453SJohn Snow  */
3596d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3597d58d8453SJohn Snow {
3598d58d8453SJohn Snow     assert(hbi->hb);
3599d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3600d58d8453SJohn Snow }
3601d58d8453SJohn Snow 
360220dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3603aaa0eb75SLiran Schour {
3604e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3605aaa0eb75SLiran Schour }
3606f88e1a42SJes Sorensen 
36079fcb0251SFam Zheng /* Get a reference to bs */
36089fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
36099fcb0251SFam Zheng {
36109fcb0251SFam Zheng     bs->refcnt++;
36119fcb0251SFam Zheng }
36129fcb0251SFam Zheng 
36139fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
36149fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
36159fcb0251SFam Zheng  * deleted. */
36169fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
36179fcb0251SFam Zheng {
36189a4d5ca6SJeff Cody     if (!bs) {
36199a4d5ca6SJeff Cody         return;
36209a4d5ca6SJeff Cody     }
36219fcb0251SFam Zheng     assert(bs->refcnt > 0);
36229fcb0251SFam Zheng     if (--bs->refcnt == 0) {
36239fcb0251SFam Zheng         bdrv_delete(bs);
36249fcb0251SFam Zheng     }
36259fcb0251SFam Zheng }
36269fcb0251SFam Zheng 
3627fbe40ff7SFam Zheng struct BdrvOpBlocker {
3628fbe40ff7SFam Zheng     Error *reason;
3629fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3630fbe40ff7SFam Zheng };
3631fbe40ff7SFam Zheng 
3632fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3633fbe40ff7SFam Zheng {
3634fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3635fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3636fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3637fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3638fbe40ff7SFam Zheng         if (errp) {
363981e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
364081e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3641bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3642fbe40ff7SFam Zheng         }
3643fbe40ff7SFam Zheng         return true;
3644fbe40ff7SFam Zheng     }
3645fbe40ff7SFam Zheng     return false;
3646fbe40ff7SFam Zheng }
3647fbe40ff7SFam Zheng 
3648fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3649fbe40ff7SFam Zheng {
3650fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3651fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3652fbe40ff7SFam Zheng 
36535839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3654fbe40ff7SFam Zheng     blocker->reason = reason;
3655fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3656fbe40ff7SFam Zheng }
3657fbe40ff7SFam Zheng 
3658fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3659fbe40ff7SFam Zheng {
3660fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3661fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3662fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3663fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3664fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3665fbe40ff7SFam Zheng             g_free(blocker);
3666fbe40ff7SFam Zheng         }
3667fbe40ff7SFam Zheng     }
3668fbe40ff7SFam Zheng }
3669fbe40ff7SFam Zheng 
3670fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3671fbe40ff7SFam Zheng {
3672fbe40ff7SFam Zheng     int i;
3673fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3674fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3675fbe40ff7SFam Zheng     }
3676fbe40ff7SFam Zheng }
3677fbe40ff7SFam Zheng 
3678fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3679fbe40ff7SFam Zheng {
3680fbe40ff7SFam Zheng     int i;
3681fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3682fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3683fbe40ff7SFam Zheng     }
3684fbe40ff7SFam Zheng }
3685fbe40ff7SFam Zheng 
3686fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3687fbe40ff7SFam Zheng {
3688fbe40ff7SFam Zheng     int i;
3689fbe40ff7SFam Zheng 
3690fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3691fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3692fbe40ff7SFam Zheng             return false;
3693fbe40ff7SFam Zheng         }
3694fbe40ff7SFam Zheng     }
3695fbe40ff7SFam Zheng     return true;
3696fbe40ff7SFam Zheng }
3697fbe40ff7SFam Zheng 
3698d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3699f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3700f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3701f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3702f88e1a42SJes Sorensen {
370383d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
370483d0521aSChunyan Liu     QemuOpts *opts = NULL;
370583d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
370683d0521aSChunyan Liu     int64_t size;
3707f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3708cc84d90fSMax Reitz     Error *local_err = NULL;
3709f88e1a42SJes Sorensen     int ret = 0;
3710f88e1a42SJes Sorensen 
3711f88e1a42SJes Sorensen     /* Find driver and parse its options */
3712f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3713f88e1a42SJes Sorensen     if (!drv) {
371471c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3715d92ada22SLuiz Capitulino         return;
3716f88e1a42SJes Sorensen     }
3717f88e1a42SJes Sorensen 
3718b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3719f88e1a42SJes Sorensen     if (!proto_drv) {
3720d92ada22SLuiz Capitulino         return;
3721f88e1a42SJes Sorensen     }
3722f88e1a42SJes Sorensen 
3723c6149724SMax Reitz     if (!drv->create_opts) {
3724c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3725c6149724SMax Reitz                    drv->format_name);
3726c6149724SMax Reitz         return;
3727c6149724SMax Reitz     }
3728c6149724SMax Reitz 
3729c6149724SMax Reitz     if (!proto_drv->create_opts) {
3730c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3731c6149724SMax Reitz                    proto_drv->format_name);
3732c6149724SMax Reitz         return;
3733c6149724SMax Reitz     }
3734c6149724SMax Reitz 
3735c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3736c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3737f88e1a42SJes Sorensen 
3738f88e1a42SJes Sorensen     /* Create parameter list with default values */
373983d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
374039101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3741f88e1a42SJes Sorensen 
3742f88e1a42SJes Sorensen     /* Parse -o options */
3743f88e1a42SJes Sorensen     if (options) {
3744dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3745dc523cd3SMarkus Armbruster         if (local_err) {
3746dc523cd3SMarkus Armbruster             error_report_err(local_err);
3747dc523cd3SMarkus Armbruster             local_err = NULL;
374883d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3749f88e1a42SJes Sorensen             goto out;
3750f88e1a42SJes Sorensen         }
3751f88e1a42SJes Sorensen     }
3752f88e1a42SJes Sorensen 
3753f88e1a42SJes Sorensen     if (base_filename) {
3754f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
37556be4194bSMarkus Armbruster         if (local_err) {
375671c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
375771c79813SLuiz Capitulino                        fmt);
3758f88e1a42SJes Sorensen             goto out;
3759f88e1a42SJes Sorensen         }
3760f88e1a42SJes Sorensen     }
3761f88e1a42SJes Sorensen 
3762f88e1a42SJes Sorensen     if (base_fmt) {
3763f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
37646be4194bSMarkus Armbruster         if (local_err) {
376571c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
376671c79813SLuiz Capitulino                              "format '%s'", fmt);
3767f88e1a42SJes Sorensen             goto out;
3768f88e1a42SJes Sorensen         }
3769f88e1a42SJes Sorensen     }
3770f88e1a42SJes Sorensen 
377183d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
377283d0521aSChunyan Liu     if (backing_file) {
377383d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
377471c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
377571c79813SLuiz Capitulino                              "same filename as the backing file");
3776792da93aSJes Sorensen             goto out;
3777792da93aSJes Sorensen         }
3778792da93aSJes Sorensen     }
3779792da93aSJes Sorensen 
378083d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3781f88e1a42SJes Sorensen 
3782f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3783f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
378483d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
378583d0521aSChunyan Liu     if (size == -1) {
378683d0521aSChunyan Liu         if (backing_file) {
378766f6b814SMax Reitz             BlockDriverState *bs;
378829168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
378952bf1e72SMarkus Armbruster             int64_t size;
379063090dacSPaolo Bonzini             int back_flags;
3791e6641719SMax Reitz             QDict *backing_options = NULL;
379263090dacSPaolo Bonzini 
379329168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
379429168018SMax Reitz                                                          full_backing, PATH_MAX,
379529168018SMax Reitz                                                          &local_err);
379629168018SMax Reitz             if (local_err) {
379729168018SMax Reitz                 g_free(full_backing);
379829168018SMax Reitz                 goto out;
379929168018SMax Reitz             }
380029168018SMax Reitz 
380163090dacSPaolo Bonzini             /* backing files always opened read-only */
380263090dacSPaolo Bonzini             back_flags =
380363090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3804f88e1a42SJes Sorensen 
3805e6641719SMax Reitz             if (backing_fmt) {
3806e6641719SMax Reitz                 backing_options = qdict_new();
3807e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3808e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3809e6641719SMax Reitz             }
3810e6641719SMax Reitz 
3811f67503e5SMax Reitz             bs = NULL;
3812e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
38136ebf9aa2SMax Reitz                             back_flags, &local_err);
381429168018SMax Reitz             g_free(full_backing);
3815f88e1a42SJes Sorensen             if (ret < 0) {
3816f88e1a42SJes Sorensen                 goto out;
3817f88e1a42SJes Sorensen             }
381852bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
381952bf1e72SMarkus Armbruster             if (size < 0) {
382052bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
382152bf1e72SMarkus Armbruster                                  backing_file);
382252bf1e72SMarkus Armbruster                 bdrv_unref(bs);
382352bf1e72SMarkus Armbruster                 goto out;
382452bf1e72SMarkus Armbruster             }
3825f88e1a42SJes Sorensen 
382639101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
382766f6b814SMax Reitz 
382866f6b814SMax Reitz             bdrv_unref(bs);
3829f88e1a42SJes Sorensen         } else {
383071c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3831f88e1a42SJes Sorensen             goto out;
3832f88e1a42SJes Sorensen         }
3833f88e1a42SJes Sorensen     }
3834f88e1a42SJes Sorensen 
3835f382d43aSMiroslav Rezanina     if (!quiet) {
3836f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
383743c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3838f88e1a42SJes Sorensen         puts("");
3839f382d43aSMiroslav Rezanina     }
384083d0521aSChunyan Liu 
3841c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
384283d0521aSChunyan Liu 
3843cc84d90fSMax Reitz     if (ret == -EFBIG) {
3844cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3845cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3846cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3847f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
384883d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3849f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3850f3f4d2c0SKevin Wolf         }
3851cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3852cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3853cc84d90fSMax Reitz         error_free(local_err);
3854cc84d90fSMax Reitz         local_err = NULL;
3855f88e1a42SJes Sorensen     }
3856f88e1a42SJes Sorensen 
3857f88e1a42SJes Sorensen out:
385883d0521aSChunyan Liu     qemu_opts_del(opts);
385983d0521aSChunyan Liu     qemu_opts_free(create_opts);
386084d18f06SMarkus Armbruster     if (local_err) {
3861cc84d90fSMax Reitz         error_propagate(errp, local_err);
3862cc84d90fSMax Reitz     }
3863f88e1a42SJes Sorensen }
386485d126f3SStefan Hajnoczi 
386585d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
386685d126f3SStefan Hajnoczi {
3867dcd04228SStefan Hajnoczi     return bs->aio_context;
3868dcd04228SStefan Hajnoczi }
3869dcd04228SStefan Hajnoczi 
3870dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3871dcd04228SStefan Hajnoczi {
387233384421SMax Reitz     BdrvAioNotifier *baf;
387333384421SMax Reitz 
3874dcd04228SStefan Hajnoczi     if (!bs->drv) {
3875dcd04228SStefan Hajnoczi         return;
3876dcd04228SStefan Hajnoczi     }
3877dcd04228SStefan Hajnoczi 
387833384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
387933384421SMax Reitz         baf->detach_aio_context(baf->opaque);
388033384421SMax Reitz     }
388133384421SMax Reitz 
3882a0d64a61SAlberto Garcia     if (bs->throttle_state) {
38830e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
388413af91ebSStefan Hajnoczi     }
3885dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3886dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3887dcd04228SStefan Hajnoczi     }
3888dcd04228SStefan Hajnoczi     if (bs->file) {
38899a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3890dcd04228SStefan Hajnoczi     }
3891760e0063SKevin Wolf     if (bs->backing) {
3892760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3893dcd04228SStefan Hajnoczi     }
3894dcd04228SStefan Hajnoczi 
3895dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3896dcd04228SStefan Hajnoczi }
3897dcd04228SStefan Hajnoczi 
3898dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3899dcd04228SStefan Hajnoczi                              AioContext *new_context)
3900dcd04228SStefan Hajnoczi {
390133384421SMax Reitz     BdrvAioNotifier *ban;
390233384421SMax Reitz 
3903dcd04228SStefan Hajnoczi     if (!bs->drv) {
3904dcd04228SStefan Hajnoczi         return;
3905dcd04228SStefan Hajnoczi     }
3906dcd04228SStefan Hajnoczi 
3907dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3908dcd04228SStefan Hajnoczi 
3909760e0063SKevin Wolf     if (bs->backing) {
3910760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3911dcd04228SStefan Hajnoczi     }
3912dcd04228SStefan Hajnoczi     if (bs->file) {
39139a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3914dcd04228SStefan Hajnoczi     }
3915dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3916dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3917dcd04228SStefan Hajnoczi     }
3918a0d64a61SAlberto Garcia     if (bs->throttle_state) {
39190e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
392013af91ebSStefan Hajnoczi     }
392133384421SMax Reitz 
392233384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
392333384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
392433384421SMax Reitz     }
3925dcd04228SStefan Hajnoczi }
3926dcd04228SStefan Hajnoczi 
3927dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3928dcd04228SStefan Hajnoczi {
392953ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3930dcd04228SStefan Hajnoczi 
3931dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3932dcd04228SStefan Hajnoczi 
3933dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3934dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3935dcd04228SStefan Hajnoczi      */
3936dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3937dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3938dcd04228SStefan Hajnoczi     aio_context_release(new_context);
393985d126f3SStefan Hajnoczi }
3940d616b224SStefan Hajnoczi 
394133384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
394233384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
394333384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
394433384421SMax Reitz {
394533384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
394633384421SMax Reitz     *ban = (BdrvAioNotifier){
394733384421SMax Reitz         .attached_aio_context = attached_aio_context,
394833384421SMax Reitz         .detach_aio_context   = detach_aio_context,
394933384421SMax Reitz         .opaque               = opaque
395033384421SMax Reitz     };
395133384421SMax Reitz 
395233384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
395333384421SMax Reitz }
395433384421SMax Reitz 
395533384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
395633384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
395733384421SMax Reitz                                                                    void *),
395833384421SMax Reitz                                       void (*detach_aio_context)(void *),
395933384421SMax Reitz                                       void *opaque)
396033384421SMax Reitz {
396133384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
396233384421SMax Reitz 
396333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
396433384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
396533384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
396633384421SMax Reitz             ban->opaque               == opaque)
396733384421SMax Reitz         {
396833384421SMax Reitz             QLIST_REMOVE(ban, list);
396933384421SMax Reitz             g_free(ban);
397033384421SMax Reitz 
397133384421SMax Reitz             return;
397233384421SMax Reitz         }
397333384421SMax Reitz     }
397433384421SMax Reitz 
397533384421SMax Reitz     abort();
397633384421SMax Reitz }
397733384421SMax Reitz 
397877485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
397977485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
39806f176b48SMax Reitz {
3981c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
39826f176b48SMax Reitz         return -ENOTSUP;
39836f176b48SMax Reitz     }
398477485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
39856f176b48SMax Reitz }
3986f6186f49SBenoît Canet 
3987b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3988b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3989b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3990b5042a36SBenoît Canet  * node graph.
3991212a5a8fSBenoît Canet  */
3992212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3993212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3994f6186f49SBenoît Canet {
3995b5042a36SBenoît Canet     /* return false if basic checks fails */
3996b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3997b5042a36SBenoît Canet         return false;
3998b5042a36SBenoît Canet     }
3999b5042a36SBenoît Canet 
4000b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
4001b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
4002b5042a36SBenoît Canet      */
4003b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
4004b5042a36SBenoît Canet         return bs == candidate;
4005b5042a36SBenoît Canet     }
4006b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
4007b5042a36SBenoît Canet 
4008b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
4009b5042a36SBenoît Canet      * the node graph.
4010b5042a36SBenoît Canet      */
4011b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
4012212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4013212a5a8fSBenoît Canet     }
4014212a5a8fSBenoît Canet 
4015b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
4016b5042a36SBenoît Canet      */
4017b5042a36SBenoît Canet     return false;
4018212a5a8fSBenoît Canet }
4019212a5a8fSBenoît Canet 
4020212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
4021212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
4022212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
4023212a5a8fSBenoît Canet  */
4024212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4025212a5a8fSBenoît Canet {
4026212a5a8fSBenoît Canet     BlockDriverState *bs;
4027212a5a8fSBenoît Canet 
4028212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
4029212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
4030212a5a8fSBenoît Canet         bool perm;
4031212a5a8fSBenoît Canet 
4032b5042a36SBenoît Canet         /* try to recurse in this top level bs */
4033e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
4034212a5a8fSBenoît Canet 
4035212a5a8fSBenoît Canet         /* candidate is the first non filter */
4036212a5a8fSBenoît Canet         if (perm) {
4037212a5a8fSBenoît Canet             return true;
4038212a5a8fSBenoît Canet         }
4039212a5a8fSBenoît Canet     }
4040212a5a8fSBenoît Canet 
4041212a5a8fSBenoît Canet     return false;
4042f6186f49SBenoît Canet }
404309158f00SBenoît Canet 
4044e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4045e12f3784SWen Congyang                                         const char *node_name, Error **errp)
404609158f00SBenoît Canet {
404709158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
40485a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
40495a7e7a0bSStefan Hajnoczi 
405009158f00SBenoît Canet     if (!to_replace_bs) {
405109158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
405209158f00SBenoît Canet         return NULL;
405309158f00SBenoît Canet     }
405409158f00SBenoît Canet 
40555a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
40565a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
40575a7e7a0bSStefan Hajnoczi 
405809158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
40595a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40605a7e7a0bSStefan Hajnoczi         goto out;
406109158f00SBenoît Canet     }
406209158f00SBenoît Canet 
406309158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
406409158f00SBenoît Canet      * most non filter in order to prevent data corruption.
406509158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
406609158f00SBenoît Canet      * blocked by the backing blockers.
406709158f00SBenoît Canet      */
4068e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
406909158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
40705a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40715a7e7a0bSStefan Hajnoczi         goto out;
407209158f00SBenoît Canet     }
407309158f00SBenoît Canet 
40745a7e7a0bSStefan Hajnoczi out:
40755a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
407609158f00SBenoît Canet     return to_replace_bs;
407709158f00SBenoît Canet }
4078448ad91dSMing Lei 
407991af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
408091af7014SMax Reitz {
408191af7014SMax Reitz     const QDictEntry *entry;
40829e700c1aSKevin Wolf     QemuOptDesc *desc;
4083260fecf1SKevin Wolf     BdrvChild *child;
408491af7014SMax Reitz     bool found_any = false;
4085260fecf1SKevin Wolf     const char *p;
408691af7014SMax Reitz 
408791af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
408891af7014SMax Reitz          entry = qdict_next(bs->options, entry))
408991af7014SMax Reitz     {
4090260fecf1SKevin Wolf         /* Exclude options for children */
4091260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
4092260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
4093260fecf1SKevin Wolf                 && (!*p || *p == '.'))
4094260fecf1SKevin Wolf             {
4095260fecf1SKevin Wolf                 break;
4096260fecf1SKevin Wolf             }
4097260fecf1SKevin Wolf         }
4098260fecf1SKevin Wolf         if (child) {
40999e700c1aSKevin Wolf             continue;
41009e700c1aSKevin Wolf         }
41019e700c1aSKevin Wolf 
41029e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
41039e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
41049e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
41059e700c1aSKevin Wolf                 break;
41069e700c1aSKevin Wolf             }
41079e700c1aSKevin Wolf         }
41089e700c1aSKevin Wolf         if (desc->name) {
41099e700c1aSKevin Wolf             continue;
41109e700c1aSKevin Wolf         }
41119e700c1aSKevin Wolf 
411291af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
411391af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
411491af7014SMax Reitz         found_any = true;
411591af7014SMax Reitz     }
411691af7014SMax Reitz 
411791af7014SMax Reitz     return found_any;
411891af7014SMax Reitz }
411991af7014SMax Reitz 
412091af7014SMax Reitz /* Updates the following BDS fields:
412191af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
412291af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
412391af7014SMax Reitz  *                    other options; so reading and writing must return the same
412491af7014SMax Reitz  *                    results, but caching etc. may be different)
412591af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
412691af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
412791af7014SMax Reitz  *                       equalling the given one
412891af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
412991af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
413091af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
413191af7014SMax Reitz  */
413291af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
413391af7014SMax Reitz {
413491af7014SMax Reitz     BlockDriver *drv = bs->drv;
413591af7014SMax Reitz     QDict *opts;
413691af7014SMax Reitz 
413791af7014SMax Reitz     if (!drv) {
413891af7014SMax Reitz         return;
413991af7014SMax Reitz     }
414091af7014SMax Reitz 
414191af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
414291af7014SMax Reitz      * refresh that first */
414391af7014SMax Reitz     if (bs->file) {
41449a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
414591af7014SMax Reitz     }
414691af7014SMax Reitz 
414791af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
414891af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
414991af7014SMax Reitz          * information before refreshing it */
415091af7014SMax Reitz         bs->exact_filename[0] = '\0';
415191af7014SMax Reitz         if (bs->full_open_options) {
415291af7014SMax Reitz             QDECREF(bs->full_open_options);
415391af7014SMax Reitz             bs->full_open_options = NULL;
415491af7014SMax Reitz         }
415591af7014SMax Reitz 
41564cdd01d3SKevin Wolf         opts = qdict_new();
41574cdd01d3SKevin Wolf         append_open_options(opts, bs);
41584cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
41594cdd01d3SKevin Wolf         QDECREF(opts);
416091af7014SMax Reitz     } else if (bs->file) {
416191af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
416291af7014SMax Reitz         bool has_open_options;
416391af7014SMax Reitz 
416491af7014SMax Reitz         bs->exact_filename[0] = '\0';
416591af7014SMax Reitz         if (bs->full_open_options) {
416691af7014SMax Reitz             QDECREF(bs->full_open_options);
416791af7014SMax Reitz             bs->full_open_options = NULL;
416891af7014SMax Reitz         }
416991af7014SMax Reitz 
417091af7014SMax Reitz         opts = qdict_new();
417191af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
417291af7014SMax Reitz 
417391af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
417491af7014SMax Reitz          * the underlying file should suffice for this one as well */
41759a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
41769a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
417791af7014SMax Reitz         }
417891af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
417991af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
418091af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
418191af7014SMax Reitz          * contain a representation of the filename, therefore the following
418291af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
41839a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
418491af7014SMax Reitz             qdict_put_obj(opts, "driver",
418591af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
41869a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
41879a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
41889a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
418991af7014SMax Reitz 
419091af7014SMax Reitz             bs->full_open_options = opts;
419191af7014SMax Reitz         } else {
419291af7014SMax Reitz             QDECREF(opts);
419391af7014SMax Reitz         }
419491af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
419591af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
419691af7014SMax Reitz          * so the full options QDict should be equal to the options given
419791af7014SMax Reitz          * specifically for this block device when it was opened (plus the
419891af7014SMax Reitz          * driver specification).
419991af7014SMax Reitz          * Because those options don't change, there is no need to update
420091af7014SMax Reitz          * full_open_options when it's already set. */
420191af7014SMax Reitz 
420291af7014SMax Reitz         opts = qdict_new();
420391af7014SMax Reitz         append_open_options(opts, bs);
420491af7014SMax Reitz         qdict_put_obj(opts, "driver",
420591af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
420691af7014SMax Reitz 
420791af7014SMax Reitz         if (bs->exact_filename[0]) {
420891af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
420991af7014SMax Reitz              * require this filename to be parsed), but we have to find some
421091af7014SMax Reitz              * default solution here, so just include it. If some block driver
421191af7014SMax Reitz              * does not support pure options without any filename at all or
421291af7014SMax Reitz              * needs some special format of the options QDict, it needs to
421391af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
421491af7014SMax Reitz              */
421591af7014SMax Reitz             qdict_put_obj(opts, "filename",
421691af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
421791af7014SMax Reitz         }
421891af7014SMax Reitz 
421991af7014SMax Reitz         bs->full_open_options = opts;
422091af7014SMax Reitz     }
422191af7014SMax Reitz 
422291af7014SMax Reitz     if (bs->exact_filename[0]) {
422391af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
422491af7014SMax Reitz     } else if (bs->full_open_options) {
422591af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
422691af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
422791af7014SMax Reitz                  qstring_get_str(json));
422891af7014SMax Reitz         QDECREF(json);
422991af7014SMax Reitz     }
423091af7014SMax Reitz }
4231