xref: /openbmc/qemu/block.c (revision 2c1d04e002dc91a6f34e8e683ea6b84f61a0b9fd)
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"
3291a097e7SKevin Wolf #include "qapi/qmp/qbool.h"
337b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
34bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
359c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
361de7afc9SPaolo Bonzini #include "qemu/notify.h"
3710817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
38c13163fbSBenoît Canet #include "block/qapi.h"
39b2023818SLuiz Capitulino #include "qmp-commands.h"
401de7afc9SPaolo Bonzini #include "qemu/timer.h"
41a5ee7bd4SWenchao Xia #include "qapi-event.h"
42db628338SAlberto Garcia #include "block/throttle-groups.h"
43fc01f7e7Sbellard 
4471e72a19SJuan Quintela #ifdef CONFIG_BSD
457674e7bfSbellard #include <sys/types.h>
467674e7bfSbellard #include <sys/stat.h>
477674e7bfSbellard #include <sys/ioctl.h>
4872cf2d4fSBlue Swirl #include <sys/queue.h>
49c5e97233Sblueswir1 #ifndef __DragonFly__
507674e7bfSbellard #include <sys/disk.h>
517674e7bfSbellard #endif
52c5e97233Sblueswir1 #endif
537674e7bfSbellard 
5449dc768dSaliguori #ifdef _WIN32
5549dc768dSaliguori #include <windows.h>
5649dc768dSaliguori #endif
5749dc768dSaliguori 
589bd2b08fSJohn Snow /**
599bd2b08fSJohn Snow  * A BdrvDirtyBitmap can be in three possible states:
609bd2b08fSJohn Snow  * (1) successor is NULL and disabled is false: full r/w mode
619bd2b08fSJohn Snow  * (2) successor is NULL and disabled is true: read only mode ("disabled")
629bd2b08fSJohn Snow  * (3) successor is set: frozen mode.
639bd2b08fSJohn Snow  *     A frozen bitmap cannot be renamed, deleted, anonymized, cleared, set,
649bd2b08fSJohn Snow  *     or enabled. A frozen bitmap can only abdicate() or reclaim().
659bd2b08fSJohn Snow  */
66e4654d2dSFam Zheng struct BdrvDirtyBitmap {
67aa0c7ca5SJohn Snow     HBitmap *bitmap;            /* Dirty sector bitmap implementation */
68aa0c7ca5SJohn Snow     BdrvDirtyBitmap *successor; /* Anonymous child; implies frozen status */
69aa0c7ca5SJohn Snow     char *name;                 /* Optional non-empty unique ID */
70aa0c7ca5SJohn Snow     int64_t size;               /* Size of the bitmap (Number of sectors) */
71aa0c7ca5SJohn Snow     bool disabled;              /* Bitmap is read-only */
72e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
73e4654d2dSFam Zheng };
74e4654d2dSFam Zheng 
751c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
761c9805a3SStefan Hajnoczi 
77c69a4dd8SMax Reitz struct BdrvStates bdrv_states = QTAILQ_HEAD_INITIALIZER(bdrv_states);
787ee930d0Sblueswir1 
79dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
80dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
81dc364f4cSBenoît Canet 
82*2c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
83*2c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
84*2c1d04e0SMax Reitz 
858a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
868a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
87ea2384d3Sbellard 
88f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
89f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
90f3930ed0SKevin Wolf                              BlockDriverState *parent,
91ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
92f3930ed0SKevin Wolf 
93ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs);
94c5acdc9aSMax Reitz static void bdrv_release_named_dirty_bitmaps(BlockDriverState *bs);
95c5acdc9aSMax Reitz 
96eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
97eb852011SMarkus Armbruster static int use_bdrv_whitelist;
98eb852011SMarkus Armbruster 
9964dff520SMax Reitz static void bdrv_close(BlockDriverState *bs);
10064dff520SMax Reitz 
1019e0b22f4SStefan Hajnoczi #ifdef _WIN32
1029e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1039e0b22f4SStefan Hajnoczi {
1049e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1059e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1069e0b22f4SStefan Hajnoczi             filename[1] == ':');
1079e0b22f4SStefan Hajnoczi }
1089e0b22f4SStefan Hajnoczi 
1099e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1109e0b22f4SStefan Hajnoczi {
1119e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1129e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1139e0b22f4SStefan Hajnoczi         return 1;
1149e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1159e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1169e0b22f4SStefan Hajnoczi         return 1;
1179e0b22f4SStefan Hajnoczi     return 0;
1189e0b22f4SStefan Hajnoczi }
1199e0b22f4SStefan Hajnoczi #endif
1209e0b22f4SStefan Hajnoczi 
121339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
122339064d5SKevin Wolf {
123339064d5SKevin Wolf     if (!bs || !bs->drv) {
124459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
125459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
126339064d5SKevin Wolf     }
127339064d5SKevin Wolf 
128339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
129339064d5SKevin Wolf }
130339064d5SKevin Wolf 
1314196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1324196d2f0SDenis V. Lunev {
1334196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
134459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
135459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1364196d2f0SDenis V. Lunev     }
1374196d2f0SDenis V. Lunev 
1384196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1394196d2f0SDenis V. Lunev }
1404196d2f0SDenis V. Lunev 
1419e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1425c98415bSMax Reitz int path_has_protocol(const char *path)
1439e0b22f4SStefan Hajnoczi {
144947995c0SPaolo Bonzini     const char *p;
145947995c0SPaolo Bonzini 
1469e0b22f4SStefan Hajnoczi #ifdef _WIN32
1479e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1489e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1499e0b22f4SStefan Hajnoczi         return 0;
1509e0b22f4SStefan Hajnoczi     }
151947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
152947995c0SPaolo Bonzini #else
153947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1549e0b22f4SStefan Hajnoczi #endif
1559e0b22f4SStefan Hajnoczi 
156947995c0SPaolo Bonzini     return *p == ':';
1579e0b22f4SStefan Hajnoczi }
1589e0b22f4SStefan Hajnoczi 
15983f64091Sbellard int path_is_absolute(const char *path)
16083f64091Sbellard {
16121664424Sbellard #ifdef _WIN32
16221664424Sbellard     /* specific case for names like: "\\.\d:" */
163f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
16421664424Sbellard         return 1;
165f53f4da9SPaolo Bonzini     }
166f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1673b9f94e1Sbellard #else
168f53f4da9SPaolo Bonzini     return (*path == '/');
1693b9f94e1Sbellard #endif
17083f64091Sbellard }
17183f64091Sbellard 
17283f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
17383f64091Sbellard    path to it by considering it is relative to base_path. URL are
17483f64091Sbellard    supported. */
17583f64091Sbellard void path_combine(char *dest, int dest_size,
17683f64091Sbellard                   const char *base_path,
17783f64091Sbellard                   const char *filename)
17883f64091Sbellard {
17983f64091Sbellard     const char *p, *p1;
18083f64091Sbellard     int len;
18183f64091Sbellard 
18283f64091Sbellard     if (dest_size <= 0)
18383f64091Sbellard         return;
18483f64091Sbellard     if (path_is_absolute(filename)) {
18583f64091Sbellard         pstrcpy(dest, dest_size, filename);
18683f64091Sbellard     } else {
18783f64091Sbellard         p = strchr(base_path, ':');
18883f64091Sbellard         if (p)
18983f64091Sbellard             p++;
19083f64091Sbellard         else
19183f64091Sbellard             p = base_path;
1923b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1933b9f94e1Sbellard #ifdef _WIN32
1943b9f94e1Sbellard         {
1953b9f94e1Sbellard             const char *p2;
1963b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1973b9f94e1Sbellard             if (!p1 || p2 > p1)
1983b9f94e1Sbellard                 p1 = p2;
1993b9f94e1Sbellard         }
2003b9f94e1Sbellard #endif
20183f64091Sbellard         if (p1)
20283f64091Sbellard             p1++;
20383f64091Sbellard         else
20483f64091Sbellard             p1 = base_path;
20583f64091Sbellard         if (p1 > p)
20683f64091Sbellard             p = p1;
20783f64091Sbellard         len = p - base_path;
20883f64091Sbellard         if (len > dest_size - 1)
20983f64091Sbellard             len = dest_size - 1;
21083f64091Sbellard         memcpy(dest, base_path, len);
21183f64091Sbellard         dest[len] = '\0';
21283f64091Sbellard         pstrcat(dest, dest_size, filename);
21383f64091Sbellard     }
21483f64091Sbellard }
21583f64091Sbellard 
2160a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
2170a82855aSMax Reitz                                                   const char *backing,
2189f07429eSMax Reitz                                                   char *dest, size_t sz,
2199f07429eSMax Reitz                                                   Error **errp)
2200a82855aSMax Reitz {
2219f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2229f07429eSMax Reitz         path_is_absolute(backing))
2239f07429eSMax Reitz     {
2240a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2259f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2269f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2279f07429eSMax Reitz                    backed);
2280a82855aSMax Reitz     } else {
2290a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2300a82855aSMax Reitz     }
2310a82855aSMax Reitz }
2320a82855aSMax Reitz 
2339f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2349f07429eSMax Reitz                                     Error **errp)
235dc5a1371SPaolo Bonzini {
2369f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2379f07429eSMax Reitz 
2389f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2399f07429eSMax Reitz                                                  dest, sz, errp);
240dc5a1371SPaolo Bonzini }
241dc5a1371SPaolo Bonzini 
2420eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2430eb7217eSStefan Hajnoczi {
2440eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
245b2e12bc6SChristoph Hellwig 
2468a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
247ea2384d3Sbellard }
248b338082bSbellard 
2497f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
250fc01f7e7Sbellard {
2517f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
252e4e9986bSMarkus Armbruster 
253e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
254e4e9986bSMarkus Armbruster     return bs;
255e4e9986bSMarkus Armbruster }
256e4e9986bSMarkus Armbruster 
257e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
258e4e9986bSMarkus Armbruster {
259e4e9986bSMarkus Armbruster     BlockDriverState *bs;
260e4e9986bSMarkus Armbruster     int i;
261e4e9986bSMarkus Armbruster 
2625839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
263e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
264fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
265fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
266fbe40ff7SFam Zheng     }
267d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
268cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
269cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2709fcb0251SFam Zheng     bs->refcnt = 1;
271dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
272d7d512f6SPaolo Bonzini 
273*2c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
274*2c1d04e0SMax Reitz 
275b338082bSbellard     return bs;
276b338082bSbellard }
277b338082bSbellard 
278ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
279ea2384d3Sbellard {
280ea2384d3Sbellard     BlockDriver *drv1;
2818a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2828a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
283ea2384d3Sbellard             return drv1;
284ea2384d3Sbellard         }
2858a22f02aSStefan Hajnoczi     }
286ea2384d3Sbellard     return NULL;
287ea2384d3Sbellard }
288ea2384d3Sbellard 
289b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
290eb852011SMarkus Armbruster {
291b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
292b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
293b64ec4e4SFam Zheng     };
294b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
295b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
296eb852011SMarkus Armbruster     };
297eb852011SMarkus Armbruster     const char **p;
298eb852011SMarkus Armbruster 
299b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
300eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
301b64ec4e4SFam Zheng     }
302eb852011SMarkus Armbruster 
303b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
304eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
305eb852011SMarkus Armbruster             return 1;
306eb852011SMarkus Armbruster         }
307eb852011SMarkus Armbruster     }
308b64ec4e4SFam Zheng     if (read_only) {
309b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
310b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
311b64ec4e4SFam Zheng                 return 1;
312b64ec4e4SFam Zheng             }
313b64ec4e4SFam Zheng         }
314b64ec4e4SFam Zheng     }
315eb852011SMarkus Armbruster     return 0;
316eb852011SMarkus Armbruster }
317eb852011SMarkus Armbruster 
3185b7e1542SZhi Yong Wu typedef struct CreateCo {
3195b7e1542SZhi Yong Wu     BlockDriver *drv;
3205b7e1542SZhi Yong Wu     char *filename;
32183d0521aSChunyan Liu     QemuOpts *opts;
3225b7e1542SZhi Yong Wu     int ret;
323cc84d90fSMax Reitz     Error *err;
3245b7e1542SZhi Yong Wu } CreateCo;
3255b7e1542SZhi Yong Wu 
3265b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3275b7e1542SZhi Yong Wu {
328cc84d90fSMax Reitz     Error *local_err = NULL;
329cc84d90fSMax Reitz     int ret;
330cc84d90fSMax Reitz 
3315b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3325b7e1542SZhi Yong Wu     assert(cco->drv);
3335b7e1542SZhi Yong Wu 
334c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
33584d18f06SMarkus Armbruster     if (local_err) {
336cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
337cc84d90fSMax Reitz     }
338cc84d90fSMax Reitz     cco->ret = ret;
3395b7e1542SZhi Yong Wu }
3405b7e1542SZhi Yong Wu 
3410e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
34283d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
343ea2384d3Sbellard {
3445b7e1542SZhi Yong Wu     int ret;
3450e7e1989SKevin Wolf 
3465b7e1542SZhi Yong Wu     Coroutine *co;
3475b7e1542SZhi Yong Wu     CreateCo cco = {
3485b7e1542SZhi Yong Wu         .drv = drv,
3495b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
35083d0521aSChunyan Liu         .opts = opts,
3515b7e1542SZhi Yong Wu         .ret = NOT_DONE,
352cc84d90fSMax Reitz         .err = NULL,
3535b7e1542SZhi Yong Wu     };
3545b7e1542SZhi Yong Wu 
355c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
356cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35780168bffSLuiz Capitulino         ret = -ENOTSUP;
35880168bffSLuiz Capitulino         goto out;
3595b7e1542SZhi Yong Wu     }
3605b7e1542SZhi Yong Wu 
3615b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3625b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3635b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3645b7e1542SZhi Yong Wu     } else {
3655b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3665b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3675b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
368b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3695b7e1542SZhi Yong Wu         }
3705b7e1542SZhi Yong Wu     }
3715b7e1542SZhi Yong Wu 
3725b7e1542SZhi Yong Wu     ret = cco.ret;
373cc84d90fSMax Reitz     if (ret < 0) {
37484d18f06SMarkus Armbruster         if (cco.err) {
375cc84d90fSMax Reitz             error_propagate(errp, cco.err);
376cc84d90fSMax Reitz         } else {
377cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
378cc84d90fSMax Reitz         }
379cc84d90fSMax Reitz     }
3805b7e1542SZhi Yong Wu 
38180168bffSLuiz Capitulino out:
38280168bffSLuiz Capitulino     g_free(cco.filename);
3835b7e1542SZhi Yong Wu     return ret;
384ea2384d3Sbellard }
385ea2384d3Sbellard 
386c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38784a12e66SChristoph Hellwig {
38884a12e66SChristoph Hellwig     BlockDriver *drv;
389cc84d90fSMax Reitz     Error *local_err = NULL;
390cc84d90fSMax Reitz     int ret;
39184a12e66SChristoph Hellwig 
392b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
39384a12e66SChristoph Hellwig     if (drv == NULL) {
39416905d71SStefan Hajnoczi         return -ENOENT;
39584a12e66SChristoph Hellwig     }
39684a12e66SChristoph Hellwig 
397c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
39884d18f06SMarkus Armbruster     if (local_err) {
399cc84d90fSMax Reitz         error_propagate(errp, local_err);
400cc84d90fSMax Reitz     }
401cc84d90fSMax Reitz     return ret;
40284a12e66SChristoph Hellwig }
40384a12e66SChristoph Hellwig 
404892b7de8SEkaterina Tumanova /**
405892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
406892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
407892b7de8SEkaterina Tumanova  * On failure return -errno.
408892b7de8SEkaterina Tumanova  * @bs must not be empty.
409892b7de8SEkaterina Tumanova  */
410892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
411892b7de8SEkaterina Tumanova {
412892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
413892b7de8SEkaterina Tumanova 
414892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
415892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
416892b7de8SEkaterina Tumanova     }
417892b7de8SEkaterina Tumanova 
418892b7de8SEkaterina Tumanova     return -ENOTSUP;
419892b7de8SEkaterina Tumanova }
420892b7de8SEkaterina Tumanova 
421892b7de8SEkaterina Tumanova /**
422892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
423892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
424892b7de8SEkaterina Tumanova  * On failure return -errno.
425892b7de8SEkaterina Tumanova  * @bs must not be empty.
426892b7de8SEkaterina Tumanova  */
427892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
428892b7de8SEkaterina Tumanova {
429892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
430892b7de8SEkaterina Tumanova 
431892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
432892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
433892b7de8SEkaterina Tumanova     }
434892b7de8SEkaterina Tumanova 
435892b7de8SEkaterina Tumanova     return -ENOTSUP;
436892b7de8SEkaterina Tumanova }
437892b7de8SEkaterina Tumanova 
438eba25057SJim Meyering /*
439eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
440eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
441eba25057SJim Meyering  */
442eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
443eba25057SJim Meyering {
444d5249393Sbellard #ifdef _WIN32
4453b9f94e1Sbellard     char temp_dir[MAX_PATH];
446eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
447eba25057SJim Meyering        have length MAX_PATH or greater.  */
448eba25057SJim Meyering     assert(size >= MAX_PATH);
449eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
450eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
451eba25057SJim Meyering             ? 0 : -GetLastError());
452d5249393Sbellard #else
453ea2384d3Sbellard     int fd;
4547ccfb2ebSblueswir1     const char *tmpdir;
4550badc1eeSaurel32     tmpdir = getenv("TMPDIR");
45669bef793SAmit Shah     if (!tmpdir) {
45769bef793SAmit Shah         tmpdir = "/var/tmp";
45869bef793SAmit Shah     }
459eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
460eba25057SJim Meyering         return -EOVERFLOW;
461ea2384d3Sbellard     }
462eba25057SJim Meyering     fd = mkstemp(filename);
463fe235a06SDunrong Huang     if (fd < 0) {
464fe235a06SDunrong Huang         return -errno;
465fe235a06SDunrong Huang     }
466fe235a06SDunrong Huang     if (close(fd) != 0) {
467fe235a06SDunrong Huang         unlink(filename);
468eba25057SJim Meyering         return -errno;
469eba25057SJim Meyering     }
470eba25057SJim Meyering     return 0;
471d5249393Sbellard #endif
472eba25057SJim Meyering }
473ea2384d3Sbellard 
474f3a5d3f8SChristoph Hellwig /*
475f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
476f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
477f3a5d3f8SChristoph Hellwig  */
478f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
479f3a5d3f8SChristoph Hellwig {
480508c7cb3SChristoph Hellwig     int score_max = 0, score;
481508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
482f3a5d3f8SChristoph Hellwig 
4838a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
484508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
485508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
486508c7cb3SChristoph Hellwig             if (score > score_max) {
487508c7cb3SChristoph Hellwig                 score_max = score;
488508c7cb3SChristoph Hellwig                 drv = d;
489f3a5d3f8SChristoph Hellwig             }
490508c7cb3SChristoph Hellwig         }
491f3a5d3f8SChristoph Hellwig     }
492f3a5d3f8SChristoph Hellwig 
493508c7cb3SChristoph Hellwig     return drv;
494f3a5d3f8SChristoph Hellwig }
495f3a5d3f8SChristoph Hellwig 
49698289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
497b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
498b65a5e12SMax Reitz                                 Error **errp)
49984a12e66SChristoph Hellwig {
50084a12e66SChristoph Hellwig     BlockDriver *drv1;
50184a12e66SChristoph Hellwig     char protocol[128];
50284a12e66SChristoph Hellwig     int len;
50384a12e66SChristoph Hellwig     const char *p;
50484a12e66SChristoph Hellwig 
50566f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
50666f82ceeSKevin Wolf 
50739508e7aSChristoph Hellwig     /*
50839508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
50939508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
51039508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
51139508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
51239508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
51339508e7aSChristoph Hellwig      */
51484a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
51539508e7aSChristoph Hellwig     if (drv1) {
51684a12e66SChristoph Hellwig         return drv1;
51784a12e66SChristoph Hellwig     }
51839508e7aSChristoph Hellwig 
51998289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
520ef810437SMax Reitz         return &bdrv_file;
52139508e7aSChristoph Hellwig     }
52298289620SKevin Wolf 
5239e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5249e0b22f4SStefan Hajnoczi     assert(p != NULL);
52584a12e66SChristoph Hellwig     len = p - filename;
52684a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
52784a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
52884a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
52984a12e66SChristoph Hellwig     protocol[len] = '\0';
53084a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
53184a12e66SChristoph Hellwig         if (drv1->protocol_name &&
53284a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
53384a12e66SChristoph Hellwig             return drv1;
53484a12e66SChristoph Hellwig         }
53584a12e66SChristoph Hellwig     }
536b65a5e12SMax Reitz 
537b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
53884a12e66SChristoph Hellwig     return NULL;
53984a12e66SChristoph Hellwig }
54084a12e66SChristoph Hellwig 
541c6684249SMarkus Armbruster /*
542c6684249SMarkus Armbruster  * Guess image format by probing its contents.
543c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
544c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
545c6684249SMarkus Armbruster  *
546c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5477cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5487cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
549c6684249SMarkus Armbruster  * @filename    is its filename.
550c6684249SMarkus Armbruster  *
551c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
552c6684249SMarkus Armbruster  * probing score.
553c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
554c6684249SMarkus Armbruster  */
55538f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
556c6684249SMarkus Armbruster                             const char *filename)
557c6684249SMarkus Armbruster {
558c6684249SMarkus Armbruster     int score_max = 0, score;
559c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
560c6684249SMarkus Armbruster 
561c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
562c6684249SMarkus Armbruster         if (d->bdrv_probe) {
563c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
564c6684249SMarkus Armbruster             if (score > score_max) {
565c6684249SMarkus Armbruster                 score_max = score;
566c6684249SMarkus Armbruster                 drv = d;
567c6684249SMarkus Armbruster             }
568c6684249SMarkus Armbruster         }
569c6684249SMarkus Armbruster     }
570c6684249SMarkus Armbruster 
571c6684249SMarkus Armbruster     return drv;
572c6684249SMarkus Armbruster }
573c6684249SMarkus Armbruster 
574f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
57534b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
576ea2384d3Sbellard {
577c6684249SMarkus Armbruster     BlockDriver *drv;
5787cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
579f500a6d3SKevin Wolf     int ret = 0;
580f8ea0b00SNicholas Bellinger 
58108a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
582b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
583ef810437SMax Reitz         *pdrv = &bdrv_raw;
584c98ac35dSStefan Weil         return ret;
5851a396859SNicholas A. Bellinger     }
586f8ea0b00SNicholas Bellinger 
58783f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
588ea2384d3Sbellard     if (ret < 0) {
58934b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
59034b5d2c6SMax Reitz                          "format");
591c98ac35dSStefan Weil         *pdrv = NULL;
592c98ac35dSStefan Weil         return ret;
593ea2384d3Sbellard     }
594ea2384d3Sbellard 
595c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
596c98ac35dSStefan Weil     if (!drv) {
59734b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
59834b5d2c6SMax Reitz                    "driver found");
599c98ac35dSStefan Weil         ret = -ENOENT;
600c98ac35dSStefan Weil     }
601c98ac35dSStefan Weil     *pdrv = drv;
602c98ac35dSStefan Weil     return ret;
603ea2384d3Sbellard }
604ea2384d3Sbellard 
60551762288SStefan Hajnoczi /**
60651762288SStefan Hajnoczi  * Set the current 'total_sectors' value
60765a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
60851762288SStefan Hajnoczi  */
60951762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
61051762288SStefan Hajnoczi {
61151762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
61251762288SStefan Hajnoczi 
613396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
614b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
615396759adSNicholas Bellinger         return 0;
616396759adSNicholas Bellinger 
61751762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
61851762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
61951762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
62051762288SStefan Hajnoczi         if (length < 0) {
62151762288SStefan Hajnoczi             return length;
62251762288SStefan Hajnoczi         }
6237e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
62451762288SStefan Hajnoczi     }
62551762288SStefan Hajnoczi 
62651762288SStefan Hajnoczi     bs->total_sectors = hint;
62751762288SStefan Hajnoczi     return 0;
62851762288SStefan Hajnoczi }
62951762288SStefan Hajnoczi 
630c3993cdcSStefan Hajnoczi /**
631cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
632cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
633cddff5baSKevin Wolf  */
634cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
635cddff5baSKevin Wolf                               QDict *old_options)
636cddff5baSKevin Wolf {
637cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
638cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
639cddff5baSKevin Wolf     } else {
640cddff5baSKevin Wolf         qdict_join(options, old_options, false);
641cddff5baSKevin Wolf     }
642cddff5baSKevin Wolf }
643cddff5baSKevin Wolf 
644cddff5baSKevin Wolf /**
6459e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6469e8f1835SPaolo Bonzini  *
6479e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6489e8f1835SPaolo Bonzini  */
6499e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6509e8f1835SPaolo Bonzini {
6519e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6529e8f1835SPaolo Bonzini 
6539e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6549e8f1835SPaolo Bonzini         /* do nothing */
6559e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6569e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6579e8f1835SPaolo Bonzini     } else {
6589e8f1835SPaolo Bonzini         return -1;
6599e8f1835SPaolo Bonzini     }
6609e8f1835SPaolo Bonzini 
6619e8f1835SPaolo Bonzini     return 0;
6629e8f1835SPaolo Bonzini }
6639e8f1835SPaolo Bonzini 
6649e8f1835SPaolo Bonzini /**
665c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
666c3993cdcSStefan Hajnoczi  *
667c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
668c3993cdcSStefan Hajnoczi  */
669c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
670c3993cdcSStefan Hajnoczi {
671c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
672c3993cdcSStefan Hajnoczi 
673c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
674c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
67592196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
67692196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
677c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
678c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
679c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
680c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
681c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
682c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
683c3993cdcSStefan Hajnoczi         /* this is the default */
684c3993cdcSStefan Hajnoczi     } else {
685c3993cdcSStefan Hajnoczi         return -1;
686c3993cdcSStefan Hajnoczi     }
687c3993cdcSStefan Hajnoczi 
688c3993cdcSStefan Hajnoczi     return 0;
689c3993cdcSStefan Hajnoczi }
690c3993cdcSStefan Hajnoczi 
6910b50cc88SKevin Wolf /*
692b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
693b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
694b1e6fc08SKevin Wolf  * like a backing file)
695b1e6fc08SKevin Wolf  */
696b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
697b1e6fc08SKevin Wolf {
698b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
699b1e6fc08SKevin Wolf }
700b1e6fc08SKevin Wolf 
701b1e6fc08SKevin Wolf /*
7028e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
7038e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
7040b50cc88SKevin Wolf  */
7058e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
7068e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
7070b50cc88SKevin Wolf {
7088e2160e2SKevin Wolf     int flags = parent_flags;
7098e2160e2SKevin Wolf 
7100b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
7110b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
7120b50cc88SKevin Wolf 
71391a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
71491a097e7SKevin Wolf      * the parent. */
71591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
71691a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
71791a097e7SKevin Wolf 
7180b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
71991a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
72091a097e7SKevin Wolf      * corresponding parent options. */
72191a097e7SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
72291a097e7SKevin Wolf     flags |= BDRV_O_UNMAP;
7230b50cc88SKevin Wolf 
7240b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
7255669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
7260b50cc88SKevin Wolf 
7278e2160e2SKevin Wolf     *child_flags = flags;
7280b50cc88SKevin Wolf }
7290b50cc88SKevin Wolf 
730f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7318e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
732f3930ed0SKevin Wolf };
733f3930ed0SKevin Wolf 
734f3930ed0SKevin Wolf /*
7358e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7368e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7378e2160e2SKevin Wolf  * flags for the parent BDS
738f3930ed0SKevin Wolf  */
7398e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7408e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
741f3930ed0SKevin Wolf {
7428e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7438e2160e2SKevin Wolf                                parent_flags, parent_options);
7448e2160e2SKevin Wolf 
7458e2160e2SKevin Wolf     *child_flags &= ~BDRV_O_PROTOCOL;
746f3930ed0SKevin Wolf }
747f3930ed0SKevin Wolf 
748f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7498e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
750f3930ed0SKevin Wolf };
751f3930ed0SKevin Wolf 
752317fc44eSKevin Wolf /*
7538e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7548e2160e2SKevin Wolf  * given options and flags for the parent BDS
755317fc44eSKevin Wolf  */
7568e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7578e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
758317fc44eSKevin Wolf {
7598e2160e2SKevin Wolf     int flags = parent_flags;
7608e2160e2SKevin Wolf 
76191a097e7SKevin Wolf     /* The cache mode is inherited unmodified for backing files */
76291a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_WB);
76391a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
76491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
76591a097e7SKevin Wolf 
766317fc44eSKevin Wolf     /* backing files always opened read-only */
767317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
768317fc44eSKevin Wolf 
769317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7708bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
771317fc44eSKevin Wolf 
7728e2160e2SKevin Wolf     *child_flags = flags;
773317fc44eSKevin Wolf }
774317fc44eSKevin Wolf 
775f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7768e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
777f3930ed0SKevin Wolf };
778f3930ed0SKevin Wolf 
7797b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7807b272452SKevin Wolf {
7817b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7827b272452SKevin Wolf 
7837b272452SKevin Wolf     /*
7847b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7857b272452SKevin Wolf      * image.
7867b272452SKevin Wolf      */
78720cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7887b272452SKevin Wolf 
7897b272452SKevin Wolf     /*
7907b272452SKevin Wolf      * Snapshots should be writable.
7917b272452SKevin Wolf      */
7928bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7937b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7947b272452SKevin Wolf     }
7957b272452SKevin Wolf 
7967b272452SKevin Wolf     return open_flags;
7977b272452SKevin Wolf }
7987b272452SKevin Wolf 
79991a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
80091a097e7SKevin Wolf {
80191a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
80291a097e7SKevin Wolf 
80391a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_WB));
80491a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, false)) {
80591a097e7SKevin Wolf         *flags |= BDRV_O_CACHE_WB;
80691a097e7SKevin Wolf     }
80791a097e7SKevin Wolf 
80891a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
80991a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
81091a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
81191a097e7SKevin Wolf     }
81291a097e7SKevin Wolf 
81391a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
81491a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
81591a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
81691a097e7SKevin Wolf     }
81791a097e7SKevin Wolf }
81891a097e7SKevin Wolf 
81991a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
82091a097e7SKevin Wolf {
82191a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_WB)) {
82291a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_WB,
82391a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_CACHE_WB));
82491a097e7SKevin Wolf     }
82591a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
82691a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
82791a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
82891a097e7SKevin Wolf     }
82991a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
83091a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
83191a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
83291a097e7SKevin Wolf     }
83391a097e7SKevin Wolf }
83491a097e7SKevin Wolf 
835636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8366913c0c2SBenoît Canet                                   const char *node_name,
8376913c0c2SBenoît Canet                                   Error **errp)
8386913c0c2SBenoît Canet {
83915489c76SJeff Cody     char *gen_node_name = NULL;
8406913c0c2SBenoît Canet 
84115489c76SJeff Cody     if (!node_name) {
84215489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
84315489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
84415489c76SJeff Cody         /*
84515489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
84615489c76SJeff Cody          * generated (generated names use characters not available to the user)
84715489c76SJeff Cody          */
8489aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
849636ea370SKevin Wolf         return;
8506913c0c2SBenoît Canet     }
8516913c0c2SBenoît Canet 
8520c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8537f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8540c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8550c5e94eeSBenoît Canet                    node_name);
85615489c76SJeff Cody         goto out;
8570c5e94eeSBenoît Canet     }
8580c5e94eeSBenoît Canet 
8596913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8606913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8616913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
86215489c76SJeff Cody         goto out;
8636913c0c2SBenoît Canet     }
8646913c0c2SBenoît Canet 
8656913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8666913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8676913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
86815489c76SJeff Cody out:
86915489c76SJeff Cody     g_free(gen_node_name);
8706913c0c2SBenoît Canet }
8716913c0c2SBenoît Canet 
87218edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
87318edf289SKevin Wolf     .name = "bdrv_common",
87418edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
87518edf289SKevin Wolf     .desc = {
87618edf289SKevin Wolf         {
87718edf289SKevin Wolf             .name = "node-name",
87818edf289SKevin Wolf             .type = QEMU_OPT_STRING,
87918edf289SKevin Wolf             .help = "Node name of the block device node",
88018edf289SKevin Wolf         },
88162392ebbSKevin Wolf         {
88262392ebbSKevin Wolf             .name = "driver",
88362392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
88462392ebbSKevin Wolf             .help = "Block driver to use for the node",
88562392ebbSKevin Wolf         },
88691a097e7SKevin Wolf         {
88791a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
88891a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
88991a097e7SKevin Wolf             .help = "Enable writeback mode",
89091a097e7SKevin Wolf         },
89191a097e7SKevin Wolf         {
89291a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
89391a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
89491a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
89591a097e7SKevin Wolf         },
89691a097e7SKevin Wolf         {
89791a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
89891a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
89991a097e7SKevin Wolf             .help = "Ignore flush requests",
90091a097e7SKevin Wolf         },
90118edf289SKevin Wolf         { /* end of list */ }
90218edf289SKevin Wolf     },
90318edf289SKevin Wolf };
90418edf289SKevin Wolf 
905b6ce07aaSKevin Wolf /*
90657915332SKevin Wolf  * Common part for opening disk images and files
907b6ad491aSKevin Wolf  *
908b6ad491aSKevin Wolf  * Removes all processed options from *options.
90957915332SKevin Wolf  */
9109a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
91182dc8b41SKevin Wolf                             QDict *options, Error **errp)
91257915332SKevin Wolf {
91357915332SKevin Wolf     int ret, open_flags;
914035fccdfSKevin Wolf     const char *filename;
91562392ebbSKevin Wolf     const char *driver_name = NULL;
9166913c0c2SBenoît Canet     const char *node_name = NULL;
91718edf289SKevin Wolf     QemuOpts *opts;
91862392ebbSKevin Wolf     BlockDriver *drv;
91934b5d2c6SMax Reitz     Error *local_err = NULL;
92057915332SKevin Wolf 
9216405875cSPaolo Bonzini     assert(bs->file == NULL);
922707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
92357915332SKevin Wolf 
92462392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
92562392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
92662392ebbSKevin Wolf     if (local_err) {
92762392ebbSKevin Wolf         error_propagate(errp, local_err);
92862392ebbSKevin Wolf         ret = -EINVAL;
92962392ebbSKevin Wolf         goto fail_opts;
93062392ebbSKevin Wolf     }
93162392ebbSKevin Wolf 
93262392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
93362392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
93462392ebbSKevin Wolf     assert(drv != NULL);
93562392ebbSKevin Wolf 
93645673671SKevin Wolf     if (file != NULL) {
9379a4f4c31SKevin Wolf         filename = file->bs->filename;
93845673671SKevin Wolf     } else {
93945673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
94045673671SKevin Wolf     }
94145673671SKevin Wolf 
942765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
943765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
944765003dbSKevin Wolf                    drv->format_name);
94518edf289SKevin Wolf         ret = -EINVAL;
94618edf289SKevin Wolf         goto fail_opts;
94718edf289SKevin Wolf     }
94818edf289SKevin Wolf 
94982dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
95082dc8b41SKevin Wolf                            drv->format_name);
95162392ebbSKevin Wolf 
95218edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
953636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9540fb6395cSMarkus Armbruster     if (local_err) {
955636ea370SKevin Wolf         error_propagate(errp, local_err);
95618edf289SKevin Wolf         ret = -EINVAL;
95718edf289SKevin Wolf         goto fail_opts;
9585d186eb0SKevin Wolf     }
9595d186eb0SKevin Wolf 
960c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9610d51b4deSAsias He     bs->zero_beyond_eof = true;
96282dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
963b64ec4e4SFam Zheng 
964b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9658f94a6e4SKevin Wolf         error_setg(errp,
9668f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9678f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9688f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9698f94a6e4SKevin Wolf                    drv->format_name);
97018edf289SKevin Wolf         ret = -ENOTSUP;
97118edf289SKevin Wolf         goto fail_opts;
972b64ec4e4SFam Zheng     }
97357915332SKevin Wolf 
97453fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
97582dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9760ebd24e0SKevin Wolf         if (!bs->read_only) {
97753fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9780ebd24e0SKevin Wolf         } else {
9790ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
98018edf289SKevin Wolf             ret = -EINVAL;
98118edf289SKevin Wolf             goto fail_opts;
9820ebd24e0SKevin Wolf         }
98353fec9d3SStefan Hajnoczi     }
98453fec9d3SStefan Hajnoczi 
985c2ad1b0cSKevin Wolf     if (filename != NULL) {
98657915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
987c2ad1b0cSKevin Wolf     } else {
988c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
989c2ad1b0cSKevin Wolf     }
99091af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
99157915332SKevin Wolf 
99257915332SKevin Wolf     bs->drv = drv;
9937267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
99457915332SKevin Wolf 
99591a097e7SKevin Wolf     /* Apply cache mode options */
99691a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
99791a097e7SKevin Wolf     bdrv_set_enable_write_cache(bs, bs->open_flags & BDRV_O_CACHE_WB);
998e7c63796SStefan Hajnoczi 
99966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
100082dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
100166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
10025d186eb0SKevin Wolf         assert(file == NULL);
1003030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
100434b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
1005f500a6d3SKevin Wolf     } else {
10062af5ef70SKevin Wolf         if (file == NULL) {
100734b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
100834b5d2c6SMax Reitz                        "protocol level", drv->format_name);
10092af5ef70SKevin Wolf             ret = -EINVAL;
10102af5ef70SKevin Wolf             goto free_and_fail;
10112af5ef70SKevin Wolf         }
1012f500a6d3SKevin Wolf         bs->file = file;
101334b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
101466f82ceeSKevin Wolf     }
101566f82ceeSKevin Wolf 
101657915332SKevin Wolf     if (ret < 0) {
101784d18f06SMarkus Armbruster         if (local_err) {
101834b5d2c6SMax Reitz             error_propagate(errp, local_err);
10192fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
10202fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
102134b5d2c6SMax Reitz         } else {
102234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
102334b5d2c6SMax Reitz         }
102457915332SKevin Wolf         goto free_and_fail;
102557915332SKevin Wolf     }
102657915332SKevin Wolf 
1027a1f688f4SMarkus Armbruster     if (bs->encrypted) {
1028a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
1029a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
1030a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
1031a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
1032a1f688f4SMarkus Armbruster     }
1033a1f688f4SMarkus Armbruster 
103451762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
103551762288SStefan Hajnoczi     if (ret < 0) {
103634b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
103751762288SStefan Hajnoczi         goto free_and_fail;
103857915332SKevin Wolf     }
103951762288SStefan Hajnoczi 
10403baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10413baca891SKevin Wolf     if (local_err) {
10423baca891SKevin Wolf         error_propagate(errp, local_err);
10433baca891SKevin Wolf         ret = -EINVAL;
10443baca891SKevin Wolf         goto free_and_fail;
10453baca891SKevin Wolf     }
10463baca891SKevin Wolf 
1047c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10484196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1049b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
105018edf289SKevin Wolf 
105118edf289SKevin Wolf     qemu_opts_del(opts);
105257915332SKevin Wolf     return 0;
105357915332SKevin Wolf 
105457915332SKevin Wolf free_and_fail:
105566f82ceeSKevin Wolf     bs->file = NULL;
10567267c094SAnthony Liguori     g_free(bs->opaque);
105757915332SKevin Wolf     bs->opaque = NULL;
105857915332SKevin Wolf     bs->drv = NULL;
105918edf289SKevin Wolf fail_opts:
106018edf289SKevin Wolf     qemu_opts_del(opts);
106157915332SKevin Wolf     return ret;
106257915332SKevin Wolf }
106357915332SKevin Wolf 
10645e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10655e5c4f63SKevin Wolf {
10665e5c4f63SKevin Wolf     QObject *options_obj;
10675e5c4f63SKevin Wolf     QDict *options;
10685e5c4f63SKevin Wolf     int ret;
10695e5c4f63SKevin Wolf 
10705e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10715e5c4f63SKevin Wolf     assert(ret);
10725e5c4f63SKevin Wolf 
10735e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10745e5c4f63SKevin Wolf     if (!options_obj) {
10755e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10765e5c4f63SKevin Wolf         return NULL;
10775e5c4f63SKevin Wolf     }
10785e5c4f63SKevin Wolf 
10795e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10805e5c4f63SKevin Wolf         qobject_decref(options_obj);
10815e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10825e5c4f63SKevin Wolf         return NULL;
10835e5c4f63SKevin Wolf     }
10845e5c4f63SKevin Wolf 
10855e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10865e5c4f63SKevin Wolf     qdict_flatten(options);
10875e5c4f63SKevin Wolf 
10885e5c4f63SKevin Wolf     return options;
10895e5c4f63SKevin Wolf }
10905e5c4f63SKevin Wolf 
1091de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1092de3b53f0SKevin Wolf                                 Error **errp)
1093de3b53f0SKevin Wolf {
1094de3b53f0SKevin Wolf     QDict *json_options;
1095de3b53f0SKevin Wolf     Error *local_err = NULL;
1096de3b53f0SKevin Wolf 
1097de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1098de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1099de3b53f0SKevin Wolf         return;
1100de3b53f0SKevin Wolf     }
1101de3b53f0SKevin Wolf 
1102de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1103de3b53f0SKevin Wolf     if (local_err) {
1104de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1105de3b53f0SKevin Wolf         return;
1106de3b53f0SKevin Wolf     }
1107de3b53f0SKevin Wolf 
1108de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1109de3b53f0SKevin Wolf      * specified directly */
1110de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1111de3b53f0SKevin Wolf     QDECREF(json_options);
1112de3b53f0SKevin Wolf     *pfilename = NULL;
1113de3b53f0SKevin Wolf }
1114de3b53f0SKevin Wolf 
111557915332SKevin Wolf /*
1116f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1117f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
111853a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
111953a29513SMax Reitz  * block driver has been specified explicitly.
1120f54120ffSKevin Wolf  */
1121de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1122053e1578SMax Reitz                              int *flags, Error **errp)
1123f54120ffSKevin Wolf {
1124f54120ffSKevin Wolf     const char *drvname;
112553a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1126f54120ffSKevin Wolf     bool parse_filename = false;
1127053e1578SMax Reitz     BlockDriver *drv = NULL;
1128f54120ffSKevin Wolf     Error *local_err = NULL;
1129f54120ffSKevin Wolf 
113053a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1131053e1578SMax Reitz     if (drvname) {
1132053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1133053e1578SMax Reitz         if (!drv) {
1134053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1135053e1578SMax Reitz             return -ENOENT;
1136053e1578SMax Reitz         }
113753a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
113853a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1139053e1578SMax Reitz         protocol = drv->bdrv_file_open;
114053a29513SMax Reitz     }
114153a29513SMax Reitz 
114253a29513SMax Reitz     if (protocol) {
114353a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
114453a29513SMax Reitz     } else {
114553a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
114653a29513SMax Reitz     }
114753a29513SMax Reitz 
114891a097e7SKevin Wolf     /* Translate cache options from flags into options */
114991a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
115091a097e7SKevin Wolf 
1151f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
115217b005f1SKevin Wolf     if (protocol && filename) {
1153f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1154f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1155f54120ffSKevin Wolf             parse_filename = true;
1156f54120ffSKevin Wolf         } else {
1157f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1158f54120ffSKevin Wolf                              "the same time");
1159f54120ffSKevin Wolf             return -EINVAL;
1160f54120ffSKevin Wolf         }
1161f54120ffSKevin Wolf     }
1162f54120ffSKevin Wolf 
1163f54120ffSKevin Wolf     /* Find the right block driver */
1164f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1165f54120ffSKevin Wolf 
116617b005f1SKevin Wolf     if (!drvname && protocol) {
1167f54120ffSKevin Wolf         if (filename) {
1168b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1169f54120ffSKevin Wolf             if (!drv) {
1170f54120ffSKevin Wolf                 return -EINVAL;
1171f54120ffSKevin Wolf             }
1172f54120ffSKevin Wolf 
1173f54120ffSKevin Wolf             drvname = drv->format_name;
1174f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1175f54120ffSKevin Wolf         } else {
1176f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1177f54120ffSKevin Wolf             return -EINVAL;
1178f54120ffSKevin Wolf         }
117917b005f1SKevin Wolf     }
118017b005f1SKevin Wolf 
118117b005f1SKevin Wolf     assert(drv || !protocol);
1182f54120ffSKevin Wolf 
1183f54120ffSKevin Wolf     /* Driver-specific filename parsing */
118417b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1185f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1186f54120ffSKevin Wolf         if (local_err) {
1187f54120ffSKevin Wolf             error_propagate(errp, local_err);
1188f54120ffSKevin Wolf             return -EINVAL;
1189f54120ffSKevin Wolf         }
1190f54120ffSKevin Wolf 
1191f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1192f54120ffSKevin Wolf             qdict_del(*options, "filename");
1193f54120ffSKevin Wolf         }
1194f54120ffSKevin Wolf     }
1195f54120ffSKevin Wolf 
1196d44f928aSMax Reitz     if (runstate_check(RUN_STATE_INMIGRATE)) {
119704c01a5cSKevin Wolf         *flags |= BDRV_O_INACTIVE;
1198d44f928aSMax Reitz     }
1199d44f928aSMax Reitz 
1200f54120ffSKevin Wolf     return 0;
1201f54120ffSKevin Wolf }
1202f54120ffSKevin Wolf 
1203b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1204df581792SKevin Wolf                                     BlockDriverState *child_bs,
1205260fecf1SKevin Wolf                                     const char *child_name,
1206df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1207df581792SKevin Wolf {
1208df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1209df581792SKevin Wolf     *child = (BdrvChild) {
1210df581792SKevin Wolf         .bs     = child_bs,
1211260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1212df581792SKevin Wolf         .role   = child_role,
1213df581792SKevin Wolf     };
1214df581792SKevin Wolf 
1215df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1216d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1217b4b059f6SKevin Wolf 
1218b4b059f6SKevin Wolf     return child;
1219df581792SKevin Wolf }
1220df581792SKevin Wolf 
12213f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
122233a60407SKevin Wolf {
122333a60407SKevin Wolf     QLIST_REMOVE(child, next);
1224d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1225260fecf1SKevin Wolf     g_free(child->name);
122633a60407SKevin Wolf     g_free(child);
122733a60407SKevin Wolf }
122833a60407SKevin Wolf 
122933a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
123033a60407SKevin Wolf {
1231779020cbSKevin Wolf     BlockDriverState *child_bs;
1232779020cbSKevin Wolf 
1233779020cbSKevin Wolf     if (child == NULL) {
1234779020cbSKevin Wolf         return;
1235779020cbSKevin Wolf     }
123633a60407SKevin Wolf 
123733a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
123833a60407SKevin Wolf         child->bs->inherits_from = NULL;
123933a60407SKevin Wolf     }
124033a60407SKevin Wolf 
1241779020cbSKevin Wolf     child_bs = child->bs;
124233a60407SKevin Wolf     bdrv_detach_child(child);
124333a60407SKevin Wolf     bdrv_unref(child_bs);
124433a60407SKevin Wolf }
124533a60407SKevin Wolf 
12465db15a57SKevin Wolf /*
12475db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12485db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12495db15a57SKevin Wolf  */
12508d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12518d24cce1SFam Zheng {
12525db15a57SKevin Wolf     if (backing_hd) {
12535db15a57SKevin Wolf         bdrv_ref(backing_hd);
12545db15a57SKevin Wolf     }
12558d24cce1SFam Zheng 
1256760e0063SKevin Wolf     if (bs->backing) {
1257826b6ca0SFam Zheng         assert(bs->backing_blocker);
1258760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12595db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1260826b6ca0SFam Zheng     } else if (backing_hd) {
1261826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
126281e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
126381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1264826b6ca0SFam Zheng     }
1265826b6ca0SFam Zheng 
12668d24cce1SFam Zheng     if (!backing_hd) {
1267826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1268826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1269760e0063SKevin Wolf         bs->backing = NULL;
12708d24cce1SFam Zheng         goto out;
12718d24cce1SFam Zheng     }
1272260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
12738d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
12748d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
12758d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
12768d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1277826b6ca0SFam Zheng 
1278760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1279826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1280760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1281826b6ca0SFam Zheng                     bs->backing_blocker);
12828d24cce1SFam Zheng out:
12833baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
12848d24cce1SFam Zheng }
12858d24cce1SFam Zheng 
128631ca6d07SKevin Wolf /*
128731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
128831ca6d07SKevin Wolf  *
1289d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1290d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1291d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1292d9b7b057SKevin Wolf  * BlockdevRef.
1293d9b7b057SKevin Wolf  *
1294d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
129531ca6d07SKevin Wolf  */
1296d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1297d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12989156df12SPaolo Bonzini {
12991ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1300d9b7b057SKevin Wolf     char *bdref_key_dot;
1301d9b7b057SKevin Wolf     const char *reference = NULL;
1302317fc44eSKevin Wolf     int ret = 0;
13038d24cce1SFam Zheng     BlockDriverState *backing_hd;
1304d9b7b057SKevin Wolf     QDict *options;
1305d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
130634b5d2c6SMax Reitz     Error *local_err = NULL;
13079156df12SPaolo Bonzini 
1308760e0063SKevin Wolf     if (bs->backing != NULL) {
13091ba4b6a5SBenoît Canet         goto free_exit;
13109156df12SPaolo Bonzini     }
13119156df12SPaolo Bonzini 
131231ca6d07SKevin Wolf     /* NULL means an empty set of options */
1313d9b7b057SKevin Wolf     if (parent_options == NULL) {
1314d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1315d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
131631ca6d07SKevin Wolf     }
131731ca6d07SKevin Wolf 
13189156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1319d9b7b057SKevin Wolf 
1320d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1321d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1322d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1323d9b7b057SKevin Wolf 
1324d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1325d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13261cb6f506SKevin Wolf         backing_filename[0] = '\0';
13271cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
132831ca6d07SKevin Wolf         QDECREF(options);
13291ba4b6a5SBenoît Canet         goto free_exit;
1330dbecebddSFam Zheng     } else {
13319f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13329f07429eSMax Reitz                                        &local_err);
13339f07429eSMax Reitz         if (local_err) {
13349f07429eSMax Reitz             ret = -EINVAL;
13359f07429eSMax Reitz             error_propagate(errp, local_err);
13369f07429eSMax Reitz             QDECREF(options);
13379f07429eSMax Reitz             goto free_exit;
13389f07429eSMax Reitz         }
13399156df12SPaolo Bonzini     }
13409156df12SPaolo Bonzini 
13418ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13428ee79e70SKevin Wolf         ret = -EINVAL;
13438ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13448ee79e70SKevin Wolf         QDECREF(options);
13458ee79e70SKevin Wolf         goto free_exit;
13468ee79e70SKevin Wolf     }
13478ee79e70SKevin Wolf 
1348c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1349c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13509156df12SPaolo Bonzini     }
13519156df12SPaolo Bonzini 
1352d9b7b057SKevin Wolf     backing_hd = NULL;
1353f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1354f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1355d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1356e43bfd9cSMarkus Armbruster                             errp);
13579156df12SPaolo Bonzini     if (ret < 0) {
13589156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1359e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13601ba4b6a5SBenoît Canet         goto free_exit;
13619156df12SPaolo Bonzini     }
1362df581792SKevin Wolf 
13635db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13645db15a57SKevin Wolf      * backing_hd reference now */
13658d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13665db15a57SKevin Wolf     bdrv_unref(backing_hd);
1367d80ac658SPeter Feiner 
1368d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1369d9b7b057SKevin Wolf 
13701ba4b6a5SBenoît Canet free_exit:
13711ba4b6a5SBenoît Canet     g_free(backing_filename);
1372d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
13731ba4b6a5SBenoît Canet     return ret;
13749156df12SPaolo Bonzini }
13759156df12SPaolo Bonzini 
1376b6ce07aaSKevin Wolf /*
1377da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1378da557aacSMax Reitz  * device's options.
1379da557aacSMax Reitz  *
1380da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1381b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1382da557aacSMax Reitz  *
1383da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1384da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1385da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1386da557aacSMax Reitz  * BlockdevRef.
1387da557aacSMax Reitz  *
1388da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1389da557aacSMax Reitz  */
1390b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1391f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1392b4b059f6SKevin Wolf                            BlockDriverState* parent,
1393b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1394f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1395da557aacSMax Reitz {
1396b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1397b4b059f6SKevin Wolf     BlockDriverState *bs;
1398da557aacSMax Reitz     QDict *image_options;
1399da557aacSMax Reitz     int ret;
1400da557aacSMax Reitz     char *bdref_key_dot;
1401da557aacSMax Reitz     const char *reference;
1402da557aacSMax Reitz 
1403df581792SKevin Wolf     assert(child_role != NULL);
1404f67503e5SMax Reitz 
1405da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1406da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1407da557aacSMax Reitz     g_free(bdref_key_dot);
1408da557aacSMax Reitz 
1409da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1410da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1411b4b059f6SKevin Wolf         if (!allow_none) {
1412da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1413da557aacSMax Reitz                        bdref_key);
1414da557aacSMax Reitz         }
1415b20e61e0SMarkus Armbruster         QDECREF(image_options);
1416da557aacSMax Reitz         goto done;
1417da557aacSMax Reitz     }
1418da557aacSMax Reitz 
1419b4b059f6SKevin Wolf     bs = NULL;
1420b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1421ce343771SMax Reitz                             parent, child_role, errp);
1422df581792SKevin Wolf     if (ret < 0) {
1423df581792SKevin Wolf         goto done;
1424df581792SKevin Wolf     }
1425df581792SKevin Wolf 
1426260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1427da557aacSMax Reitz 
1428da557aacSMax Reitz done:
1429da557aacSMax Reitz     qdict_del(options, bdref_key);
1430b4b059f6SKevin Wolf     return c;
1431b4b059f6SKevin Wolf }
1432b4b059f6SKevin Wolf 
14336b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1434b998875dSKevin Wolf {
1435b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14361ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1437b998875dSKevin Wolf     int64_t total_size;
143883d0521aSChunyan Liu     QemuOpts *opts = NULL;
1439b998875dSKevin Wolf     QDict *snapshot_options;
1440b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1441c2e0dbbfSFam Zheng     Error *local_err = NULL;
1442b998875dSKevin Wolf     int ret;
1443b998875dSKevin Wolf 
1444b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1445b998875dSKevin Wolf        instead of opening 'filename' directly */
1446b998875dSKevin Wolf 
1447b998875dSKevin Wolf     /* Get the required size from the image */
1448f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1449f187743aSKevin Wolf     if (total_size < 0) {
14506b8aeca5SChen Gang         ret = total_size;
1451f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14521ba4b6a5SBenoît Canet         goto out;
1453f187743aSKevin Wolf     }
1454b998875dSKevin Wolf 
1455b998875dSKevin Wolf     /* Create the temporary image */
14561ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1457b998875dSKevin Wolf     if (ret < 0) {
1458b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14591ba4b6a5SBenoît Canet         goto out;
1460b998875dSKevin Wolf     }
1461b998875dSKevin Wolf 
1462ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1463c282e1fdSChunyan Liu                             &error_abort);
146439101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1465e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
146683d0521aSChunyan Liu     qemu_opts_del(opts);
1467b998875dSKevin Wolf     if (ret < 0) {
1468e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1469e43bfd9cSMarkus Armbruster                       tmp_filename);
14701ba4b6a5SBenoît Canet         goto out;
1471b998875dSKevin Wolf     }
1472b998875dSKevin Wolf 
1473b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1474b998875dSKevin Wolf     snapshot_options = qdict_new();
1475b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1476b998875dSKevin Wolf               qstring_from_str("file"));
1477b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1478b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1479e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1480e6641719SMax Reitz               qstring_from_str("qcow2"));
1481b998875dSKevin Wolf 
1482e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1483b998875dSKevin Wolf 
1484b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
14856ebf9aa2SMax Reitz                     flags, &local_err);
1486b998875dSKevin Wolf     if (ret < 0) {
1487b998875dSKevin Wolf         error_propagate(errp, local_err);
14881ba4b6a5SBenoît Canet         goto out;
1489b998875dSKevin Wolf     }
1490b998875dSKevin Wolf 
1491b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14921ba4b6a5SBenoît Canet 
14931ba4b6a5SBenoît Canet out:
14941ba4b6a5SBenoît Canet     g_free(tmp_filename);
14956b8aeca5SChen Gang     return ret;
1496b998875dSKevin Wolf }
1497b998875dSKevin Wolf 
1498da557aacSMax Reitz /*
1499b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1500de9c0cecSKevin Wolf  *
1501de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1502de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1503de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1504de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1505f67503e5SMax Reitz  *
1506f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1507f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1508ddf5636dSMax Reitz  *
1509ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1510ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1511ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1512b6ce07aaSKevin Wolf  */
1513f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1514ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1515f3930ed0SKevin Wolf                              BlockDriverState *parent,
1516ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1517ea2384d3Sbellard {
1518b6ce07aaSKevin Wolf     int ret;
15199a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15209a4f4c31SKevin Wolf     BlockDriverState *bs;
1521ce343771SMax Reitz     BlockDriver *drv = NULL;
152274fe54f2SKevin Wolf     const char *drvname;
15233e8c2e57SAlberto Garcia     const char *backing;
152434b5d2c6SMax Reitz     Error *local_err = NULL;
1525b1e6fc08SKevin Wolf     int snapshot_flags = 0;
152633e3963eSbellard 
1527f67503e5SMax Reitz     assert(pbs);
1528f3930ed0SKevin Wolf     assert(!child_role || !flags);
1529f3930ed0SKevin Wolf     assert(!child_role == !parent);
1530f67503e5SMax Reitz 
1531ddf5636dSMax Reitz     if (reference) {
1532ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1533ddf5636dSMax Reitz         QDECREF(options);
1534ddf5636dSMax Reitz 
1535ddf5636dSMax Reitz         if (*pbs) {
1536ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1537ddf5636dSMax Reitz                        "another block device");
1538ddf5636dSMax Reitz             return -EINVAL;
1539ddf5636dSMax Reitz         }
1540ddf5636dSMax Reitz 
1541ddf5636dSMax Reitz         if (filename || options_non_empty) {
1542ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1543ddf5636dSMax Reitz                        "additional options or a new filename");
1544ddf5636dSMax Reitz             return -EINVAL;
1545ddf5636dSMax Reitz         }
1546ddf5636dSMax Reitz 
1547ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1548ddf5636dSMax Reitz         if (!bs) {
1549ddf5636dSMax Reitz             return -ENODEV;
1550ddf5636dSMax Reitz         }
1551ddf5636dSMax Reitz         bdrv_ref(bs);
1552ddf5636dSMax Reitz         *pbs = bs;
1553ddf5636dSMax Reitz         return 0;
1554ddf5636dSMax Reitz     }
1555ddf5636dSMax Reitz 
1556f67503e5SMax Reitz     if (*pbs) {
1557f67503e5SMax Reitz         bs = *pbs;
1558f67503e5SMax Reitz     } else {
1559e4e9986bSMarkus Armbruster         bs = bdrv_new();
1560f67503e5SMax Reitz     }
1561f67503e5SMax Reitz 
1562de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1563de9c0cecSKevin Wolf     if (options == NULL) {
1564de9c0cecSKevin Wolf         options = qdict_new();
1565de9c0cecSKevin Wolf     }
1566de9c0cecSKevin Wolf 
1567145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1568de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1569de3b53f0SKevin Wolf     if (local_err) {
1570de3b53f0SKevin Wolf         ret = -EINVAL;
1571de3b53f0SKevin Wolf         goto fail;
1572de3b53f0SKevin Wolf     }
1573de3b53f0SKevin Wolf 
1574145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1575145f598eSKevin Wolf 
1576f3930ed0SKevin Wolf     if (child_role) {
1577bddcec37SKevin Wolf         bs->inherits_from = parent;
15788e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
15798e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1580f3930ed0SKevin Wolf     }
1581f3930ed0SKevin Wolf 
1582de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1583462f5bcfSKevin Wolf     if (local_err) {
1584462f5bcfSKevin Wolf         goto fail;
1585462f5bcfSKevin Wolf     }
1586462f5bcfSKevin Wolf 
158762392ebbSKevin Wolf     bs->open_flags = flags;
158862392ebbSKevin Wolf     bs->options = options;
158962392ebbSKevin Wolf     options = qdict_clone_shallow(options);
159062392ebbSKevin Wolf 
159176c591b0SKevin Wolf     /* Find the right image format driver */
159276c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
159376c591b0SKevin Wolf     if (drvname) {
159476c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
159576c591b0SKevin Wolf         if (!drv) {
159676c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
159776c591b0SKevin Wolf             ret = -EINVAL;
159876c591b0SKevin Wolf             goto fail;
159976c591b0SKevin Wolf         }
160076c591b0SKevin Wolf     }
160176c591b0SKevin Wolf 
160276c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
160376c591b0SKevin Wolf 
16043e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
16053e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16063e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16073e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16083e8c2e57SAlberto Garcia     }
16093e8c2e57SAlberto Garcia 
1610f500a6d3SKevin Wolf     /* Open image file without format layer */
1611f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1612be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1613be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1614be028adcSJeff Cody         }
1615b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1616b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
16178e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1618b1e6fc08SKevin Wolf         }
1619be028adcSJeff Cody 
1620f3930ed0SKevin Wolf         bs->open_flags = flags;
16211fdd6933SKevin Wolf 
16229a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16231fdd6933SKevin Wolf                                &child_file, true, &local_err);
16241fdd6933SKevin Wolf         if (local_err) {
16251fdd6933SKevin Wolf             ret = -EINVAL;
16268bfea15dSKevin Wolf             goto fail;
1627f500a6d3SKevin Wolf         }
1628f4788adcSKevin Wolf     }
1629f500a6d3SKevin Wolf 
163076c591b0SKevin Wolf     /* Image format probing */
163138f3ef57SKevin Wolf     bs->probed = !drv;
163276c591b0SKevin Wolf     if (!drv && file) {
16339a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
163417b005f1SKevin Wolf         if (ret < 0) {
163517b005f1SKevin Wolf             goto fail;
163617b005f1SKevin Wolf         }
163762392ebbSKevin Wolf         /*
163862392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
163962392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
164062392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
164162392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
164262392ebbSKevin Wolf          *
164362392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
164462392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
164562392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
164662392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
164762392ebbSKevin Wolf          */
164862392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
164962392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
165076c591b0SKevin Wolf     } else if (!drv) {
16512a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16522a05cbe4SMax Reitz         ret = -EINVAL;
16538bfea15dSKevin Wolf         goto fail;
16542a05cbe4SMax Reitz     }
1655f500a6d3SKevin Wolf 
165653a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
165753a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
165853a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
165953a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
166053a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
166153a29513SMax Reitz 
1662b6ce07aaSKevin Wolf     /* Open the image */
166382dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1664b6ce07aaSKevin Wolf     if (ret < 0) {
16658bfea15dSKevin Wolf         goto fail;
16666987307cSChristoph Hellwig     }
16676987307cSChristoph Hellwig 
16682a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16699a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1670f500a6d3SKevin Wolf         file = NULL;
1671f500a6d3SKevin Wolf     }
1672f500a6d3SKevin Wolf 
1673b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16749156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1675d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1676b6ce07aaSKevin Wolf         if (ret < 0) {
1677b6ad491aSKevin Wolf             goto close_and_fail;
1678b6ce07aaSKevin Wolf         }
1679b6ce07aaSKevin Wolf     }
1680b6ce07aaSKevin Wolf 
168191af7014SMax Reitz     bdrv_refresh_filename(bs);
168291af7014SMax Reitz 
1683b6ad491aSKevin Wolf     /* Check if any unknown options were used */
16845acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1685b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
16865acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
16875acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
16885acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
16895acd9d81SMax Reitz         } else {
169034b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
16915acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1692bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
16935acd9d81SMax Reitz         }
1694b6ad491aSKevin Wolf 
1695b6ad491aSKevin Wolf         ret = -EINVAL;
1696b6ad491aSKevin Wolf         goto close_and_fail;
1697b6ad491aSKevin Wolf     }
1698b6ad491aSKevin Wolf 
1699b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1700a7f53e26SMarkus Armbruster         if (bs->blk) {
1701a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1702a7f53e26SMarkus Armbruster         }
1703c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1704c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1705c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1706c3adb58fSMarkus Armbruster         error_setg(errp,
1707c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1708c3adb58fSMarkus Armbruster         ret = -EBUSY;
1709c3adb58fSMarkus Armbruster         goto close_and_fail;
1710b6ce07aaSKevin Wolf     }
1711b6ce07aaSKevin Wolf 
1712c3adb58fSMarkus Armbruster     QDECREF(options);
1713f67503e5SMax Reitz     *pbs = bs;
1714dd62f1caSKevin Wolf 
1715dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1716dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1717dd62f1caSKevin Wolf     if (snapshot_flags) {
1718dd62f1caSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1719dd62f1caSKevin Wolf         if (local_err) {
1720dd62f1caSKevin Wolf             goto close_and_fail;
1721dd62f1caSKevin Wolf         }
1722dd62f1caSKevin Wolf     }
1723dd62f1caSKevin Wolf 
1724b6ce07aaSKevin Wolf     return 0;
1725b6ce07aaSKevin Wolf 
17268bfea15dSKevin Wolf fail:
1727f500a6d3SKevin Wolf     if (file != NULL) {
17289a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1729f500a6d3SKevin Wolf     }
1730145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1731de9c0cecSKevin Wolf     QDECREF(bs->options);
1732b6ad491aSKevin Wolf     QDECREF(options);
1733de9c0cecSKevin Wolf     bs->options = NULL;
1734f67503e5SMax Reitz     if (!*pbs) {
1735f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1736f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1737f67503e5SMax Reitz            since it has not really been opened yet. */
1738f67503e5SMax Reitz         bdrv_unref(bs);
1739f67503e5SMax Reitz     }
174084d18f06SMarkus Armbruster     if (local_err) {
174134b5d2c6SMax Reitz         error_propagate(errp, local_err);
174234b5d2c6SMax Reitz     }
1743b6ad491aSKevin Wolf     return ret;
1744de9c0cecSKevin Wolf 
1745b6ad491aSKevin Wolf close_and_fail:
1746f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1747f67503e5SMax Reitz     if (*pbs) {
1748b6ad491aSKevin Wolf         bdrv_close(bs);
1749f67503e5SMax Reitz     } else {
1750f67503e5SMax Reitz         bdrv_unref(bs);
1751f67503e5SMax Reitz     }
1752b6ad491aSKevin Wolf     QDECREF(options);
175384d18f06SMarkus Armbruster     if (local_err) {
175434b5d2c6SMax Reitz         error_propagate(errp, local_err);
175534b5d2c6SMax Reitz     }
1756b6ce07aaSKevin Wolf     return ret;
1757b6ce07aaSKevin Wolf }
1758b6ce07aaSKevin Wolf 
1759f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
17606ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1761f3930ed0SKevin Wolf {
1762f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1763ce343771SMax Reitz                              NULL, errp);
1764f3930ed0SKevin Wolf }
1765f3930ed0SKevin Wolf 
1766e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1767e971aa12SJeff Cody      bool prepared;
1768e971aa12SJeff Cody      BDRVReopenState state;
1769e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1770e971aa12SJeff Cody } BlockReopenQueueEntry;
1771e971aa12SJeff Cody 
1772e971aa12SJeff Cody /*
1773e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1774e971aa12SJeff Cody  * reopen of multiple devices.
1775e971aa12SJeff Cody  *
1776e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1777e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1778e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1779e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1780e971aa12SJeff Cody  * atomic 'set'.
1781e971aa12SJeff Cody  *
1782e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1783e971aa12SJeff Cody  *
17844d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17854d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
17864d2cb092SKevin Wolf  *
1787e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1788e971aa12SJeff Cody  *
1789e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1790e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1791e971aa12SJeff Cody  *
1792e971aa12SJeff Cody  */
179328518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
17944d2cb092SKevin Wolf                                                  BlockDriverState *bs,
179528518102SKevin Wolf                                                  QDict *options,
179628518102SKevin Wolf                                                  int flags,
179728518102SKevin Wolf                                                  const BdrvChildRole *role,
179828518102SKevin Wolf                                                  QDict *parent_options,
179928518102SKevin Wolf                                                  int parent_flags)
1800e971aa12SJeff Cody {
1801e971aa12SJeff Cody     assert(bs != NULL);
1802e971aa12SJeff Cody 
1803e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
180467251a31SKevin Wolf     BdrvChild *child;
1805145f598eSKevin Wolf     QDict *old_options, *explicit_options;
180667251a31SKevin Wolf 
1807e971aa12SJeff Cody     if (bs_queue == NULL) {
1808e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1809e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1810e971aa12SJeff Cody     }
1811e971aa12SJeff Cody 
18124d2cb092SKevin Wolf     if (!options) {
18134d2cb092SKevin Wolf         options = qdict_new();
18144d2cb092SKevin Wolf     }
18154d2cb092SKevin Wolf 
181628518102SKevin Wolf     /*
181728518102SKevin Wolf      * Precedence of options:
181828518102SKevin Wolf      * 1. Explicitly passed in options (highest)
181991a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1820145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18218e2160e2SKevin Wolf      * 4. Inherited from parent node
182228518102SKevin Wolf      * 5. Retained from effective options of bs
182328518102SKevin Wolf      */
182428518102SKevin Wolf 
182591a097e7SKevin Wolf     if (!parent_options) {
182691a097e7SKevin Wolf         /*
182791a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
182891a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
182991a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
183091a097e7SKevin Wolf          * not considered.
183191a097e7SKevin Wolf          */
183291a097e7SKevin Wolf         update_options_from_flags(options, flags);
183391a097e7SKevin Wolf     }
183491a097e7SKevin Wolf 
1835145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1836145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1837145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1838145f598eSKevin Wolf     QDECREF(old_options);
1839145f598eSKevin Wolf 
1840145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1841145f598eSKevin Wolf 
184228518102SKevin Wolf     /* Inherit from parent node */
184328518102SKevin Wolf     if (parent_options) {
184428518102SKevin Wolf         assert(!flags);
18458e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
184628518102SKevin Wolf     }
184728518102SKevin Wolf 
184828518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18494d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1850cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18514d2cb092SKevin Wolf     QDECREF(old_options);
18524d2cb092SKevin Wolf 
1853f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1854f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1855f1f25a2eSKevin Wolf 
185667251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18574c9dfe5dSKevin Wolf         QDict *new_child_options;
18584c9dfe5dSKevin Wolf         char *child_key_dot;
185967251a31SKevin Wolf 
18604c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18614c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18624c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
186367251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
186467251a31SKevin Wolf             continue;
186567251a31SKevin Wolf         }
186667251a31SKevin Wolf 
18674c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18684c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18694c9dfe5dSKevin Wolf         g_free(child_key_dot);
18704c9dfe5dSKevin Wolf 
187128518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
187228518102SKevin Wolf                                 child->role, options, flags);
1873e971aa12SJeff Cody     }
1874e971aa12SJeff Cody 
1875e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1876e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1877e971aa12SJeff Cody 
1878e971aa12SJeff Cody     bs_entry->state.bs = bs;
18794d2cb092SKevin Wolf     bs_entry->state.options = options;
1880145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1881e971aa12SJeff Cody     bs_entry->state.flags = flags;
1882e971aa12SJeff Cody 
1883e971aa12SJeff Cody     return bs_queue;
1884e971aa12SJeff Cody }
1885e971aa12SJeff Cody 
188628518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
188728518102SKevin Wolf                                     BlockDriverState *bs,
188828518102SKevin Wolf                                     QDict *options, int flags)
188928518102SKevin Wolf {
189028518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
189128518102SKevin Wolf                                    NULL, NULL, 0);
189228518102SKevin Wolf }
189328518102SKevin Wolf 
1894e971aa12SJeff Cody /*
1895e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1896e971aa12SJeff Cody  *
1897e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1898e971aa12SJeff Cody  * via bdrv_reopen_queue().
1899e971aa12SJeff Cody  *
1900e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1901e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1902e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1903e971aa12SJeff Cody  * data cleaned up.
1904e971aa12SJeff Cody  *
1905e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1906e971aa12SJeff Cody  * to all devices.
1907e971aa12SJeff Cody  *
1908e971aa12SJeff Cody  */
1909e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1910e971aa12SJeff Cody {
1911e971aa12SJeff Cody     int ret = -1;
1912e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1913e971aa12SJeff Cody     Error *local_err = NULL;
1914e971aa12SJeff Cody 
1915e971aa12SJeff Cody     assert(bs_queue != NULL);
1916e971aa12SJeff Cody 
1917e971aa12SJeff Cody     bdrv_drain_all();
1918e971aa12SJeff Cody 
1919e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1920e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1921e971aa12SJeff Cody             error_propagate(errp, local_err);
1922e971aa12SJeff Cody             goto cleanup;
1923e971aa12SJeff Cody         }
1924e971aa12SJeff Cody         bs_entry->prepared = true;
1925e971aa12SJeff Cody     }
1926e971aa12SJeff Cody 
1927e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1928e971aa12SJeff Cody      * changes
1929e971aa12SJeff Cody      */
1930e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1931e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1932e971aa12SJeff Cody     }
1933e971aa12SJeff Cody 
1934e971aa12SJeff Cody     ret = 0;
1935e971aa12SJeff Cody 
1936e971aa12SJeff Cody cleanup:
1937e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1938e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1939e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1940145f598eSKevin Wolf         } else if (ret) {
1941145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1942e971aa12SJeff Cody         }
19434d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1944e971aa12SJeff Cody         g_free(bs_entry);
1945e971aa12SJeff Cody     }
1946e971aa12SJeff Cody     g_free(bs_queue);
1947e971aa12SJeff Cody     return ret;
1948e971aa12SJeff Cody }
1949e971aa12SJeff Cody 
1950e971aa12SJeff Cody 
1951e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1952e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1953e971aa12SJeff Cody {
1954e971aa12SJeff Cody     int ret = -1;
1955e971aa12SJeff Cody     Error *local_err = NULL;
19564d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1957e971aa12SJeff Cody 
1958e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1959e971aa12SJeff Cody     if (local_err != NULL) {
1960e971aa12SJeff Cody         error_propagate(errp, local_err);
1961e971aa12SJeff Cody     }
1962e971aa12SJeff Cody     return ret;
1963e971aa12SJeff Cody }
1964e971aa12SJeff Cody 
1965e971aa12SJeff Cody 
1966e971aa12SJeff Cody /*
1967e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1968e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1969e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1970e971aa12SJeff Cody  *
1971e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1972e971aa12SJeff Cody  * flags are the new open flags
1973e971aa12SJeff Cody  * queue is the reopen queue
1974e971aa12SJeff Cody  *
1975e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1976e971aa12SJeff Cody  * as well.
1977e971aa12SJeff Cody  *
1978e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1979e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1980e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1981e971aa12SJeff Cody  *
1982e971aa12SJeff Cody  */
1983e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1984e971aa12SJeff Cody                         Error **errp)
1985e971aa12SJeff Cody {
1986e971aa12SJeff Cody     int ret = -1;
1987e971aa12SJeff Cody     Error *local_err = NULL;
1988e971aa12SJeff Cody     BlockDriver *drv;
1989ccf9dc07SKevin Wolf     QemuOpts *opts;
1990ccf9dc07SKevin Wolf     const char *value;
1991e971aa12SJeff Cody 
1992e971aa12SJeff Cody     assert(reopen_state != NULL);
1993e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1994e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1995e971aa12SJeff Cody 
1996ccf9dc07SKevin Wolf     /* Process generic block layer options */
1997ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1998ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
1999ccf9dc07SKevin Wolf     if (local_err) {
2000ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2001ccf9dc07SKevin Wolf         ret = -EINVAL;
2002ccf9dc07SKevin Wolf         goto error;
2003ccf9dc07SKevin Wolf     }
2004ccf9dc07SKevin Wolf 
200591a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
200691a097e7SKevin Wolf 
200791a097e7SKevin Wolf     /* If a guest device is attached, it owns WCE */
200891a097e7SKevin Wolf     if (reopen_state->bs->blk && blk_get_attached_dev(reopen_state->bs->blk)) {
200991a097e7SKevin Wolf         bool old_wce = bdrv_enable_write_cache(reopen_state->bs);
201091a097e7SKevin Wolf         bool new_wce = (reopen_state->flags & BDRV_O_CACHE_WB);
201191a097e7SKevin Wolf         if (old_wce != new_wce) {
201291a097e7SKevin Wolf             error_setg(errp, "Cannot change cache.writeback: Device attached");
201391a097e7SKevin Wolf             ret = -EINVAL;
201491a097e7SKevin Wolf             goto error;
201591a097e7SKevin Wolf         }
201691a097e7SKevin Wolf     }
201791a097e7SKevin Wolf 
2018ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2019ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2020ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2021ccf9dc07SKevin Wolf     if (value) {
2022ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2023ccf9dc07SKevin Wolf     }
2024ccf9dc07SKevin Wolf 
2025ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2026ccf9dc07SKevin Wolf     if (value) {
2027ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2028ccf9dc07SKevin Wolf     }
2029ccf9dc07SKevin Wolf 
2030e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2031e971aa12SJeff Cody      * to r/w */
2032e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2033e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
203481e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
203581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2036e971aa12SJeff Cody         goto error;
2037e971aa12SJeff Cody     }
2038e971aa12SJeff Cody 
2039e971aa12SJeff Cody 
2040e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2041e971aa12SJeff Cody     if (ret) {
2042455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2043e971aa12SJeff Cody         goto error;
2044e971aa12SJeff Cody     }
2045e971aa12SJeff Cody 
2046e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2047e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2048e971aa12SJeff Cody         if (ret) {
2049e971aa12SJeff Cody             if (local_err != NULL) {
2050e971aa12SJeff Cody                 error_propagate(errp, local_err);
2051e971aa12SJeff Cody             } else {
2052d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2053e971aa12SJeff Cody                            reopen_state->bs->filename);
2054e971aa12SJeff Cody             }
2055e971aa12SJeff Cody             goto error;
2056e971aa12SJeff Cody         }
2057e971aa12SJeff Cody     } else {
2058e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2059e971aa12SJeff Cody          * handler for each supported drv. */
206081e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206181e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
206281e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2063e971aa12SJeff Cody         ret = -1;
2064e971aa12SJeff Cody         goto error;
2065e971aa12SJeff Cody     }
2066e971aa12SJeff Cody 
20674d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20684d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20694d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20704d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20714d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20724d2cb092SKevin Wolf 
20734d2cb092SKevin Wolf         do {
20744d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20754d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20764d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20774d2cb092SKevin Wolf                                                 entry->key);
20784d2cb092SKevin Wolf 
20794d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20804d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20814d2cb092SKevin Wolf                 ret = -EINVAL;
20824d2cb092SKevin Wolf                 goto error;
20834d2cb092SKevin Wolf             }
20844d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20854d2cb092SKevin Wolf     }
20864d2cb092SKevin Wolf 
2087e971aa12SJeff Cody     ret = 0;
2088e971aa12SJeff Cody 
2089e971aa12SJeff Cody error:
2090ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2091e971aa12SJeff Cody     return ret;
2092e971aa12SJeff Cody }
2093e971aa12SJeff Cody 
2094e971aa12SJeff Cody /*
2095e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2096e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2097e971aa12SJeff Cody  * the active BlockDriverState contents.
2098e971aa12SJeff Cody  */
2099e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2100e971aa12SJeff Cody {
2101e971aa12SJeff Cody     BlockDriver *drv;
2102e971aa12SJeff Cody 
2103e971aa12SJeff Cody     assert(reopen_state != NULL);
2104e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2105e971aa12SJeff Cody     assert(drv != NULL);
2106e971aa12SJeff Cody 
2107e971aa12SJeff Cody     /* If there are any driver level actions to take */
2108e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2109e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2110e971aa12SJeff Cody     }
2111e971aa12SJeff Cody 
2112e971aa12SJeff Cody     /* set BDS specific flags now */
2113145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2114145f598eSKevin Wolf 
2115145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2116e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2117e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
2118e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
2119e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2120355ef4acSKevin Wolf 
21213baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2122e971aa12SJeff Cody }
2123e971aa12SJeff Cody 
2124e971aa12SJeff Cody /*
2125e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2126e971aa12SJeff Cody  * reopen_state
2127e971aa12SJeff Cody  */
2128e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2129e971aa12SJeff Cody {
2130e971aa12SJeff Cody     BlockDriver *drv;
2131e971aa12SJeff Cody 
2132e971aa12SJeff Cody     assert(reopen_state != NULL);
2133e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2134e971aa12SJeff Cody     assert(drv != NULL);
2135e971aa12SJeff Cody 
2136e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2137e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2138e971aa12SJeff Cody     }
2139145f598eSKevin Wolf 
2140145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2141e971aa12SJeff Cody }
2142e971aa12SJeff Cody 
2143e971aa12SJeff Cody 
214464dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2145fc01f7e7Sbellard {
214633384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
214733384421SMax Reitz 
21483e914655SPaolo Bonzini     if (bs->job) {
21493e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
21503e914655SPaolo Bonzini     }
215199b7e775SAlberto Garcia 
215299b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
2153a0d64a61SAlberto Garcia     if (bs->throttle_state) {
215499b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
215599b7e775SAlberto Garcia     }
215699b7e775SAlberto Garcia 
2157fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
215858fda173SStefan Hajnoczi     bdrv_flush(bs);
215953ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2160fc27291dSPaolo Bonzini 
2161c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2162c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2163c5acdc9aSMax Reitz 
2164b4d02820SMax Reitz     if (bs->blk) {
2165b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
2166b4d02820SMax Reitz     }
2167b4d02820SMax Reitz 
21683cbc002cSPaolo Bonzini     if (bs->drv) {
21696e93e7c4SKevin Wolf         BdrvChild *child, *next;
21706e93e7c4SKevin Wolf 
21719a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21729a4f4c31SKevin Wolf         bs->drv = NULL;
21739a7dedbcSKevin Wolf 
21749a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21759a7dedbcSKevin Wolf 
21769a4f4c31SKevin Wolf         if (bs->file != NULL) {
21779a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21789a4f4c31SKevin Wolf             bs->file = NULL;
21799a4f4c31SKevin Wolf         }
21809a4f4c31SKevin Wolf 
21816e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
218233a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
218333a60407SKevin Wolf              * bdrv_unref_child() here */
2184bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2185bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2186bddcec37SKevin Wolf             }
218733a60407SKevin Wolf             bdrv_detach_child(child);
21886e93e7c4SKevin Wolf         }
21896e93e7c4SKevin Wolf 
21907267c094SAnthony Liguori         g_free(bs->opaque);
2191ea2384d3Sbellard         bs->opaque = NULL;
219253fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2193a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2194a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
21956405875cSPaolo Bonzini         bs->total_sectors = 0;
21966405875cSPaolo Bonzini         bs->encrypted = 0;
21976405875cSPaolo Bonzini         bs->valid_key = 0;
21986405875cSPaolo Bonzini         bs->sg = 0;
21990d51b4deSAsias He         bs->zero_beyond_eof = false;
2200de9c0cecSKevin Wolf         QDECREF(bs->options);
2201145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2202de9c0cecSKevin Wolf         bs->options = NULL;
220391af7014SMax Reitz         QDECREF(bs->full_open_options);
220491af7014SMax Reitz         bs->full_open_options = NULL;
22059ca11154SPavel Hrdina     }
220666f82ceeSKevin Wolf 
220733384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
220833384421SMax Reitz         g_free(ban);
220933384421SMax Reitz     }
221033384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2211fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2212b338082bSbellard }
2213b338082bSbellard 
22142bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22152bc93fedSMORITA Kazutaka {
22162bc93fedSMORITA Kazutaka     BlockDriverState *bs;
22172bc93fedSMORITA Kazutaka 
2218dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2219ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2220ed78cda3SStefan Hajnoczi 
2221ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
22222bc93fedSMORITA Kazutaka         bdrv_close(bs);
2223ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
22242bc93fedSMORITA Kazutaka     }
22252bc93fedSMORITA Kazutaka }
22262bc93fedSMORITA Kazutaka 
2227dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
2228dc364f4cSBenoît Canet  * graph_bdrv_state list.
2229d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
2230d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
2231d22b2f41SRyan Harper {
2232bfb197e0SMarkus Armbruster     /*
2233bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
2234bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
2235bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
2236bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
2237bfb197e0SMarkus Armbruster      * resetting it to null on remove.
2238bfb197e0SMarkus Armbruster      */
2239bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
2240dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
2241bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
2242d22b2f41SRyan Harper     }
2243dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
2244dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2245dc364f4cSBenoît Canet     }
2246dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
2247d22b2f41SRyan Harper }
2248d22b2f41SRyan Harper 
22498e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
22504ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
22514ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
22524ddc07caSPaolo Bonzini {
22534ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
22544ddc07caSPaolo Bonzini 
22554ddc07caSPaolo Bonzini     /* dev info */
22564ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
22574ddc07caSPaolo Bonzini 
22584ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
22594ddc07caSPaolo Bonzini 
2260dd62f1caSKevin Wolf     /* dirty bitmap */
2261dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2262dd62f1caSKevin Wolf }
2263dd62f1caSKevin Wolf 
2264dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2265dd62f1caSKevin Wolf                                        BlockDriverState *to)
2266dd62f1caSKevin Wolf {
2267dd62f1caSKevin Wolf     BdrvChild *c, *next;
2268dd62f1caSKevin Wolf 
2269dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2270dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2271dd62f1caSKevin Wolf         c->bs = to;
2272dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2273dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2274dd62f1caSKevin Wolf         bdrv_ref(to);
2275dd62f1caSKevin Wolf         bdrv_unref(from);
2276dd62f1caSKevin Wolf     }
2277dd62f1caSKevin Wolf     if (from->blk) {
2278dd62f1caSKevin Wolf         blk_set_bs(from->blk, to);
2279dd62f1caSKevin Wolf         if (!to->device_list.tqe_prev) {
2280dd62f1caSKevin Wolf             QTAILQ_INSERT_BEFORE(from, to, device_list);
2281dd62f1caSKevin Wolf         }
2282dd62f1caSKevin Wolf         QTAILQ_REMOVE(&bdrv_states, from, device_list);
2283dd62f1caSKevin Wolf     }
2284dd62f1caSKevin Wolf }
2285dd62f1caSKevin Wolf 
2286dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2287dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2288dd62f1caSKevin Wolf {
2289dd62f1caSKevin Wolf     BlockDriverState tmp;
2290dd62f1caSKevin Wolf 
2291dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2292dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2293dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2294dd62f1caSKevin Wolf 
2295dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2296dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2297dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2298dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2299dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2300dd62f1caSKevin Wolf     }
2301dd62f1caSKevin Wolf }
2302dd62f1caSKevin Wolf 
23038802d1fdSJeff Cody /*
23048802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
23058802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
23068802d1fdSJeff Cody  *
23078802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
23088802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
23098802d1fdSJeff Cody  *
2310bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2311f6801b83SJeff Cody  *
23128802d1fdSJeff Cody  * This function does not create any image files.
2313dd62f1caSKevin Wolf  *
2314dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2315dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2316dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2317dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
23188802d1fdSJeff Cody  */
23198802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
23208802d1fdSJeff Cody {
2321dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2322dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
23238802d1fdSJeff Cody 
2324dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2325dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2326dd62f1caSKevin Wolf 
2327dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2328dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2329dd62f1caSKevin Wolf 
2330dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2331dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2332dd62f1caSKevin Wolf 
2333dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2334dd62f1caSKevin Wolf      * additional reference any more. */
2335dd62f1caSKevin Wolf     bdrv_unref(bs_new);
23368802d1fdSJeff Cody }
23378802d1fdSJeff Cody 
23383f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
23393f09bfbcSKevin Wolf {
23403f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
23413f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
23423f09bfbcSKevin Wolf 
23433f09bfbcSKevin Wolf     bdrv_ref(old);
23443f09bfbcSKevin Wolf 
23453f09bfbcSKevin Wolf     if (old->blk) {
23463f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
23473f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
23483f09bfbcSKevin Wolf          *
23493f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
23503f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
23513f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
23523f09bfbcSKevin Wolf         assert(!new->blk);
23533f09bfbcSKevin Wolf         swap_feature_fields(old, new);
23543f09bfbcSKevin Wolf     }
23553f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
23563f09bfbcSKevin Wolf 
23573f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
23583f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
23593f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
23603f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
23613f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
23623f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
23633f09bfbcSKevin Wolf     }
23643f09bfbcSKevin Wolf 
23653f09bfbcSKevin Wolf     bdrv_unref(old);
23663f09bfbcSKevin Wolf }
23673f09bfbcSKevin Wolf 
23684f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2369b338082bSbellard {
23703e914655SPaolo Bonzini     assert(!bs->job);
23713718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
23724f6fd349SFam Zheng     assert(!bs->refcnt);
237318846deeSMarkus Armbruster 
2374e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2375e1b5c52eSStefan Hajnoczi 
23761b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2377d22b2f41SRyan Harper     bdrv_make_anon(bs);
237834c6f050Saurel32 
2379*2c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
2380*2c1d04e0SMax Reitz 
23817267c094SAnthony Liguori     g_free(bs);
2382fc01f7e7Sbellard }
2383fc01f7e7Sbellard 
2384e97fc193Saliguori /*
2385e97fc193Saliguori  * Run consistency checks on an image
2386e97fc193Saliguori  *
2387e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2388a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2389e076f338SKevin Wolf  * check are stored in res.
2390e97fc193Saliguori  */
23914534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2392e97fc193Saliguori {
2393908bcd54SMax Reitz     if (bs->drv == NULL) {
2394908bcd54SMax Reitz         return -ENOMEDIUM;
2395908bcd54SMax Reitz     }
2396e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2397e97fc193Saliguori         return -ENOTSUP;
2398e97fc193Saliguori     }
2399e97fc193Saliguori 
2400e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
24014534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2402e97fc193Saliguori }
2403e97fc193Saliguori 
24048a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
24058a426614SKevin Wolf 
240633e3963eSbellard /* commit COW file into the raw image */
240733e3963eSbellard int bdrv_commit(BlockDriverState *bs)
240833e3963eSbellard {
240919cb3738Sbellard     BlockDriver *drv = bs->drv;
241072706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
24118a426614SKevin Wolf     int n, ro, open_flags;
24120bce597dSJeff Cody     int ret = 0;
241372706ea4SJeff Cody     uint8_t *buf = NULL;
241433e3963eSbellard 
241519cb3738Sbellard     if (!drv)
241619cb3738Sbellard         return -ENOMEDIUM;
241733e3963eSbellard 
2418760e0063SKevin Wolf     if (!bs->backing) {
24194dca4b63SNaphtali Sprei         return -ENOTSUP;
24204dca4b63SNaphtali Sprei     }
24214dca4b63SNaphtali Sprei 
2422bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2423760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
24242d3735d3SStefan Hajnoczi         return -EBUSY;
24252d3735d3SStefan Hajnoczi     }
24262d3735d3SStefan Hajnoczi 
2427760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2428760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
24294dca4b63SNaphtali Sprei 
24304dca4b63SNaphtali Sprei     if (ro) {
2431760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
24320bce597dSJeff Cody             return -EACCES;
24334dca4b63SNaphtali Sprei         }
2434ea2384d3Sbellard     }
2435ea2384d3Sbellard 
243672706ea4SJeff Cody     length = bdrv_getlength(bs);
243772706ea4SJeff Cody     if (length < 0) {
243872706ea4SJeff Cody         ret = length;
243972706ea4SJeff Cody         goto ro_cleanup;
244072706ea4SJeff Cody     }
244172706ea4SJeff Cody 
2442760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
244372706ea4SJeff Cody     if (backing_length < 0) {
244472706ea4SJeff Cody         ret = backing_length;
244572706ea4SJeff Cody         goto ro_cleanup;
244672706ea4SJeff Cody     }
244772706ea4SJeff Cody 
244872706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
244972706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
245072706ea4SJeff Cody      * we must return an error */
245172706ea4SJeff Cody     if (length > backing_length) {
2452760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
245372706ea4SJeff Cody         if (ret < 0) {
245472706ea4SJeff Cody             goto ro_cleanup;
245572706ea4SJeff Cody         }
245672706ea4SJeff Cody     }
245772706ea4SJeff Cody 
245872706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2459857d4f46SKevin Wolf 
2460857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2461760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2462857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2463857d4f46SKevin Wolf     if (buf == NULL) {
2464857d4f46SKevin Wolf         ret = -ENOMEM;
2465857d4f46SKevin Wolf         goto ro_cleanup;
2466857d4f46SKevin Wolf     }
24678a426614SKevin Wolf 
24688a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2469d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2470d663640cSPaolo Bonzini         if (ret < 0) {
2471d663640cSPaolo Bonzini             goto ro_cleanup;
2472d663640cSPaolo Bonzini         }
2473d663640cSPaolo Bonzini         if (ret) {
2474dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2475dabfa6ccSKevin Wolf             if (ret < 0) {
24764dca4b63SNaphtali Sprei                 goto ro_cleanup;
247733e3963eSbellard             }
247833e3963eSbellard 
2479760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2480dabfa6ccSKevin Wolf             if (ret < 0) {
24814dca4b63SNaphtali Sprei                 goto ro_cleanup;
248233e3963eSbellard             }
248333e3963eSbellard         }
248433e3963eSbellard     }
248595389c86Sbellard 
24861d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
24871d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2488dabfa6ccSKevin Wolf         if (ret < 0) {
2489dabfa6ccSKevin Wolf             goto ro_cleanup;
2490dabfa6ccSKevin Wolf         }
24911d44952fSChristoph Hellwig         bdrv_flush(bs);
24921d44952fSChristoph Hellwig     }
249395389c86Sbellard 
24943f5075aeSChristoph Hellwig     /*
24953f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24963f5075aeSChristoph Hellwig      * stable on disk.
24973f5075aeSChristoph Hellwig      */
2498760e0063SKevin Wolf     if (bs->backing) {
2499760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2500dabfa6ccSKevin Wolf     }
25014dca4b63SNaphtali Sprei 
2502dabfa6ccSKevin Wolf     ret = 0;
25034dca4b63SNaphtali Sprei ro_cleanup:
2504857d4f46SKevin Wolf     qemu_vfree(buf);
25054dca4b63SNaphtali Sprei 
25064dca4b63SNaphtali Sprei     if (ro) {
25070bce597dSJeff Cody         /* ignoring error return here */
2508760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
25094dca4b63SNaphtali Sprei     }
25104dca4b63SNaphtali Sprei 
25111d44952fSChristoph Hellwig     return ret;
251233e3963eSbellard }
251333e3963eSbellard 
2514e8877497SStefan Hajnoczi int bdrv_commit_all(void)
25156ab4b5abSMarkus Armbruster {
25166ab4b5abSMarkus Armbruster     BlockDriverState *bs;
25176ab4b5abSMarkus Armbruster 
2518dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2519ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2520ed78cda3SStefan Hajnoczi 
2521ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2522760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2523e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2524e8877497SStefan Hajnoczi             if (ret < 0) {
2525ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2526e8877497SStefan Hajnoczi                 return ret;
25276ab4b5abSMarkus Armbruster             }
25286ab4b5abSMarkus Armbruster         }
2529ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2530272d2d8eSJeff Cody     }
2531e8877497SStefan Hajnoczi     return 0;
2532e8877497SStefan Hajnoczi }
25336ab4b5abSMarkus Armbruster 
2534756e6736SKevin Wolf /*
2535756e6736SKevin Wolf  * Return values:
2536756e6736SKevin Wolf  * 0        - success
2537756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2538756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2539756e6736SKevin Wolf  *            image file header
2540756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2541756e6736SKevin Wolf  */
2542756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2543756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2544756e6736SKevin Wolf {
2545756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2546469ef350SPaolo Bonzini     int ret;
2547756e6736SKevin Wolf 
25485f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25495f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25505f377794SPaolo Bonzini         return -EINVAL;
25515f377794SPaolo Bonzini     }
25525f377794SPaolo Bonzini 
2553756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2554469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2555756e6736SKevin Wolf     } else {
2556469ef350SPaolo Bonzini         ret = -ENOTSUP;
2557756e6736SKevin Wolf     }
2558469ef350SPaolo Bonzini 
2559469ef350SPaolo Bonzini     if (ret == 0) {
2560469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2561469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2562469ef350SPaolo Bonzini     }
2563469ef350SPaolo Bonzini     return ret;
2564756e6736SKevin Wolf }
2565756e6736SKevin Wolf 
25666ebdcee2SJeff Cody /*
25676ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25686ebdcee2SJeff Cody  *
25696ebdcee2SJeff Cody  * active is the current topmost image.
25706ebdcee2SJeff Cody  *
25716ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25726ebdcee2SJeff Cody  * or if active == bs.
25734caf0fcdSJeff Cody  *
25744caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25756ebdcee2SJeff Cody  */
25766ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25776ebdcee2SJeff Cody                                     BlockDriverState *bs)
25786ebdcee2SJeff Cody {
2579760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2580760e0063SKevin Wolf         active = backing_bs(active);
25816ebdcee2SJeff Cody     }
25826ebdcee2SJeff Cody 
25834caf0fcdSJeff Cody     return active;
25846ebdcee2SJeff Cody }
25856ebdcee2SJeff Cody 
25864caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25874caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25884caf0fcdSJeff Cody {
25894caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25906ebdcee2SJeff Cody }
25916ebdcee2SJeff Cody 
25926ebdcee2SJeff Cody /*
25936ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25946ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25956ebdcee2SJeff Cody  *
25966ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25976ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25986ebdcee2SJeff Cody  *
25996ebdcee2SJeff Cody  * E.g., this will convert the following chain:
26006ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
26016ebdcee2SJeff Cody  *
26026ebdcee2SJeff Cody  * to
26036ebdcee2SJeff Cody  *
26046ebdcee2SJeff Cody  * bottom <- base <- active
26056ebdcee2SJeff Cody  *
26066ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
26076ebdcee2SJeff Cody  *
26086ebdcee2SJeff Cody  * base <- intermediate <- top <- active
26096ebdcee2SJeff Cody  *
26106ebdcee2SJeff Cody  * to
26116ebdcee2SJeff Cody  *
26126ebdcee2SJeff Cody  * base <- active
26136ebdcee2SJeff Cody  *
261454e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
261554e26900SJeff Cody  * overlay image metadata.
261654e26900SJeff Cody  *
26176ebdcee2SJeff Cody  * Error conditions:
26186ebdcee2SJeff Cody  *  if active == top, that is considered an error
26196ebdcee2SJeff Cody  *
26206ebdcee2SJeff Cody  */
26216ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
262254e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
26236ebdcee2SJeff Cody {
26246ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26256ebdcee2SJeff Cody     int ret = -EIO;
26266ebdcee2SJeff Cody 
26276ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26286ebdcee2SJeff Cody         goto exit;
26296ebdcee2SJeff Cody     }
26306ebdcee2SJeff Cody 
26316ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26326ebdcee2SJeff Cody 
26336ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26346ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26356ebdcee2SJeff Cody         goto exit;
26366ebdcee2SJeff Cody     }
26376ebdcee2SJeff Cody 
2638760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
26396ebdcee2SJeff Cody      * to do, no intermediate images */
2640760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
26416ebdcee2SJeff Cody         ret = 0;
26426ebdcee2SJeff Cody         goto exit;
26436ebdcee2SJeff Cody     }
26446ebdcee2SJeff Cody 
26455db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
26465db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
26476ebdcee2SJeff Cody         goto exit;
26486ebdcee2SJeff Cody     }
26496ebdcee2SJeff Cody 
26506ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26515db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
265254e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26535db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
26546ebdcee2SJeff Cody     if (ret) {
26556ebdcee2SJeff Cody         goto exit;
26566ebdcee2SJeff Cody     }
26575db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
26586ebdcee2SJeff Cody 
26596ebdcee2SJeff Cody     ret = 0;
26606ebdcee2SJeff Cody exit:
26616ebdcee2SJeff Cody     return ret;
26626ebdcee2SJeff Cody }
26636ebdcee2SJeff Cody 
266483f64091Sbellard /**
266583f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
266683f64091Sbellard  */
266783f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
266883f64091Sbellard {
266983f64091Sbellard     BlockDriver *drv = bs->drv;
267051762288SStefan Hajnoczi     int ret;
267183f64091Sbellard     if (!drv)
267219cb3738Sbellard         return -ENOMEDIUM;
267383f64091Sbellard     if (!drv->bdrv_truncate)
267483f64091Sbellard         return -ENOTSUP;
267559f2689dSNaphtali Sprei     if (bs->read_only)
267659f2689dSNaphtali Sprei         return -EACCES;
26779c75e168SJeff Cody 
267851762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
267951762288SStefan Hajnoczi     if (ret == 0) {
268051762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2681ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2682a7f53e26SMarkus Armbruster         if (bs->blk) {
2683a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2684a7f53e26SMarkus Armbruster         }
268551762288SStefan Hajnoczi     }
268651762288SStefan Hajnoczi     return ret;
268783f64091Sbellard }
268883f64091Sbellard 
268983f64091Sbellard /**
26904a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26914a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26924a1d5e1fSFam Zheng  */
26934a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26944a1d5e1fSFam Zheng {
26954a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26964a1d5e1fSFam Zheng     if (!drv) {
26974a1d5e1fSFam Zheng         return -ENOMEDIUM;
26984a1d5e1fSFam Zheng     }
26994a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
27004a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
27014a1d5e1fSFam Zheng     }
27024a1d5e1fSFam Zheng     if (bs->file) {
27039a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
27044a1d5e1fSFam Zheng     }
27054a1d5e1fSFam Zheng     return -ENOTSUP;
27064a1d5e1fSFam Zheng }
27074a1d5e1fSFam Zheng 
27084a1d5e1fSFam Zheng /**
270965a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
271083f64091Sbellard  */
271165a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
271283f64091Sbellard {
271383f64091Sbellard     BlockDriver *drv = bs->drv;
271465a9bb25SMarkus Armbruster 
271583f64091Sbellard     if (!drv)
271619cb3738Sbellard         return -ENOMEDIUM;
271751762288SStefan Hajnoczi 
2718b94a2610SKevin Wolf     if (drv->has_variable_length) {
2719b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2720b94a2610SKevin Wolf         if (ret < 0) {
2721b94a2610SKevin Wolf             return ret;
2722fc01f7e7Sbellard         }
272346a4e4e6SStefan Hajnoczi     }
272465a9bb25SMarkus Armbruster     return bs->total_sectors;
272565a9bb25SMarkus Armbruster }
272665a9bb25SMarkus Armbruster 
272765a9bb25SMarkus Armbruster /**
272865a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
272965a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
273065a9bb25SMarkus Armbruster  */
273165a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
273265a9bb25SMarkus Armbruster {
273365a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
273465a9bb25SMarkus Armbruster 
27354a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
273665a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
273746a4e4e6SStefan Hajnoczi }
2738fc01f7e7Sbellard 
273919cb3738Sbellard /* return 0 as number of sectors if no device present or error */
274096b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2741fc01f7e7Sbellard {
274265a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
274365a9bb25SMarkus Armbruster 
274465a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2745fc01f7e7Sbellard }
2746cf98951bSbellard 
2747b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2748b338082bSbellard {
2749b338082bSbellard     return bs->read_only;
2750b338082bSbellard }
2751b338082bSbellard 
2752985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2753985a03b0Sths {
2754985a03b0Sths     return bs->sg;
2755985a03b0Sths }
2756985a03b0Sths 
2757e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2758e900a7b7SChristoph Hellwig {
2759e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2760e900a7b7SChristoph Hellwig }
2761e900a7b7SChristoph Hellwig 
2762425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2763425b0148SPaolo Bonzini {
2764425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
276555b110f2SJeff Cody 
276655b110f2SJeff Cody     /* so a reopen() will preserve wce */
276755b110f2SJeff Cody     if (wce) {
276855b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
276955b110f2SJeff Cody     } else {
277055b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
277155b110f2SJeff Cody     }
2772425b0148SPaolo Bonzini }
2773425b0148SPaolo Bonzini 
2774ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2775ea2384d3Sbellard {
2776760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2777ea2384d3Sbellard         return 1;
2778760e0063SKevin Wolf     }
2779ea2384d3Sbellard     return bs->encrypted;
2780ea2384d3Sbellard }
2781ea2384d3Sbellard 
2782c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2783c0f4ce77Saliguori {
2784760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2785c0f4ce77Saliguori 
2786760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2787c0f4ce77Saliguori         return 1;
2788760e0063SKevin Wolf     }
2789c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2790c0f4ce77Saliguori }
2791c0f4ce77Saliguori 
2792ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2793ea2384d3Sbellard {
2794ea2384d3Sbellard     int ret;
2795760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2796760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2797ea2384d3Sbellard         if (ret < 0)
2798ea2384d3Sbellard             return ret;
2799ea2384d3Sbellard         if (!bs->encrypted)
2800ea2384d3Sbellard             return 0;
2801ea2384d3Sbellard     }
2802fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2803fd04a2aeSShahar Havivi         return -EINVAL;
2804fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2805fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2806fd04a2aeSShahar Havivi     }
2807c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2808bb5fc20fSaliguori     if (ret < 0) {
2809bb5fc20fSaliguori         bs->valid_key = 0;
2810bb5fc20fSaliguori     } else if (!bs->valid_key) {
2811bb5fc20fSaliguori         bs->valid_key = 1;
2812a7f53e26SMarkus Armbruster         if (bs->blk) {
2813bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2814a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2815a7f53e26SMarkus Armbruster         }
2816bb5fc20fSaliguori     }
2817c0f4ce77Saliguori     return ret;
2818ea2384d3Sbellard }
2819ea2384d3Sbellard 
28204d2855a3SMarkus Armbruster /*
28214d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
28224d2855a3SMarkus Armbruster  * If @key is non-null:
28234d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
28244d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
28254d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
28264d2855a3SMarkus Armbruster  * If @key is null:
28274d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
28284d2855a3SMarkus Armbruster  *     Else do nothing.
28294d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
28304d2855a3SMarkus Armbruster  */
28314d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
28324d2855a3SMarkus Armbruster {
28334d2855a3SMarkus Armbruster     if (key) {
28344d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
283581e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
283681e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
28374d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2838c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
28394d2855a3SMarkus Armbruster         }
28404d2855a3SMarkus Armbruster     } else {
28414d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2842b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2843b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
284481e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
28454d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
28464d2855a3SMarkus Armbruster         }
28474d2855a3SMarkus Armbruster     }
28484d2855a3SMarkus Armbruster }
28494d2855a3SMarkus Armbruster 
2850f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2851ea2384d3Sbellard {
2852f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2853ea2384d3Sbellard }
2854ea2384d3Sbellard 
2855ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2856ada42401SStefan Hajnoczi {
2857ada42401SStefan Hajnoczi     return strcmp(a, b);
2858ada42401SStefan Hajnoczi }
2859ada42401SStefan Hajnoczi 
2860ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2861ea2384d3Sbellard                          void *opaque)
2862ea2384d3Sbellard {
2863ea2384d3Sbellard     BlockDriver *drv;
2864e855e4fbSJeff Cody     int count = 0;
2865ada42401SStefan Hajnoczi     int i;
2866e855e4fbSJeff Cody     const char **formats = NULL;
2867ea2384d3Sbellard 
28688a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2869e855e4fbSJeff Cody         if (drv->format_name) {
2870e855e4fbSJeff Cody             bool found = false;
2871e855e4fbSJeff Cody             int i = count;
2872e855e4fbSJeff Cody             while (formats && i && !found) {
2873e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2874e855e4fbSJeff Cody             }
2875e855e4fbSJeff Cody 
2876e855e4fbSJeff Cody             if (!found) {
28775839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2878e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2879ea2384d3Sbellard             }
2880ea2384d3Sbellard         }
2881e855e4fbSJeff Cody     }
2882ada42401SStefan Hajnoczi 
2883ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2884ada42401SStefan Hajnoczi 
2885ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2886ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2887ada42401SStefan Hajnoczi     }
2888ada42401SStefan Hajnoczi 
2889e855e4fbSJeff Cody     g_free(formats);
2890e855e4fbSJeff Cody }
2891ea2384d3Sbellard 
2892dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2893dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2894dc364f4cSBenoît Canet {
2895dc364f4cSBenoît Canet     BlockDriverState *bs;
2896dc364f4cSBenoît Canet 
2897dc364f4cSBenoît Canet     assert(node_name);
2898dc364f4cSBenoît Canet 
2899dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2900dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2901dc364f4cSBenoît Canet             return bs;
2902dc364f4cSBenoît Canet         }
2903dc364f4cSBenoît Canet     }
2904dc364f4cSBenoît Canet     return NULL;
2905dc364f4cSBenoît Canet }
2906dc364f4cSBenoît Canet 
2907c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2908d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2909c13163fbSBenoît Canet {
2910c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2911c13163fbSBenoît Canet     BlockDriverState *bs;
2912c13163fbSBenoît Canet 
2913c13163fbSBenoît Canet     list = NULL;
2914c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2915d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2916d5a8ee60SAlberto Garcia         if (!info) {
2917d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2918d5a8ee60SAlberto Garcia             return NULL;
2919d5a8ee60SAlberto Garcia         }
2920c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2921d5a8ee60SAlberto Garcia         entry->value = info;
2922c13163fbSBenoît Canet         entry->next = list;
2923c13163fbSBenoît Canet         list = entry;
2924c13163fbSBenoît Canet     }
2925c13163fbSBenoît Canet 
2926c13163fbSBenoît Canet     return list;
2927c13163fbSBenoît Canet }
2928c13163fbSBenoît Canet 
292912d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
293012d3ba82SBenoît Canet                                  const char *node_name,
293112d3ba82SBenoît Canet                                  Error **errp)
293212d3ba82SBenoît Canet {
29337f06d47eSMarkus Armbruster     BlockBackend *blk;
29347f06d47eSMarkus Armbruster     BlockDriverState *bs;
293512d3ba82SBenoît Canet 
293612d3ba82SBenoît Canet     if (device) {
29377f06d47eSMarkus Armbruster         blk = blk_by_name(device);
293812d3ba82SBenoît Canet 
29397f06d47eSMarkus Armbruster         if (blk) {
29409f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
29419f4ed6fbSAlberto Garcia             if (!bs) {
29425433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
29435433c24fSMax Reitz             }
29445433c24fSMax Reitz 
29459f4ed6fbSAlberto Garcia             return bs;
294612d3ba82SBenoît Canet         }
2947dd67fa50SBenoît Canet     }
294812d3ba82SBenoît Canet 
2949dd67fa50SBenoît Canet     if (node_name) {
295012d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
295112d3ba82SBenoît Canet 
2952dd67fa50SBenoît Canet         if (bs) {
2953dd67fa50SBenoît Canet             return bs;
2954dd67fa50SBenoît Canet         }
295512d3ba82SBenoît Canet     }
295612d3ba82SBenoît Canet 
2957dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2958dd67fa50SBenoît Canet                      device ? device : "",
2959dd67fa50SBenoît Canet                      node_name ? node_name : "");
2960dd67fa50SBenoît Canet     return NULL;
296112d3ba82SBenoît Canet }
296212d3ba82SBenoît Canet 
29635a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
29645a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
29655a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
29665a6684d2SJeff Cody {
29675a6684d2SJeff Cody     while (top && top != base) {
2968760e0063SKevin Wolf         top = backing_bs(top);
29695a6684d2SJeff Cody     }
29705a6684d2SJeff Cody 
29715a6684d2SJeff Cody     return top != NULL;
29725a6684d2SJeff Cody }
29735a6684d2SJeff Cody 
297404df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
297504df765aSFam Zheng {
297604df765aSFam Zheng     if (!bs) {
297704df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
297804df765aSFam Zheng     }
297904df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
298004df765aSFam Zheng }
298104df765aSFam Zheng 
29822f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29832f399b0aSMarkus Armbruster {
29842f399b0aSMarkus Armbruster     if (!bs) {
29852f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
29862f399b0aSMarkus Armbruster     }
2987dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
29882f399b0aSMarkus Armbruster }
29892f399b0aSMarkus Armbruster 
299020a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
299120a9e77dSFam Zheng {
299220a9e77dSFam Zheng     return bs->node_name;
299320a9e77dSFam Zheng }
299420a9e77dSFam Zheng 
29957f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2996bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2997ea2384d3Sbellard {
2998bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2999ea2384d3Sbellard }
3000ea2384d3Sbellard 
30019b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
30029b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
30039b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
30049b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
30059b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
30069b2aa84fSAlberto Garcia {
30079b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
30089b2aa84fSAlberto Garcia }
30099b2aa84fSAlberto Garcia 
3010c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3011c8433287SMarkus Armbruster {
3012c8433287SMarkus Armbruster     return bs->open_flags;
3013c8433287SMarkus Armbruster }
3014c8433287SMarkus Armbruster 
30153ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30163ac21627SPeter Lieven {
30173ac21627SPeter Lieven     return 1;
30183ac21627SPeter Lieven }
30193ac21627SPeter Lieven 
3020f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3021f2feebbdSKevin Wolf {
3022f2feebbdSKevin Wolf     assert(bs->drv);
3023f2feebbdSKevin Wolf 
302411212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
302511212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
3026760e0063SKevin Wolf     if (bs->backing) {
302711212d8fSPaolo Bonzini         return 0;
302811212d8fSPaolo Bonzini     }
3029336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3030336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3031f2feebbdSKevin Wolf     }
3032f2feebbdSKevin Wolf 
30333ac21627SPeter Lieven     /* safe default */
30343ac21627SPeter Lieven     return 0;
3035f2feebbdSKevin Wolf }
3036f2feebbdSKevin Wolf 
30374ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
30384ce78691SPeter Lieven {
30394ce78691SPeter Lieven     BlockDriverInfo bdi;
30404ce78691SPeter Lieven 
3041760e0063SKevin Wolf     if (bs->backing) {
30424ce78691SPeter Lieven         return false;
30434ce78691SPeter Lieven     }
30444ce78691SPeter Lieven 
30454ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30464ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
30474ce78691SPeter Lieven     }
30484ce78691SPeter Lieven 
30494ce78691SPeter Lieven     return false;
30504ce78691SPeter Lieven }
30514ce78691SPeter Lieven 
30524ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
30534ce78691SPeter Lieven {
30544ce78691SPeter Lieven     BlockDriverInfo bdi;
30554ce78691SPeter Lieven 
3056760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
30574ce78691SPeter Lieven         return false;
30584ce78691SPeter Lieven     }
30594ce78691SPeter Lieven 
30604ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30614ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
30624ce78691SPeter Lieven     }
30634ce78691SPeter Lieven 
30644ce78691SPeter Lieven     return false;
30654ce78691SPeter Lieven }
30664ce78691SPeter Lieven 
3067045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3068045df330Saliguori {
3069760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
3070045df330Saliguori         return bs->backing_file;
3071045df330Saliguori     else if (bs->encrypted)
3072045df330Saliguori         return bs->filename;
3073045df330Saliguori     else
3074045df330Saliguori         return NULL;
3075045df330Saliguori }
3076045df330Saliguori 
307783f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
307883f64091Sbellard                                char *filename, int filename_size)
307983f64091Sbellard {
308083f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
308183f64091Sbellard }
308283f64091Sbellard 
3083faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3084faea38e7Sbellard {
3085faea38e7Sbellard     BlockDriver *drv = bs->drv;
3086faea38e7Sbellard     if (!drv)
308719cb3738Sbellard         return -ENOMEDIUM;
3088faea38e7Sbellard     if (!drv->bdrv_get_info)
3089faea38e7Sbellard         return -ENOTSUP;
3090faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3091faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3092faea38e7Sbellard }
3093faea38e7Sbellard 
3094eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3095eae041feSMax Reitz {
3096eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3097eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3098eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3099eae041feSMax Reitz     }
3100eae041feSMax Reitz     return NULL;
3101eae041feSMax Reitz }
3102eae041feSMax Reitz 
3103a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
31048b9b0cc2SKevin Wolf {
3105bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
31068b9b0cc2SKevin Wolf         return;
31078b9b0cc2SKevin Wolf     }
31088b9b0cc2SKevin Wolf 
3109bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
311041c695c7SKevin Wolf }
31118b9b0cc2SKevin Wolf 
311241c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
311341c695c7SKevin Wolf                           const char *tag)
311441c695c7SKevin Wolf {
311541c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
31169a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
311741c695c7SKevin Wolf     }
311841c695c7SKevin Wolf 
311941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
312041c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
312141c695c7SKevin Wolf     }
312241c695c7SKevin Wolf 
312341c695c7SKevin Wolf     return -ENOTSUP;
312441c695c7SKevin Wolf }
312541c695c7SKevin Wolf 
31264cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
31274cc70e93SFam Zheng {
31284cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
31299a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
31304cc70e93SFam Zheng     }
31314cc70e93SFam Zheng 
31324cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
31334cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
31344cc70e93SFam Zheng     }
31354cc70e93SFam Zheng 
31364cc70e93SFam Zheng     return -ENOTSUP;
31374cc70e93SFam Zheng }
31384cc70e93SFam Zheng 
313941c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
314041c695c7SKevin Wolf {
3141938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
31429a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
314341c695c7SKevin Wolf     }
314441c695c7SKevin Wolf 
314541c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
314641c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
314741c695c7SKevin Wolf     }
314841c695c7SKevin Wolf 
314941c695c7SKevin Wolf     return -ENOTSUP;
315041c695c7SKevin Wolf }
315141c695c7SKevin Wolf 
315241c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
315341c695c7SKevin Wolf {
315441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
31559a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
315641c695c7SKevin Wolf     }
315741c695c7SKevin Wolf 
315841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
315941c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
316041c695c7SKevin Wolf     }
316141c695c7SKevin Wolf 
316241c695c7SKevin Wolf     return false;
31638b9b0cc2SKevin Wolf }
31648b9b0cc2SKevin Wolf 
3165199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3166199630b6SBlue Swirl {
3167199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3168199630b6SBlue Swirl }
3169199630b6SBlue Swirl 
3170b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3171b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3172b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3173b1b1d783SJeff Cody  * the CWD rather than the chain. */
3174e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3175e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3176e8a6bb9cSMarcelo Tosatti {
3177b1b1d783SJeff Cody     char *filename_full = NULL;
3178b1b1d783SJeff Cody     char *backing_file_full = NULL;
3179b1b1d783SJeff Cody     char *filename_tmp = NULL;
3180b1b1d783SJeff Cody     int is_protocol = 0;
3181b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3182b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3183b1b1d783SJeff Cody 
3184b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3185e8a6bb9cSMarcelo Tosatti         return NULL;
3186e8a6bb9cSMarcelo Tosatti     }
3187e8a6bb9cSMarcelo Tosatti 
3188b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3189b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3190b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3191b1b1d783SJeff Cody 
3192b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3193b1b1d783SJeff Cody 
3194760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3195b1b1d783SJeff Cody 
3196b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3197b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3198b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3199b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3200760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3201b1b1d783SJeff Cody                 break;
3202b1b1d783SJeff Cody             }
3203e8a6bb9cSMarcelo Tosatti         } else {
3204b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3205b1b1d783SJeff Cody              * image's filename path */
3206b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3207b1b1d783SJeff Cody                          backing_file);
3208b1b1d783SJeff Cody 
3209b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3210b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3211b1b1d783SJeff Cody                 continue;
3212b1b1d783SJeff Cody             }
3213b1b1d783SJeff Cody 
3214b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3215b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3216b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3217b1b1d783SJeff Cody                          curr_bs->backing_file);
3218b1b1d783SJeff Cody 
3219b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3220b1b1d783SJeff Cody                 continue;
3221b1b1d783SJeff Cody             }
3222b1b1d783SJeff Cody 
3223b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3224760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3225b1b1d783SJeff Cody                 break;
3226b1b1d783SJeff Cody             }
3227e8a6bb9cSMarcelo Tosatti         }
3228e8a6bb9cSMarcelo Tosatti     }
3229e8a6bb9cSMarcelo Tosatti 
3230b1b1d783SJeff Cody     g_free(filename_full);
3231b1b1d783SJeff Cody     g_free(backing_file_full);
3232b1b1d783SJeff Cody     g_free(filename_tmp);
3233b1b1d783SJeff Cody     return retval;
3234e8a6bb9cSMarcelo Tosatti }
3235e8a6bb9cSMarcelo Tosatti 
3236f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3237f198fd1cSBenoît Canet {
3238f198fd1cSBenoît Canet     if (!bs->drv) {
3239f198fd1cSBenoît Canet         return 0;
3240f198fd1cSBenoît Canet     }
3241f198fd1cSBenoît Canet 
3242760e0063SKevin Wolf     if (!bs->backing) {
3243f198fd1cSBenoît Canet         return 0;
3244f198fd1cSBenoît Canet     }
3245f198fd1cSBenoît Canet 
3246760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3247f198fd1cSBenoît Canet }
3248f198fd1cSBenoît Canet 
3249ea2384d3Sbellard void bdrv_init(void)
3250ea2384d3Sbellard {
32515efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3252ea2384d3Sbellard }
3253ce1a14dcSpbrook 
3254eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3255eb852011SMarkus Armbruster {
3256eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3257eb852011SMarkus Armbruster     bdrv_init();
3258eb852011SMarkus Armbruster }
3259eb852011SMarkus Armbruster 
32605a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
32610f15423cSAnthony Liguori {
32625a8a30dbSKevin Wolf     Error *local_err = NULL;
32635a8a30dbSKevin Wolf     int ret;
32645a8a30dbSKevin Wolf 
32653456a8d1SKevin Wolf     if (!bs->drv)  {
32663456a8d1SKevin Wolf         return;
32670f15423cSAnthony Liguori     }
32683456a8d1SKevin Wolf 
326904c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
32707ea2d269SAlexey Kardashevskiy         return;
32717ea2d269SAlexey Kardashevskiy     }
327204c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
32737ea2d269SAlexey Kardashevskiy 
32743456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
32755a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
32763456a8d1SKevin Wolf     } else if (bs->file) {
32779a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
32785a8a30dbSKevin Wolf     }
32795a8a30dbSKevin Wolf     if (local_err) {
328004c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32815a8a30dbSKevin Wolf         error_propagate(errp, local_err);
32825a8a30dbSKevin Wolf         return;
32833456a8d1SKevin Wolf     }
32843456a8d1SKevin Wolf 
32855a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
32865a8a30dbSKevin Wolf     if (ret < 0) {
328704c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32885a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
32895a8a30dbSKevin Wolf         return;
32905a8a30dbSKevin Wolf     }
32910f15423cSAnthony Liguori }
32920f15423cSAnthony Liguori 
32935a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
32940f15423cSAnthony Liguori {
32950f15423cSAnthony Liguori     BlockDriverState *bs;
32965a8a30dbSKevin Wolf     Error *local_err = NULL;
32970f15423cSAnthony Liguori 
3298dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3299ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3300ed78cda3SStefan Hajnoczi 
3301ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
33025a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3303ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
33045a8a30dbSKevin Wolf         if (local_err) {
33055a8a30dbSKevin Wolf             error_propagate(errp, local_err);
33065a8a30dbSKevin Wolf             return;
33075a8a30dbSKevin Wolf         }
33080f15423cSAnthony Liguori     }
33090f15423cSAnthony Liguori }
33100f15423cSAnthony Liguori 
331176b1c7feSKevin Wolf static int bdrv_inactivate(BlockDriverState *bs)
331276b1c7feSKevin Wolf {
331376b1c7feSKevin Wolf     int ret;
331476b1c7feSKevin Wolf 
331576b1c7feSKevin Wolf     if (bs->drv->bdrv_inactivate) {
331676b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
331776b1c7feSKevin Wolf         if (ret < 0) {
331876b1c7feSKevin Wolf             return ret;
331976b1c7feSKevin Wolf         }
332076b1c7feSKevin Wolf     }
332176b1c7feSKevin Wolf 
332276b1c7feSKevin Wolf     bs->open_flags |= BDRV_O_INACTIVE;
332376b1c7feSKevin Wolf     return 0;
332476b1c7feSKevin Wolf }
332576b1c7feSKevin Wolf 
332676b1c7feSKevin Wolf int bdrv_inactivate_all(void)
332776b1c7feSKevin Wolf {
332876b1c7feSKevin Wolf     BlockDriverState *bs;
332976b1c7feSKevin Wolf     int ret;
333076b1c7feSKevin Wolf 
333176b1c7feSKevin Wolf     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
333276b1c7feSKevin Wolf         AioContext *aio_context = bdrv_get_aio_context(bs);
333376b1c7feSKevin Wolf 
333476b1c7feSKevin Wolf         aio_context_acquire(aio_context);
333576b1c7feSKevin Wolf         ret = bdrv_inactivate(bs);
333676b1c7feSKevin Wolf         aio_context_release(aio_context);
333776b1c7feSKevin Wolf         if (ret < 0) {
333876b1c7feSKevin Wolf             return ret;
333976b1c7feSKevin Wolf         }
334076b1c7feSKevin Wolf     }
334176b1c7feSKevin Wolf 
334276b1c7feSKevin Wolf     return 0;
334376b1c7feSKevin Wolf }
334476b1c7feSKevin Wolf 
3345f9f05dc5SKevin Wolf /**************************************************************/
334619cb3738Sbellard /* removable device support */
334719cb3738Sbellard 
334819cb3738Sbellard /**
334919cb3738Sbellard  * Return TRUE if the media is present
335019cb3738Sbellard  */
3351e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
335219cb3738Sbellard {
335319cb3738Sbellard     BlockDriver *drv = bs->drv;
335428d7a789SMax Reitz     BdrvChild *child;
3355a1aff5bfSMarkus Armbruster 
3356e031f750SMax Reitz     if (!drv) {
3357e031f750SMax Reitz         return false;
3358e031f750SMax Reitz     }
335928d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3360a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
336119cb3738Sbellard     }
336228d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
336328d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
336428d7a789SMax Reitz             return false;
336528d7a789SMax Reitz         }
336628d7a789SMax Reitz     }
336728d7a789SMax Reitz     return true;
336828d7a789SMax Reitz }
336919cb3738Sbellard 
337019cb3738Sbellard /**
33718e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
33728e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
337319cb3738Sbellard  */
337419cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
337519cb3738Sbellard {
337619cb3738Sbellard     BlockDriver *drv = bs->drv;
337719cb3738Sbellard 
33788e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33798e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33808e49ca46SMarkus Armbruster     }
33818e49ca46SMarkus Armbruster     return -ENOTSUP;
338219cb3738Sbellard }
338319cb3738Sbellard 
338419cb3738Sbellard /**
338519cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
338619cb3738Sbellard  */
3387f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
338819cb3738Sbellard {
338919cb3738Sbellard     BlockDriver *drv = bs->drv;
3390bfb197e0SMarkus Armbruster     const char *device_name;
339119cb3738Sbellard 
3392822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3393822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
339419cb3738Sbellard     }
33956f382ed2SLuiz Capitulino 
3396bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3397bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3398bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3399a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
34006f382ed2SLuiz Capitulino     }
340119cb3738Sbellard }
340219cb3738Sbellard 
340319cb3738Sbellard /**
340419cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
340519cb3738Sbellard  * to eject it manually).
340619cb3738Sbellard  */
3407025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
340819cb3738Sbellard {
340919cb3738Sbellard     BlockDriver *drv = bs->drv;
341019cb3738Sbellard 
3411025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3412b8c6d095SStefan Hajnoczi 
3413025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3414025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
341519cb3738Sbellard     }
341619cb3738Sbellard }
3417985a03b0Sths 
34180db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
34190db6e54aSFam Zheng {
34200db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
34210db6e54aSFam Zheng 
34220db6e54aSFam Zheng     assert(name);
34230db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
34240db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
34250db6e54aSFam Zheng             return bm;
34260db6e54aSFam Zheng         }
34270db6e54aSFam Zheng     }
34280db6e54aSFam Zheng     return NULL;
34290db6e54aSFam Zheng }
34300db6e54aSFam Zheng 
343120dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
34320db6e54aSFam Zheng {
34339bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
34340db6e54aSFam Zheng     g_free(bitmap->name);
34350db6e54aSFam Zheng     bitmap->name = NULL;
34360db6e54aSFam Zheng }
34370db6e54aSFam Zheng 
34380db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
34395fba6c0eSJohn Snow                                           uint32_t granularity,
34400db6e54aSFam Zheng                                           const char *name,
3441b8afb520SFam Zheng                                           Error **errp)
34427cd1e32aSlirans@il.ibm.com {
34437cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3444e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
34455fba6c0eSJohn Snow     uint32_t sector_granularity;
3446a55eb92cSJan Kiszka 
344750717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
344850717e94SPaolo Bonzini 
34490db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
34500db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
34510db6e54aSFam Zheng         return NULL;
34520db6e54aSFam Zheng     }
34535fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
34545fba6c0eSJohn Snow     assert(sector_granularity);
345557322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3456b8afb520SFam Zheng     if (bitmap_size < 0) {
3457b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3458b8afb520SFam Zheng         errno = -bitmap_size;
3459b8afb520SFam Zheng         return NULL;
3460b8afb520SFam Zheng     }
34615839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
34625fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3463e74e6b78SJohn Snow     bitmap->size = bitmap_size;
34640db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3465b8e6fb75SJohn Snow     bitmap->disabled = false;
3466e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3467e4654d2dSFam Zheng     return bitmap;
3468e4654d2dSFam Zheng }
3469e4654d2dSFam Zheng 
34709bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
34719bd2b08fSJohn Snow {
34729bd2b08fSJohn Snow     return bitmap->successor;
34739bd2b08fSJohn Snow }
34749bd2b08fSJohn Snow 
3475b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3476b8e6fb75SJohn Snow {
34779bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
34789bd2b08fSJohn Snow }
34799bd2b08fSJohn Snow 
34809abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
34819abe3bdcSJohn Snow {
34829abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
34839abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
34849abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
34859abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
34869abe3bdcSJohn Snow     } else {
34879abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
34889abe3bdcSJohn Snow     }
34899abe3bdcSJohn Snow }
34909abe3bdcSJohn Snow 
34919bd2b08fSJohn Snow /**
34929bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
34939bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
34949bd2b08fSJohn Snow  */
34959bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
34969bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
34979bd2b08fSJohn Snow {
34989bd2b08fSJohn Snow     uint64_t granularity;
34999bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
35009bd2b08fSJohn Snow 
35019bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
35029bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
35039bd2b08fSJohn Snow                    "currently frozen");
35049bd2b08fSJohn Snow         return -1;
35059bd2b08fSJohn Snow     }
35069bd2b08fSJohn Snow     assert(!bitmap->successor);
35079bd2b08fSJohn Snow 
35089bd2b08fSJohn Snow     /* Create an anonymous successor */
35099bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
35109bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
35119bd2b08fSJohn Snow     if (!child) {
35129bd2b08fSJohn Snow         return -1;
35139bd2b08fSJohn Snow     }
35149bd2b08fSJohn Snow 
35159bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
35169bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
35179bd2b08fSJohn Snow 
35189bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
35199bd2b08fSJohn Snow     bitmap->successor = child;
35209bd2b08fSJohn Snow     return 0;
35219bd2b08fSJohn Snow }
35229bd2b08fSJohn Snow 
35239bd2b08fSJohn Snow /**
35249bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
35259bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
35269bd2b08fSJohn Snow  */
35279bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
35289bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
35299bd2b08fSJohn Snow                                             Error **errp)
35309bd2b08fSJohn Snow {
35319bd2b08fSJohn Snow     char *name;
35329bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
35339bd2b08fSJohn Snow 
35349bd2b08fSJohn Snow     if (successor == NULL) {
35359bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
35369bd2b08fSJohn Snow                    "there's no successor present");
35379bd2b08fSJohn Snow         return NULL;
35389bd2b08fSJohn Snow     }
35399bd2b08fSJohn Snow 
35409bd2b08fSJohn Snow     name = bitmap->name;
35419bd2b08fSJohn Snow     bitmap->name = NULL;
35429bd2b08fSJohn Snow     successor->name = name;
35439bd2b08fSJohn Snow     bitmap->successor = NULL;
35449bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
35459bd2b08fSJohn Snow 
35469bd2b08fSJohn Snow     return successor;
35479bd2b08fSJohn Snow }
35489bd2b08fSJohn Snow 
35499bd2b08fSJohn Snow /**
35509bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
35519bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
35529bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
35539bd2b08fSJohn Snow  */
35549bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
35559bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
35569bd2b08fSJohn Snow                                            Error **errp)
35579bd2b08fSJohn Snow {
35589bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
35599bd2b08fSJohn Snow 
35609bd2b08fSJohn Snow     if (!successor) {
35619bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
35629bd2b08fSJohn Snow         return NULL;
35639bd2b08fSJohn Snow     }
35649bd2b08fSJohn Snow 
35659bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
35669bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
35679bd2b08fSJohn Snow         return NULL;
35689bd2b08fSJohn Snow     }
35699bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
35709bd2b08fSJohn Snow     parent->successor = NULL;
35719bd2b08fSJohn Snow 
35729bd2b08fSJohn Snow     return parent;
3573b8e6fb75SJohn Snow }
3574b8e6fb75SJohn Snow 
3575ce1ffea8SJohn Snow /**
3576ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3577ce1ffea8SJohn Snow  */
3578ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3579ce1ffea8SJohn Snow {
3580ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3581ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3582ce1ffea8SJohn Snow 
3583ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
358406207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3585ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
35865270b6a0SJohn Snow         bitmap->size = size;
3587ce1ffea8SJohn Snow     }
3588ce1ffea8SJohn Snow }
3589ce1ffea8SJohn Snow 
3590c5acdc9aSMax Reitz static void bdrv_do_release_matching_dirty_bitmap(BlockDriverState *bs,
3591c5acdc9aSMax Reitz                                                   BdrvDirtyBitmap *bitmap,
3592c5acdc9aSMax Reitz                                                   bool only_named)
3593e4654d2dSFam Zheng {
3594e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3595e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3596c5acdc9aSMax Reitz         if ((!bitmap || bm == bitmap) && (!only_named || bm->name)) {
35979bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3598c5acdc9aSMax Reitz             QLIST_REMOVE(bm, list);
3599c5acdc9aSMax Reitz             hbitmap_free(bm->bitmap);
3600c5acdc9aSMax Reitz             g_free(bm->name);
3601c5acdc9aSMax Reitz             g_free(bm);
3602c5acdc9aSMax Reitz 
3603c5acdc9aSMax Reitz             if (bitmap) {
3604e4654d2dSFam Zheng                 return;
36057cd1e32aSlirans@il.ibm.com             }
36067cd1e32aSlirans@il.ibm.com         }
36077cd1e32aSlirans@il.ibm.com     }
3608c5acdc9aSMax Reitz }
3609c5acdc9aSMax Reitz 
3610c5acdc9aSMax Reitz void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3611c5acdc9aSMax Reitz {
3612c5acdc9aSMax Reitz     bdrv_do_release_matching_dirty_bitmap(bs, bitmap, false);
3613c5acdc9aSMax Reitz }
3614c5acdc9aSMax Reitz 
3615c5acdc9aSMax Reitz /**
3616c5acdc9aSMax Reitz  * Release all named dirty bitmaps attached to a BDS (for use in bdrv_close()).
3617c5acdc9aSMax Reitz  * There must not be any frozen bitmaps attached.
3618c5acdc9aSMax Reitz  */
3619c5acdc9aSMax Reitz static void bdrv_release_named_dirty_bitmaps(BlockDriverState *bs)
3620c5acdc9aSMax Reitz {
3621c5acdc9aSMax Reitz     bdrv_do_release_matching_dirty_bitmap(bs, NULL, true);
3622c5acdc9aSMax Reitz }
36237cd1e32aSlirans@il.ibm.com 
3624b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3625b8e6fb75SJohn Snow {
36269bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3627b8e6fb75SJohn Snow     bitmap->disabled = true;
3628b8e6fb75SJohn Snow }
3629b8e6fb75SJohn Snow 
3630b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3631b8e6fb75SJohn Snow {
36329bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3633b8e6fb75SJohn Snow     bitmap->disabled = false;
3634b8e6fb75SJohn Snow }
3635b8e6fb75SJohn Snow 
363621b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
363721b56835SFam Zheng {
363821b56835SFam Zheng     BdrvDirtyBitmap *bm;
363921b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
364021b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
364121b56835SFam Zheng 
364221b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
36435839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
36445839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
364520dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3646592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
36470db6e54aSFam Zheng         info->has_name = !!bm->name;
36480db6e54aSFam Zheng         info->name = g_strdup(bm->name);
36499abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
365021b56835SFam Zheng         entry->value = info;
365121b56835SFam Zheng         *plist = entry;
365221b56835SFam Zheng         plist = &entry->next;
365321b56835SFam Zheng     }
365421b56835SFam Zheng 
365521b56835SFam Zheng     return list;
365621b56835SFam Zheng }
365721b56835SFam Zheng 
3658e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
36597cd1e32aSlirans@il.ibm.com {
3660e4654d2dSFam Zheng     if (bitmap) {
3661e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
36627cd1e32aSlirans@il.ibm.com     } else {
36637cd1e32aSlirans@il.ibm.com         return 0;
36647cd1e32aSlirans@il.ibm.com     }
36657cd1e32aSlirans@il.ibm.com }
36667cd1e32aSlirans@il.ibm.com 
3667341ebc2fSJohn Snow /**
3668341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3669341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3670341ebc2fSJohn Snow  * is no cluster size information available.
3671341ebc2fSJohn Snow  */
3672341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3673341ebc2fSJohn Snow {
3674341ebc2fSJohn Snow     BlockDriverInfo bdi;
3675341ebc2fSJohn Snow     uint32_t granularity;
3676341ebc2fSJohn Snow 
3677341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3678341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3679341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3680341ebc2fSJohn Snow     } else {
3681341ebc2fSJohn Snow         granularity = 65536;
3682341ebc2fSJohn Snow     }
3683341ebc2fSJohn Snow 
3684341ebc2fSJohn Snow     return granularity;
3685341ebc2fSJohn Snow }
3686341ebc2fSJohn Snow 
3687592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3688592fdd02SJohn Snow {
3689592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3690592fdd02SJohn Snow }
3691592fdd02SJohn Snow 
369220dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
36931755da16SPaolo Bonzini {
3694e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
36951755da16SPaolo Bonzini }
36961755da16SPaolo Bonzini 
369720dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3698c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3699c4237dfaSVladimir Sementsov-Ogievskiy {
3700b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3701c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3702c4237dfaSVladimir Sementsov-Ogievskiy }
3703c4237dfaSVladimir Sementsov-Ogievskiy 
370420dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3705c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3706c4237dfaSVladimir Sementsov-Ogievskiy {
3707b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3708c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3709c4237dfaSVladimir Sementsov-Ogievskiy }
3710c4237dfaSVladimir Sementsov-Ogievskiy 
3711df9a681dSFam Zheng void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap **out)
3712e74e6b78SJohn Snow {
3713e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3714df9a681dSFam Zheng     if (!out) {
3715c6a8c328SWen Congyang         hbitmap_reset_all(bitmap->bitmap);
3716df9a681dSFam Zheng     } else {
3717df9a681dSFam Zheng         HBitmap *backup = bitmap->bitmap;
3718df9a681dSFam Zheng         bitmap->bitmap = hbitmap_alloc(bitmap->size,
3719df9a681dSFam Zheng                                        hbitmap_granularity(backup));
3720df9a681dSFam Zheng         *out = backup;
3721df9a681dSFam Zheng     }
3722df9a681dSFam Zheng }
3723df9a681dSFam Zheng 
3724df9a681dSFam Zheng void bdrv_undo_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap, HBitmap *in)
3725df9a681dSFam Zheng {
3726df9a681dSFam Zheng     HBitmap *tmp = bitmap->bitmap;
3727df9a681dSFam Zheng     assert(bdrv_dirty_bitmap_enabled(bitmap));
3728df9a681dSFam Zheng     bitmap->bitmap = in;
3729df9a681dSFam Zheng     hbitmap_free(tmp);
3730e74e6b78SJohn Snow }
3731e74e6b78SJohn Snow 
3732e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
37331755da16SPaolo Bonzini                     int nr_sectors)
37341755da16SPaolo Bonzini {
3735e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3736e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3737b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3738b8e6fb75SJohn Snow             continue;
3739b8e6fb75SJohn Snow         }
3740e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3741e4654d2dSFam Zheng     }
37421755da16SPaolo Bonzini }
37431755da16SPaolo Bonzini 
3744d58d8453SJohn Snow /**
3745d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3746d58d8453SJohn Snow  */
3747d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3748d58d8453SJohn Snow {
3749d58d8453SJohn Snow     assert(hbi->hb);
3750d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3751d58d8453SJohn Snow }
3752d58d8453SJohn Snow 
375320dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3754aaa0eb75SLiran Schour {
3755e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3756aaa0eb75SLiran Schour }
3757f88e1a42SJes Sorensen 
37589fcb0251SFam Zheng /* Get a reference to bs */
37599fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
37609fcb0251SFam Zheng {
37619fcb0251SFam Zheng     bs->refcnt++;
37629fcb0251SFam Zheng }
37639fcb0251SFam Zheng 
37649fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
37659fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
37669fcb0251SFam Zheng  * deleted. */
37679fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
37689fcb0251SFam Zheng {
37699a4d5ca6SJeff Cody     if (!bs) {
37709a4d5ca6SJeff Cody         return;
37719a4d5ca6SJeff Cody     }
37729fcb0251SFam Zheng     assert(bs->refcnt > 0);
37739fcb0251SFam Zheng     if (--bs->refcnt == 0) {
37749fcb0251SFam Zheng         bdrv_delete(bs);
37759fcb0251SFam Zheng     }
37769fcb0251SFam Zheng }
37779fcb0251SFam Zheng 
3778fbe40ff7SFam Zheng struct BdrvOpBlocker {
3779fbe40ff7SFam Zheng     Error *reason;
3780fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3781fbe40ff7SFam Zheng };
3782fbe40ff7SFam Zheng 
3783fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3784fbe40ff7SFam Zheng {
3785fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3786fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3787fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3788fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3789fbe40ff7SFam Zheng         if (errp) {
3790e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3791e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3792e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3793fbe40ff7SFam Zheng         }
3794fbe40ff7SFam Zheng         return true;
3795fbe40ff7SFam Zheng     }
3796fbe40ff7SFam Zheng     return false;
3797fbe40ff7SFam Zheng }
3798fbe40ff7SFam Zheng 
3799fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3800fbe40ff7SFam Zheng {
3801fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3802fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3803fbe40ff7SFam Zheng 
38045839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3805fbe40ff7SFam Zheng     blocker->reason = reason;
3806fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3807fbe40ff7SFam Zheng }
3808fbe40ff7SFam Zheng 
3809fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3810fbe40ff7SFam Zheng {
3811fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3812fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3813fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3814fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3815fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3816fbe40ff7SFam Zheng             g_free(blocker);
3817fbe40ff7SFam Zheng         }
3818fbe40ff7SFam Zheng     }
3819fbe40ff7SFam Zheng }
3820fbe40ff7SFam Zheng 
3821fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3822fbe40ff7SFam Zheng {
3823fbe40ff7SFam Zheng     int i;
3824fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3825fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3826fbe40ff7SFam Zheng     }
3827fbe40ff7SFam Zheng }
3828fbe40ff7SFam Zheng 
3829fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3830fbe40ff7SFam Zheng {
3831fbe40ff7SFam Zheng     int i;
3832fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3833fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3834fbe40ff7SFam Zheng     }
3835fbe40ff7SFam Zheng }
3836fbe40ff7SFam Zheng 
3837fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3838fbe40ff7SFam Zheng {
3839fbe40ff7SFam Zheng     int i;
3840fbe40ff7SFam Zheng 
3841fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3842fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3843fbe40ff7SFam Zheng             return false;
3844fbe40ff7SFam Zheng         }
3845fbe40ff7SFam Zheng     }
3846fbe40ff7SFam Zheng     return true;
3847fbe40ff7SFam Zheng }
3848fbe40ff7SFam Zheng 
3849d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3850f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3851f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3852f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3853f88e1a42SJes Sorensen {
385483d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
385583d0521aSChunyan Liu     QemuOpts *opts = NULL;
385683d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
385783d0521aSChunyan Liu     int64_t size;
3858f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3859cc84d90fSMax Reitz     Error *local_err = NULL;
3860f88e1a42SJes Sorensen     int ret = 0;
3861f88e1a42SJes Sorensen 
3862f88e1a42SJes Sorensen     /* Find driver and parse its options */
3863f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3864f88e1a42SJes Sorensen     if (!drv) {
386571c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3866d92ada22SLuiz Capitulino         return;
3867f88e1a42SJes Sorensen     }
3868f88e1a42SJes Sorensen 
3869b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3870f88e1a42SJes Sorensen     if (!proto_drv) {
3871d92ada22SLuiz Capitulino         return;
3872f88e1a42SJes Sorensen     }
3873f88e1a42SJes Sorensen 
3874c6149724SMax Reitz     if (!drv->create_opts) {
3875c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3876c6149724SMax Reitz                    drv->format_name);
3877c6149724SMax Reitz         return;
3878c6149724SMax Reitz     }
3879c6149724SMax Reitz 
3880c6149724SMax Reitz     if (!proto_drv->create_opts) {
3881c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3882c6149724SMax Reitz                    proto_drv->format_name);
3883c6149724SMax Reitz         return;
3884c6149724SMax Reitz     }
3885c6149724SMax Reitz 
3886c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3887c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3888f88e1a42SJes Sorensen 
3889f88e1a42SJes Sorensen     /* Create parameter list with default values */
389083d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
389139101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3892f88e1a42SJes Sorensen 
3893f88e1a42SJes Sorensen     /* Parse -o options */
3894f88e1a42SJes Sorensen     if (options) {
3895dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3896dc523cd3SMarkus Armbruster         if (local_err) {
3897dc523cd3SMarkus Armbruster             error_report_err(local_err);
3898dc523cd3SMarkus Armbruster             local_err = NULL;
389983d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3900f88e1a42SJes Sorensen             goto out;
3901f88e1a42SJes Sorensen         }
3902f88e1a42SJes Sorensen     }
3903f88e1a42SJes Sorensen 
3904f88e1a42SJes Sorensen     if (base_filename) {
3905f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
39066be4194bSMarkus Armbruster         if (local_err) {
390771c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
390871c79813SLuiz Capitulino                        fmt);
3909f88e1a42SJes Sorensen             goto out;
3910f88e1a42SJes Sorensen         }
3911f88e1a42SJes Sorensen     }
3912f88e1a42SJes Sorensen 
3913f88e1a42SJes Sorensen     if (base_fmt) {
3914f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
39156be4194bSMarkus Armbruster         if (local_err) {
391671c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
391771c79813SLuiz Capitulino                              "format '%s'", fmt);
3918f88e1a42SJes Sorensen             goto out;
3919f88e1a42SJes Sorensen         }
3920f88e1a42SJes Sorensen     }
3921f88e1a42SJes Sorensen 
392283d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
392383d0521aSChunyan Liu     if (backing_file) {
392483d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
392571c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
392671c79813SLuiz Capitulino                              "same filename as the backing file");
3927792da93aSJes Sorensen             goto out;
3928792da93aSJes Sorensen         }
3929792da93aSJes Sorensen     }
3930792da93aSJes Sorensen 
393183d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3932f88e1a42SJes Sorensen 
3933f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3934f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
393583d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
393683d0521aSChunyan Liu     if (size == -1) {
393783d0521aSChunyan Liu         if (backing_file) {
393866f6b814SMax Reitz             BlockDriverState *bs;
393929168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
394052bf1e72SMarkus Armbruster             int64_t size;
394163090dacSPaolo Bonzini             int back_flags;
3942e6641719SMax Reitz             QDict *backing_options = NULL;
394363090dacSPaolo Bonzini 
394429168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
394529168018SMax Reitz                                                          full_backing, PATH_MAX,
394629168018SMax Reitz                                                          &local_err);
394729168018SMax Reitz             if (local_err) {
394829168018SMax Reitz                 g_free(full_backing);
394929168018SMax Reitz                 goto out;
395029168018SMax Reitz             }
395129168018SMax Reitz 
395263090dacSPaolo Bonzini             /* backing files always opened read-only */
395363090dacSPaolo Bonzini             back_flags =
395463090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3955f88e1a42SJes Sorensen 
3956e6641719SMax Reitz             if (backing_fmt) {
3957e6641719SMax Reitz                 backing_options = qdict_new();
3958e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3959e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3960e6641719SMax Reitz             }
3961e6641719SMax Reitz 
3962f67503e5SMax Reitz             bs = NULL;
3963e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
39646ebf9aa2SMax Reitz                             back_flags, &local_err);
396529168018SMax Reitz             g_free(full_backing);
3966f88e1a42SJes Sorensen             if (ret < 0) {
3967f88e1a42SJes Sorensen                 goto out;
3968f88e1a42SJes Sorensen             }
396952bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
397052bf1e72SMarkus Armbruster             if (size < 0) {
397152bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
397252bf1e72SMarkus Armbruster                                  backing_file);
397352bf1e72SMarkus Armbruster                 bdrv_unref(bs);
397452bf1e72SMarkus Armbruster                 goto out;
397552bf1e72SMarkus Armbruster             }
3976f88e1a42SJes Sorensen 
397739101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
397866f6b814SMax Reitz 
397966f6b814SMax Reitz             bdrv_unref(bs);
3980f88e1a42SJes Sorensen         } else {
398171c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3982f88e1a42SJes Sorensen             goto out;
3983f88e1a42SJes Sorensen         }
3984f88e1a42SJes Sorensen     }
3985f88e1a42SJes Sorensen 
3986f382d43aSMiroslav Rezanina     if (!quiet) {
3987f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
398843c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3989f88e1a42SJes Sorensen         puts("");
3990f382d43aSMiroslav Rezanina     }
399183d0521aSChunyan Liu 
3992c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
399383d0521aSChunyan Liu 
3994cc84d90fSMax Reitz     if (ret == -EFBIG) {
3995cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3996cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3997cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3998f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
399983d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
4000f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
4001f3f4d2c0SKevin Wolf         }
4002cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
4003cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
4004cc84d90fSMax Reitz         error_free(local_err);
4005cc84d90fSMax Reitz         local_err = NULL;
4006f88e1a42SJes Sorensen     }
4007f88e1a42SJes Sorensen 
4008f88e1a42SJes Sorensen out:
400983d0521aSChunyan Liu     qemu_opts_del(opts);
401083d0521aSChunyan Liu     qemu_opts_free(create_opts);
401184d18f06SMarkus Armbruster     if (local_err) {
4012cc84d90fSMax Reitz         error_propagate(errp, local_err);
4013cc84d90fSMax Reitz     }
4014f88e1a42SJes Sorensen }
401585d126f3SStefan Hajnoczi 
401685d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
401785d126f3SStefan Hajnoczi {
4018dcd04228SStefan Hajnoczi     return bs->aio_context;
4019dcd04228SStefan Hajnoczi }
4020dcd04228SStefan Hajnoczi 
4021dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
4022dcd04228SStefan Hajnoczi {
402333384421SMax Reitz     BdrvAioNotifier *baf;
402433384421SMax Reitz 
4025dcd04228SStefan Hajnoczi     if (!bs->drv) {
4026dcd04228SStefan Hajnoczi         return;
4027dcd04228SStefan Hajnoczi     }
4028dcd04228SStefan Hajnoczi 
402933384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
403033384421SMax Reitz         baf->detach_aio_context(baf->opaque);
403133384421SMax Reitz     }
403233384421SMax Reitz 
4033a0d64a61SAlberto Garcia     if (bs->throttle_state) {
40340e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
403513af91ebSStefan Hajnoczi     }
4036dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
4037dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
4038dcd04228SStefan Hajnoczi     }
4039dcd04228SStefan Hajnoczi     if (bs->file) {
40409a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
4041dcd04228SStefan Hajnoczi     }
4042760e0063SKevin Wolf     if (bs->backing) {
4043760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
4044dcd04228SStefan Hajnoczi     }
4045dcd04228SStefan Hajnoczi 
4046dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
4047dcd04228SStefan Hajnoczi }
4048dcd04228SStefan Hajnoczi 
4049dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
4050dcd04228SStefan Hajnoczi                              AioContext *new_context)
4051dcd04228SStefan Hajnoczi {
405233384421SMax Reitz     BdrvAioNotifier *ban;
405333384421SMax Reitz 
4054dcd04228SStefan Hajnoczi     if (!bs->drv) {
4055dcd04228SStefan Hajnoczi         return;
4056dcd04228SStefan Hajnoczi     }
4057dcd04228SStefan Hajnoczi 
4058dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
4059dcd04228SStefan Hajnoczi 
4060760e0063SKevin Wolf     if (bs->backing) {
4061760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
4062dcd04228SStefan Hajnoczi     }
4063dcd04228SStefan Hajnoczi     if (bs->file) {
40649a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
4065dcd04228SStefan Hajnoczi     }
4066dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
4067dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
4068dcd04228SStefan Hajnoczi     }
4069a0d64a61SAlberto Garcia     if (bs->throttle_state) {
40700e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
407113af91ebSStefan Hajnoczi     }
407233384421SMax Reitz 
407333384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
407433384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
407533384421SMax Reitz     }
4076dcd04228SStefan Hajnoczi }
4077dcd04228SStefan Hajnoczi 
4078dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
4079dcd04228SStefan Hajnoczi {
408053ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
4081dcd04228SStefan Hajnoczi 
4082dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
4083dcd04228SStefan Hajnoczi 
4084dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
4085dcd04228SStefan Hajnoczi      * case it runs in a different thread.
4086dcd04228SStefan Hajnoczi      */
4087dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
4088dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
4089dcd04228SStefan Hajnoczi     aio_context_release(new_context);
409085d126f3SStefan Hajnoczi }
4091d616b224SStefan Hajnoczi 
409233384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
409333384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
409433384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
409533384421SMax Reitz {
409633384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
409733384421SMax Reitz     *ban = (BdrvAioNotifier){
409833384421SMax Reitz         .attached_aio_context = attached_aio_context,
409933384421SMax Reitz         .detach_aio_context   = detach_aio_context,
410033384421SMax Reitz         .opaque               = opaque
410133384421SMax Reitz     };
410233384421SMax Reitz 
410333384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
410433384421SMax Reitz }
410533384421SMax Reitz 
410633384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
410733384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
410833384421SMax Reitz                                                                    void *),
410933384421SMax Reitz                                       void (*detach_aio_context)(void *),
411033384421SMax Reitz                                       void *opaque)
411133384421SMax Reitz {
411233384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
411333384421SMax Reitz 
411433384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
411533384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
411633384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
411733384421SMax Reitz             ban->opaque               == opaque)
411833384421SMax Reitz         {
411933384421SMax Reitz             QLIST_REMOVE(ban, list);
412033384421SMax Reitz             g_free(ban);
412133384421SMax Reitz 
412233384421SMax Reitz             return;
412333384421SMax Reitz         }
412433384421SMax Reitz     }
412533384421SMax Reitz 
412633384421SMax Reitz     abort();
412733384421SMax Reitz }
412833384421SMax Reitz 
412977485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
41308b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
41316f176b48SMax Reitz {
4132c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
41336f176b48SMax Reitz         return -ENOTSUP;
41346f176b48SMax Reitz     }
41358b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
41366f176b48SMax Reitz }
4137f6186f49SBenoît Canet 
4138b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
4139b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
4140b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
4141b5042a36SBenoît Canet  * node graph.
4142212a5a8fSBenoît Canet  */
4143212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
4144212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
4145f6186f49SBenoît Canet {
4146b5042a36SBenoît Canet     /* return false if basic checks fails */
4147b5042a36SBenoît Canet     if (!bs || !bs->drv) {
4148b5042a36SBenoît Canet         return false;
4149b5042a36SBenoît Canet     }
4150b5042a36SBenoît Canet 
4151b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
4152b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
4153b5042a36SBenoît Canet      */
4154b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
4155b5042a36SBenoît Canet         return bs == candidate;
4156b5042a36SBenoît Canet     }
4157b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
4158b5042a36SBenoît Canet 
4159b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
4160b5042a36SBenoît Canet      * the node graph.
4161b5042a36SBenoît Canet      */
4162b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
4163212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4164212a5a8fSBenoît Canet     }
4165212a5a8fSBenoît Canet 
4166b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
4167b5042a36SBenoît Canet      */
4168b5042a36SBenoît Canet     return false;
4169212a5a8fSBenoît Canet }
4170212a5a8fSBenoît Canet 
4171212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
4172212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
4173212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
4174212a5a8fSBenoît Canet  */
4175212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4176212a5a8fSBenoît Canet {
4177212a5a8fSBenoît Canet     BlockDriverState *bs;
4178212a5a8fSBenoît Canet 
4179212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
4180212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
4181212a5a8fSBenoît Canet         bool perm;
4182212a5a8fSBenoît Canet 
4183b5042a36SBenoît Canet         /* try to recurse in this top level bs */
4184e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
4185212a5a8fSBenoît Canet 
4186212a5a8fSBenoît Canet         /* candidate is the first non filter */
4187212a5a8fSBenoît Canet         if (perm) {
4188212a5a8fSBenoît Canet             return true;
4189212a5a8fSBenoît Canet         }
4190212a5a8fSBenoît Canet     }
4191212a5a8fSBenoît Canet 
4192212a5a8fSBenoît Canet     return false;
4193f6186f49SBenoît Canet }
419409158f00SBenoît Canet 
4195e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4196e12f3784SWen Congyang                                         const char *node_name, Error **errp)
419709158f00SBenoît Canet {
419809158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
41995a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
42005a7e7a0bSStefan Hajnoczi 
420109158f00SBenoît Canet     if (!to_replace_bs) {
420209158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
420309158f00SBenoît Canet         return NULL;
420409158f00SBenoît Canet     }
420509158f00SBenoît Canet 
42065a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
42075a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
42085a7e7a0bSStefan Hajnoczi 
420909158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
42105a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
42115a7e7a0bSStefan Hajnoczi         goto out;
421209158f00SBenoît Canet     }
421309158f00SBenoît Canet 
421409158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
421509158f00SBenoît Canet      * most non filter in order to prevent data corruption.
421609158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
421709158f00SBenoît Canet      * blocked by the backing blockers.
421809158f00SBenoît Canet      */
4219e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
422009158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
42215a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
42225a7e7a0bSStefan Hajnoczi         goto out;
422309158f00SBenoît Canet     }
422409158f00SBenoît Canet 
42255a7e7a0bSStefan Hajnoczi out:
42265a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
422709158f00SBenoît Canet     return to_replace_bs;
422809158f00SBenoît Canet }
4229448ad91dSMing Lei 
423091af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
423191af7014SMax Reitz {
423291af7014SMax Reitz     const QDictEntry *entry;
42339e700c1aSKevin Wolf     QemuOptDesc *desc;
4234260fecf1SKevin Wolf     BdrvChild *child;
423591af7014SMax Reitz     bool found_any = false;
4236260fecf1SKevin Wolf     const char *p;
423791af7014SMax Reitz 
423891af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
423991af7014SMax Reitz          entry = qdict_next(bs->options, entry))
424091af7014SMax Reitz     {
4241260fecf1SKevin Wolf         /* Exclude options for children */
4242260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
4243260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
4244260fecf1SKevin Wolf                 && (!*p || *p == '.'))
4245260fecf1SKevin Wolf             {
4246260fecf1SKevin Wolf                 break;
4247260fecf1SKevin Wolf             }
4248260fecf1SKevin Wolf         }
4249260fecf1SKevin Wolf         if (child) {
42509e700c1aSKevin Wolf             continue;
42519e700c1aSKevin Wolf         }
42529e700c1aSKevin Wolf 
42539e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
42549e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
42559e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
42569e700c1aSKevin Wolf                 break;
42579e700c1aSKevin Wolf             }
42589e700c1aSKevin Wolf         }
42599e700c1aSKevin Wolf         if (desc->name) {
42609e700c1aSKevin Wolf             continue;
42619e700c1aSKevin Wolf         }
42629e700c1aSKevin Wolf 
426391af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
426491af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
426591af7014SMax Reitz         found_any = true;
426691af7014SMax Reitz     }
426791af7014SMax Reitz 
426891af7014SMax Reitz     return found_any;
426991af7014SMax Reitz }
427091af7014SMax Reitz 
427191af7014SMax Reitz /* Updates the following BDS fields:
427291af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
427391af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
427491af7014SMax Reitz  *                    other options; so reading and writing must return the same
427591af7014SMax Reitz  *                    results, but caching etc. may be different)
427691af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
427791af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
427891af7014SMax Reitz  *                       equalling the given one
427991af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
428091af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
428191af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
428291af7014SMax Reitz  */
428391af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
428491af7014SMax Reitz {
428591af7014SMax Reitz     BlockDriver *drv = bs->drv;
428691af7014SMax Reitz     QDict *opts;
428791af7014SMax Reitz 
428891af7014SMax Reitz     if (!drv) {
428991af7014SMax Reitz         return;
429091af7014SMax Reitz     }
429191af7014SMax Reitz 
429291af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
429391af7014SMax Reitz      * refresh that first */
429491af7014SMax Reitz     if (bs->file) {
42959a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
429691af7014SMax Reitz     }
429791af7014SMax Reitz 
429891af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
429991af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
430091af7014SMax Reitz          * information before refreshing it */
430191af7014SMax Reitz         bs->exact_filename[0] = '\0';
430291af7014SMax Reitz         if (bs->full_open_options) {
430391af7014SMax Reitz             QDECREF(bs->full_open_options);
430491af7014SMax Reitz             bs->full_open_options = NULL;
430591af7014SMax Reitz         }
430691af7014SMax Reitz 
43074cdd01d3SKevin Wolf         opts = qdict_new();
43084cdd01d3SKevin Wolf         append_open_options(opts, bs);
43094cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
43104cdd01d3SKevin Wolf         QDECREF(opts);
431191af7014SMax Reitz     } else if (bs->file) {
431291af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
431391af7014SMax Reitz         bool has_open_options;
431491af7014SMax Reitz 
431591af7014SMax Reitz         bs->exact_filename[0] = '\0';
431691af7014SMax Reitz         if (bs->full_open_options) {
431791af7014SMax Reitz             QDECREF(bs->full_open_options);
431891af7014SMax Reitz             bs->full_open_options = NULL;
431991af7014SMax Reitz         }
432091af7014SMax Reitz 
432191af7014SMax Reitz         opts = qdict_new();
432291af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
432391af7014SMax Reitz 
432491af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
432591af7014SMax Reitz          * the underlying file should suffice for this one as well */
43269a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
43279a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
432891af7014SMax Reitz         }
432991af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
433091af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
433191af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
433291af7014SMax Reitz          * contain a representation of the filename, therefore the following
433391af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
43349a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
433591af7014SMax Reitz             qdict_put_obj(opts, "driver",
433691af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
43379a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
43389a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
43399a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
434091af7014SMax Reitz 
434191af7014SMax Reitz             bs->full_open_options = opts;
434291af7014SMax Reitz         } else {
434391af7014SMax Reitz             QDECREF(opts);
434491af7014SMax Reitz         }
434591af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
434691af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
434791af7014SMax Reitz          * so the full options QDict should be equal to the options given
434891af7014SMax Reitz          * specifically for this block device when it was opened (plus the
434991af7014SMax Reitz          * driver specification).
435091af7014SMax Reitz          * Because those options don't change, there is no need to update
435191af7014SMax Reitz          * full_open_options when it's already set. */
435291af7014SMax Reitz 
435391af7014SMax Reitz         opts = qdict_new();
435491af7014SMax Reitz         append_open_options(opts, bs);
435591af7014SMax Reitz         qdict_put_obj(opts, "driver",
435691af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
435791af7014SMax Reitz 
435891af7014SMax Reitz         if (bs->exact_filename[0]) {
435991af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
436091af7014SMax Reitz              * require this filename to be parsed), but we have to find some
436191af7014SMax Reitz              * default solution here, so just include it. If some block driver
436291af7014SMax Reitz              * does not support pure options without any filename at all or
436391af7014SMax Reitz              * needs some special format of the options QDict, it needs to
436491af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
436591af7014SMax Reitz              */
436691af7014SMax Reitz             qdict_put_obj(opts, "filename",
436791af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
436891af7014SMax Reitz         }
436991af7014SMax Reitz 
437091af7014SMax Reitz         bs->full_open_options = opts;
437191af7014SMax Reitz     }
437291af7014SMax Reitz 
437391af7014SMax Reitz     if (bs->exact_filename[0]) {
437491af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
437591af7014SMax Reitz     } else if (bs->full_open_options) {
437691af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
437791af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
437891af7014SMax Reitz                  qstring_get_str(json));
437991af7014SMax Reitz         QDECREF(json);
438091af7014SMax Reitz     }
438191af7014SMax Reitz }
4382