xref: /openbmc/qemu/block.c (revision 3e8c2e57056614933fc5eb022e1d6d0f28071b44)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
27737e150eSPaolo Bonzini #include "block/block_int.h"
28737e150eSPaolo Bonzini #include "block/blockjob.h"
29d49b6836SMarkus Armbruster #include "qemu/error-report.h"
301de7afc9SPaolo Bonzini #include "qemu/module.h"
31cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
327b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
33bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
349c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
351de7afc9SPaolo Bonzini #include "qemu/notify.h"
3610817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
37c13163fbSBenoît Canet #include "block/qapi.h"
38b2023818SLuiz Capitulino #include "qmp-commands.h"
391de7afc9SPaolo Bonzini #include "qemu/timer.h"
40a5ee7bd4SWenchao Xia #include "qapi-event.h"
41db628338SAlberto Garcia #include "block/throttle-groups.h"
42fc01f7e7Sbellard 
4371e72a19SJuan Quintela #ifdef CONFIG_BSD
447674e7bfSbellard #include <sys/types.h>
457674e7bfSbellard #include <sys/stat.h>
467674e7bfSbellard #include <sys/ioctl.h>
4772cf2d4fSBlue Swirl #include <sys/queue.h>
48c5e97233Sblueswir1 #ifndef __DragonFly__
497674e7bfSbellard #include <sys/disk.h>
507674e7bfSbellard #endif
51c5e97233Sblueswir1 #endif
527674e7bfSbellard 
5349dc768dSaliguori #ifdef _WIN32
5449dc768dSaliguori #include <windows.h>
5549dc768dSaliguori #endif
5649dc768dSaliguori 
579bd2b08fSJohn Snow /**
589bd2b08fSJohn Snow  * A BdrvDirtyBitmap can be in three possible states:
599bd2b08fSJohn Snow  * (1) successor is NULL and disabled is false: full r/w mode
609bd2b08fSJohn Snow  * (2) successor is NULL and disabled is true: read only mode ("disabled")
619bd2b08fSJohn Snow  * (3) successor is set: frozen mode.
629bd2b08fSJohn Snow  *     A frozen bitmap cannot be renamed, deleted, anonymized, cleared, set,
639bd2b08fSJohn Snow  *     or enabled. A frozen bitmap can only abdicate() or reclaim().
649bd2b08fSJohn Snow  */
65e4654d2dSFam Zheng struct BdrvDirtyBitmap {
66aa0c7ca5SJohn Snow     HBitmap *bitmap;            /* Dirty sector bitmap implementation */
67aa0c7ca5SJohn Snow     BdrvDirtyBitmap *successor; /* Anonymous child; implies frozen status */
68aa0c7ca5SJohn Snow     char *name;                 /* Optional non-empty unique ID */
69aa0c7ca5SJohn Snow     int64_t size;               /* Size of the bitmap (Number of sectors) */
70aa0c7ca5SJohn Snow     bool disabled;              /* Bitmap is read-only */
71e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
72e4654d2dSFam Zheng };
73e4654d2dSFam Zheng 
741c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
751c9805a3SStefan Hajnoczi 
76c69a4dd8SMax Reitz struct BdrvStates bdrv_states = QTAILQ_HEAD_INITIALIZER(bdrv_states);
777ee930d0Sblueswir1 
78dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
79dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
80dc364f4cSBenoît Canet 
818a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
828a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
83ea2384d3Sbellard 
84f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
85f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
86f3930ed0SKevin Wolf                              BlockDriverState *parent,
87ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
88f3930ed0SKevin Wolf 
89ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs);
90eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
91eb852011SMarkus Armbruster static int use_bdrv_whitelist;
92eb852011SMarkus Armbruster 
939e0b22f4SStefan Hajnoczi #ifdef _WIN32
949e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
959e0b22f4SStefan Hajnoczi {
969e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
979e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
989e0b22f4SStefan Hajnoczi             filename[1] == ':');
999e0b22f4SStefan Hajnoczi }
1009e0b22f4SStefan Hajnoczi 
1019e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1029e0b22f4SStefan Hajnoczi {
1039e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1049e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1059e0b22f4SStefan Hajnoczi         return 1;
1069e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1079e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1089e0b22f4SStefan Hajnoczi         return 1;
1099e0b22f4SStefan Hajnoczi     return 0;
1109e0b22f4SStefan Hajnoczi }
1119e0b22f4SStefan Hajnoczi #endif
1129e0b22f4SStefan Hajnoczi 
113339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
114339064d5SKevin Wolf {
115339064d5SKevin Wolf     if (!bs || !bs->drv) {
116459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
117459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
118339064d5SKevin Wolf     }
119339064d5SKevin Wolf 
120339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
121339064d5SKevin Wolf }
122339064d5SKevin Wolf 
1234196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1244196d2f0SDenis V. Lunev {
1254196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
126459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
127459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1284196d2f0SDenis V. Lunev     }
1294196d2f0SDenis V. Lunev 
1304196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1314196d2f0SDenis V. Lunev }
1324196d2f0SDenis V. Lunev 
1339e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1345c98415bSMax Reitz int path_has_protocol(const char *path)
1359e0b22f4SStefan Hajnoczi {
136947995c0SPaolo Bonzini     const char *p;
137947995c0SPaolo Bonzini 
1389e0b22f4SStefan Hajnoczi #ifdef _WIN32
1399e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1409e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1419e0b22f4SStefan Hajnoczi         return 0;
1429e0b22f4SStefan Hajnoczi     }
143947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
144947995c0SPaolo Bonzini #else
145947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1469e0b22f4SStefan Hajnoczi #endif
1479e0b22f4SStefan Hajnoczi 
148947995c0SPaolo Bonzini     return *p == ':';
1499e0b22f4SStefan Hajnoczi }
1509e0b22f4SStefan Hajnoczi 
15183f64091Sbellard int path_is_absolute(const char *path)
15283f64091Sbellard {
15321664424Sbellard #ifdef _WIN32
15421664424Sbellard     /* specific case for names like: "\\.\d:" */
155f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
15621664424Sbellard         return 1;
157f53f4da9SPaolo Bonzini     }
158f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1593b9f94e1Sbellard #else
160f53f4da9SPaolo Bonzini     return (*path == '/');
1613b9f94e1Sbellard #endif
16283f64091Sbellard }
16383f64091Sbellard 
16483f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
16583f64091Sbellard    path to it by considering it is relative to base_path. URL are
16683f64091Sbellard    supported. */
16783f64091Sbellard void path_combine(char *dest, int dest_size,
16883f64091Sbellard                   const char *base_path,
16983f64091Sbellard                   const char *filename)
17083f64091Sbellard {
17183f64091Sbellard     const char *p, *p1;
17283f64091Sbellard     int len;
17383f64091Sbellard 
17483f64091Sbellard     if (dest_size <= 0)
17583f64091Sbellard         return;
17683f64091Sbellard     if (path_is_absolute(filename)) {
17783f64091Sbellard         pstrcpy(dest, dest_size, filename);
17883f64091Sbellard     } else {
17983f64091Sbellard         p = strchr(base_path, ':');
18083f64091Sbellard         if (p)
18183f64091Sbellard             p++;
18283f64091Sbellard         else
18383f64091Sbellard             p = base_path;
1843b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1853b9f94e1Sbellard #ifdef _WIN32
1863b9f94e1Sbellard         {
1873b9f94e1Sbellard             const char *p2;
1883b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1893b9f94e1Sbellard             if (!p1 || p2 > p1)
1903b9f94e1Sbellard                 p1 = p2;
1913b9f94e1Sbellard         }
1923b9f94e1Sbellard #endif
19383f64091Sbellard         if (p1)
19483f64091Sbellard             p1++;
19583f64091Sbellard         else
19683f64091Sbellard             p1 = base_path;
19783f64091Sbellard         if (p1 > p)
19883f64091Sbellard             p = p1;
19983f64091Sbellard         len = p - base_path;
20083f64091Sbellard         if (len > dest_size - 1)
20183f64091Sbellard             len = dest_size - 1;
20283f64091Sbellard         memcpy(dest, base_path, len);
20383f64091Sbellard         dest[len] = '\0';
20483f64091Sbellard         pstrcat(dest, dest_size, filename);
20583f64091Sbellard     }
20683f64091Sbellard }
20783f64091Sbellard 
2080a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
2090a82855aSMax Reitz                                                   const char *backing,
2109f07429eSMax Reitz                                                   char *dest, size_t sz,
2119f07429eSMax Reitz                                                   Error **errp)
2120a82855aSMax Reitz {
2139f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2149f07429eSMax Reitz         path_is_absolute(backing))
2159f07429eSMax Reitz     {
2160a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2179f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2189f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2199f07429eSMax Reitz                    backed);
2200a82855aSMax Reitz     } else {
2210a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2220a82855aSMax Reitz     }
2230a82855aSMax Reitz }
2240a82855aSMax Reitz 
2259f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2269f07429eSMax Reitz                                     Error **errp)
227dc5a1371SPaolo Bonzini {
2289f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2299f07429eSMax Reitz 
2309f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2319f07429eSMax Reitz                                                  dest, sz, errp);
232dc5a1371SPaolo Bonzini }
233dc5a1371SPaolo Bonzini 
2340eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2350eb7217eSStefan Hajnoczi {
2360eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
237b2e12bc6SChristoph Hellwig 
2388a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
239ea2384d3Sbellard }
240b338082bSbellard 
2417f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
242fc01f7e7Sbellard {
2437f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
244e4e9986bSMarkus Armbruster 
245e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
246e4e9986bSMarkus Armbruster     return bs;
247e4e9986bSMarkus Armbruster }
248e4e9986bSMarkus Armbruster 
249e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
250e4e9986bSMarkus Armbruster {
251e4e9986bSMarkus Armbruster     BlockDriverState *bs;
252e4e9986bSMarkus Armbruster     int i;
253e4e9986bSMarkus Armbruster 
2545839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
255e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
256fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
257fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
258fbe40ff7SFam Zheng     }
259d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
260d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
261cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
262cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2639fcb0251SFam Zheng     bs->refcnt = 1;
264dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
265d7d512f6SPaolo Bonzini 
266b338082bSbellard     return bs;
267b338082bSbellard }
268b338082bSbellard 
269d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
270d7d512f6SPaolo Bonzini {
271d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
272d7d512f6SPaolo Bonzini }
273d7d512f6SPaolo Bonzini 
274ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
275ea2384d3Sbellard {
276ea2384d3Sbellard     BlockDriver *drv1;
2778a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2788a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
279ea2384d3Sbellard             return drv1;
280ea2384d3Sbellard         }
2818a22f02aSStefan Hajnoczi     }
282ea2384d3Sbellard     return NULL;
283ea2384d3Sbellard }
284ea2384d3Sbellard 
285b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
286eb852011SMarkus Armbruster {
287b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
288b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
289b64ec4e4SFam Zheng     };
290b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
291b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
292eb852011SMarkus Armbruster     };
293eb852011SMarkus Armbruster     const char **p;
294eb852011SMarkus Armbruster 
295b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
296eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
297b64ec4e4SFam Zheng     }
298eb852011SMarkus Armbruster 
299b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
300eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
301eb852011SMarkus Armbruster             return 1;
302eb852011SMarkus Armbruster         }
303eb852011SMarkus Armbruster     }
304b64ec4e4SFam Zheng     if (read_only) {
305b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
306b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
307b64ec4e4SFam Zheng                 return 1;
308b64ec4e4SFam Zheng             }
309b64ec4e4SFam Zheng         }
310b64ec4e4SFam Zheng     }
311eb852011SMarkus Armbruster     return 0;
312eb852011SMarkus Armbruster }
313eb852011SMarkus Armbruster 
3145b7e1542SZhi Yong Wu typedef struct CreateCo {
3155b7e1542SZhi Yong Wu     BlockDriver *drv;
3165b7e1542SZhi Yong Wu     char *filename;
31783d0521aSChunyan Liu     QemuOpts *opts;
3185b7e1542SZhi Yong Wu     int ret;
319cc84d90fSMax Reitz     Error *err;
3205b7e1542SZhi Yong Wu } CreateCo;
3215b7e1542SZhi Yong Wu 
3225b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3235b7e1542SZhi Yong Wu {
324cc84d90fSMax Reitz     Error *local_err = NULL;
325cc84d90fSMax Reitz     int ret;
326cc84d90fSMax Reitz 
3275b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3285b7e1542SZhi Yong Wu     assert(cco->drv);
3295b7e1542SZhi Yong Wu 
330c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
33184d18f06SMarkus Armbruster     if (local_err) {
332cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
333cc84d90fSMax Reitz     }
334cc84d90fSMax Reitz     cco->ret = ret;
3355b7e1542SZhi Yong Wu }
3365b7e1542SZhi Yong Wu 
3370e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
33883d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
339ea2384d3Sbellard {
3405b7e1542SZhi Yong Wu     int ret;
3410e7e1989SKevin Wolf 
3425b7e1542SZhi Yong Wu     Coroutine *co;
3435b7e1542SZhi Yong Wu     CreateCo cco = {
3445b7e1542SZhi Yong Wu         .drv = drv,
3455b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
34683d0521aSChunyan Liu         .opts = opts,
3475b7e1542SZhi Yong Wu         .ret = NOT_DONE,
348cc84d90fSMax Reitz         .err = NULL,
3495b7e1542SZhi Yong Wu     };
3505b7e1542SZhi Yong Wu 
351c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
352cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35380168bffSLuiz Capitulino         ret = -ENOTSUP;
35480168bffSLuiz Capitulino         goto out;
3555b7e1542SZhi Yong Wu     }
3565b7e1542SZhi Yong Wu 
3575b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3585b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3595b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3605b7e1542SZhi Yong Wu     } else {
3615b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3625b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3635b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
364b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3655b7e1542SZhi Yong Wu         }
3665b7e1542SZhi Yong Wu     }
3675b7e1542SZhi Yong Wu 
3685b7e1542SZhi Yong Wu     ret = cco.ret;
369cc84d90fSMax Reitz     if (ret < 0) {
37084d18f06SMarkus Armbruster         if (cco.err) {
371cc84d90fSMax Reitz             error_propagate(errp, cco.err);
372cc84d90fSMax Reitz         } else {
373cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
374cc84d90fSMax Reitz         }
375cc84d90fSMax Reitz     }
3765b7e1542SZhi Yong Wu 
37780168bffSLuiz Capitulino out:
37880168bffSLuiz Capitulino     g_free(cco.filename);
3795b7e1542SZhi Yong Wu     return ret;
380ea2384d3Sbellard }
381ea2384d3Sbellard 
382c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38384a12e66SChristoph Hellwig {
38484a12e66SChristoph Hellwig     BlockDriver *drv;
385cc84d90fSMax Reitz     Error *local_err = NULL;
386cc84d90fSMax Reitz     int ret;
38784a12e66SChristoph Hellwig 
388b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
38984a12e66SChristoph Hellwig     if (drv == NULL) {
39016905d71SStefan Hajnoczi         return -ENOENT;
39184a12e66SChristoph Hellwig     }
39284a12e66SChristoph Hellwig 
393c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
39484d18f06SMarkus Armbruster     if (local_err) {
395cc84d90fSMax Reitz         error_propagate(errp, local_err);
396cc84d90fSMax Reitz     }
397cc84d90fSMax Reitz     return ret;
39884a12e66SChristoph Hellwig }
39984a12e66SChristoph Hellwig 
400892b7de8SEkaterina Tumanova /**
401892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
402892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
403892b7de8SEkaterina Tumanova  * On failure return -errno.
404892b7de8SEkaterina Tumanova  * @bs must not be empty.
405892b7de8SEkaterina Tumanova  */
406892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
407892b7de8SEkaterina Tumanova {
408892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
409892b7de8SEkaterina Tumanova 
410892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
411892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
412892b7de8SEkaterina Tumanova     }
413892b7de8SEkaterina Tumanova 
414892b7de8SEkaterina Tumanova     return -ENOTSUP;
415892b7de8SEkaterina Tumanova }
416892b7de8SEkaterina Tumanova 
417892b7de8SEkaterina Tumanova /**
418892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
419892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
420892b7de8SEkaterina Tumanova  * On failure return -errno.
421892b7de8SEkaterina Tumanova  * @bs must not be empty.
422892b7de8SEkaterina Tumanova  */
423892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
424892b7de8SEkaterina Tumanova {
425892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
426892b7de8SEkaterina Tumanova 
427892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
428892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
429892b7de8SEkaterina Tumanova     }
430892b7de8SEkaterina Tumanova 
431892b7de8SEkaterina Tumanova     return -ENOTSUP;
432892b7de8SEkaterina Tumanova }
433892b7de8SEkaterina Tumanova 
434eba25057SJim Meyering /*
435eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
436eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
437eba25057SJim Meyering  */
438eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
439eba25057SJim Meyering {
440d5249393Sbellard #ifdef _WIN32
4413b9f94e1Sbellard     char temp_dir[MAX_PATH];
442eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
443eba25057SJim Meyering        have length MAX_PATH or greater.  */
444eba25057SJim Meyering     assert(size >= MAX_PATH);
445eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
446eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
447eba25057SJim Meyering             ? 0 : -GetLastError());
448d5249393Sbellard #else
449ea2384d3Sbellard     int fd;
4507ccfb2ebSblueswir1     const char *tmpdir;
4510badc1eeSaurel32     tmpdir = getenv("TMPDIR");
45269bef793SAmit Shah     if (!tmpdir) {
45369bef793SAmit Shah         tmpdir = "/var/tmp";
45469bef793SAmit Shah     }
455eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
456eba25057SJim Meyering         return -EOVERFLOW;
457ea2384d3Sbellard     }
458eba25057SJim Meyering     fd = mkstemp(filename);
459fe235a06SDunrong Huang     if (fd < 0) {
460fe235a06SDunrong Huang         return -errno;
461fe235a06SDunrong Huang     }
462fe235a06SDunrong Huang     if (close(fd) != 0) {
463fe235a06SDunrong Huang         unlink(filename);
464eba25057SJim Meyering         return -errno;
465eba25057SJim Meyering     }
466eba25057SJim Meyering     return 0;
467d5249393Sbellard #endif
468eba25057SJim Meyering }
469ea2384d3Sbellard 
470f3a5d3f8SChristoph Hellwig /*
471f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
472f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
473f3a5d3f8SChristoph Hellwig  */
474f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
475f3a5d3f8SChristoph Hellwig {
476508c7cb3SChristoph Hellwig     int score_max = 0, score;
477508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
478f3a5d3f8SChristoph Hellwig 
4798a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
480508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
481508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
482508c7cb3SChristoph Hellwig             if (score > score_max) {
483508c7cb3SChristoph Hellwig                 score_max = score;
484508c7cb3SChristoph Hellwig                 drv = d;
485f3a5d3f8SChristoph Hellwig             }
486508c7cb3SChristoph Hellwig         }
487f3a5d3f8SChristoph Hellwig     }
488f3a5d3f8SChristoph Hellwig 
489508c7cb3SChristoph Hellwig     return drv;
490f3a5d3f8SChristoph Hellwig }
491f3a5d3f8SChristoph Hellwig 
49298289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
493b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
494b65a5e12SMax Reitz                                 Error **errp)
49584a12e66SChristoph Hellwig {
49684a12e66SChristoph Hellwig     BlockDriver *drv1;
49784a12e66SChristoph Hellwig     char protocol[128];
49884a12e66SChristoph Hellwig     int len;
49984a12e66SChristoph Hellwig     const char *p;
50084a12e66SChristoph Hellwig 
50166f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
50266f82ceeSKevin Wolf 
50339508e7aSChristoph Hellwig     /*
50439508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
50539508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
50639508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
50739508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
50839508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
50939508e7aSChristoph Hellwig      */
51084a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
51139508e7aSChristoph Hellwig     if (drv1) {
51284a12e66SChristoph Hellwig         return drv1;
51384a12e66SChristoph Hellwig     }
51439508e7aSChristoph Hellwig 
51598289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
516ef810437SMax Reitz         return &bdrv_file;
51739508e7aSChristoph Hellwig     }
51898289620SKevin Wolf 
5199e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5209e0b22f4SStefan Hajnoczi     assert(p != NULL);
52184a12e66SChristoph Hellwig     len = p - filename;
52284a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
52384a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
52484a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
52584a12e66SChristoph Hellwig     protocol[len] = '\0';
52684a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
52784a12e66SChristoph Hellwig         if (drv1->protocol_name &&
52884a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
52984a12e66SChristoph Hellwig             return drv1;
53084a12e66SChristoph Hellwig         }
53184a12e66SChristoph Hellwig     }
532b65a5e12SMax Reitz 
533b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
53484a12e66SChristoph Hellwig     return NULL;
53584a12e66SChristoph Hellwig }
53684a12e66SChristoph Hellwig 
537c6684249SMarkus Armbruster /*
538c6684249SMarkus Armbruster  * Guess image format by probing its contents.
539c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
540c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
541c6684249SMarkus Armbruster  *
542c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5437cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5447cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
545c6684249SMarkus Armbruster  * @filename    is its filename.
546c6684249SMarkus Armbruster  *
547c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
548c6684249SMarkus Armbruster  * probing score.
549c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
550c6684249SMarkus Armbruster  */
55138f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
552c6684249SMarkus Armbruster                             const char *filename)
553c6684249SMarkus Armbruster {
554c6684249SMarkus Armbruster     int score_max = 0, score;
555c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
556c6684249SMarkus Armbruster 
557c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
558c6684249SMarkus Armbruster         if (d->bdrv_probe) {
559c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
560c6684249SMarkus Armbruster             if (score > score_max) {
561c6684249SMarkus Armbruster                 score_max = score;
562c6684249SMarkus Armbruster                 drv = d;
563c6684249SMarkus Armbruster             }
564c6684249SMarkus Armbruster         }
565c6684249SMarkus Armbruster     }
566c6684249SMarkus Armbruster 
567c6684249SMarkus Armbruster     return drv;
568c6684249SMarkus Armbruster }
569c6684249SMarkus Armbruster 
570f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
57134b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
572ea2384d3Sbellard {
573c6684249SMarkus Armbruster     BlockDriver *drv;
5747cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
575f500a6d3SKevin Wolf     int ret = 0;
576f8ea0b00SNicholas Bellinger 
57708a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
578b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
579ef810437SMax Reitz         *pdrv = &bdrv_raw;
580c98ac35dSStefan Weil         return ret;
5811a396859SNicholas A. Bellinger     }
582f8ea0b00SNicholas Bellinger 
58383f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
584ea2384d3Sbellard     if (ret < 0) {
58534b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
58634b5d2c6SMax Reitz                          "format");
587c98ac35dSStefan Weil         *pdrv = NULL;
588c98ac35dSStefan Weil         return ret;
589ea2384d3Sbellard     }
590ea2384d3Sbellard 
591c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
592c98ac35dSStefan Weil     if (!drv) {
59334b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
59434b5d2c6SMax Reitz                    "driver found");
595c98ac35dSStefan Weil         ret = -ENOENT;
596c98ac35dSStefan Weil     }
597c98ac35dSStefan Weil     *pdrv = drv;
598c98ac35dSStefan Weil     return ret;
599ea2384d3Sbellard }
600ea2384d3Sbellard 
60151762288SStefan Hajnoczi /**
60251762288SStefan Hajnoczi  * Set the current 'total_sectors' value
60365a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
60451762288SStefan Hajnoczi  */
60551762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
60651762288SStefan Hajnoczi {
60751762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
60851762288SStefan Hajnoczi 
609396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
610b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
611396759adSNicholas Bellinger         return 0;
612396759adSNicholas Bellinger 
61351762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
61451762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
61551762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
61651762288SStefan Hajnoczi         if (length < 0) {
61751762288SStefan Hajnoczi             return length;
61851762288SStefan Hajnoczi         }
6197e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
62051762288SStefan Hajnoczi     }
62151762288SStefan Hajnoczi 
62251762288SStefan Hajnoczi     bs->total_sectors = hint;
62351762288SStefan Hajnoczi     return 0;
62451762288SStefan Hajnoczi }
62551762288SStefan Hajnoczi 
626c3993cdcSStefan Hajnoczi /**
6279e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6289e8f1835SPaolo Bonzini  *
6299e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6309e8f1835SPaolo Bonzini  */
6319e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6329e8f1835SPaolo Bonzini {
6339e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6349e8f1835SPaolo Bonzini 
6359e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6369e8f1835SPaolo Bonzini         /* do nothing */
6379e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6389e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6399e8f1835SPaolo Bonzini     } else {
6409e8f1835SPaolo Bonzini         return -1;
6419e8f1835SPaolo Bonzini     }
6429e8f1835SPaolo Bonzini 
6439e8f1835SPaolo Bonzini     return 0;
6449e8f1835SPaolo Bonzini }
6459e8f1835SPaolo Bonzini 
6469e8f1835SPaolo Bonzini /**
647c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
648c3993cdcSStefan Hajnoczi  *
649c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
650c3993cdcSStefan Hajnoczi  */
651c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
652c3993cdcSStefan Hajnoczi {
653c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
654c3993cdcSStefan Hajnoczi 
655c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
656c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
65792196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
65892196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
659c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
660c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
661c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
662c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
663c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
664c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
665c3993cdcSStefan Hajnoczi         /* this is the default */
666c3993cdcSStefan Hajnoczi     } else {
667c3993cdcSStefan Hajnoczi         return -1;
668c3993cdcSStefan Hajnoczi     }
669c3993cdcSStefan Hajnoczi 
670c3993cdcSStefan Hajnoczi     return 0;
671c3993cdcSStefan Hajnoczi }
672c3993cdcSStefan Hajnoczi 
6730b50cc88SKevin Wolf /*
674b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
675b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
676b1e6fc08SKevin Wolf  * like a backing file)
677b1e6fc08SKevin Wolf  */
678b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
679b1e6fc08SKevin Wolf {
680b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
681b1e6fc08SKevin Wolf }
682b1e6fc08SKevin Wolf 
683b1e6fc08SKevin Wolf /*
684f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if a protocol driver is expected,
685f3930ed0SKevin Wolf  * based on the given flags for the parent BDS
6860b50cc88SKevin Wolf  */
6870b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
6880b50cc88SKevin Wolf {
6890b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6900b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
6910b50cc88SKevin Wolf 
6920b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
6930b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
6940b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
6950b50cc88SKevin Wolf 
6960b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
6975669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
6980b50cc88SKevin Wolf 
6990b50cc88SKevin Wolf     return flags;
7000b50cc88SKevin Wolf }
7010b50cc88SKevin Wolf 
702f3930ed0SKevin Wolf const BdrvChildRole child_file = {
703f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_flags,
704f3930ed0SKevin Wolf };
705f3930ed0SKevin Wolf 
706f3930ed0SKevin Wolf /*
707f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if the use of formats (and not
708f3930ed0SKevin Wolf  * only protocols) is permitted for it, based on the given flags for the parent
709f3930ed0SKevin Wolf  * BDS
710f3930ed0SKevin Wolf  */
711f3930ed0SKevin Wolf static int bdrv_inherited_fmt_flags(int parent_flags)
712f3930ed0SKevin Wolf {
713f3930ed0SKevin Wolf     int flags = child_file.inherit_flags(parent_flags);
714f3930ed0SKevin Wolf     return flags & ~BDRV_O_PROTOCOL;
715f3930ed0SKevin Wolf }
716f3930ed0SKevin Wolf 
717f3930ed0SKevin Wolf const BdrvChildRole child_format = {
718f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_fmt_flags,
719f3930ed0SKevin Wolf };
720f3930ed0SKevin Wolf 
721317fc44eSKevin Wolf /*
722760e0063SKevin Wolf  * Returns the flags that bs->backing should get, based on the given flags
723317fc44eSKevin Wolf  * for the parent BDS
724317fc44eSKevin Wolf  */
725317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
726317fc44eSKevin Wolf {
727317fc44eSKevin Wolf     /* backing files always opened read-only */
728317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
729317fc44eSKevin Wolf 
730317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7318bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
732317fc44eSKevin Wolf 
733317fc44eSKevin Wolf     return flags;
734317fc44eSKevin Wolf }
735317fc44eSKevin Wolf 
736f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
737f3930ed0SKevin Wolf     .inherit_flags = bdrv_backing_flags,
738f3930ed0SKevin Wolf };
739f3930ed0SKevin Wolf 
7407b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7417b272452SKevin Wolf {
7427b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7437b272452SKevin Wolf 
7447b272452SKevin Wolf     /*
7457b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7467b272452SKevin Wolf      * image.
7477b272452SKevin Wolf      */
74820cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7497b272452SKevin Wolf 
7507b272452SKevin Wolf     /*
7517b272452SKevin Wolf      * Snapshots should be writable.
7527b272452SKevin Wolf      */
7538bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7547b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7557b272452SKevin Wolf     }
7567b272452SKevin Wolf 
7577b272452SKevin Wolf     return open_flags;
7587b272452SKevin Wolf }
7597b272452SKevin Wolf 
760636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
7616913c0c2SBenoît Canet                                   const char *node_name,
7626913c0c2SBenoît Canet                                   Error **errp)
7636913c0c2SBenoît Canet {
76415489c76SJeff Cody     char *gen_node_name = NULL;
7656913c0c2SBenoît Canet 
76615489c76SJeff Cody     if (!node_name) {
76715489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
76815489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
76915489c76SJeff Cody         /*
77015489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
77115489c76SJeff Cody          * generated (generated names use characters not available to the user)
77215489c76SJeff Cody          */
7739aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
774636ea370SKevin Wolf         return;
7756913c0c2SBenoît Canet     }
7766913c0c2SBenoît Canet 
7770c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
7787f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
7790c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
7800c5e94eeSBenoît Canet                    node_name);
78115489c76SJeff Cody         goto out;
7820c5e94eeSBenoît Canet     }
7830c5e94eeSBenoît Canet 
7846913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
7856913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
7866913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
78715489c76SJeff Cody         goto out;
7886913c0c2SBenoît Canet     }
7896913c0c2SBenoît Canet 
7906913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
7916913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
7926913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
79315489c76SJeff Cody out:
79415489c76SJeff Cody     g_free(gen_node_name);
7956913c0c2SBenoît Canet }
7966913c0c2SBenoît Canet 
79718edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
79818edf289SKevin Wolf     .name = "bdrv_common",
79918edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
80018edf289SKevin Wolf     .desc = {
80118edf289SKevin Wolf         {
80218edf289SKevin Wolf             .name = "node-name",
80318edf289SKevin Wolf             .type = QEMU_OPT_STRING,
80418edf289SKevin Wolf             .help = "Node name of the block device node",
80518edf289SKevin Wolf         },
80618edf289SKevin Wolf         { /* end of list */ }
80718edf289SKevin Wolf     },
80818edf289SKevin Wolf };
80918edf289SKevin Wolf 
810b6ce07aaSKevin Wolf /*
81157915332SKevin Wolf  * Common part for opening disk images and files
812b6ad491aSKevin Wolf  *
813b6ad491aSKevin Wolf  * Removes all processed options from *options.
81457915332SKevin Wolf  */
8159a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
81634b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
81757915332SKevin Wolf {
81857915332SKevin Wolf     int ret, open_flags;
819035fccdfSKevin Wolf     const char *filename;
8206913c0c2SBenoît Canet     const char *node_name = NULL;
82118edf289SKevin Wolf     QemuOpts *opts;
82234b5d2c6SMax Reitz     Error *local_err = NULL;
82357915332SKevin Wolf 
82457915332SKevin Wolf     assert(drv != NULL);
8256405875cSPaolo Bonzini     assert(bs->file == NULL);
826707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
82757915332SKevin Wolf 
82845673671SKevin Wolf     if (file != NULL) {
8299a4f4c31SKevin Wolf         filename = file->bs->filename;
83045673671SKevin Wolf     } else {
83145673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
83245673671SKevin Wolf     }
83345673671SKevin Wolf 
834765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
835765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
836765003dbSKevin Wolf                    drv->format_name);
837765003dbSKevin Wolf         return -EINVAL;
838765003dbSKevin Wolf     }
839765003dbSKevin Wolf 
84045673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
84128dcee10SStefan Hajnoczi 
84218edf289SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
84318edf289SKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
84418edf289SKevin Wolf     if (local_err) {
84518edf289SKevin Wolf         error_propagate(errp, local_err);
84618edf289SKevin Wolf         ret = -EINVAL;
84718edf289SKevin Wolf         goto fail_opts;
84818edf289SKevin Wolf     }
84918edf289SKevin Wolf 
85018edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
851636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8520fb6395cSMarkus Armbruster     if (local_err) {
853636ea370SKevin Wolf         error_propagate(errp, local_err);
85418edf289SKevin Wolf         ret = -EINVAL;
85518edf289SKevin Wolf         goto fail_opts;
8565d186eb0SKevin Wolf     }
8575d186eb0SKevin Wolf 
858c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8590d51b4deSAsias He     bs->zero_beyond_eof = true;
860b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
861b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
862b64ec4e4SFam Zheng 
863b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8648f94a6e4SKevin Wolf         error_setg(errp,
8658f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8668f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8678f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8688f94a6e4SKevin Wolf                    drv->format_name);
86918edf289SKevin Wolf         ret = -ENOTSUP;
87018edf289SKevin Wolf         goto fail_opts;
871b64ec4e4SFam Zheng     }
87257915332SKevin Wolf 
87353fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8740ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8750ebd24e0SKevin Wolf         if (!bs->read_only) {
87653fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8770ebd24e0SKevin Wolf         } else {
8780ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
87918edf289SKevin Wolf             ret = -EINVAL;
88018edf289SKevin Wolf             goto fail_opts;
8810ebd24e0SKevin Wolf         }
88253fec9d3SStefan Hajnoczi     }
88353fec9d3SStefan Hajnoczi 
884c2ad1b0cSKevin Wolf     if (filename != NULL) {
88557915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
886c2ad1b0cSKevin Wolf     } else {
887c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
888c2ad1b0cSKevin Wolf     }
88991af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
89057915332SKevin Wolf 
89157915332SKevin Wolf     bs->drv = drv;
8927267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
89357915332SKevin Wolf 
89403f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
895e7c63796SStefan Hajnoczi 
89666f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
89766f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8985d186eb0SKevin Wolf         assert(file == NULL);
899030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
90034b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
901f500a6d3SKevin Wolf     } else {
9022af5ef70SKevin Wolf         if (file == NULL) {
90334b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
90434b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9052af5ef70SKevin Wolf             ret = -EINVAL;
9062af5ef70SKevin Wolf             goto free_and_fail;
9072af5ef70SKevin Wolf         }
908f500a6d3SKevin Wolf         bs->file = file;
90934b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
91066f82ceeSKevin Wolf     }
91166f82ceeSKevin Wolf 
91257915332SKevin Wolf     if (ret < 0) {
91384d18f06SMarkus Armbruster         if (local_err) {
91434b5d2c6SMax Reitz             error_propagate(errp, local_err);
9152fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9162fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
91734b5d2c6SMax Reitz         } else {
91834b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
91934b5d2c6SMax Reitz         }
92057915332SKevin Wolf         goto free_and_fail;
92157915332SKevin Wolf     }
92257915332SKevin Wolf 
923a1f688f4SMarkus Armbruster     if (bs->encrypted) {
924a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
925a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
926a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
927a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
928a1f688f4SMarkus Armbruster     }
929a1f688f4SMarkus Armbruster 
93051762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
93151762288SStefan Hajnoczi     if (ret < 0) {
93234b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
93351762288SStefan Hajnoczi         goto free_and_fail;
93457915332SKevin Wolf     }
93551762288SStefan Hajnoczi 
9363baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
9373baca891SKevin Wolf     if (local_err) {
9383baca891SKevin Wolf         error_propagate(errp, local_err);
9393baca891SKevin Wolf         ret = -EINVAL;
9403baca891SKevin Wolf         goto free_and_fail;
9413baca891SKevin Wolf     }
9423baca891SKevin Wolf 
943c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9444196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
945b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
94618edf289SKevin Wolf 
94718edf289SKevin Wolf     qemu_opts_del(opts);
94857915332SKevin Wolf     return 0;
94957915332SKevin Wolf 
95057915332SKevin Wolf free_and_fail:
95166f82ceeSKevin Wolf     bs->file = NULL;
9527267c094SAnthony Liguori     g_free(bs->opaque);
95357915332SKevin Wolf     bs->opaque = NULL;
95457915332SKevin Wolf     bs->drv = NULL;
95518edf289SKevin Wolf fail_opts:
95618edf289SKevin Wolf     qemu_opts_del(opts);
95757915332SKevin Wolf     return ret;
95857915332SKevin Wolf }
95957915332SKevin Wolf 
9605e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9615e5c4f63SKevin Wolf {
9625e5c4f63SKevin Wolf     QObject *options_obj;
9635e5c4f63SKevin Wolf     QDict *options;
9645e5c4f63SKevin Wolf     int ret;
9655e5c4f63SKevin Wolf 
9665e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
9675e5c4f63SKevin Wolf     assert(ret);
9685e5c4f63SKevin Wolf 
9695e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
9705e5c4f63SKevin Wolf     if (!options_obj) {
9715e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
9725e5c4f63SKevin Wolf         return NULL;
9735e5c4f63SKevin Wolf     }
9745e5c4f63SKevin Wolf 
9755e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
9765e5c4f63SKevin Wolf         qobject_decref(options_obj);
9775e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
9785e5c4f63SKevin Wolf         return NULL;
9795e5c4f63SKevin Wolf     }
9805e5c4f63SKevin Wolf 
9815e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
9825e5c4f63SKevin Wolf     qdict_flatten(options);
9835e5c4f63SKevin Wolf 
9845e5c4f63SKevin Wolf     return options;
9855e5c4f63SKevin Wolf }
9865e5c4f63SKevin Wolf 
98757915332SKevin Wolf /*
988f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
989f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
99053a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
99153a29513SMax Reitz  * block driver has been specified explicitly.
992f54120ffSKevin Wolf  */
99353a29513SMax Reitz static int bdrv_fill_options(QDict **options, const char **pfilename,
994053e1578SMax Reitz                              int *flags, Error **errp)
995f54120ffSKevin Wolf {
9965e5c4f63SKevin Wolf     const char *filename = *pfilename;
997f54120ffSKevin Wolf     const char *drvname;
99853a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
999f54120ffSKevin Wolf     bool parse_filename = false;
1000053e1578SMax Reitz     BlockDriver *drv = NULL;
1001f54120ffSKevin Wolf     Error *local_err = NULL;
1002f54120ffSKevin Wolf 
10035e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10045e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10055e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10065e5c4f63SKevin Wolf         if (local_err) {
10075e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10085e5c4f63SKevin Wolf             return -EINVAL;
10095e5c4f63SKevin Wolf         }
10105e5c4f63SKevin Wolf 
10115e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10125e5c4f63SKevin Wolf          * specified directly */
10135e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10145e5c4f63SKevin Wolf         QDECREF(json_options);
10155e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10165e5c4f63SKevin Wolf     }
10175e5c4f63SKevin Wolf 
101853a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1019053e1578SMax Reitz     if (drvname) {
1020053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1021053e1578SMax Reitz         if (!drv) {
1022053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1023053e1578SMax Reitz             return -ENOENT;
1024053e1578SMax Reitz         }
102553a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
102653a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1027053e1578SMax Reitz         protocol = drv->bdrv_file_open;
102853a29513SMax Reitz     }
102953a29513SMax Reitz 
103053a29513SMax Reitz     if (protocol) {
103153a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
103253a29513SMax Reitz     } else {
103353a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
103453a29513SMax Reitz     }
103553a29513SMax Reitz 
1036f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
103717b005f1SKevin Wolf     if (protocol && filename) {
1038f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1039f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1040f54120ffSKevin Wolf             parse_filename = true;
1041f54120ffSKevin Wolf         } else {
1042f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1043f54120ffSKevin Wolf                              "the same time");
1044f54120ffSKevin Wolf             return -EINVAL;
1045f54120ffSKevin Wolf         }
1046f54120ffSKevin Wolf     }
1047f54120ffSKevin Wolf 
1048f54120ffSKevin Wolf     /* Find the right block driver */
1049f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1050f54120ffSKevin Wolf 
105117b005f1SKevin Wolf     if (!drvname && protocol) {
1052f54120ffSKevin Wolf         if (filename) {
1053b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1054f54120ffSKevin Wolf             if (!drv) {
1055f54120ffSKevin Wolf                 return -EINVAL;
1056f54120ffSKevin Wolf             }
1057f54120ffSKevin Wolf 
1058f54120ffSKevin Wolf             drvname = drv->format_name;
1059f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1060f54120ffSKevin Wolf         } else {
1061f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1062f54120ffSKevin Wolf             return -EINVAL;
1063f54120ffSKevin Wolf         }
106417b005f1SKevin Wolf     }
106517b005f1SKevin Wolf 
106617b005f1SKevin Wolf     assert(drv || !protocol);
1067f54120ffSKevin Wolf 
1068f54120ffSKevin Wolf     /* Driver-specific filename parsing */
106917b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1070f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1071f54120ffSKevin Wolf         if (local_err) {
1072f54120ffSKevin Wolf             error_propagate(errp, local_err);
1073f54120ffSKevin Wolf             return -EINVAL;
1074f54120ffSKevin Wolf         }
1075f54120ffSKevin Wolf 
1076f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1077f54120ffSKevin Wolf             qdict_del(*options, "filename");
1078f54120ffSKevin Wolf         }
1079f54120ffSKevin Wolf     }
1080f54120ffSKevin Wolf 
1081d44f928aSMax Reitz     if (runstate_check(RUN_STATE_INMIGRATE)) {
1082d44f928aSMax Reitz         *flags |= BDRV_O_INCOMING;
1083d44f928aSMax Reitz     }
1084d44f928aSMax Reitz 
1085f54120ffSKevin Wolf     return 0;
1086f54120ffSKevin Wolf }
1087f54120ffSKevin Wolf 
1088b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1089df581792SKevin Wolf                                     BlockDriverState *child_bs,
1090df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1091df581792SKevin Wolf {
1092df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1093df581792SKevin Wolf     *child = (BdrvChild) {
1094df581792SKevin Wolf         .bs     = child_bs,
1095df581792SKevin Wolf         .role   = child_role,
1096df581792SKevin Wolf     };
1097df581792SKevin Wolf 
1098df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1099d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1100b4b059f6SKevin Wolf 
1101b4b059f6SKevin Wolf     return child;
1102df581792SKevin Wolf }
1103df581792SKevin Wolf 
11043f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
110533a60407SKevin Wolf {
110633a60407SKevin Wolf     QLIST_REMOVE(child, next);
1107d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
110833a60407SKevin Wolf     g_free(child);
110933a60407SKevin Wolf }
111033a60407SKevin Wolf 
111133a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
111233a60407SKevin Wolf {
1113779020cbSKevin Wolf     BlockDriverState *child_bs;
1114779020cbSKevin Wolf 
1115779020cbSKevin Wolf     if (child == NULL) {
1116779020cbSKevin Wolf         return;
1117779020cbSKevin Wolf     }
111833a60407SKevin Wolf 
111933a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
112033a60407SKevin Wolf         child->bs->inherits_from = NULL;
112133a60407SKevin Wolf     }
112233a60407SKevin Wolf 
1123779020cbSKevin Wolf     child_bs = child->bs;
112433a60407SKevin Wolf     bdrv_detach_child(child);
112533a60407SKevin Wolf     bdrv_unref(child_bs);
112633a60407SKevin Wolf }
112733a60407SKevin Wolf 
11285db15a57SKevin Wolf /*
11295db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
11305db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
11315db15a57SKevin Wolf  */
11328d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11338d24cce1SFam Zheng {
11345db15a57SKevin Wolf     if (backing_hd) {
11355db15a57SKevin Wolf         bdrv_ref(backing_hd);
11365db15a57SKevin Wolf     }
11378d24cce1SFam Zheng 
1138760e0063SKevin Wolf     if (bs->backing) {
1139826b6ca0SFam Zheng         assert(bs->backing_blocker);
1140760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
11415db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1142826b6ca0SFam Zheng     } else if (backing_hd) {
1143826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
114481e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
114581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1146826b6ca0SFam Zheng     }
1147826b6ca0SFam Zheng 
11488d24cce1SFam Zheng     if (!backing_hd) {
1149826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1150826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1151760e0063SKevin Wolf         bs->backing = NULL;
11528d24cce1SFam Zheng         goto out;
11538d24cce1SFam Zheng     }
1154760e0063SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, &child_backing);
11558d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11568d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11578d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11588d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1159826b6ca0SFam Zheng 
1160760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1161826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1162760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1163826b6ca0SFam Zheng                     bs->backing_blocker);
11648d24cce1SFam Zheng out:
11653baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11668d24cce1SFam Zheng }
11678d24cce1SFam Zheng 
116831ca6d07SKevin Wolf /*
116931ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
117031ca6d07SKevin Wolf  *
117131ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
117231ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
117331ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
117431ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
117531ca6d07SKevin Wolf  */
117634b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11779156df12SPaolo Bonzini {
11781ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1179317fc44eSKevin Wolf     int ret = 0;
11808d24cce1SFam Zheng     BlockDriverState *backing_hd;
118134b5d2c6SMax Reitz     Error *local_err = NULL;
11829156df12SPaolo Bonzini 
1183760e0063SKevin Wolf     if (bs->backing != NULL) {
118431ca6d07SKevin Wolf         QDECREF(options);
11851ba4b6a5SBenoît Canet         goto free_exit;
11869156df12SPaolo Bonzini     }
11879156df12SPaolo Bonzini 
118831ca6d07SKevin Wolf     /* NULL means an empty set of options */
118931ca6d07SKevin Wolf     if (options == NULL) {
119031ca6d07SKevin Wolf         options = qdict_new();
119131ca6d07SKevin Wolf     }
119231ca6d07SKevin Wolf 
11939156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11941cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11951cb6f506SKevin Wolf         backing_filename[0] = '\0';
11961cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
119731ca6d07SKevin Wolf         QDECREF(options);
11981ba4b6a5SBenoît Canet         goto free_exit;
1199dbecebddSFam Zheng     } else {
12009f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
12019f07429eSMax Reitz                                        &local_err);
12029f07429eSMax Reitz         if (local_err) {
12039f07429eSMax Reitz             ret = -EINVAL;
12049f07429eSMax Reitz             error_propagate(errp, local_err);
12059f07429eSMax Reitz             QDECREF(options);
12069f07429eSMax Reitz             goto free_exit;
12079f07429eSMax Reitz         }
12089156df12SPaolo Bonzini     }
12099156df12SPaolo Bonzini 
12108ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12118ee79e70SKevin Wolf         ret = -EINVAL;
12128ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12138ee79e70SKevin Wolf         QDECREF(options);
12148ee79e70SKevin Wolf         goto free_exit;
12158ee79e70SKevin Wolf     }
12168ee79e70SKevin Wolf 
1217e4e9986bSMarkus Armbruster     backing_hd = bdrv_new();
12188d24cce1SFam Zheng 
1219c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1220c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
12219156df12SPaolo Bonzini     }
12229156df12SPaolo Bonzini 
1223760e0063SKevin Wolf     assert(bs->backing == NULL);
1224f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1225f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1226ce343771SMax Reitz                             NULL, options, 0, bs, &child_backing, &local_err);
12279156df12SPaolo Bonzini     if (ret < 0) {
12288d24cce1SFam Zheng         bdrv_unref(backing_hd);
12298d24cce1SFam Zheng         backing_hd = NULL;
12309156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1231b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1232b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1233b04b6b6eSFam Zheng         error_free(local_err);
12341ba4b6a5SBenoît Canet         goto free_exit;
12359156df12SPaolo Bonzini     }
1236df581792SKevin Wolf 
12375db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
12385db15a57SKevin Wolf      * backing_hd reference now */
12398d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
12405db15a57SKevin Wolf     bdrv_unref(backing_hd);
1241d80ac658SPeter Feiner 
12421ba4b6a5SBenoît Canet free_exit:
12431ba4b6a5SBenoît Canet     g_free(backing_filename);
12441ba4b6a5SBenoît Canet     return ret;
12459156df12SPaolo Bonzini }
12469156df12SPaolo Bonzini 
1247b6ce07aaSKevin Wolf /*
1248da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1249da557aacSMax Reitz  * device's options.
1250da557aacSMax Reitz  *
1251da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1252b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1253da557aacSMax Reitz  *
1254da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1255da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1256da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1257da557aacSMax Reitz  * BlockdevRef.
1258da557aacSMax Reitz  *
1259da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1260da557aacSMax Reitz  */
1261b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1262f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1263b4b059f6SKevin Wolf                            BlockDriverState* parent,
1264b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1265f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1266da557aacSMax Reitz {
1267b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1268b4b059f6SKevin Wolf     BlockDriverState *bs;
1269da557aacSMax Reitz     QDict *image_options;
1270da557aacSMax Reitz     int ret;
1271da557aacSMax Reitz     char *bdref_key_dot;
1272da557aacSMax Reitz     const char *reference;
1273da557aacSMax Reitz 
1274df581792SKevin Wolf     assert(child_role != NULL);
1275f67503e5SMax Reitz 
1276da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1277da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1278da557aacSMax Reitz     g_free(bdref_key_dot);
1279da557aacSMax Reitz 
1280da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1281da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1282b4b059f6SKevin Wolf         if (!allow_none) {
1283da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1284da557aacSMax Reitz                        bdref_key);
1285da557aacSMax Reitz         }
1286b20e61e0SMarkus Armbruster         QDECREF(image_options);
1287da557aacSMax Reitz         goto done;
1288da557aacSMax Reitz     }
1289da557aacSMax Reitz 
1290b4b059f6SKevin Wolf     bs = NULL;
1291b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1292ce343771SMax Reitz                             parent, child_role, errp);
1293df581792SKevin Wolf     if (ret < 0) {
1294df581792SKevin Wolf         goto done;
1295df581792SKevin Wolf     }
1296df581792SKevin Wolf 
1297b4b059f6SKevin Wolf     c = bdrv_attach_child(parent, bs, child_role);
1298da557aacSMax Reitz 
1299da557aacSMax Reitz done:
1300da557aacSMax Reitz     qdict_del(options, bdref_key);
1301b4b059f6SKevin Wolf     return c;
1302b4b059f6SKevin Wolf }
1303b4b059f6SKevin Wolf 
13046b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1305b998875dSKevin Wolf {
1306b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
13071ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1308b998875dSKevin Wolf     int64_t total_size;
130983d0521aSChunyan Liu     QemuOpts *opts = NULL;
1310b998875dSKevin Wolf     QDict *snapshot_options;
1311b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1312c2e0dbbfSFam Zheng     Error *local_err = NULL;
1313b998875dSKevin Wolf     int ret;
1314b998875dSKevin Wolf 
1315b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1316b998875dSKevin Wolf        instead of opening 'filename' directly */
1317b998875dSKevin Wolf 
1318b998875dSKevin Wolf     /* Get the required size from the image */
1319f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1320f187743aSKevin Wolf     if (total_size < 0) {
13216b8aeca5SChen Gang         ret = total_size;
1322f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13231ba4b6a5SBenoît Canet         goto out;
1324f187743aSKevin Wolf     }
1325b998875dSKevin Wolf 
1326b998875dSKevin Wolf     /* Create the temporary image */
13271ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1328b998875dSKevin Wolf     if (ret < 0) {
1329b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13301ba4b6a5SBenoît Canet         goto out;
1331b998875dSKevin Wolf     }
1332b998875dSKevin Wolf 
1333ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1334c282e1fdSChunyan Liu                             &error_abort);
133539101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1336ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
133783d0521aSChunyan Liu     qemu_opts_del(opts);
1338b998875dSKevin Wolf     if (ret < 0) {
1339b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1340b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1341b998875dSKevin Wolf                          error_get_pretty(local_err));
1342b998875dSKevin Wolf         error_free(local_err);
13431ba4b6a5SBenoît Canet         goto out;
1344b998875dSKevin Wolf     }
1345b998875dSKevin Wolf 
1346b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1347b998875dSKevin Wolf     snapshot_options = qdict_new();
1348b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1349b998875dSKevin Wolf               qstring_from_str("file"));
1350b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1351b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1352e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1353e6641719SMax Reitz               qstring_from_str("qcow2"));
1354b998875dSKevin Wolf 
1355e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1356b998875dSKevin Wolf 
1357b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
13586ebf9aa2SMax Reitz                     flags, &local_err);
1359b998875dSKevin Wolf     if (ret < 0) {
1360b998875dSKevin Wolf         error_propagate(errp, local_err);
13611ba4b6a5SBenoît Canet         goto out;
1362b998875dSKevin Wolf     }
1363b998875dSKevin Wolf 
1364b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
13651ba4b6a5SBenoît Canet 
13661ba4b6a5SBenoît Canet out:
13671ba4b6a5SBenoît Canet     g_free(tmp_filename);
13686b8aeca5SChen Gang     return ret;
1369b998875dSKevin Wolf }
1370b998875dSKevin Wolf 
1371da557aacSMax Reitz /*
1372b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1373de9c0cecSKevin Wolf  *
1374de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1375de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1376de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1377de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1378f67503e5SMax Reitz  *
1379f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1380f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1381ddf5636dSMax Reitz  *
1382ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1383ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1384ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1385b6ce07aaSKevin Wolf  */
1386f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1387ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1388f3930ed0SKevin Wolf                              BlockDriverState *parent,
1389ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1390ea2384d3Sbellard {
1391b6ce07aaSKevin Wolf     int ret;
13929a4f4c31SKevin Wolf     BdrvChild *file = NULL;
13939a4f4c31SKevin Wolf     BlockDriverState *bs;
1394ce343771SMax Reitz     BlockDriver *drv = NULL;
139574fe54f2SKevin Wolf     const char *drvname;
1396*3e8c2e57SAlberto Garcia     const char *backing;
139734b5d2c6SMax Reitz     Error *local_err = NULL;
1398b1e6fc08SKevin Wolf     int snapshot_flags = 0;
139933e3963eSbellard 
1400f67503e5SMax Reitz     assert(pbs);
1401f3930ed0SKevin Wolf     assert(!child_role || !flags);
1402f3930ed0SKevin Wolf     assert(!child_role == !parent);
1403f67503e5SMax Reitz 
1404ddf5636dSMax Reitz     if (reference) {
1405ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1406ddf5636dSMax Reitz         QDECREF(options);
1407ddf5636dSMax Reitz 
1408ddf5636dSMax Reitz         if (*pbs) {
1409ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1410ddf5636dSMax Reitz                        "another block device");
1411ddf5636dSMax Reitz             return -EINVAL;
1412ddf5636dSMax Reitz         }
1413ddf5636dSMax Reitz 
1414ddf5636dSMax Reitz         if (filename || options_non_empty) {
1415ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1416ddf5636dSMax Reitz                        "additional options or a new filename");
1417ddf5636dSMax Reitz             return -EINVAL;
1418ddf5636dSMax Reitz         }
1419ddf5636dSMax Reitz 
1420ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1421ddf5636dSMax Reitz         if (!bs) {
1422ddf5636dSMax Reitz             return -ENODEV;
1423ddf5636dSMax Reitz         }
1424ddf5636dSMax Reitz         bdrv_ref(bs);
1425ddf5636dSMax Reitz         *pbs = bs;
1426ddf5636dSMax Reitz         return 0;
1427ddf5636dSMax Reitz     }
1428ddf5636dSMax Reitz 
1429f67503e5SMax Reitz     if (*pbs) {
1430f67503e5SMax Reitz         bs = *pbs;
1431f67503e5SMax Reitz     } else {
1432e4e9986bSMarkus Armbruster         bs = bdrv_new();
1433f67503e5SMax Reitz     }
1434f67503e5SMax Reitz 
1435de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1436de9c0cecSKevin Wolf     if (options == NULL) {
1437de9c0cecSKevin Wolf         options = qdict_new();
1438de9c0cecSKevin Wolf     }
1439de9c0cecSKevin Wolf 
1440f3930ed0SKevin Wolf     if (child_role) {
1441bddcec37SKevin Wolf         bs->inherits_from = parent;
1442f3930ed0SKevin Wolf         flags = child_role->inherit_flags(parent->open_flags);
1443f3930ed0SKevin Wolf     }
1444f3930ed0SKevin Wolf 
1445053e1578SMax Reitz     ret = bdrv_fill_options(&options, &filename, &flags, &local_err);
1446462f5bcfSKevin Wolf     if (local_err) {
1447462f5bcfSKevin Wolf         goto fail;
1448462f5bcfSKevin Wolf     }
1449462f5bcfSKevin Wolf 
145076c591b0SKevin Wolf     /* Find the right image format driver */
145176c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
145276c591b0SKevin Wolf     if (drvname) {
145376c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
145476c591b0SKevin Wolf         qdict_del(options, "driver");
145576c591b0SKevin Wolf         if (!drv) {
145676c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
145776c591b0SKevin Wolf             ret = -EINVAL;
145876c591b0SKevin Wolf             goto fail;
145976c591b0SKevin Wolf         }
146076c591b0SKevin Wolf     }
146176c591b0SKevin Wolf 
146276c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
146376c591b0SKevin Wolf 
1464*3e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
1465*3e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
1466*3e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
1467*3e8c2e57SAlberto Garcia         qdict_del(options, "backing");
1468*3e8c2e57SAlberto Garcia     }
1469*3e8c2e57SAlberto Garcia 
1470f3930ed0SKevin Wolf     bs->open_flags = flags;
1471de9c0cecSKevin Wolf     bs->options = options;
1472b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1473de9c0cecSKevin Wolf 
1474f500a6d3SKevin Wolf     /* Open image file without format layer */
1475f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1476be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1477be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1478be028adcSJeff Cody         }
1479b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1480b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1481b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1482b1e6fc08SKevin Wolf         }
1483be028adcSJeff Cody 
1484f3930ed0SKevin Wolf         bs->open_flags = flags;
14851fdd6933SKevin Wolf 
14869a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
14871fdd6933SKevin Wolf                                &child_file, true, &local_err);
14881fdd6933SKevin Wolf         if (local_err) {
14891fdd6933SKevin Wolf             ret = -EINVAL;
14908bfea15dSKevin Wolf             goto fail;
1491f500a6d3SKevin Wolf         }
1492f4788adcSKevin Wolf     }
1493f500a6d3SKevin Wolf 
149476c591b0SKevin Wolf     /* Image format probing */
149538f3ef57SKevin Wolf     bs->probed = !drv;
149676c591b0SKevin Wolf     if (!drv && file) {
14979a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
149817b005f1SKevin Wolf         if (ret < 0) {
149917b005f1SKevin Wolf             goto fail;
150017b005f1SKevin Wolf         }
150176c591b0SKevin Wolf     } else if (!drv) {
15022a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
15032a05cbe4SMax Reitz         ret = -EINVAL;
15048bfea15dSKevin Wolf         goto fail;
15052a05cbe4SMax Reitz     }
1506f500a6d3SKevin Wolf 
150753a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
150853a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
150953a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
151053a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
151153a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
151253a29513SMax Reitz 
1513b6ce07aaSKevin Wolf     /* Open the image */
151434b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1515b6ce07aaSKevin Wolf     if (ret < 0) {
15168bfea15dSKevin Wolf         goto fail;
15176987307cSChristoph Hellwig     }
15186987307cSChristoph Hellwig 
15192a05cbe4SMax Reitz     if (file && (bs->file != file)) {
15209a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1521f500a6d3SKevin Wolf         file = NULL;
1522f500a6d3SKevin Wolf     }
1523f500a6d3SKevin Wolf 
1524b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
15259156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
152631ca6d07SKevin Wolf         QDict *backing_options;
152731ca6d07SKevin Wolf 
15285726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
152934b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1530b6ce07aaSKevin Wolf         if (ret < 0) {
1531b6ad491aSKevin Wolf             goto close_and_fail;
1532b6ce07aaSKevin Wolf         }
1533b6ce07aaSKevin Wolf     }
1534b6ce07aaSKevin Wolf 
153591af7014SMax Reitz     bdrv_refresh_filename(bs);
153691af7014SMax Reitz 
1537b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15385acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1539b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15405acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15415acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15425acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15435acd9d81SMax Reitz         } else {
154434b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15455acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1546bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
15475acd9d81SMax Reitz         }
1548b6ad491aSKevin Wolf 
1549b6ad491aSKevin Wolf         ret = -EINVAL;
1550b6ad491aSKevin Wolf         goto close_and_fail;
1551b6ad491aSKevin Wolf     }
1552b6ad491aSKevin Wolf 
1553b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1554a7f53e26SMarkus Armbruster         if (bs->blk) {
1555a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1556a7f53e26SMarkus Armbruster         }
1557c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1558c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1559c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1560c3adb58fSMarkus Armbruster         error_setg(errp,
1561c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1562c3adb58fSMarkus Armbruster         ret = -EBUSY;
1563c3adb58fSMarkus Armbruster         goto close_and_fail;
1564b6ce07aaSKevin Wolf     }
1565b6ce07aaSKevin Wolf 
1566c3adb58fSMarkus Armbruster     QDECREF(options);
1567f67503e5SMax Reitz     *pbs = bs;
1568dd62f1caSKevin Wolf 
1569dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1570dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1571dd62f1caSKevin Wolf     if (snapshot_flags) {
1572dd62f1caSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1573dd62f1caSKevin Wolf         if (local_err) {
1574dd62f1caSKevin Wolf             goto close_and_fail;
1575dd62f1caSKevin Wolf         }
1576dd62f1caSKevin Wolf     }
1577dd62f1caSKevin Wolf 
1578b6ce07aaSKevin Wolf     return 0;
1579b6ce07aaSKevin Wolf 
15808bfea15dSKevin Wolf fail:
1581f500a6d3SKevin Wolf     if (file != NULL) {
15829a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1583f500a6d3SKevin Wolf     }
1584de9c0cecSKevin Wolf     QDECREF(bs->options);
1585b6ad491aSKevin Wolf     QDECREF(options);
1586de9c0cecSKevin Wolf     bs->options = NULL;
1587f67503e5SMax Reitz     if (!*pbs) {
1588f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1589f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1590f67503e5SMax Reitz            since it has not really been opened yet. */
1591f67503e5SMax Reitz         bdrv_unref(bs);
1592f67503e5SMax Reitz     }
159384d18f06SMarkus Armbruster     if (local_err) {
159434b5d2c6SMax Reitz         error_propagate(errp, local_err);
159534b5d2c6SMax Reitz     }
1596b6ad491aSKevin Wolf     return ret;
1597de9c0cecSKevin Wolf 
1598b6ad491aSKevin Wolf close_and_fail:
1599f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1600f67503e5SMax Reitz     if (*pbs) {
1601b6ad491aSKevin Wolf         bdrv_close(bs);
1602f67503e5SMax Reitz     } else {
1603f67503e5SMax Reitz         bdrv_unref(bs);
1604f67503e5SMax Reitz     }
1605b6ad491aSKevin Wolf     QDECREF(options);
160684d18f06SMarkus Armbruster     if (local_err) {
160734b5d2c6SMax Reitz         error_propagate(errp, local_err);
160834b5d2c6SMax Reitz     }
1609b6ce07aaSKevin Wolf     return ret;
1610b6ce07aaSKevin Wolf }
1611b6ce07aaSKevin Wolf 
1612f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
16136ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1614f3930ed0SKevin Wolf {
1615f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1616ce343771SMax Reitz                              NULL, errp);
1617f3930ed0SKevin Wolf }
1618f3930ed0SKevin Wolf 
1619e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1620e971aa12SJeff Cody      bool prepared;
1621e971aa12SJeff Cody      BDRVReopenState state;
1622e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1623e971aa12SJeff Cody } BlockReopenQueueEntry;
1624e971aa12SJeff Cody 
1625e971aa12SJeff Cody /*
1626e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1627e971aa12SJeff Cody  * reopen of multiple devices.
1628e971aa12SJeff Cody  *
1629e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1630e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1631e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1632e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1633e971aa12SJeff Cody  * atomic 'set'.
1634e971aa12SJeff Cody  *
1635e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1636e971aa12SJeff Cody  *
16374d2cb092SKevin Wolf  * options contains the changed options for the associated bs
16384d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
16394d2cb092SKevin Wolf  *
1640e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1641e971aa12SJeff Cody  *
1642e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1643e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1644e971aa12SJeff Cody  *
1645e971aa12SJeff Cody  */
1646e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
16474d2cb092SKevin Wolf                                     BlockDriverState *bs,
16484d2cb092SKevin Wolf                                     QDict *options, int flags)
1649e971aa12SJeff Cody {
1650e971aa12SJeff Cody     assert(bs != NULL);
1651e971aa12SJeff Cody 
1652e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
165367251a31SKevin Wolf     BdrvChild *child;
16544d2cb092SKevin Wolf     QDict *old_options;
165567251a31SKevin Wolf 
1656e971aa12SJeff Cody     if (bs_queue == NULL) {
1657e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1658e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1659e971aa12SJeff Cody     }
1660e971aa12SJeff Cody 
16614d2cb092SKevin Wolf     if (!options) {
16624d2cb092SKevin Wolf         options = qdict_new();
16634d2cb092SKevin Wolf     }
16644d2cb092SKevin Wolf 
16654d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
16664d2cb092SKevin Wolf     qdict_join(options, old_options, false);
16674d2cb092SKevin Wolf     QDECREF(old_options);
16684d2cb092SKevin Wolf 
1669f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1670f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1671f1f25a2eSKevin Wolf 
167267251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
167367251a31SKevin Wolf         int child_flags;
167467251a31SKevin Wolf 
167567251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
167667251a31SKevin Wolf             continue;
167767251a31SKevin Wolf         }
167867251a31SKevin Wolf 
167967251a31SKevin Wolf         child_flags = child->role->inherit_flags(flags);
16804d2cb092SKevin Wolf         /* TODO Pass down child flags (backing.*, extents.*, ...) */
16814d2cb092SKevin Wolf         bdrv_reopen_queue(bs_queue, child->bs, NULL, child_flags);
1682e971aa12SJeff Cody     }
1683e971aa12SJeff Cody 
1684e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1685e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1686e971aa12SJeff Cody 
1687e971aa12SJeff Cody     bs_entry->state.bs = bs;
16884d2cb092SKevin Wolf     bs_entry->state.options = options;
1689e971aa12SJeff Cody     bs_entry->state.flags = flags;
1690e971aa12SJeff Cody 
1691e971aa12SJeff Cody     return bs_queue;
1692e971aa12SJeff Cody }
1693e971aa12SJeff Cody 
1694e971aa12SJeff Cody /*
1695e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1696e971aa12SJeff Cody  *
1697e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1698e971aa12SJeff Cody  * via bdrv_reopen_queue().
1699e971aa12SJeff Cody  *
1700e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1701e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1702e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1703e971aa12SJeff Cody  * data cleaned up.
1704e971aa12SJeff Cody  *
1705e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1706e971aa12SJeff Cody  * to all devices.
1707e971aa12SJeff Cody  *
1708e971aa12SJeff Cody  */
1709e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1710e971aa12SJeff Cody {
1711e971aa12SJeff Cody     int ret = -1;
1712e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1713e971aa12SJeff Cody     Error *local_err = NULL;
1714e971aa12SJeff Cody 
1715e971aa12SJeff Cody     assert(bs_queue != NULL);
1716e971aa12SJeff Cody 
1717e971aa12SJeff Cody     bdrv_drain_all();
1718e971aa12SJeff Cody 
1719e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1720e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1721e971aa12SJeff Cody             error_propagate(errp, local_err);
1722e971aa12SJeff Cody             goto cleanup;
1723e971aa12SJeff Cody         }
1724e971aa12SJeff Cody         bs_entry->prepared = true;
1725e971aa12SJeff Cody     }
1726e971aa12SJeff Cody 
1727e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1728e971aa12SJeff Cody      * changes
1729e971aa12SJeff Cody      */
1730e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1731e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1732e971aa12SJeff Cody     }
1733e971aa12SJeff Cody 
1734e971aa12SJeff Cody     ret = 0;
1735e971aa12SJeff Cody 
1736e971aa12SJeff Cody cleanup:
1737e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1738e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1739e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1740e971aa12SJeff Cody         }
17414d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1742e971aa12SJeff Cody         g_free(bs_entry);
1743e971aa12SJeff Cody     }
1744e971aa12SJeff Cody     g_free(bs_queue);
1745e971aa12SJeff Cody     return ret;
1746e971aa12SJeff Cody }
1747e971aa12SJeff Cody 
1748e971aa12SJeff Cody 
1749e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1750e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1751e971aa12SJeff Cody {
1752e971aa12SJeff Cody     int ret = -1;
1753e971aa12SJeff Cody     Error *local_err = NULL;
17544d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1755e971aa12SJeff Cody 
1756e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1757e971aa12SJeff Cody     if (local_err != NULL) {
1758e971aa12SJeff Cody         error_propagate(errp, local_err);
1759e971aa12SJeff Cody     }
1760e971aa12SJeff Cody     return ret;
1761e971aa12SJeff Cody }
1762e971aa12SJeff Cody 
1763e971aa12SJeff Cody 
1764e971aa12SJeff Cody /*
1765e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1766e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1767e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1768e971aa12SJeff Cody  *
1769e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1770e971aa12SJeff Cody  * flags are the new open flags
1771e971aa12SJeff Cody  * queue is the reopen queue
1772e971aa12SJeff Cody  *
1773e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1774e971aa12SJeff Cody  * as well.
1775e971aa12SJeff Cody  *
1776e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1777e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1778e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1779e971aa12SJeff Cody  *
1780e971aa12SJeff Cody  */
1781e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1782e971aa12SJeff Cody                         Error **errp)
1783e971aa12SJeff Cody {
1784e971aa12SJeff Cody     int ret = -1;
1785e971aa12SJeff Cody     Error *local_err = NULL;
1786e971aa12SJeff Cody     BlockDriver *drv;
1787e971aa12SJeff Cody 
1788e971aa12SJeff Cody     assert(reopen_state != NULL);
1789e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1790e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1791e971aa12SJeff Cody 
1792e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1793e971aa12SJeff Cody      * to r/w */
1794e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1795e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
179681e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
179781e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1798e971aa12SJeff Cody         goto error;
1799e971aa12SJeff Cody     }
1800e971aa12SJeff Cody 
1801e971aa12SJeff Cody 
1802e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1803e971aa12SJeff Cody     if (ret) {
1804e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1805e971aa12SJeff Cody                   strerror(-ret));
1806e971aa12SJeff Cody         goto error;
1807e971aa12SJeff Cody     }
1808e971aa12SJeff Cody 
1809e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1810e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1811e971aa12SJeff Cody         if (ret) {
1812e971aa12SJeff Cody             if (local_err != NULL) {
1813e971aa12SJeff Cody                 error_propagate(errp, local_err);
1814e971aa12SJeff Cody             } else {
1815d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1816e971aa12SJeff Cody                            reopen_state->bs->filename);
1817e971aa12SJeff Cody             }
1818e971aa12SJeff Cody             goto error;
1819e971aa12SJeff Cody         }
1820e971aa12SJeff Cody     } else {
1821e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1822e971aa12SJeff Cody          * handler for each supported drv. */
182381e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
182481e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
182581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1826e971aa12SJeff Cody         ret = -1;
1827e971aa12SJeff Cody         goto error;
1828e971aa12SJeff Cody     }
1829e971aa12SJeff Cody 
18304d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
18314d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
18324d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
18334d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
18344d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
18354d2cb092SKevin Wolf 
18364d2cb092SKevin Wolf         do {
18374d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
18384d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
18394d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
18404d2cb092SKevin Wolf                                                 entry->key);
18414d2cb092SKevin Wolf 
18424d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
18434d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
18444d2cb092SKevin Wolf                 ret = -EINVAL;
18454d2cb092SKevin Wolf                 goto error;
18464d2cb092SKevin Wolf             }
18474d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
18484d2cb092SKevin Wolf     }
18494d2cb092SKevin Wolf 
1850e971aa12SJeff Cody     ret = 0;
1851e971aa12SJeff Cody 
1852e971aa12SJeff Cody error:
1853e971aa12SJeff Cody     return ret;
1854e971aa12SJeff Cody }
1855e971aa12SJeff Cody 
1856e971aa12SJeff Cody /*
1857e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1858e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1859e971aa12SJeff Cody  * the active BlockDriverState contents.
1860e971aa12SJeff Cody  */
1861e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1862e971aa12SJeff Cody {
1863e971aa12SJeff Cody     BlockDriver *drv;
1864e971aa12SJeff Cody 
1865e971aa12SJeff Cody     assert(reopen_state != NULL);
1866e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1867e971aa12SJeff Cody     assert(drv != NULL);
1868e971aa12SJeff Cody 
1869e971aa12SJeff Cody     /* If there are any driver level actions to take */
1870e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1871e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1872e971aa12SJeff Cody     }
1873e971aa12SJeff Cody 
1874e971aa12SJeff Cody     /* set BDS specific flags now */
1875e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1876e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1877e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1878e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1879355ef4acSKevin Wolf 
18803baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1881e971aa12SJeff Cody }
1882e971aa12SJeff Cody 
1883e971aa12SJeff Cody /*
1884e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1885e971aa12SJeff Cody  * reopen_state
1886e971aa12SJeff Cody  */
1887e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1888e971aa12SJeff Cody {
1889e971aa12SJeff Cody     BlockDriver *drv;
1890e971aa12SJeff Cody 
1891e971aa12SJeff Cody     assert(reopen_state != NULL);
1892e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1893e971aa12SJeff Cody     assert(drv != NULL);
1894e971aa12SJeff Cody 
1895e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1896e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1897e971aa12SJeff Cody     }
1898e971aa12SJeff Cody }
1899e971aa12SJeff Cody 
1900e971aa12SJeff Cody 
1901fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1902fc01f7e7Sbellard {
190333384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
190433384421SMax Reitz 
19053e914655SPaolo Bonzini     if (bs->job) {
19063e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
19073e914655SPaolo Bonzini     }
190899b7e775SAlberto Garcia 
190999b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
191099b7e775SAlberto Garcia     if (bs->io_limits_enabled) {
191199b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
191299b7e775SAlberto Garcia     }
191399b7e775SAlberto Garcia 
191453ec73e2SFam Zheng     bdrv_drain(bs); /* complete I/O */
191558fda173SStefan Hajnoczi     bdrv_flush(bs);
191653ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
1917d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
19187094f12fSKevin Wolf 
1919b4d02820SMax Reitz     if (bs->blk) {
1920b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
1921b4d02820SMax Reitz     }
1922b4d02820SMax Reitz 
19233cbc002cSPaolo Bonzini     if (bs->drv) {
19246e93e7c4SKevin Wolf         BdrvChild *child, *next;
19256e93e7c4SKevin Wolf 
19269a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
19279a4f4c31SKevin Wolf         bs->drv = NULL;
19289a7dedbcSKevin Wolf 
19299a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
19309a7dedbcSKevin Wolf 
19319a4f4c31SKevin Wolf         if (bs->file != NULL) {
19329a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
19339a4f4c31SKevin Wolf             bs->file = NULL;
19349a4f4c31SKevin Wolf         }
19359a4f4c31SKevin Wolf 
19366e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
193733a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
193833a60407SKevin Wolf              * bdrv_unref_child() here */
1939bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
1940bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
1941bddcec37SKevin Wolf             }
194233a60407SKevin Wolf             bdrv_detach_child(child);
19436e93e7c4SKevin Wolf         }
19446e93e7c4SKevin Wolf 
19457267c094SAnthony Liguori         g_free(bs->opaque);
1946ea2384d3Sbellard         bs->opaque = NULL;
194753fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1948a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1949a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
19506405875cSPaolo Bonzini         bs->total_sectors = 0;
19516405875cSPaolo Bonzini         bs->encrypted = 0;
19526405875cSPaolo Bonzini         bs->valid_key = 0;
19536405875cSPaolo Bonzini         bs->sg = 0;
19540d51b4deSAsias He         bs->zero_beyond_eof = false;
1955de9c0cecSKevin Wolf         QDECREF(bs->options);
1956de9c0cecSKevin Wolf         bs->options = NULL;
195791af7014SMax Reitz         QDECREF(bs->full_open_options);
195891af7014SMax Reitz         bs->full_open_options = NULL;
19599ca11154SPavel Hrdina     }
196066f82ceeSKevin Wolf 
196133384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
196233384421SMax Reitz         g_free(ban);
196333384421SMax Reitz     }
196433384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1965b338082bSbellard }
1966b338082bSbellard 
19672bc93fedSMORITA Kazutaka void bdrv_close_all(void)
19682bc93fedSMORITA Kazutaka {
19692bc93fedSMORITA Kazutaka     BlockDriverState *bs;
19702bc93fedSMORITA Kazutaka 
1971dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1972ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1973ed78cda3SStefan Hajnoczi 
1974ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
19752bc93fedSMORITA Kazutaka         bdrv_close(bs);
1976ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
19772bc93fedSMORITA Kazutaka     }
19782bc93fedSMORITA Kazutaka }
19792bc93fedSMORITA Kazutaka 
1980dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1981dc364f4cSBenoît Canet  * graph_bdrv_state list.
1982d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1983d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1984d22b2f41SRyan Harper {
1985bfb197e0SMarkus Armbruster     /*
1986bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
1987bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
1988bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
1989bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
1990bfb197e0SMarkus Armbruster      * resetting it to null on remove.
1991bfb197e0SMarkus Armbruster      */
1992bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
1993dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1994bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
1995d22b2f41SRyan Harper     }
1996dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1997dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1998dc364f4cSBenoît Canet     }
1999dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
2000d22b2f41SRyan Harper }
2001d22b2f41SRyan Harper 
20028e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
20034ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
20044ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
20054ddc07caSPaolo Bonzini {
20064ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
20074ddc07caSPaolo Bonzini 
20084ddc07caSPaolo Bonzini     /* dev info */
20094ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
20104ddc07caSPaolo Bonzini 
20114ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
20124ddc07caSPaolo Bonzini 
2013dd62f1caSKevin Wolf     /* dirty bitmap */
2014dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2015dd62f1caSKevin Wolf }
2016dd62f1caSKevin Wolf 
2017dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2018dd62f1caSKevin Wolf                                        BlockDriverState *to)
2019dd62f1caSKevin Wolf {
2020dd62f1caSKevin Wolf     BdrvChild *c, *next;
2021dd62f1caSKevin Wolf 
2022dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2023dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2024dd62f1caSKevin Wolf         c->bs = to;
2025dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2026dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2027dd62f1caSKevin Wolf         bdrv_ref(to);
2028dd62f1caSKevin Wolf         bdrv_unref(from);
2029dd62f1caSKevin Wolf     }
2030dd62f1caSKevin Wolf     if (from->blk) {
2031dd62f1caSKevin Wolf         blk_set_bs(from->blk, to);
2032dd62f1caSKevin Wolf         if (!to->device_list.tqe_prev) {
2033dd62f1caSKevin Wolf             QTAILQ_INSERT_BEFORE(from, to, device_list);
2034dd62f1caSKevin Wolf         }
2035dd62f1caSKevin Wolf         QTAILQ_REMOVE(&bdrv_states, from, device_list);
2036dd62f1caSKevin Wolf     }
2037dd62f1caSKevin Wolf }
2038dd62f1caSKevin Wolf 
2039dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2040dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2041dd62f1caSKevin Wolf {
2042dd62f1caSKevin Wolf     BlockDriverState tmp;
2043dd62f1caSKevin Wolf 
2044dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2045dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2046dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2047dd62f1caSKevin Wolf 
2048dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2049dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2050dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2051dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2052dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2053dd62f1caSKevin Wolf     }
2054dd62f1caSKevin Wolf }
2055dd62f1caSKevin Wolf 
20568802d1fdSJeff Cody /*
20578802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
20588802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
20598802d1fdSJeff Cody  *
20608802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
20618802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
20628802d1fdSJeff Cody  *
2063bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2064f6801b83SJeff Cody  *
20658802d1fdSJeff Cody  * This function does not create any image files.
2066dd62f1caSKevin Wolf  *
2067dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2068dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2069dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2070dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
20718802d1fdSJeff Cody  */
20728802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
20738802d1fdSJeff Cody {
2074dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2075dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
20768802d1fdSJeff Cody 
2077dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2078dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2079dd62f1caSKevin Wolf 
2080dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2081dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2082dd62f1caSKevin Wolf 
2083dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2084dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2085dd62f1caSKevin Wolf 
2086dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2087dd62f1caSKevin Wolf      * additional reference any more. */
2088dd62f1caSKevin Wolf     bdrv_unref(bs_new);
20898802d1fdSJeff Cody }
20908802d1fdSJeff Cody 
20913f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
20923f09bfbcSKevin Wolf {
20933f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
20943f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
20953f09bfbcSKevin Wolf 
20963f09bfbcSKevin Wolf     bdrv_ref(old);
20973f09bfbcSKevin Wolf 
20983f09bfbcSKevin Wolf     if (old->blk) {
20993f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
21003f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
21013f09bfbcSKevin Wolf          *
21023f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
21033f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
21043f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
21053f09bfbcSKevin Wolf         assert(!new->blk);
21063f09bfbcSKevin Wolf         swap_feature_fields(old, new);
21073f09bfbcSKevin Wolf     }
21083f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
21093f09bfbcSKevin Wolf 
21103f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
21113f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
21123f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
21133f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
21143f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
21153f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
21163f09bfbcSKevin Wolf     }
21173f09bfbcSKevin Wolf 
21183f09bfbcSKevin Wolf     bdrv_unref(old);
21193f09bfbcSKevin Wolf }
21203f09bfbcSKevin Wolf 
21214f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2122b338082bSbellard {
21233e914655SPaolo Bonzini     assert(!bs->job);
21243718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21254f6fd349SFam Zheng     assert(!bs->refcnt);
2126e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
212718846deeSMarkus Armbruster 
2128e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2129e1b5c52eSStefan Hajnoczi 
21301b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2131d22b2f41SRyan Harper     bdrv_make_anon(bs);
213234c6f050Saurel32 
21337267c094SAnthony Liguori     g_free(bs);
2134fc01f7e7Sbellard }
2135fc01f7e7Sbellard 
2136e97fc193Saliguori /*
2137e97fc193Saliguori  * Run consistency checks on an image
2138e97fc193Saliguori  *
2139e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2140a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2141e076f338SKevin Wolf  * check are stored in res.
2142e97fc193Saliguori  */
21434534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2144e97fc193Saliguori {
2145908bcd54SMax Reitz     if (bs->drv == NULL) {
2146908bcd54SMax Reitz         return -ENOMEDIUM;
2147908bcd54SMax Reitz     }
2148e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2149e97fc193Saliguori         return -ENOTSUP;
2150e97fc193Saliguori     }
2151e97fc193Saliguori 
2152e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21534534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2154e97fc193Saliguori }
2155e97fc193Saliguori 
21568a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21578a426614SKevin Wolf 
215833e3963eSbellard /* commit COW file into the raw image */
215933e3963eSbellard int bdrv_commit(BlockDriverState *bs)
216033e3963eSbellard {
216119cb3738Sbellard     BlockDriver *drv = bs->drv;
216272706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21638a426614SKevin Wolf     int n, ro, open_flags;
21640bce597dSJeff Cody     int ret = 0;
216572706ea4SJeff Cody     uint8_t *buf = NULL;
216633e3963eSbellard 
216719cb3738Sbellard     if (!drv)
216819cb3738Sbellard         return -ENOMEDIUM;
216933e3963eSbellard 
2170760e0063SKevin Wolf     if (!bs->backing) {
21714dca4b63SNaphtali Sprei         return -ENOTSUP;
21724dca4b63SNaphtali Sprei     }
21734dca4b63SNaphtali Sprei 
2174bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2175760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
21762d3735d3SStefan Hajnoczi         return -EBUSY;
21772d3735d3SStefan Hajnoczi     }
21782d3735d3SStefan Hajnoczi 
2179760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2180760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
21814dca4b63SNaphtali Sprei 
21824dca4b63SNaphtali Sprei     if (ro) {
2183760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
21840bce597dSJeff Cody             return -EACCES;
21854dca4b63SNaphtali Sprei         }
2186ea2384d3Sbellard     }
2187ea2384d3Sbellard 
218872706ea4SJeff Cody     length = bdrv_getlength(bs);
218972706ea4SJeff Cody     if (length < 0) {
219072706ea4SJeff Cody         ret = length;
219172706ea4SJeff Cody         goto ro_cleanup;
219272706ea4SJeff Cody     }
219372706ea4SJeff Cody 
2194760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
219572706ea4SJeff Cody     if (backing_length < 0) {
219672706ea4SJeff Cody         ret = backing_length;
219772706ea4SJeff Cody         goto ro_cleanup;
219872706ea4SJeff Cody     }
219972706ea4SJeff Cody 
220072706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
220172706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
220272706ea4SJeff Cody      * we must return an error */
220372706ea4SJeff Cody     if (length > backing_length) {
2204760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
220572706ea4SJeff Cody         if (ret < 0) {
220672706ea4SJeff Cody             goto ro_cleanup;
220772706ea4SJeff Cody         }
220872706ea4SJeff Cody     }
220972706ea4SJeff Cody 
221072706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2211857d4f46SKevin Wolf 
2212857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2213760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2214857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2215857d4f46SKevin Wolf     if (buf == NULL) {
2216857d4f46SKevin Wolf         ret = -ENOMEM;
2217857d4f46SKevin Wolf         goto ro_cleanup;
2218857d4f46SKevin Wolf     }
22198a426614SKevin Wolf 
22208a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2221d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2222d663640cSPaolo Bonzini         if (ret < 0) {
2223d663640cSPaolo Bonzini             goto ro_cleanup;
2224d663640cSPaolo Bonzini         }
2225d663640cSPaolo Bonzini         if (ret) {
2226dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2227dabfa6ccSKevin Wolf             if (ret < 0) {
22284dca4b63SNaphtali Sprei                 goto ro_cleanup;
222933e3963eSbellard             }
223033e3963eSbellard 
2231760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2232dabfa6ccSKevin Wolf             if (ret < 0) {
22334dca4b63SNaphtali Sprei                 goto ro_cleanup;
223433e3963eSbellard             }
223533e3963eSbellard         }
223633e3963eSbellard     }
223795389c86Sbellard 
22381d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22391d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2240dabfa6ccSKevin Wolf         if (ret < 0) {
2241dabfa6ccSKevin Wolf             goto ro_cleanup;
2242dabfa6ccSKevin Wolf         }
22431d44952fSChristoph Hellwig         bdrv_flush(bs);
22441d44952fSChristoph Hellwig     }
224595389c86Sbellard 
22463f5075aeSChristoph Hellwig     /*
22473f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22483f5075aeSChristoph Hellwig      * stable on disk.
22493f5075aeSChristoph Hellwig      */
2250760e0063SKevin Wolf     if (bs->backing) {
2251760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2252dabfa6ccSKevin Wolf     }
22534dca4b63SNaphtali Sprei 
2254dabfa6ccSKevin Wolf     ret = 0;
22554dca4b63SNaphtali Sprei ro_cleanup:
2256857d4f46SKevin Wolf     qemu_vfree(buf);
22574dca4b63SNaphtali Sprei 
22584dca4b63SNaphtali Sprei     if (ro) {
22590bce597dSJeff Cody         /* ignoring error return here */
2260760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
22614dca4b63SNaphtali Sprei     }
22624dca4b63SNaphtali Sprei 
22631d44952fSChristoph Hellwig     return ret;
226433e3963eSbellard }
226533e3963eSbellard 
2266e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22676ab4b5abSMarkus Armbruster {
22686ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22696ab4b5abSMarkus Armbruster 
2270dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2271ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2272ed78cda3SStefan Hajnoczi 
2273ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2274760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2275e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2276e8877497SStefan Hajnoczi             if (ret < 0) {
2277ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2278e8877497SStefan Hajnoczi                 return ret;
22796ab4b5abSMarkus Armbruster             }
22806ab4b5abSMarkus Armbruster         }
2281ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2282272d2d8eSJeff Cody     }
2283e8877497SStefan Hajnoczi     return 0;
2284e8877497SStefan Hajnoczi }
22856ab4b5abSMarkus Armbruster 
2286756e6736SKevin Wolf /*
2287756e6736SKevin Wolf  * Return values:
2288756e6736SKevin Wolf  * 0        - success
2289756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2290756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2291756e6736SKevin Wolf  *            image file header
2292756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2293756e6736SKevin Wolf  */
2294756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2295756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2296756e6736SKevin Wolf {
2297756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2298469ef350SPaolo Bonzini     int ret;
2299756e6736SKevin Wolf 
23005f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23015f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23025f377794SPaolo Bonzini         return -EINVAL;
23035f377794SPaolo Bonzini     }
23045f377794SPaolo Bonzini 
2305756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2306469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2307756e6736SKevin Wolf     } else {
2308469ef350SPaolo Bonzini         ret = -ENOTSUP;
2309756e6736SKevin Wolf     }
2310469ef350SPaolo Bonzini 
2311469ef350SPaolo Bonzini     if (ret == 0) {
2312469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2313469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2314469ef350SPaolo Bonzini     }
2315469ef350SPaolo Bonzini     return ret;
2316756e6736SKevin Wolf }
2317756e6736SKevin Wolf 
23186ebdcee2SJeff Cody /*
23196ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23206ebdcee2SJeff Cody  *
23216ebdcee2SJeff Cody  * active is the current topmost image.
23226ebdcee2SJeff Cody  *
23236ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23246ebdcee2SJeff Cody  * or if active == bs.
23254caf0fcdSJeff Cody  *
23264caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
23276ebdcee2SJeff Cody  */
23286ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23296ebdcee2SJeff Cody                                     BlockDriverState *bs)
23306ebdcee2SJeff Cody {
2331760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2332760e0063SKevin Wolf         active = backing_bs(active);
23336ebdcee2SJeff Cody     }
23346ebdcee2SJeff Cody 
23354caf0fcdSJeff Cody     return active;
23366ebdcee2SJeff Cody }
23376ebdcee2SJeff Cody 
23384caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
23394caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
23404caf0fcdSJeff Cody {
23414caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
23426ebdcee2SJeff Cody }
23436ebdcee2SJeff Cody 
23446ebdcee2SJeff Cody /*
23456ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23466ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23476ebdcee2SJeff Cody  *
23486ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23496ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23506ebdcee2SJeff Cody  *
23516ebdcee2SJeff Cody  * E.g., this will convert the following chain:
23526ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
23536ebdcee2SJeff Cody  *
23546ebdcee2SJeff Cody  * to
23556ebdcee2SJeff Cody  *
23566ebdcee2SJeff Cody  * bottom <- base <- active
23576ebdcee2SJeff Cody  *
23586ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
23596ebdcee2SJeff Cody  *
23606ebdcee2SJeff Cody  * base <- intermediate <- top <- active
23616ebdcee2SJeff Cody  *
23626ebdcee2SJeff Cody  * to
23636ebdcee2SJeff Cody  *
23646ebdcee2SJeff Cody  * base <- active
23656ebdcee2SJeff Cody  *
236654e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
236754e26900SJeff Cody  * overlay image metadata.
236854e26900SJeff Cody  *
23696ebdcee2SJeff Cody  * Error conditions:
23706ebdcee2SJeff Cody  *  if active == top, that is considered an error
23716ebdcee2SJeff Cody  *
23726ebdcee2SJeff Cody  */
23736ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
237454e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
23756ebdcee2SJeff Cody {
23766ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
23776ebdcee2SJeff Cody     int ret = -EIO;
23786ebdcee2SJeff Cody 
23796ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
23806ebdcee2SJeff Cody         goto exit;
23816ebdcee2SJeff Cody     }
23826ebdcee2SJeff Cody 
23836ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
23846ebdcee2SJeff Cody 
23856ebdcee2SJeff Cody     if (new_top_bs == NULL) {
23866ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
23876ebdcee2SJeff Cody         goto exit;
23886ebdcee2SJeff Cody     }
23896ebdcee2SJeff Cody 
2390760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
23916ebdcee2SJeff Cody      * to do, no intermediate images */
2392760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
23936ebdcee2SJeff Cody         ret = 0;
23946ebdcee2SJeff Cody         goto exit;
23956ebdcee2SJeff Cody     }
23966ebdcee2SJeff Cody 
23975db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
23985db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
23996ebdcee2SJeff Cody         goto exit;
24006ebdcee2SJeff Cody     }
24016ebdcee2SJeff Cody 
24026ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
24035db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
240454e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
24055db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
24066ebdcee2SJeff Cody     if (ret) {
24076ebdcee2SJeff Cody         goto exit;
24086ebdcee2SJeff Cody     }
24095db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
24106ebdcee2SJeff Cody 
24116ebdcee2SJeff Cody     ret = 0;
24126ebdcee2SJeff Cody exit:
24136ebdcee2SJeff Cody     return ret;
24146ebdcee2SJeff Cody }
24156ebdcee2SJeff Cody 
241683f64091Sbellard /**
241783f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
241883f64091Sbellard  */
241983f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
242083f64091Sbellard {
242183f64091Sbellard     BlockDriver *drv = bs->drv;
242251762288SStefan Hajnoczi     int ret;
242383f64091Sbellard     if (!drv)
242419cb3738Sbellard         return -ENOMEDIUM;
242583f64091Sbellard     if (!drv->bdrv_truncate)
242683f64091Sbellard         return -ENOTSUP;
242759f2689dSNaphtali Sprei     if (bs->read_only)
242859f2689dSNaphtali Sprei         return -EACCES;
24299c75e168SJeff Cody 
243051762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
243151762288SStefan Hajnoczi     if (ret == 0) {
243251762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2433ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2434a7f53e26SMarkus Armbruster         if (bs->blk) {
2435a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2436a7f53e26SMarkus Armbruster         }
243751762288SStefan Hajnoczi     }
243851762288SStefan Hajnoczi     return ret;
243983f64091Sbellard }
244083f64091Sbellard 
244183f64091Sbellard /**
24424a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
24434a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
24444a1d5e1fSFam Zheng  */
24454a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
24464a1d5e1fSFam Zheng {
24474a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
24484a1d5e1fSFam Zheng     if (!drv) {
24494a1d5e1fSFam Zheng         return -ENOMEDIUM;
24504a1d5e1fSFam Zheng     }
24514a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
24524a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
24534a1d5e1fSFam Zheng     }
24544a1d5e1fSFam Zheng     if (bs->file) {
24559a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
24564a1d5e1fSFam Zheng     }
24574a1d5e1fSFam Zheng     return -ENOTSUP;
24584a1d5e1fSFam Zheng }
24594a1d5e1fSFam Zheng 
24604a1d5e1fSFam Zheng /**
246165a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
246283f64091Sbellard  */
246365a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
246483f64091Sbellard {
246583f64091Sbellard     BlockDriver *drv = bs->drv;
246665a9bb25SMarkus Armbruster 
246783f64091Sbellard     if (!drv)
246819cb3738Sbellard         return -ENOMEDIUM;
246951762288SStefan Hajnoczi 
2470b94a2610SKevin Wolf     if (drv->has_variable_length) {
2471b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2472b94a2610SKevin Wolf         if (ret < 0) {
2473b94a2610SKevin Wolf             return ret;
2474fc01f7e7Sbellard         }
247546a4e4e6SStefan Hajnoczi     }
247665a9bb25SMarkus Armbruster     return bs->total_sectors;
247765a9bb25SMarkus Armbruster }
247865a9bb25SMarkus Armbruster 
247965a9bb25SMarkus Armbruster /**
248065a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
248165a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
248265a9bb25SMarkus Armbruster  */
248365a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
248465a9bb25SMarkus Armbruster {
248565a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
248665a9bb25SMarkus Armbruster 
24874a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
248865a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
248946a4e4e6SStefan Hajnoczi }
2490fc01f7e7Sbellard 
249119cb3738Sbellard /* return 0 as number of sectors if no device present or error */
249296b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2493fc01f7e7Sbellard {
249465a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
249565a9bb25SMarkus Armbruster 
249665a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2497fc01f7e7Sbellard }
2498cf98951bSbellard 
2499b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2500b338082bSbellard {
2501b338082bSbellard     return bs->read_only;
2502b338082bSbellard }
2503b338082bSbellard 
2504985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2505985a03b0Sths {
2506985a03b0Sths     return bs->sg;
2507985a03b0Sths }
2508985a03b0Sths 
2509e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2510e900a7b7SChristoph Hellwig {
2511e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2512e900a7b7SChristoph Hellwig }
2513e900a7b7SChristoph Hellwig 
2514425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2515425b0148SPaolo Bonzini {
2516425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
251755b110f2SJeff Cody 
251855b110f2SJeff Cody     /* so a reopen() will preserve wce */
251955b110f2SJeff Cody     if (wce) {
252055b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
252155b110f2SJeff Cody     } else {
252255b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
252355b110f2SJeff Cody     }
2524425b0148SPaolo Bonzini }
2525425b0148SPaolo Bonzini 
2526ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2527ea2384d3Sbellard {
2528760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2529ea2384d3Sbellard         return 1;
2530760e0063SKevin Wolf     }
2531ea2384d3Sbellard     return bs->encrypted;
2532ea2384d3Sbellard }
2533ea2384d3Sbellard 
2534c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2535c0f4ce77Saliguori {
2536760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2537c0f4ce77Saliguori 
2538760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2539c0f4ce77Saliguori         return 1;
2540760e0063SKevin Wolf     }
2541c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2542c0f4ce77Saliguori }
2543c0f4ce77Saliguori 
2544ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2545ea2384d3Sbellard {
2546ea2384d3Sbellard     int ret;
2547760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2548760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2549ea2384d3Sbellard         if (ret < 0)
2550ea2384d3Sbellard             return ret;
2551ea2384d3Sbellard         if (!bs->encrypted)
2552ea2384d3Sbellard             return 0;
2553ea2384d3Sbellard     }
2554fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2555fd04a2aeSShahar Havivi         return -EINVAL;
2556fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2557fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2558fd04a2aeSShahar Havivi     }
2559c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2560bb5fc20fSaliguori     if (ret < 0) {
2561bb5fc20fSaliguori         bs->valid_key = 0;
2562bb5fc20fSaliguori     } else if (!bs->valid_key) {
2563bb5fc20fSaliguori         bs->valid_key = 1;
2564a7f53e26SMarkus Armbruster         if (bs->blk) {
2565bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2566a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2567a7f53e26SMarkus Armbruster         }
2568bb5fc20fSaliguori     }
2569c0f4ce77Saliguori     return ret;
2570ea2384d3Sbellard }
2571ea2384d3Sbellard 
25724d2855a3SMarkus Armbruster /*
25734d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
25744d2855a3SMarkus Armbruster  * If @key is non-null:
25754d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
25764d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
25774d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
25784d2855a3SMarkus Armbruster  * If @key is null:
25794d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
25804d2855a3SMarkus Armbruster  *     Else do nothing.
25814d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
25824d2855a3SMarkus Armbruster  */
25834d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
25844d2855a3SMarkus Armbruster {
25854d2855a3SMarkus Armbruster     if (key) {
25864d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
258781e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
258881e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
25894d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2590c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
25914d2855a3SMarkus Armbruster         }
25924d2855a3SMarkus Armbruster     } else {
25934d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2594b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2595b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
259681e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
25974d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
25984d2855a3SMarkus Armbruster         }
25994d2855a3SMarkus Armbruster     }
26004d2855a3SMarkus Armbruster }
26014d2855a3SMarkus Armbruster 
2602f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2603ea2384d3Sbellard {
2604f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2605ea2384d3Sbellard }
2606ea2384d3Sbellard 
2607ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2608ada42401SStefan Hajnoczi {
2609ada42401SStefan Hajnoczi     return strcmp(a, b);
2610ada42401SStefan Hajnoczi }
2611ada42401SStefan Hajnoczi 
2612ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2613ea2384d3Sbellard                          void *opaque)
2614ea2384d3Sbellard {
2615ea2384d3Sbellard     BlockDriver *drv;
2616e855e4fbSJeff Cody     int count = 0;
2617ada42401SStefan Hajnoczi     int i;
2618e855e4fbSJeff Cody     const char **formats = NULL;
2619ea2384d3Sbellard 
26208a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2621e855e4fbSJeff Cody         if (drv->format_name) {
2622e855e4fbSJeff Cody             bool found = false;
2623e855e4fbSJeff Cody             int i = count;
2624e855e4fbSJeff Cody             while (formats && i && !found) {
2625e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2626e855e4fbSJeff Cody             }
2627e855e4fbSJeff Cody 
2628e855e4fbSJeff Cody             if (!found) {
26295839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2630e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2631ea2384d3Sbellard             }
2632ea2384d3Sbellard         }
2633e855e4fbSJeff Cody     }
2634ada42401SStefan Hajnoczi 
2635ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2636ada42401SStefan Hajnoczi 
2637ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2638ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2639ada42401SStefan Hajnoczi     }
2640ada42401SStefan Hajnoczi 
2641e855e4fbSJeff Cody     g_free(formats);
2642e855e4fbSJeff Cody }
2643ea2384d3Sbellard 
2644dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2645dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2646dc364f4cSBenoît Canet {
2647dc364f4cSBenoît Canet     BlockDriverState *bs;
2648dc364f4cSBenoît Canet 
2649dc364f4cSBenoît Canet     assert(node_name);
2650dc364f4cSBenoît Canet 
2651dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2652dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2653dc364f4cSBenoît Canet             return bs;
2654dc364f4cSBenoît Canet         }
2655dc364f4cSBenoît Canet     }
2656dc364f4cSBenoît Canet     return NULL;
2657dc364f4cSBenoît Canet }
2658dc364f4cSBenoît Canet 
2659c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2660d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2661c13163fbSBenoît Canet {
2662c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2663c13163fbSBenoît Canet     BlockDriverState *bs;
2664c13163fbSBenoît Canet 
2665c13163fbSBenoît Canet     list = NULL;
2666c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2667d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2668d5a8ee60SAlberto Garcia         if (!info) {
2669d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2670d5a8ee60SAlberto Garcia             return NULL;
2671d5a8ee60SAlberto Garcia         }
2672c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2673d5a8ee60SAlberto Garcia         entry->value = info;
2674c13163fbSBenoît Canet         entry->next = list;
2675c13163fbSBenoît Canet         list = entry;
2676c13163fbSBenoît Canet     }
2677c13163fbSBenoît Canet 
2678c13163fbSBenoît Canet     return list;
2679c13163fbSBenoît Canet }
2680c13163fbSBenoît Canet 
268112d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
268212d3ba82SBenoît Canet                                  const char *node_name,
268312d3ba82SBenoît Canet                                  Error **errp)
268412d3ba82SBenoît Canet {
26857f06d47eSMarkus Armbruster     BlockBackend *blk;
26867f06d47eSMarkus Armbruster     BlockDriverState *bs;
268712d3ba82SBenoît Canet 
268812d3ba82SBenoît Canet     if (device) {
26897f06d47eSMarkus Armbruster         blk = blk_by_name(device);
269012d3ba82SBenoît Canet 
26917f06d47eSMarkus Armbruster         if (blk) {
26929f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
26939f4ed6fbSAlberto Garcia             if (!bs) {
26945433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
26955433c24fSMax Reitz             }
26965433c24fSMax Reitz 
26979f4ed6fbSAlberto Garcia             return bs;
269812d3ba82SBenoît Canet         }
2699dd67fa50SBenoît Canet     }
270012d3ba82SBenoît Canet 
2701dd67fa50SBenoît Canet     if (node_name) {
270212d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
270312d3ba82SBenoît Canet 
2704dd67fa50SBenoît Canet         if (bs) {
2705dd67fa50SBenoît Canet             return bs;
2706dd67fa50SBenoît Canet         }
270712d3ba82SBenoît Canet     }
270812d3ba82SBenoît Canet 
2709dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2710dd67fa50SBenoît Canet                      device ? device : "",
2711dd67fa50SBenoît Canet                      node_name ? node_name : "");
2712dd67fa50SBenoît Canet     return NULL;
271312d3ba82SBenoît Canet }
271412d3ba82SBenoît Canet 
27155a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
27165a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
27175a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
27185a6684d2SJeff Cody {
27195a6684d2SJeff Cody     while (top && top != base) {
2720760e0063SKevin Wolf         top = backing_bs(top);
27215a6684d2SJeff Cody     }
27225a6684d2SJeff Cody 
27235a6684d2SJeff Cody     return top != NULL;
27245a6684d2SJeff Cody }
27255a6684d2SJeff Cody 
272604df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
272704df765aSFam Zheng {
272804df765aSFam Zheng     if (!bs) {
272904df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
273004df765aSFam Zheng     }
273104df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
273204df765aSFam Zheng }
273304df765aSFam Zheng 
27342f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
27352f399b0aSMarkus Armbruster {
27362f399b0aSMarkus Armbruster     if (!bs) {
27372f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
27382f399b0aSMarkus Armbruster     }
2739dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
27402f399b0aSMarkus Armbruster }
27412f399b0aSMarkus Armbruster 
274220a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
274320a9e77dSFam Zheng {
274420a9e77dSFam Zheng     return bs->node_name;
274520a9e77dSFam Zheng }
274620a9e77dSFam Zheng 
27477f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2748bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2749ea2384d3Sbellard {
2750bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2751ea2384d3Sbellard }
2752ea2384d3Sbellard 
27539b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
27549b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
27559b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
27569b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
27579b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
27589b2aa84fSAlberto Garcia {
27599b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
27609b2aa84fSAlberto Garcia }
27619b2aa84fSAlberto Garcia 
2762c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2763c8433287SMarkus Armbruster {
2764c8433287SMarkus Armbruster     return bs->open_flags;
2765c8433287SMarkus Armbruster }
2766c8433287SMarkus Armbruster 
27673ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
27683ac21627SPeter Lieven {
27693ac21627SPeter Lieven     return 1;
27703ac21627SPeter Lieven }
27713ac21627SPeter Lieven 
2772f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2773f2feebbdSKevin Wolf {
2774f2feebbdSKevin Wolf     assert(bs->drv);
2775f2feebbdSKevin Wolf 
277611212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
277711212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2778760e0063SKevin Wolf     if (bs->backing) {
277911212d8fSPaolo Bonzini         return 0;
278011212d8fSPaolo Bonzini     }
2781336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2782336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2783f2feebbdSKevin Wolf     }
2784f2feebbdSKevin Wolf 
27853ac21627SPeter Lieven     /* safe default */
27863ac21627SPeter Lieven     return 0;
2787f2feebbdSKevin Wolf }
2788f2feebbdSKevin Wolf 
27894ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
27904ce78691SPeter Lieven {
27914ce78691SPeter Lieven     BlockDriverInfo bdi;
27924ce78691SPeter Lieven 
2793760e0063SKevin Wolf     if (bs->backing) {
27944ce78691SPeter Lieven         return false;
27954ce78691SPeter Lieven     }
27964ce78691SPeter Lieven 
27974ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
27984ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
27994ce78691SPeter Lieven     }
28004ce78691SPeter Lieven 
28014ce78691SPeter Lieven     return false;
28024ce78691SPeter Lieven }
28034ce78691SPeter Lieven 
28044ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
28054ce78691SPeter Lieven {
28064ce78691SPeter Lieven     BlockDriverInfo bdi;
28074ce78691SPeter Lieven 
2808760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
28094ce78691SPeter Lieven         return false;
28104ce78691SPeter Lieven     }
28114ce78691SPeter Lieven 
28124ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28134ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
28144ce78691SPeter Lieven     }
28154ce78691SPeter Lieven 
28164ce78691SPeter Lieven     return false;
28174ce78691SPeter Lieven }
28184ce78691SPeter Lieven 
2819045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2820045df330Saliguori {
2821760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2822045df330Saliguori         return bs->backing_file;
2823045df330Saliguori     else if (bs->encrypted)
2824045df330Saliguori         return bs->filename;
2825045df330Saliguori     else
2826045df330Saliguori         return NULL;
2827045df330Saliguori }
2828045df330Saliguori 
282983f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
283083f64091Sbellard                                char *filename, int filename_size)
283183f64091Sbellard {
283283f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
283383f64091Sbellard }
283483f64091Sbellard 
2835faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2836faea38e7Sbellard {
2837faea38e7Sbellard     BlockDriver *drv = bs->drv;
2838faea38e7Sbellard     if (!drv)
283919cb3738Sbellard         return -ENOMEDIUM;
2840faea38e7Sbellard     if (!drv->bdrv_get_info)
2841faea38e7Sbellard         return -ENOTSUP;
2842faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2843faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2844faea38e7Sbellard }
2845faea38e7Sbellard 
2846eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2847eae041feSMax Reitz {
2848eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2849eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2850eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2851eae041feSMax Reitz     }
2852eae041feSMax Reitz     return NULL;
2853eae041feSMax Reitz }
2854eae041feSMax Reitz 
28558b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
28568b9b0cc2SKevin Wolf {
2857bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
28588b9b0cc2SKevin Wolf         return;
28598b9b0cc2SKevin Wolf     }
28608b9b0cc2SKevin Wolf 
2861bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
286241c695c7SKevin Wolf }
28638b9b0cc2SKevin Wolf 
286441c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
286541c695c7SKevin Wolf                           const char *tag)
286641c695c7SKevin Wolf {
286741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
28689a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
286941c695c7SKevin Wolf     }
287041c695c7SKevin Wolf 
287141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
287241c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
287341c695c7SKevin Wolf     }
287441c695c7SKevin Wolf 
287541c695c7SKevin Wolf     return -ENOTSUP;
287641c695c7SKevin Wolf }
287741c695c7SKevin Wolf 
28784cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
28794cc70e93SFam Zheng {
28804cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
28819a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
28824cc70e93SFam Zheng     }
28834cc70e93SFam Zheng 
28844cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
28854cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
28864cc70e93SFam Zheng     }
28874cc70e93SFam Zheng 
28884cc70e93SFam Zheng     return -ENOTSUP;
28894cc70e93SFam Zheng }
28904cc70e93SFam Zheng 
289141c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
289241c695c7SKevin Wolf {
2893938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
28949a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
289541c695c7SKevin Wolf     }
289641c695c7SKevin Wolf 
289741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
289841c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
289941c695c7SKevin Wolf     }
290041c695c7SKevin Wolf 
290141c695c7SKevin Wolf     return -ENOTSUP;
290241c695c7SKevin Wolf }
290341c695c7SKevin Wolf 
290441c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
290541c695c7SKevin Wolf {
290641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
29079a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
290841c695c7SKevin Wolf     }
290941c695c7SKevin Wolf 
291041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
291141c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
291241c695c7SKevin Wolf     }
291341c695c7SKevin Wolf 
291441c695c7SKevin Wolf     return false;
29158b9b0cc2SKevin Wolf }
29168b9b0cc2SKevin Wolf 
2917199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2918199630b6SBlue Swirl {
2919199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2920199630b6SBlue Swirl }
2921199630b6SBlue Swirl 
2922b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
2923b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
2924b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
2925b1b1d783SJeff Cody  * the CWD rather than the chain. */
2926e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2927e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2928e8a6bb9cSMarcelo Tosatti {
2929b1b1d783SJeff Cody     char *filename_full = NULL;
2930b1b1d783SJeff Cody     char *backing_file_full = NULL;
2931b1b1d783SJeff Cody     char *filename_tmp = NULL;
2932b1b1d783SJeff Cody     int is_protocol = 0;
2933b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
2934b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
2935b1b1d783SJeff Cody 
2936b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
2937e8a6bb9cSMarcelo Tosatti         return NULL;
2938e8a6bb9cSMarcelo Tosatti     }
2939e8a6bb9cSMarcelo Tosatti 
2940b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
2941b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
2942b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
2943b1b1d783SJeff Cody 
2944b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
2945b1b1d783SJeff Cody 
2946760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
2947b1b1d783SJeff Cody 
2948b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
2949b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
2950b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
2951b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
2952760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
2953b1b1d783SJeff Cody                 break;
2954b1b1d783SJeff Cody             }
2955e8a6bb9cSMarcelo Tosatti         } else {
2956b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
2957b1b1d783SJeff Cody              * image's filename path */
2958b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2959b1b1d783SJeff Cody                          backing_file);
2960b1b1d783SJeff Cody 
2961b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
2962b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
2963b1b1d783SJeff Cody                 continue;
2964b1b1d783SJeff Cody             }
2965b1b1d783SJeff Cody 
2966b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
2967b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
2968b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2969b1b1d783SJeff Cody                          curr_bs->backing_file);
2970b1b1d783SJeff Cody 
2971b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
2972b1b1d783SJeff Cody                 continue;
2973b1b1d783SJeff Cody             }
2974b1b1d783SJeff Cody 
2975b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
2976760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
2977b1b1d783SJeff Cody                 break;
2978b1b1d783SJeff Cody             }
2979e8a6bb9cSMarcelo Tosatti         }
2980e8a6bb9cSMarcelo Tosatti     }
2981e8a6bb9cSMarcelo Tosatti 
2982b1b1d783SJeff Cody     g_free(filename_full);
2983b1b1d783SJeff Cody     g_free(backing_file_full);
2984b1b1d783SJeff Cody     g_free(filename_tmp);
2985b1b1d783SJeff Cody     return retval;
2986e8a6bb9cSMarcelo Tosatti }
2987e8a6bb9cSMarcelo Tosatti 
2988f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
2989f198fd1cSBenoît Canet {
2990f198fd1cSBenoît Canet     if (!bs->drv) {
2991f198fd1cSBenoît Canet         return 0;
2992f198fd1cSBenoît Canet     }
2993f198fd1cSBenoît Canet 
2994760e0063SKevin Wolf     if (!bs->backing) {
2995f198fd1cSBenoît Canet         return 0;
2996f198fd1cSBenoît Canet     }
2997f198fd1cSBenoît Canet 
2998760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
2999f198fd1cSBenoît Canet }
3000f198fd1cSBenoît Canet 
3001ea2384d3Sbellard void bdrv_init(void)
3002ea2384d3Sbellard {
30035efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3004ea2384d3Sbellard }
3005ce1a14dcSpbrook 
3006eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3007eb852011SMarkus Armbruster {
3008eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3009eb852011SMarkus Armbruster     bdrv_init();
3010eb852011SMarkus Armbruster }
3011eb852011SMarkus Armbruster 
30125a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
30130f15423cSAnthony Liguori {
30145a8a30dbSKevin Wolf     Error *local_err = NULL;
30155a8a30dbSKevin Wolf     int ret;
30165a8a30dbSKevin Wolf 
30173456a8d1SKevin Wolf     if (!bs->drv)  {
30183456a8d1SKevin Wolf         return;
30190f15423cSAnthony Liguori     }
30203456a8d1SKevin Wolf 
30217ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
30227ea2d269SAlexey Kardashevskiy         return;
30237ea2d269SAlexey Kardashevskiy     }
30247ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
30257ea2d269SAlexey Kardashevskiy 
30263456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
30275a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
30283456a8d1SKevin Wolf     } else if (bs->file) {
30299a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
30305a8a30dbSKevin Wolf     }
30315a8a30dbSKevin Wolf     if (local_err) {
30325a8a30dbSKevin Wolf         error_propagate(errp, local_err);
30335a8a30dbSKevin Wolf         return;
30343456a8d1SKevin Wolf     }
30353456a8d1SKevin Wolf 
30365a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
30375a8a30dbSKevin Wolf     if (ret < 0) {
30385a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
30395a8a30dbSKevin Wolf         return;
30405a8a30dbSKevin Wolf     }
30410f15423cSAnthony Liguori }
30420f15423cSAnthony Liguori 
30435a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
30440f15423cSAnthony Liguori {
30450f15423cSAnthony Liguori     BlockDriverState *bs;
30465a8a30dbSKevin Wolf     Error *local_err = NULL;
30470f15423cSAnthony Liguori 
3048dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3049ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3050ed78cda3SStefan Hajnoczi 
3051ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
30525a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3053ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
30545a8a30dbSKevin Wolf         if (local_err) {
30555a8a30dbSKevin Wolf             error_propagate(errp, local_err);
30565a8a30dbSKevin Wolf             return;
30575a8a30dbSKevin Wolf         }
30580f15423cSAnthony Liguori     }
30590f15423cSAnthony Liguori }
30600f15423cSAnthony Liguori 
3061f9f05dc5SKevin Wolf /**************************************************************/
306219cb3738Sbellard /* removable device support */
306319cb3738Sbellard 
306419cb3738Sbellard /**
306519cb3738Sbellard  * Return TRUE if the media is present
306619cb3738Sbellard  */
3067e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
306819cb3738Sbellard {
306919cb3738Sbellard     BlockDriver *drv = bs->drv;
307028d7a789SMax Reitz     BdrvChild *child;
3071a1aff5bfSMarkus Armbruster 
3072e031f750SMax Reitz     if (!drv) {
3073e031f750SMax Reitz         return false;
3074e031f750SMax Reitz     }
307528d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3076a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
307719cb3738Sbellard     }
307828d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
307928d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
308028d7a789SMax Reitz             return false;
308128d7a789SMax Reitz         }
308228d7a789SMax Reitz     }
308328d7a789SMax Reitz     return true;
308428d7a789SMax Reitz }
308519cb3738Sbellard 
308619cb3738Sbellard /**
30878e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
30888e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
308919cb3738Sbellard  */
309019cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
309119cb3738Sbellard {
309219cb3738Sbellard     BlockDriver *drv = bs->drv;
309319cb3738Sbellard 
30948e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
30958e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
30968e49ca46SMarkus Armbruster     }
30978e49ca46SMarkus Armbruster     return -ENOTSUP;
309819cb3738Sbellard }
309919cb3738Sbellard 
310019cb3738Sbellard /**
310119cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
310219cb3738Sbellard  */
3103f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
310419cb3738Sbellard {
310519cb3738Sbellard     BlockDriver *drv = bs->drv;
3106bfb197e0SMarkus Armbruster     const char *device_name;
310719cb3738Sbellard 
3108822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3109822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
311019cb3738Sbellard     }
31116f382ed2SLuiz Capitulino 
3112bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3113bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3114bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3115a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
31166f382ed2SLuiz Capitulino     }
311719cb3738Sbellard }
311819cb3738Sbellard 
311919cb3738Sbellard /**
312019cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
312119cb3738Sbellard  * to eject it manually).
312219cb3738Sbellard  */
3123025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
312419cb3738Sbellard {
312519cb3738Sbellard     BlockDriver *drv = bs->drv;
312619cb3738Sbellard 
3127025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3128b8c6d095SStefan Hajnoczi 
3129025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3130025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
313119cb3738Sbellard     }
313219cb3738Sbellard }
3133985a03b0Sths 
31340db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
31350db6e54aSFam Zheng {
31360db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
31370db6e54aSFam Zheng 
31380db6e54aSFam Zheng     assert(name);
31390db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
31400db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
31410db6e54aSFam Zheng             return bm;
31420db6e54aSFam Zheng         }
31430db6e54aSFam Zheng     }
31440db6e54aSFam Zheng     return NULL;
31450db6e54aSFam Zheng }
31460db6e54aSFam Zheng 
314720dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
31480db6e54aSFam Zheng {
31499bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
31500db6e54aSFam Zheng     g_free(bitmap->name);
31510db6e54aSFam Zheng     bitmap->name = NULL;
31520db6e54aSFam Zheng }
31530db6e54aSFam Zheng 
31540db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
31555fba6c0eSJohn Snow                                           uint32_t granularity,
31560db6e54aSFam Zheng                                           const char *name,
3157b8afb520SFam Zheng                                           Error **errp)
31587cd1e32aSlirans@il.ibm.com {
31597cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3160e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
31615fba6c0eSJohn Snow     uint32_t sector_granularity;
3162a55eb92cSJan Kiszka 
316350717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
316450717e94SPaolo Bonzini 
31650db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
31660db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
31670db6e54aSFam Zheng         return NULL;
31680db6e54aSFam Zheng     }
31695fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
31705fba6c0eSJohn Snow     assert(sector_granularity);
317157322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3172b8afb520SFam Zheng     if (bitmap_size < 0) {
3173b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3174b8afb520SFam Zheng         errno = -bitmap_size;
3175b8afb520SFam Zheng         return NULL;
3176b8afb520SFam Zheng     }
31775839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
31785fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3179e74e6b78SJohn Snow     bitmap->size = bitmap_size;
31800db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3181b8e6fb75SJohn Snow     bitmap->disabled = false;
3182e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3183e4654d2dSFam Zheng     return bitmap;
3184e4654d2dSFam Zheng }
3185e4654d2dSFam Zheng 
31869bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
31879bd2b08fSJohn Snow {
31889bd2b08fSJohn Snow     return bitmap->successor;
31899bd2b08fSJohn Snow }
31909bd2b08fSJohn Snow 
3191b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3192b8e6fb75SJohn Snow {
31939bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
31949bd2b08fSJohn Snow }
31959bd2b08fSJohn Snow 
31969abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
31979abe3bdcSJohn Snow {
31989abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
31999abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
32009abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
32019abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
32029abe3bdcSJohn Snow     } else {
32039abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
32049abe3bdcSJohn Snow     }
32059abe3bdcSJohn Snow }
32069abe3bdcSJohn Snow 
32079bd2b08fSJohn Snow /**
32089bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
32099bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
32109bd2b08fSJohn Snow  */
32119bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
32129bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
32139bd2b08fSJohn Snow {
32149bd2b08fSJohn Snow     uint64_t granularity;
32159bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
32169bd2b08fSJohn Snow 
32179bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
32189bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
32199bd2b08fSJohn Snow                    "currently frozen");
32209bd2b08fSJohn Snow         return -1;
32219bd2b08fSJohn Snow     }
32229bd2b08fSJohn Snow     assert(!bitmap->successor);
32239bd2b08fSJohn Snow 
32249bd2b08fSJohn Snow     /* Create an anonymous successor */
32259bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
32269bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
32279bd2b08fSJohn Snow     if (!child) {
32289bd2b08fSJohn Snow         return -1;
32299bd2b08fSJohn Snow     }
32309bd2b08fSJohn Snow 
32319bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
32329bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
32339bd2b08fSJohn Snow 
32349bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
32359bd2b08fSJohn Snow     bitmap->successor = child;
32369bd2b08fSJohn Snow     return 0;
32379bd2b08fSJohn Snow }
32389bd2b08fSJohn Snow 
32399bd2b08fSJohn Snow /**
32409bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
32419bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
32429bd2b08fSJohn Snow  */
32439bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
32449bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
32459bd2b08fSJohn Snow                                             Error **errp)
32469bd2b08fSJohn Snow {
32479bd2b08fSJohn Snow     char *name;
32489bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
32499bd2b08fSJohn Snow 
32509bd2b08fSJohn Snow     if (successor == NULL) {
32519bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
32529bd2b08fSJohn Snow                    "there's no successor present");
32539bd2b08fSJohn Snow         return NULL;
32549bd2b08fSJohn Snow     }
32559bd2b08fSJohn Snow 
32569bd2b08fSJohn Snow     name = bitmap->name;
32579bd2b08fSJohn Snow     bitmap->name = NULL;
32589bd2b08fSJohn Snow     successor->name = name;
32599bd2b08fSJohn Snow     bitmap->successor = NULL;
32609bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
32619bd2b08fSJohn Snow 
32629bd2b08fSJohn Snow     return successor;
32639bd2b08fSJohn Snow }
32649bd2b08fSJohn Snow 
32659bd2b08fSJohn Snow /**
32669bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
32679bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
32689bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
32699bd2b08fSJohn Snow  */
32709bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
32719bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
32729bd2b08fSJohn Snow                                            Error **errp)
32739bd2b08fSJohn Snow {
32749bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
32759bd2b08fSJohn Snow 
32769bd2b08fSJohn Snow     if (!successor) {
32779bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
32789bd2b08fSJohn Snow         return NULL;
32799bd2b08fSJohn Snow     }
32809bd2b08fSJohn Snow 
32819bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
32829bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
32839bd2b08fSJohn Snow         return NULL;
32849bd2b08fSJohn Snow     }
32859bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
32869bd2b08fSJohn Snow     parent->successor = NULL;
32879bd2b08fSJohn Snow 
32889bd2b08fSJohn Snow     return parent;
3289b8e6fb75SJohn Snow }
3290b8e6fb75SJohn Snow 
3291ce1ffea8SJohn Snow /**
3292ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3293ce1ffea8SJohn Snow  */
3294ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3295ce1ffea8SJohn Snow {
3296ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3297ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3298ce1ffea8SJohn Snow 
3299ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
330006207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3301ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
33025270b6a0SJohn Snow         bitmap->size = size;
3303ce1ffea8SJohn Snow     }
3304ce1ffea8SJohn Snow }
3305ce1ffea8SJohn Snow 
3306e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3307e4654d2dSFam Zheng {
3308e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3309e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3310e4654d2dSFam Zheng         if (bm == bitmap) {
33119bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3312e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3313e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
33140db6e54aSFam Zheng             g_free(bitmap->name);
3315e4654d2dSFam Zheng             g_free(bitmap);
3316e4654d2dSFam Zheng             return;
33177cd1e32aSlirans@il.ibm.com         }
33187cd1e32aSlirans@il.ibm.com     }
33197cd1e32aSlirans@il.ibm.com }
33207cd1e32aSlirans@il.ibm.com 
3321b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3322b8e6fb75SJohn Snow {
33239bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3324b8e6fb75SJohn Snow     bitmap->disabled = true;
3325b8e6fb75SJohn Snow }
3326b8e6fb75SJohn Snow 
3327b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3328b8e6fb75SJohn Snow {
33299bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3330b8e6fb75SJohn Snow     bitmap->disabled = false;
3331b8e6fb75SJohn Snow }
3332b8e6fb75SJohn Snow 
333321b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
333421b56835SFam Zheng {
333521b56835SFam Zheng     BdrvDirtyBitmap *bm;
333621b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
333721b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
333821b56835SFam Zheng 
333921b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
33405839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
33415839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
334220dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3343592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
33440db6e54aSFam Zheng         info->has_name = !!bm->name;
33450db6e54aSFam Zheng         info->name = g_strdup(bm->name);
33469abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
334721b56835SFam Zheng         entry->value = info;
334821b56835SFam Zheng         *plist = entry;
334921b56835SFam Zheng         plist = &entry->next;
335021b56835SFam Zheng     }
335121b56835SFam Zheng 
335221b56835SFam Zheng     return list;
335321b56835SFam Zheng }
335421b56835SFam Zheng 
3355e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
33567cd1e32aSlirans@il.ibm.com {
3357e4654d2dSFam Zheng     if (bitmap) {
3358e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
33597cd1e32aSlirans@il.ibm.com     } else {
33607cd1e32aSlirans@il.ibm.com         return 0;
33617cd1e32aSlirans@il.ibm.com     }
33627cd1e32aSlirans@il.ibm.com }
33637cd1e32aSlirans@il.ibm.com 
3364341ebc2fSJohn Snow /**
3365341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3366341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3367341ebc2fSJohn Snow  * is no cluster size information available.
3368341ebc2fSJohn Snow  */
3369341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3370341ebc2fSJohn Snow {
3371341ebc2fSJohn Snow     BlockDriverInfo bdi;
3372341ebc2fSJohn Snow     uint32_t granularity;
3373341ebc2fSJohn Snow 
3374341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3375341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3376341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3377341ebc2fSJohn Snow     } else {
3378341ebc2fSJohn Snow         granularity = 65536;
3379341ebc2fSJohn Snow     }
3380341ebc2fSJohn Snow 
3381341ebc2fSJohn Snow     return granularity;
3382341ebc2fSJohn Snow }
3383341ebc2fSJohn Snow 
3384592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3385592fdd02SJohn Snow {
3386592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3387592fdd02SJohn Snow }
3388592fdd02SJohn Snow 
338920dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
33901755da16SPaolo Bonzini {
3391e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
33921755da16SPaolo Bonzini }
33931755da16SPaolo Bonzini 
339420dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3395c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3396c4237dfaSVladimir Sementsov-Ogievskiy {
3397b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3398c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3399c4237dfaSVladimir Sementsov-Ogievskiy }
3400c4237dfaSVladimir Sementsov-Ogievskiy 
340120dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3402c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3403c4237dfaSVladimir Sementsov-Ogievskiy {
3404b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3405c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3406c4237dfaSVladimir Sementsov-Ogievskiy }
3407c4237dfaSVladimir Sementsov-Ogievskiy 
3408e74e6b78SJohn Snow void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3409e74e6b78SJohn Snow {
3410e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3411c6a8c328SWen Congyang     hbitmap_reset_all(bitmap->bitmap);
3412e74e6b78SJohn Snow }
3413e74e6b78SJohn Snow 
3414e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
34151755da16SPaolo Bonzini                     int nr_sectors)
34161755da16SPaolo Bonzini {
3417e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3418e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3419b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3420b8e6fb75SJohn Snow             continue;
3421b8e6fb75SJohn Snow         }
3422e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3423e4654d2dSFam Zheng     }
34241755da16SPaolo Bonzini }
34251755da16SPaolo Bonzini 
3426d58d8453SJohn Snow /**
3427d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3428d58d8453SJohn Snow  */
3429d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3430d58d8453SJohn Snow {
3431d58d8453SJohn Snow     assert(hbi->hb);
3432d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3433d58d8453SJohn Snow }
3434d58d8453SJohn Snow 
343520dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3436aaa0eb75SLiran Schour {
3437e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3438aaa0eb75SLiran Schour }
3439f88e1a42SJes Sorensen 
34409fcb0251SFam Zheng /* Get a reference to bs */
34419fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
34429fcb0251SFam Zheng {
34439fcb0251SFam Zheng     bs->refcnt++;
34449fcb0251SFam Zheng }
34459fcb0251SFam Zheng 
34469fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
34479fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
34489fcb0251SFam Zheng  * deleted. */
34499fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
34509fcb0251SFam Zheng {
34519a4d5ca6SJeff Cody     if (!bs) {
34529a4d5ca6SJeff Cody         return;
34539a4d5ca6SJeff Cody     }
34549fcb0251SFam Zheng     assert(bs->refcnt > 0);
34559fcb0251SFam Zheng     if (--bs->refcnt == 0) {
34569fcb0251SFam Zheng         bdrv_delete(bs);
34579fcb0251SFam Zheng     }
34589fcb0251SFam Zheng }
34599fcb0251SFam Zheng 
3460fbe40ff7SFam Zheng struct BdrvOpBlocker {
3461fbe40ff7SFam Zheng     Error *reason;
3462fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3463fbe40ff7SFam Zheng };
3464fbe40ff7SFam Zheng 
3465fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3466fbe40ff7SFam Zheng {
3467fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3468fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3469fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3470fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3471fbe40ff7SFam Zheng         if (errp) {
347281e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
347381e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3474bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3475fbe40ff7SFam Zheng         }
3476fbe40ff7SFam Zheng         return true;
3477fbe40ff7SFam Zheng     }
3478fbe40ff7SFam Zheng     return false;
3479fbe40ff7SFam Zheng }
3480fbe40ff7SFam Zheng 
3481fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3482fbe40ff7SFam Zheng {
3483fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3484fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3485fbe40ff7SFam Zheng 
34865839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3487fbe40ff7SFam Zheng     blocker->reason = reason;
3488fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3489fbe40ff7SFam Zheng }
3490fbe40ff7SFam Zheng 
3491fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3492fbe40ff7SFam Zheng {
3493fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3494fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3495fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3496fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3497fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3498fbe40ff7SFam Zheng             g_free(blocker);
3499fbe40ff7SFam Zheng         }
3500fbe40ff7SFam Zheng     }
3501fbe40ff7SFam Zheng }
3502fbe40ff7SFam Zheng 
3503fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3504fbe40ff7SFam Zheng {
3505fbe40ff7SFam Zheng     int i;
3506fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3507fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3508fbe40ff7SFam Zheng     }
3509fbe40ff7SFam Zheng }
3510fbe40ff7SFam Zheng 
3511fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3512fbe40ff7SFam Zheng {
3513fbe40ff7SFam Zheng     int i;
3514fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3515fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3516fbe40ff7SFam Zheng     }
3517fbe40ff7SFam Zheng }
3518fbe40ff7SFam Zheng 
3519fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3520fbe40ff7SFam Zheng {
3521fbe40ff7SFam Zheng     int i;
3522fbe40ff7SFam Zheng 
3523fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3524fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3525fbe40ff7SFam Zheng             return false;
3526fbe40ff7SFam Zheng         }
3527fbe40ff7SFam Zheng     }
3528fbe40ff7SFam Zheng     return true;
3529fbe40ff7SFam Zheng }
3530fbe40ff7SFam Zheng 
3531d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3532f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3533f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3534f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3535f88e1a42SJes Sorensen {
353683d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
353783d0521aSChunyan Liu     QemuOpts *opts = NULL;
353883d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
353983d0521aSChunyan Liu     int64_t size;
3540f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3541cc84d90fSMax Reitz     Error *local_err = NULL;
3542f88e1a42SJes Sorensen     int ret = 0;
3543f88e1a42SJes Sorensen 
3544f88e1a42SJes Sorensen     /* Find driver and parse its options */
3545f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3546f88e1a42SJes Sorensen     if (!drv) {
354771c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3548d92ada22SLuiz Capitulino         return;
3549f88e1a42SJes Sorensen     }
3550f88e1a42SJes Sorensen 
3551b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3552f88e1a42SJes Sorensen     if (!proto_drv) {
3553d92ada22SLuiz Capitulino         return;
3554f88e1a42SJes Sorensen     }
3555f88e1a42SJes Sorensen 
3556c6149724SMax Reitz     if (!drv->create_opts) {
3557c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3558c6149724SMax Reitz                    drv->format_name);
3559c6149724SMax Reitz         return;
3560c6149724SMax Reitz     }
3561c6149724SMax Reitz 
3562c6149724SMax Reitz     if (!proto_drv->create_opts) {
3563c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3564c6149724SMax Reitz                    proto_drv->format_name);
3565c6149724SMax Reitz         return;
3566c6149724SMax Reitz     }
3567c6149724SMax Reitz 
3568c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3569c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3570f88e1a42SJes Sorensen 
3571f88e1a42SJes Sorensen     /* Create parameter list with default values */
357283d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
357339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3574f88e1a42SJes Sorensen 
3575f88e1a42SJes Sorensen     /* Parse -o options */
3576f88e1a42SJes Sorensen     if (options) {
3577dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3578dc523cd3SMarkus Armbruster         if (local_err) {
3579dc523cd3SMarkus Armbruster             error_report_err(local_err);
3580dc523cd3SMarkus Armbruster             local_err = NULL;
358183d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3582f88e1a42SJes Sorensen             goto out;
3583f88e1a42SJes Sorensen         }
3584f88e1a42SJes Sorensen     }
3585f88e1a42SJes Sorensen 
3586f88e1a42SJes Sorensen     if (base_filename) {
3587f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35886be4194bSMarkus Armbruster         if (local_err) {
358971c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
359071c79813SLuiz Capitulino                        fmt);
3591f88e1a42SJes Sorensen             goto out;
3592f88e1a42SJes Sorensen         }
3593f88e1a42SJes Sorensen     }
3594f88e1a42SJes Sorensen 
3595f88e1a42SJes Sorensen     if (base_fmt) {
3596f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35976be4194bSMarkus Armbruster         if (local_err) {
359871c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
359971c79813SLuiz Capitulino                              "format '%s'", fmt);
3600f88e1a42SJes Sorensen             goto out;
3601f88e1a42SJes Sorensen         }
3602f88e1a42SJes Sorensen     }
3603f88e1a42SJes Sorensen 
360483d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
360583d0521aSChunyan Liu     if (backing_file) {
360683d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
360771c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
360871c79813SLuiz Capitulino                              "same filename as the backing file");
3609792da93aSJes Sorensen             goto out;
3610792da93aSJes Sorensen         }
3611792da93aSJes Sorensen     }
3612792da93aSJes Sorensen 
361383d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3614f88e1a42SJes Sorensen 
3615f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3616f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
361783d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
361883d0521aSChunyan Liu     if (size == -1) {
361983d0521aSChunyan Liu         if (backing_file) {
362066f6b814SMax Reitz             BlockDriverState *bs;
362129168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
362252bf1e72SMarkus Armbruster             int64_t size;
362363090dacSPaolo Bonzini             int back_flags;
3624e6641719SMax Reitz             QDict *backing_options = NULL;
362563090dacSPaolo Bonzini 
362629168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
362729168018SMax Reitz                                                          full_backing, PATH_MAX,
362829168018SMax Reitz                                                          &local_err);
362929168018SMax Reitz             if (local_err) {
363029168018SMax Reitz                 g_free(full_backing);
363129168018SMax Reitz                 goto out;
363229168018SMax Reitz             }
363329168018SMax Reitz 
363463090dacSPaolo Bonzini             /* backing files always opened read-only */
363563090dacSPaolo Bonzini             back_flags =
363663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3637f88e1a42SJes Sorensen 
3638e6641719SMax Reitz             if (backing_fmt) {
3639e6641719SMax Reitz                 backing_options = qdict_new();
3640e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3641e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3642e6641719SMax Reitz             }
3643e6641719SMax Reitz 
3644f67503e5SMax Reitz             bs = NULL;
3645e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
36466ebf9aa2SMax Reitz                             back_flags, &local_err);
364729168018SMax Reitz             g_free(full_backing);
3648f88e1a42SJes Sorensen             if (ret < 0) {
3649f88e1a42SJes Sorensen                 goto out;
3650f88e1a42SJes Sorensen             }
365152bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
365252bf1e72SMarkus Armbruster             if (size < 0) {
365352bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
365452bf1e72SMarkus Armbruster                                  backing_file);
365552bf1e72SMarkus Armbruster                 bdrv_unref(bs);
365652bf1e72SMarkus Armbruster                 goto out;
365752bf1e72SMarkus Armbruster             }
3658f88e1a42SJes Sorensen 
365939101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
366066f6b814SMax Reitz 
366166f6b814SMax Reitz             bdrv_unref(bs);
3662f88e1a42SJes Sorensen         } else {
366371c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3664f88e1a42SJes Sorensen             goto out;
3665f88e1a42SJes Sorensen         }
3666f88e1a42SJes Sorensen     }
3667f88e1a42SJes Sorensen 
3668f382d43aSMiroslav Rezanina     if (!quiet) {
3669f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
367043c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3671f88e1a42SJes Sorensen         puts("");
3672f382d43aSMiroslav Rezanina     }
367383d0521aSChunyan Liu 
3674c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
367583d0521aSChunyan Liu 
3676cc84d90fSMax Reitz     if (ret == -EFBIG) {
3677cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3678cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3679cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3680f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
368183d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3682f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3683f3f4d2c0SKevin Wolf         }
3684cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3685cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3686cc84d90fSMax Reitz         error_free(local_err);
3687cc84d90fSMax Reitz         local_err = NULL;
3688f88e1a42SJes Sorensen     }
3689f88e1a42SJes Sorensen 
3690f88e1a42SJes Sorensen out:
369183d0521aSChunyan Liu     qemu_opts_del(opts);
369283d0521aSChunyan Liu     qemu_opts_free(create_opts);
369384d18f06SMarkus Armbruster     if (local_err) {
3694cc84d90fSMax Reitz         error_propagate(errp, local_err);
3695cc84d90fSMax Reitz     }
3696f88e1a42SJes Sorensen }
369785d126f3SStefan Hajnoczi 
369885d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
369985d126f3SStefan Hajnoczi {
3700dcd04228SStefan Hajnoczi     return bs->aio_context;
3701dcd04228SStefan Hajnoczi }
3702dcd04228SStefan Hajnoczi 
3703dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3704dcd04228SStefan Hajnoczi {
370533384421SMax Reitz     BdrvAioNotifier *baf;
370633384421SMax Reitz 
3707dcd04228SStefan Hajnoczi     if (!bs->drv) {
3708dcd04228SStefan Hajnoczi         return;
3709dcd04228SStefan Hajnoczi     }
3710dcd04228SStefan Hajnoczi 
371133384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
371233384421SMax Reitz         baf->detach_aio_context(baf->opaque);
371333384421SMax Reitz     }
371433384421SMax Reitz 
371513af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
37160e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
371713af91ebSStefan Hajnoczi     }
3718dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3719dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3720dcd04228SStefan Hajnoczi     }
3721dcd04228SStefan Hajnoczi     if (bs->file) {
37229a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3723dcd04228SStefan Hajnoczi     }
3724760e0063SKevin Wolf     if (bs->backing) {
3725760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3726dcd04228SStefan Hajnoczi     }
3727dcd04228SStefan Hajnoczi 
3728dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3729dcd04228SStefan Hajnoczi }
3730dcd04228SStefan Hajnoczi 
3731dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3732dcd04228SStefan Hajnoczi                              AioContext *new_context)
3733dcd04228SStefan Hajnoczi {
373433384421SMax Reitz     BdrvAioNotifier *ban;
373533384421SMax Reitz 
3736dcd04228SStefan Hajnoczi     if (!bs->drv) {
3737dcd04228SStefan Hajnoczi         return;
3738dcd04228SStefan Hajnoczi     }
3739dcd04228SStefan Hajnoczi 
3740dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3741dcd04228SStefan Hajnoczi 
3742760e0063SKevin Wolf     if (bs->backing) {
3743760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3744dcd04228SStefan Hajnoczi     }
3745dcd04228SStefan Hajnoczi     if (bs->file) {
37469a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3747dcd04228SStefan Hajnoczi     }
3748dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3749dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3750dcd04228SStefan Hajnoczi     }
375113af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
37520e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
375313af91ebSStefan Hajnoczi     }
375433384421SMax Reitz 
375533384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
375633384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
375733384421SMax Reitz     }
3758dcd04228SStefan Hajnoczi }
3759dcd04228SStefan Hajnoczi 
3760dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3761dcd04228SStefan Hajnoczi {
376253ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3763dcd04228SStefan Hajnoczi 
3764dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3765dcd04228SStefan Hajnoczi 
3766dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3767dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3768dcd04228SStefan Hajnoczi      */
3769dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3770dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3771dcd04228SStefan Hajnoczi     aio_context_release(new_context);
377285d126f3SStefan Hajnoczi }
3773d616b224SStefan Hajnoczi 
377433384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
377533384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
377633384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
377733384421SMax Reitz {
377833384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
377933384421SMax Reitz     *ban = (BdrvAioNotifier){
378033384421SMax Reitz         .attached_aio_context = attached_aio_context,
378133384421SMax Reitz         .detach_aio_context   = detach_aio_context,
378233384421SMax Reitz         .opaque               = opaque
378333384421SMax Reitz     };
378433384421SMax Reitz 
378533384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
378633384421SMax Reitz }
378733384421SMax Reitz 
378833384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
378933384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
379033384421SMax Reitz                                                                    void *),
379133384421SMax Reitz                                       void (*detach_aio_context)(void *),
379233384421SMax Reitz                                       void *opaque)
379333384421SMax Reitz {
379433384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
379533384421SMax Reitz 
379633384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
379733384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
379833384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
379933384421SMax Reitz             ban->opaque               == opaque)
380033384421SMax Reitz         {
380133384421SMax Reitz             QLIST_REMOVE(ban, list);
380233384421SMax Reitz             g_free(ban);
380333384421SMax Reitz 
380433384421SMax Reitz             return;
380533384421SMax Reitz         }
380633384421SMax Reitz     }
380733384421SMax Reitz 
380833384421SMax Reitz     abort();
380933384421SMax Reitz }
381033384421SMax Reitz 
381177485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
381277485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
38136f176b48SMax Reitz {
3814c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
38156f176b48SMax Reitz         return -ENOTSUP;
38166f176b48SMax Reitz     }
381777485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
38186f176b48SMax Reitz }
3819f6186f49SBenoît Canet 
3820b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3821b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3822b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3823b5042a36SBenoît Canet  * node graph.
3824212a5a8fSBenoît Canet  */
3825212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3826212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3827f6186f49SBenoît Canet {
3828b5042a36SBenoît Canet     /* return false if basic checks fails */
3829b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3830b5042a36SBenoît Canet         return false;
3831b5042a36SBenoît Canet     }
3832b5042a36SBenoît Canet 
3833b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3834b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3835b5042a36SBenoît Canet      */
3836b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3837b5042a36SBenoît Canet         return bs == candidate;
3838b5042a36SBenoît Canet     }
3839b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3840b5042a36SBenoît Canet 
3841b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3842b5042a36SBenoît Canet      * the node graph.
3843b5042a36SBenoît Canet      */
3844b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3845212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3846212a5a8fSBenoît Canet     }
3847212a5a8fSBenoît Canet 
3848b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3849b5042a36SBenoît Canet      */
3850b5042a36SBenoît Canet     return false;
3851212a5a8fSBenoît Canet }
3852212a5a8fSBenoît Canet 
3853212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3854212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3855212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3856212a5a8fSBenoît Canet  */
3857212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3858212a5a8fSBenoît Canet {
3859212a5a8fSBenoît Canet     BlockDriverState *bs;
3860212a5a8fSBenoît Canet 
3861212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
3862212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3863212a5a8fSBenoît Canet         bool perm;
3864212a5a8fSBenoît Canet 
3865b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3866e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3867212a5a8fSBenoît Canet 
3868212a5a8fSBenoît Canet         /* candidate is the first non filter */
3869212a5a8fSBenoît Canet         if (perm) {
3870212a5a8fSBenoît Canet             return true;
3871212a5a8fSBenoît Canet         }
3872212a5a8fSBenoît Canet     }
3873212a5a8fSBenoît Canet 
3874212a5a8fSBenoît Canet     return false;
3875f6186f49SBenoît Canet }
387609158f00SBenoît Canet 
3877e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3878e12f3784SWen Congyang                                         const char *node_name, Error **errp)
387909158f00SBenoît Canet {
388009158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38815a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38825a7e7a0bSStefan Hajnoczi 
388309158f00SBenoît Canet     if (!to_replace_bs) {
388409158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
388509158f00SBenoît Canet         return NULL;
388609158f00SBenoît Canet     }
388709158f00SBenoît Canet 
38885a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38895a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38905a7e7a0bSStefan Hajnoczi 
389109158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38925a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38935a7e7a0bSStefan Hajnoczi         goto out;
389409158f00SBenoît Canet     }
389509158f00SBenoît Canet 
389609158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
389709158f00SBenoît Canet      * most non filter in order to prevent data corruption.
389809158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
389909158f00SBenoît Canet      * blocked by the backing blockers.
390009158f00SBenoît Canet      */
3901e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
390209158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
39035a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
39045a7e7a0bSStefan Hajnoczi         goto out;
390509158f00SBenoît Canet     }
390609158f00SBenoît Canet 
39075a7e7a0bSStefan Hajnoczi out:
39085a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
390909158f00SBenoît Canet     return to_replace_bs;
391009158f00SBenoît Canet }
3911448ad91dSMing Lei 
391291af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
391391af7014SMax Reitz {
391491af7014SMax Reitz     const QDictEntry *entry;
391591af7014SMax Reitz     bool found_any = false;
391691af7014SMax Reitz 
391791af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
391891af7014SMax Reitz          entry = qdict_next(bs->options, entry))
391991af7014SMax Reitz     {
392091af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
392191af7014SMax Reitz          * options */
392291af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
392391af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
392491af7014SMax Reitz         {
392591af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
392691af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
392791af7014SMax Reitz             found_any = true;
392891af7014SMax Reitz         }
392991af7014SMax Reitz     }
393091af7014SMax Reitz 
393191af7014SMax Reitz     return found_any;
393291af7014SMax Reitz }
393391af7014SMax Reitz 
393491af7014SMax Reitz /* Updates the following BDS fields:
393591af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
393691af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
393791af7014SMax Reitz  *                    other options; so reading and writing must return the same
393891af7014SMax Reitz  *                    results, but caching etc. may be different)
393991af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
394091af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
394191af7014SMax Reitz  *                       equalling the given one
394291af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
394391af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
394491af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
394591af7014SMax Reitz  */
394691af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
394791af7014SMax Reitz {
394891af7014SMax Reitz     BlockDriver *drv = bs->drv;
394991af7014SMax Reitz     QDict *opts;
395091af7014SMax Reitz 
395191af7014SMax Reitz     if (!drv) {
395291af7014SMax Reitz         return;
395391af7014SMax Reitz     }
395491af7014SMax Reitz 
395591af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
395691af7014SMax Reitz      * refresh that first */
395791af7014SMax Reitz     if (bs->file) {
39589a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
395991af7014SMax Reitz     }
396091af7014SMax Reitz 
396191af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
396291af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
396391af7014SMax Reitz          * information before refreshing it */
396491af7014SMax Reitz         bs->exact_filename[0] = '\0';
396591af7014SMax Reitz         if (bs->full_open_options) {
396691af7014SMax Reitz             QDECREF(bs->full_open_options);
396791af7014SMax Reitz             bs->full_open_options = NULL;
396891af7014SMax Reitz         }
396991af7014SMax Reitz 
397091af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
397191af7014SMax Reitz     } else if (bs->file) {
397291af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
397391af7014SMax Reitz         bool has_open_options;
397491af7014SMax Reitz 
397591af7014SMax Reitz         bs->exact_filename[0] = '\0';
397691af7014SMax Reitz         if (bs->full_open_options) {
397791af7014SMax Reitz             QDECREF(bs->full_open_options);
397891af7014SMax Reitz             bs->full_open_options = NULL;
397991af7014SMax Reitz         }
398091af7014SMax Reitz 
398191af7014SMax Reitz         opts = qdict_new();
398291af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
398391af7014SMax Reitz 
398491af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
398591af7014SMax Reitz          * the underlying file should suffice for this one as well */
39869a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
39879a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
398891af7014SMax Reitz         }
398991af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
399091af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
399191af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
399291af7014SMax Reitz          * contain a representation of the filename, therefore the following
399391af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
39949a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
399591af7014SMax Reitz             qdict_put_obj(opts, "driver",
399691af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
39979a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
39989a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
39999a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
400091af7014SMax Reitz 
400191af7014SMax Reitz             bs->full_open_options = opts;
400291af7014SMax Reitz         } else {
400391af7014SMax Reitz             QDECREF(opts);
400491af7014SMax Reitz         }
400591af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
400691af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
400791af7014SMax Reitz          * so the full options QDict should be equal to the options given
400891af7014SMax Reitz          * specifically for this block device when it was opened (plus the
400991af7014SMax Reitz          * driver specification).
401091af7014SMax Reitz          * Because those options don't change, there is no need to update
401191af7014SMax Reitz          * full_open_options when it's already set. */
401291af7014SMax Reitz 
401391af7014SMax Reitz         opts = qdict_new();
401491af7014SMax Reitz         append_open_options(opts, bs);
401591af7014SMax Reitz         qdict_put_obj(opts, "driver",
401691af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
401791af7014SMax Reitz 
401891af7014SMax Reitz         if (bs->exact_filename[0]) {
401991af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
402091af7014SMax Reitz              * require this filename to be parsed), but we have to find some
402191af7014SMax Reitz              * default solution here, so just include it. If some block driver
402291af7014SMax Reitz              * does not support pure options without any filename at all or
402391af7014SMax Reitz              * needs some special format of the options QDict, it needs to
402491af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
402591af7014SMax Reitz              */
402691af7014SMax Reitz             qdict_put_obj(opts, "filename",
402791af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
402891af7014SMax Reitz         }
402991af7014SMax Reitz 
403091af7014SMax Reitz         bs->full_open_options = opts;
403191af7014SMax Reitz     }
403291af7014SMax Reitz 
403391af7014SMax Reitz     if (bs->exact_filename[0]) {
403491af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
403591af7014SMax Reitz     } else if (bs->full_open_options) {
403691af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
403791af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
403891af7014SMax Reitz                  qstring_get_str(json));
403991af7014SMax Reitz         QDECREF(json);
404091af7014SMax Reitz     }
404191af7014SMax Reitz }
4042