xref: /openbmc/qemu/block.c (revision 15489c769b9a4b3bec5b5848af2960689d7b4bd8)
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"
36737e150eSPaolo Bonzini #include "block/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 
761b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
771b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
787ee930d0Sblueswir1 
79dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
80dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
81dc364f4cSBenoît Canet 
828a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
838a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
84ea2384d3Sbellard 
85f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
86f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
87f3930ed0SKevin Wolf                              BlockDriverState *parent,
88ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
89f3930ed0SKevin Wolf 
90ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs);
91eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
92eb852011SMarkus Armbruster static int use_bdrv_whitelist;
93eb852011SMarkus Armbruster 
949e0b22f4SStefan Hajnoczi #ifdef _WIN32
959e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
969e0b22f4SStefan Hajnoczi {
979e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
989e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
999e0b22f4SStefan Hajnoczi             filename[1] == ':');
1009e0b22f4SStefan Hajnoczi }
1019e0b22f4SStefan Hajnoczi 
1029e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1039e0b22f4SStefan Hajnoczi {
1049e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1059e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1069e0b22f4SStefan Hajnoczi         return 1;
1079e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1089e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1099e0b22f4SStefan Hajnoczi         return 1;
1109e0b22f4SStefan Hajnoczi     return 0;
1119e0b22f4SStefan Hajnoczi }
1129e0b22f4SStefan Hajnoczi #endif
1139e0b22f4SStefan Hajnoczi 
114339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
115339064d5SKevin Wolf {
116339064d5SKevin Wolf     if (!bs || !bs->drv) {
117459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
118459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
119339064d5SKevin Wolf     }
120339064d5SKevin Wolf 
121339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
122339064d5SKevin Wolf }
123339064d5SKevin Wolf 
1244196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1254196d2f0SDenis V. Lunev {
1264196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
127459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
128459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1294196d2f0SDenis V. Lunev     }
1304196d2f0SDenis V. Lunev 
1314196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1324196d2f0SDenis V. Lunev }
1334196d2f0SDenis V. Lunev 
1349e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1355c98415bSMax Reitz int path_has_protocol(const char *path)
1369e0b22f4SStefan Hajnoczi {
137947995c0SPaolo Bonzini     const char *p;
138947995c0SPaolo Bonzini 
1399e0b22f4SStefan Hajnoczi #ifdef _WIN32
1409e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1419e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1429e0b22f4SStefan Hajnoczi         return 0;
1439e0b22f4SStefan Hajnoczi     }
144947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
145947995c0SPaolo Bonzini #else
146947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1479e0b22f4SStefan Hajnoczi #endif
1489e0b22f4SStefan Hajnoczi 
149947995c0SPaolo Bonzini     return *p == ':';
1509e0b22f4SStefan Hajnoczi }
1519e0b22f4SStefan Hajnoczi 
15283f64091Sbellard int path_is_absolute(const char *path)
15383f64091Sbellard {
15421664424Sbellard #ifdef _WIN32
15521664424Sbellard     /* specific case for names like: "\\.\d:" */
156f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
15721664424Sbellard         return 1;
158f53f4da9SPaolo Bonzini     }
159f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1603b9f94e1Sbellard #else
161f53f4da9SPaolo Bonzini     return (*path == '/');
1623b9f94e1Sbellard #endif
16383f64091Sbellard }
16483f64091Sbellard 
16583f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
16683f64091Sbellard    path to it by considering it is relative to base_path. URL are
16783f64091Sbellard    supported. */
16883f64091Sbellard void path_combine(char *dest, int dest_size,
16983f64091Sbellard                   const char *base_path,
17083f64091Sbellard                   const char *filename)
17183f64091Sbellard {
17283f64091Sbellard     const char *p, *p1;
17383f64091Sbellard     int len;
17483f64091Sbellard 
17583f64091Sbellard     if (dest_size <= 0)
17683f64091Sbellard         return;
17783f64091Sbellard     if (path_is_absolute(filename)) {
17883f64091Sbellard         pstrcpy(dest, dest_size, filename);
17983f64091Sbellard     } else {
18083f64091Sbellard         p = strchr(base_path, ':');
18183f64091Sbellard         if (p)
18283f64091Sbellard             p++;
18383f64091Sbellard         else
18483f64091Sbellard             p = base_path;
1853b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1863b9f94e1Sbellard #ifdef _WIN32
1873b9f94e1Sbellard         {
1883b9f94e1Sbellard             const char *p2;
1893b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1903b9f94e1Sbellard             if (!p1 || p2 > p1)
1913b9f94e1Sbellard                 p1 = p2;
1923b9f94e1Sbellard         }
1933b9f94e1Sbellard #endif
19483f64091Sbellard         if (p1)
19583f64091Sbellard             p1++;
19683f64091Sbellard         else
19783f64091Sbellard             p1 = base_path;
19883f64091Sbellard         if (p1 > p)
19983f64091Sbellard             p = p1;
20083f64091Sbellard         len = p - base_path;
20183f64091Sbellard         if (len > dest_size - 1)
20283f64091Sbellard             len = dest_size - 1;
20383f64091Sbellard         memcpy(dest, base_path, len);
20483f64091Sbellard         dest[len] = '\0';
20583f64091Sbellard         pstrcat(dest, dest_size, filename);
20683f64091Sbellard     }
20783f64091Sbellard }
20883f64091Sbellard 
2090a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
2100a82855aSMax Reitz                                                   const char *backing,
2119f07429eSMax Reitz                                                   char *dest, size_t sz,
2129f07429eSMax Reitz                                                   Error **errp)
2130a82855aSMax Reitz {
2149f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2159f07429eSMax Reitz         path_is_absolute(backing))
2169f07429eSMax Reitz     {
2170a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2189f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2199f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2209f07429eSMax Reitz                    backed);
2210a82855aSMax Reitz     } else {
2220a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2230a82855aSMax Reitz     }
2240a82855aSMax Reitz }
2250a82855aSMax Reitz 
2269f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2279f07429eSMax Reitz                                     Error **errp)
228dc5a1371SPaolo Bonzini {
2299f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2309f07429eSMax Reitz 
2319f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2329f07429eSMax Reitz                                                  dest, sz, errp);
233dc5a1371SPaolo Bonzini }
234dc5a1371SPaolo Bonzini 
2350eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2360eb7217eSStefan Hajnoczi {
2370eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
238b2e12bc6SChristoph Hellwig 
2398a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
240ea2384d3Sbellard }
241b338082bSbellard 
2427f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
243fc01f7e7Sbellard {
2447f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
245e4e9986bSMarkus Armbruster 
246e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
247e4e9986bSMarkus Armbruster     return bs;
248e4e9986bSMarkus Armbruster }
249e4e9986bSMarkus Armbruster 
250e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
251e4e9986bSMarkus Armbruster {
252e4e9986bSMarkus Armbruster     BlockDriverState *bs;
253e4e9986bSMarkus Armbruster     int i;
254e4e9986bSMarkus Armbruster 
2555839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
256e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
257fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
258fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
259fbe40ff7SFam Zheng     }
26028a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
261d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
262d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
263cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
264cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2659fcb0251SFam Zheng     bs->refcnt = 1;
266dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
267d7d512f6SPaolo Bonzini 
268b338082bSbellard     return bs;
269b338082bSbellard }
270b338082bSbellard 
271d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
272d7d512f6SPaolo Bonzini {
273d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
274d7d512f6SPaolo Bonzini }
275d7d512f6SPaolo Bonzini 
276ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
277ea2384d3Sbellard {
278ea2384d3Sbellard     BlockDriver *drv1;
2798a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2808a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
281ea2384d3Sbellard             return drv1;
282ea2384d3Sbellard         }
2838a22f02aSStefan Hajnoczi     }
284ea2384d3Sbellard     return NULL;
285ea2384d3Sbellard }
286ea2384d3Sbellard 
287b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
288eb852011SMarkus Armbruster {
289b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
290b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
291b64ec4e4SFam Zheng     };
292b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
293b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
294eb852011SMarkus Armbruster     };
295eb852011SMarkus Armbruster     const char **p;
296eb852011SMarkus Armbruster 
297b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
298eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
299b64ec4e4SFam Zheng     }
300eb852011SMarkus Armbruster 
301b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
302eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
303eb852011SMarkus Armbruster             return 1;
304eb852011SMarkus Armbruster         }
305eb852011SMarkus Armbruster     }
306b64ec4e4SFam Zheng     if (read_only) {
307b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
308b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
309b64ec4e4SFam Zheng                 return 1;
310b64ec4e4SFam Zheng             }
311b64ec4e4SFam Zheng         }
312b64ec4e4SFam Zheng     }
313eb852011SMarkus Armbruster     return 0;
314eb852011SMarkus Armbruster }
315eb852011SMarkus Armbruster 
3165b7e1542SZhi Yong Wu typedef struct CreateCo {
3175b7e1542SZhi Yong Wu     BlockDriver *drv;
3185b7e1542SZhi Yong Wu     char *filename;
31983d0521aSChunyan Liu     QemuOpts *opts;
3205b7e1542SZhi Yong Wu     int ret;
321cc84d90fSMax Reitz     Error *err;
3225b7e1542SZhi Yong Wu } CreateCo;
3235b7e1542SZhi Yong Wu 
3245b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3255b7e1542SZhi Yong Wu {
326cc84d90fSMax Reitz     Error *local_err = NULL;
327cc84d90fSMax Reitz     int ret;
328cc84d90fSMax Reitz 
3295b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3305b7e1542SZhi Yong Wu     assert(cco->drv);
3315b7e1542SZhi Yong Wu 
332c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
33384d18f06SMarkus Armbruster     if (local_err) {
334cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
335cc84d90fSMax Reitz     }
336cc84d90fSMax Reitz     cco->ret = ret;
3375b7e1542SZhi Yong Wu }
3385b7e1542SZhi Yong Wu 
3390e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
34083d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
341ea2384d3Sbellard {
3425b7e1542SZhi Yong Wu     int ret;
3430e7e1989SKevin Wolf 
3445b7e1542SZhi Yong Wu     Coroutine *co;
3455b7e1542SZhi Yong Wu     CreateCo cco = {
3465b7e1542SZhi Yong Wu         .drv = drv,
3475b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
34883d0521aSChunyan Liu         .opts = opts,
3495b7e1542SZhi Yong Wu         .ret = NOT_DONE,
350cc84d90fSMax Reitz         .err = NULL,
3515b7e1542SZhi Yong Wu     };
3525b7e1542SZhi Yong Wu 
353c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
354cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35580168bffSLuiz Capitulino         ret = -ENOTSUP;
35680168bffSLuiz Capitulino         goto out;
3575b7e1542SZhi Yong Wu     }
3585b7e1542SZhi Yong Wu 
3595b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3605b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3615b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3625b7e1542SZhi Yong Wu     } else {
3635b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3645b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3655b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
366b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3675b7e1542SZhi Yong Wu         }
3685b7e1542SZhi Yong Wu     }
3695b7e1542SZhi Yong Wu 
3705b7e1542SZhi Yong Wu     ret = cco.ret;
371cc84d90fSMax Reitz     if (ret < 0) {
37284d18f06SMarkus Armbruster         if (cco.err) {
373cc84d90fSMax Reitz             error_propagate(errp, cco.err);
374cc84d90fSMax Reitz         } else {
375cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
376cc84d90fSMax Reitz         }
377cc84d90fSMax Reitz     }
3785b7e1542SZhi Yong Wu 
37980168bffSLuiz Capitulino out:
38080168bffSLuiz Capitulino     g_free(cco.filename);
3815b7e1542SZhi Yong Wu     return ret;
382ea2384d3Sbellard }
383ea2384d3Sbellard 
384c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38584a12e66SChristoph Hellwig {
38684a12e66SChristoph Hellwig     BlockDriver *drv;
387cc84d90fSMax Reitz     Error *local_err = NULL;
388cc84d90fSMax Reitz     int ret;
38984a12e66SChristoph Hellwig 
390b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
39184a12e66SChristoph Hellwig     if (drv == NULL) {
39216905d71SStefan Hajnoczi         return -ENOENT;
39384a12e66SChristoph Hellwig     }
39484a12e66SChristoph Hellwig 
395c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
39684d18f06SMarkus Armbruster     if (local_err) {
397cc84d90fSMax Reitz         error_propagate(errp, local_err);
398cc84d90fSMax Reitz     }
399cc84d90fSMax Reitz     return ret;
40084a12e66SChristoph Hellwig }
40184a12e66SChristoph Hellwig 
402892b7de8SEkaterina Tumanova /**
403892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
404892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
405892b7de8SEkaterina Tumanova  * On failure return -errno.
406892b7de8SEkaterina Tumanova  * @bs must not be empty.
407892b7de8SEkaterina Tumanova  */
408892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
409892b7de8SEkaterina Tumanova {
410892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
411892b7de8SEkaterina Tumanova 
412892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
413892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
414892b7de8SEkaterina Tumanova     }
415892b7de8SEkaterina Tumanova 
416892b7de8SEkaterina Tumanova     return -ENOTSUP;
417892b7de8SEkaterina Tumanova }
418892b7de8SEkaterina Tumanova 
419892b7de8SEkaterina Tumanova /**
420892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
421892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
422892b7de8SEkaterina Tumanova  * On failure return -errno.
423892b7de8SEkaterina Tumanova  * @bs must not be empty.
424892b7de8SEkaterina Tumanova  */
425892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
426892b7de8SEkaterina Tumanova {
427892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
428892b7de8SEkaterina Tumanova 
429892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
430892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
431892b7de8SEkaterina Tumanova     }
432892b7de8SEkaterina Tumanova 
433892b7de8SEkaterina Tumanova     return -ENOTSUP;
434892b7de8SEkaterina Tumanova }
435892b7de8SEkaterina Tumanova 
436eba25057SJim Meyering /*
437eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
438eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
439eba25057SJim Meyering  */
440eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
441eba25057SJim Meyering {
442d5249393Sbellard #ifdef _WIN32
4433b9f94e1Sbellard     char temp_dir[MAX_PATH];
444eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
445eba25057SJim Meyering        have length MAX_PATH or greater.  */
446eba25057SJim Meyering     assert(size >= MAX_PATH);
447eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
448eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
449eba25057SJim Meyering             ? 0 : -GetLastError());
450d5249393Sbellard #else
451ea2384d3Sbellard     int fd;
4527ccfb2ebSblueswir1     const char *tmpdir;
4530badc1eeSaurel32     tmpdir = getenv("TMPDIR");
45469bef793SAmit Shah     if (!tmpdir) {
45569bef793SAmit Shah         tmpdir = "/var/tmp";
45669bef793SAmit Shah     }
457eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
458eba25057SJim Meyering         return -EOVERFLOW;
459ea2384d3Sbellard     }
460eba25057SJim Meyering     fd = mkstemp(filename);
461fe235a06SDunrong Huang     if (fd < 0) {
462fe235a06SDunrong Huang         return -errno;
463fe235a06SDunrong Huang     }
464fe235a06SDunrong Huang     if (close(fd) != 0) {
465fe235a06SDunrong Huang         unlink(filename);
466eba25057SJim Meyering         return -errno;
467eba25057SJim Meyering     }
468eba25057SJim Meyering     return 0;
469d5249393Sbellard #endif
470eba25057SJim Meyering }
471ea2384d3Sbellard 
472f3a5d3f8SChristoph Hellwig /*
473f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
474f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
475f3a5d3f8SChristoph Hellwig  */
476f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
477f3a5d3f8SChristoph Hellwig {
478508c7cb3SChristoph Hellwig     int score_max = 0, score;
479508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
480f3a5d3f8SChristoph Hellwig 
4818a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
482508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
483508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
484508c7cb3SChristoph Hellwig             if (score > score_max) {
485508c7cb3SChristoph Hellwig                 score_max = score;
486508c7cb3SChristoph Hellwig                 drv = d;
487f3a5d3f8SChristoph Hellwig             }
488508c7cb3SChristoph Hellwig         }
489f3a5d3f8SChristoph Hellwig     }
490f3a5d3f8SChristoph Hellwig 
491508c7cb3SChristoph Hellwig     return drv;
492f3a5d3f8SChristoph Hellwig }
493f3a5d3f8SChristoph Hellwig 
49498289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
495b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
496b65a5e12SMax Reitz                                 Error **errp)
49784a12e66SChristoph Hellwig {
49884a12e66SChristoph Hellwig     BlockDriver *drv1;
49984a12e66SChristoph Hellwig     char protocol[128];
50084a12e66SChristoph Hellwig     int len;
50184a12e66SChristoph Hellwig     const char *p;
50284a12e66SChristoph Hellwig 
50366f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
50466f82ceeSKevin Wolf 
50539508e7aSChristoph Hellwig     /*
50639508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
50739508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
50839508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
50939508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
51039508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
51139508e7aSChristoph Hellwig      */
51284a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
51339508e7aSChristoph Hellwig     if (drv1) {
51484a12e66SChristoph Hellwig         return drv1;
51584a12e66SChristoph Hellwig     }
51639508e7aSChristoph Hellwig 
51798289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
518ef810437SMax Reitz         return &bdrv_file;
51939508e7aSChristoph Hellwig     }
52098289620SKevin Wolf 
5219e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5229e0b22f4SStefan Hajnoczi     assert(p != NULL);
52384a12e66SChristoph Hellwig     len = p - filename;
52484a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
52584a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
52684a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
52784a12e66SChristoph Hellwig     protocol[len] = '\0';
52884a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
52984a12e66SChristoph Hellwig         if (drv1->protocol_name &&
53084a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
53184a12e66SChristoph Hellwig             return drv1;
53284a12e66SChristoph Hellwig         }
53384a12e66SChristoph Hellwig     }
534b65a5e12SMax Reitz 
535b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
53684a12e66SChristoph Hellwig     return NULL;
53784a12e66SChristoph Hellwig }
53884a12e66SChristoph Hellwig 
539c6684249SMarkus Armbruster /*
540c6684249SMarkus Armbruster  * Guess image format by probing its contents.
541c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
542c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
543c6684249SMarkus Armbruster  *
544c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5457cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5467cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
547c6684249SMarkus Armbruster  * @filename    is its filename.
548c6684249SMarkus Armbruster  *
549c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
550c6684249SMarkus Armbruster  * probing score.
551c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
552c6684249SMarkus Armbruster  */
55338f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
554c6684249SMarkus Armbruster                             const char *filename)
555c6684249SMarkus Armbruster {
556c6684249SMarkus Armbruster     int score_max = 0, score;
557c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
558c6684249SMarkus Armbruster 
559c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
560c6684249SMarkus Armbruster         if (d->bdrv_probe) {
561c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
562c6684249SMarkus Armbruster             if (score > score_max) {
563c6684249SMarkus Armbruster                 score_max = score;
564c6684249SMarkus Armbruster                 drv = d;
565c6684249SMarkus Armbruster             }
566c6684249SMarkus Armbruster         }
567c6684249SMarkus Armbruster     }
568c6684249SMarkus Armbruster 
569c6684249SMarkus Armbruster     return drv;
570c6684249SMarkus Armbruster }
571c6684249SMarkus Armbruster 
572f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
57334b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
574ea2384d3Sbellard {
575c6684249SMarkus Armbruster     BlockDriver *drv;
5767cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
577f500a6d3SKevin Wolf     int ret = 0;
578f8ea0b00SNicholas Bellinger 
57908a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
580b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
581ef810437SMax Reitz         *pdrv = &bdrv_raw;
582c98ac35dSStefan Weil         return ret;
5831a396859SNicholas A. Bellinger     }
584f8ea0b00SNicholas Bellinger 
58583f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
586ea2384d3Sbellard     if (ret < 0) {
58734b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
58834b5d2c6SMax Reitz                          "format");
589c98ac35dSStefan Weil         *pdrv = NULL;
590c98ac35dSStefan Weil         return ret;
591ea2384d3Sbellard     }
592ea2384d3Sbellard 
593c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
594c98ac35dSStefan Weil     if (!drv) {
59534b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
59634b5d2c6SMax Reitz                    "driver found");
597c98ac35dSStefan Weil         ret = -ENOENT;
598c98ac35dSStefan Weil     }
599c98ac35dSStefan Weil     *pdrv = drv;
600c98ac35dSStefan Weil     return ret;
601ea2384d3Sbellard }
602ea2384d3Sbellard 
60351762288SStefan Hajnoczi /**
60451762288SStefan Hajnoczi  * Set the current 'total_sectors' value
60565a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
60651762288SStefan Hajnoczi  */
60751762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
60851762288SStefan Hajnoczi {
60951762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
61051762288SStefan Hajnoczi 
611396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
612b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
613396759adSNicholas Bellinger         return 0;
614396759adSNicholas Bellinger 
61551762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
61651762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
61751762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
61851762288SStefan Hajnoczi         if (length < 0) {
61951762288SStefan Hajnoczi             return length;
62051762288SStefan Hajnoczi         }
6217e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
62251762288SStefan Hajnoczi     }
62351762288SStefan Hajnoczi 
62451762288SStefan Hajnoczi     bs->total_sectors = hint;
62551762288SStefan Hajnoczi     return 0;
62651762288SStefan Hajnoczi }
62751762288SStefan Hajnoczi 
628c3993cdcSStefan Hajnoczi /**
6299e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6309e8f1835SPaolo Bonzini  *
6319e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6329e8f1835SPaolo Bonzini  */
6339e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6349e8f1835SPaolo Bonzini {
6359e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6369e8f1835SPaolo Bonzini 
6379e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6389e8f1835SPaolo Bonzini         /* do nothing */
6399e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6409e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6419e8f1835SPaolo Bonzini     } else {
6429e8f1835SPaolo Bonzini         return -1;
6439e8f1835SPaolo Bonzini     }
6449e8f1835SPaolo Bonzini 
6459e8f1835SPaolo Bonzini     return 0;
6469e8f1835SPaolo Bonzini }
6479e8f1835SPaolo Bonzini 
6489e8f1835SPaolo Bonzini /**
649c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
650c3993cdcSStefan Hajnoczi  *
651c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
652c3993cdcSStefan Hajnoczi  */
653c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
654c3993cdcSStefan Hajnoczi {
655c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
656c3993cdcSStefan Hajnoczi 
657c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
658c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
65992196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
66092196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
661c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
662c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
663c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
664c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
665c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
666c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
667c3993cdcSStefan Hajnoczi         /* this is the default */
668c3993cdcSStefan Hajnoczi     } else {
669c3993cdcSStefan Hajnoczi         return -1;
670c3993cdcSStefan Hajnoczi     }
671c3993cdcSStefan Hajnoczi 
672c3993cdcSStefan Hajnoczi     return 0;
673c3993cdcSStefan Hajnoczi }
674c3993cdcSStefan Hajnoczi 
6750b50cc88SKevin Wolf /*
676b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
677b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
678b1e6fc08SKevin Wolf  * like a backing file)
679b1e6fc08SKevin Wolf  */
680b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
681b1e6fc08SKevin Wolf {
682b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
683b1e6fc08SKevin Wolf }
684b1e6fc08SKevin Wolf 
685b1e6fc08SKevin Wolf /*
686f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if a protocol driver is expected,
687f3930ed0SKevin Wolf  * based on the given flags for the parent BDS
6880b50cc88SKevin Wolf  */
6890b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
6900b50cc88SKevin Wolf {
6910b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6920b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
6930b50cc88SKevin Wolf 
6940b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
6950b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
6960b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
6970b50cc88SKevin Wolf 
6980b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
6995669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
7000b50cc88SKevin Wolf 
7010b50cc88SKevin Wolf     return flags;
7020b50cc88SKevin Wolf }
7030b50cc88SKevin Wolf 
704f3930ed0SKevin Wolf const BdrvChildRole child_file = {
705f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_flags,
706f3930ed0SKevin Wolf };
707f3930ed0SKevin Wolf 
708f3930ed0SKevin Wolf /*
709f3930ed0SKevin Wolf  * Returns the flags that bs->file should get if the use of formats (and not
710f3930ed0SKevin Wolf  * only protocols) is permitted for it, based on the given flags for the parent
711f3930ed0SKevin Wolf  * BDS
712f3930ed0SKevin Wolf  */
713f3930ed0SKevin Wolf static int bdrv_inherited_fmt_flags(int parent_flags)
714f3930ed0SKevin Wolf {
715f3930ed0SKevin Wolf     int flags = child_file.inherit_flags(parent_flags);
716f3930ed0SKevin Wolf     return flags & ~BDRV_O_PROTOCOL;
717f3930ed0SKevin Wolf }
718f3930ed0SKevin Wolf 
719f3930ed0SKevin Wolf const BdrvChildRole child_format = {
720f3930ed0SKevin Wolf     .inherit_flags = bdrv_inherited_fmt_flags,
721f3930ed0SKevin Wolf };
722f3930ed0SKevin Wolf 
723317fc44eSKevin Wolf /*
724760e0063SKevin Wolf  * Returns the flags that bs->backing should get, based on the given flags
725317fc44eSKevin Wolf  * for the parent BDS
726317fc44eSKevin Wolf  */
727317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
728317fc44eSKevin Wolf {
729317fc44eSKevin Wolf     /* backing files always opened read-only */
730317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
731317fc44eSKevin Wolf 
732317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7338bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
734317fc44eSKevin Wolf 
735317fc44eSKevin Wolf     return flags;
736317fc44eSKevin Wolf }
737317fc44eSKevin Wolf 
738f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
739f3930ed0SKevin Wolf     .inherit_flags = bdrv_backing_flags,
740f3930ed0SKevin Wolf };
741f3930ed0SKevin Wolf 
7427b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7437b272452SKevin Wolf {
7447b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7457b272452SKevin Wolf 
7467b272452SKevin Wolf     /*
7477b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7487b272452SKevin Wolf      * image.
7497b272452SKevin Wolf      */
75020cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7517b272452SKevin Wolf 
7527b272452SKevin Wolf     /*
7537b272452SKevin Wolf      * Snapshots should be writable.
7547b272452SKevin Wolf      */
7558bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7567b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7577b272452SKevin Wolf     }
7587b272452SKevin Wolf 
7597b272452SKevin Wolf     return open_flags;
7607b272452SKevin Wolf }
7617b272452SKevin Wolf 
762636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
7636913c0c2SBenoît Canet                                   const char *node_name,
7646913c0c2SBenoît Canet                                   Error **errp)
7656913c0c2SBenoît Canet {
766*15489c76SJeff Cody     char *gen_node_name = NULL;
7676913c0c2SBenoît Canet 
768*15489c76SJeff Cody     if (!node_name) {
769*15489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
770*15489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
771*15489c76SJeff Cody         /*
772*15489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
773*15489c76SJeff Cody          * generated (generated names use characters not available to the user)
774*15489c76SJeff Cody          */
7759aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
776636ea370SKevin Wolf         return;
7776913c0c2SBenoît Canet     }
7786913c0c2SBenoît Canet 
7790c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
7807f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
7810c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
7820c5e94eeSBenoît Canet                    node_name);
783*15489c76SJeff Cody         goto out;
7840c5e94eeSBenoît Canet     }
7850c5e94eeSBenoît Canet 
7866913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
7876913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
7886913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
789*15489c76SJeff Cody         goto out;
7906913c0c2SBenoît Canet     }
7916913c0c2SBenoît Canet 
7926913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
7936913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
7946913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
795*15489c76SJeff Cody out:
796*15489c76SJeff Cody     g_free(gen_node_name);
7976913c0c2SBenoît Canet }
7986913c0c2SBenoît Canet 
79918edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
80018edf289SKevin Wolf     .name = "bdrv_common",
80118edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
80218edf289SKevin Wolf     .desc = {
80318edf289SKevin Wolf         {
80418edf289SKevin Wolf             .name = "node-name",
80518edf289SKevin Wolf             .type = QEMU_OPT_STRING,
80618edf289SKevin Wolf             .help = "Node name of the block device node",
80718edf289SKevin Wolf         },
80818edf289SKevin Wolf         { /* end of list */ }
80918edf289SKevin Wolf     },
81018edf289SKevin Wolf };
81118edf289SKevin Wolf 
812b6ce07aaSKevin Wolf /*
81357915332SKevin Wolf  * Common part for opening disk images and files
814b6ad491aSKevin Wolf  *
815b6ad491aSKevin Wolf  * Removes all processed options from *options.
81657915332SKevin Wolf  */
8179a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
81834b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
81957915332SKevin Wolf {
82057915332SKevin Wolf     int ret, open_flags;
821035fccdfSKevin Wolf     const char *filename;
8226913c0c2SBenoît Canet     const char *node_name = NULL;
82318edf289SKevin Wolf     QemuOpts *opts;
82434b5d2c6SMax Reitz     Error *local_err = NULL;
82557915332SKevin Wolf 
82657915332SKevin Wolf     assert(drv != NULL);
8276405875cSPaolo Bonzini     assert(bs->file == NULL);
828707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
82957915332SKevin Wolf 
83045673671SKevin Wolf     if (file != NULL) {
8319a4f4c31SKevin Wolf         filename = file->bs->filename;
83245673671SKevin Wolf     } else {
83345673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
83445673671SKevin Wolf     }
83545673671SKevin Wolf 
836765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
837765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
838765003dbSKevin Wolf                    drv->format_name);
839765003dbSKevin Wolf         return -EINVAL;
840765003dbSKevin Wolf     }
841765003dbSKevin Wolf 
84245673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
84328dcee10SStefan Hajnoczi 
84418edf289SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
84518edf289SKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
84618edf289SKevin Wolf     if (local_err) {
84718edf289SKevin Wolf         error_propagate(errp, local_err);
84818edf289SKevin Wolf         ret = -EINVAL;
84918edf289SKevin Wolf         goto fail_opts;
85018edf289SKevin Wolf     }
85118edf289SKevin Wolf 
85218edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
853636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8540fb6395cSMarkus Armbruster     if (local_err) {
855636ea370SKevin Wolf         error_propagate(errp, local_err);
85618edf289SKevin Wolf         ret = -EINVAL;
85718edf289SKevin Wolf         goto fail_opts;
8585d186eb0SKevin Wolf     }
8595d186eb0SKevin Wolf 
8601b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
861c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8620d51b4deSAsias He     bs->zero_beyond_eof = true;
863b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
864b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
865b64ec4e4SFam Zheng 
866b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8678f94a6e4SKevin Wolf         error_setg(errp,
8688f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8698f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8708f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8718f94a6e4SKevin Wolf                    drv->format_name);
87218edf289SKevin Wolf         ret = -ENOTSUP;
87318edf289SKevin Wolf         goto fail_opts;
874b64ec4e4SFam Zheng     }
87557915332SKevin Wolf 
87653fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8770ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8780ebd24e0SKevin Wolf         if (!bs->read_only) {
87953fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8800ebd24e0SKevin Wolf         } else {
8810ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
88218edf289SKevin Wolf             ret = -EINVAL;
88318edf289SKevin Wolf             goto fail_opts;
8840ebd24e0SKevin Wolf         }
88553fec9d3SStefan Hajnoczi     }
88653fec9d3SStefan Hajnoczi 
887c2ad1b0cSKevin Wolf     if (filename != NULL) {
88857915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
889c2ad1b0cSKevin Wolf     } else {
890c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
891c2ad1b0cSKevin Wolf     }
89291af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
89357915332SKevin Wolf 
89457915332SKevin Wolf     bs->drv = drv;
8957267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
89657915332SKevin Wolf 
89703f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
898e7c63796SStefan Hajnoczi 
89966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
90066f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9015d186eb0SKevin Wolf         assert(file == NULL);
902030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
90334b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
904f500a6d3SKevin Wolf     } else {
9052af5ef70SKevin Wolf         if (file == NULL) {
90634b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
90734b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9082af5ef70SKevin Wolf             ret = -EINVAL;
9092af5ef70SKevin Wolf             goto free_and_fail;
9102af5ef70SKevin Wolf         }
911f500a6d3SKevin Wolf         bs->file = file;
91234b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
91366f82ceeSKevin Wolf     }
91466f82ceeSKevin Wolf 
91557915332SKevin Wolf     if (ret < 0) {
91684d18f06SMarkus Armbruster         if (local_err) {
91734b5d2c6SMax Reitz             error_propagate(errp, local_err);
9182fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9192fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
92034b5d2c6SMax Reitz         } else {
92134b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
92234b5d2c6SMax Reitz         }
92357915332SKevin Wolf         goto free_and_fail;
92457915332SKevin Wolf     }
92557915332SKevin Wolf 
926a1f688f4SMarkus Armbruster     if (bs->encrypted) {
927a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
928a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
929a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
930a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
931a1f688f4SMarkus Armbruster     }
932a1f688f4SMarkus Armbruster 
93351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
93451762288SStefan Hajnoczi     if (ret < 0) {
93534b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
93651762288SStefan Hajnoczi         goto free_and_fail;
93757915332SKevin Wolf     }
93851762288SStefan Hajnoczi 
9393baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
9403baca891SKevin Wolf     if (local_err) {
9413baca891SKevin Wolf         error_propagate(errp, local_err);
9423baca891SKevin Wolf         ret = -EINVAL;
9433baca891SKevin Wolf         goto free_and_fail;
9443baca891SKevin Wolf     }
9453baca891SKevin Wolf 
946c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9474196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
948b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
94918edf289SKevin Wolf 
95018edf289SKevin Wolf     qemu_opts_del(opts);
95157915332SKevin Wolf     return 0;
95257915332SKevin Wolf 
95357915332SKevin Wolf free_and_fail:
95466f82ceeSKevin Wolf     bs->file = NULL;
9557267c094SAnthony Liguori     g_free(bs->opaque);
95657915332SKevin Wolf     bs->opaque = NULL;
95757915332SKevin Wolf     bs->drv = NULL;
95818edf289SKevin Wolf fail_opts:
95918edf289SKevin Wolf     qemu_opts_del(opts);
96057915332SKevin Wolf     return ret;
96157915332SKevin Wolf }
96257915332SKevin Wolf 
9635e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9645e5c4f63SKevin Wolf {
9655e5c4f63SKevin Wolf     QObject *options_obj;
9665e5c4f63SKevin Wolf     QDict *options;
9675e5c4f63SKevin Wolf     int ret;
9685e5c4f63SKevin Wolf 
9695e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
9705e5c4f63SKevin Wolf     assert(ret);
9715e5c4f63SKevin Wolf 
9725e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
9735e5c4f63SKevin Wolf     if (!options_obj) {
9745e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
9755e5c4f63SKevin Wolf         return NULL;
9765e5c4f63SKevin Wolf     }
9775e5c4f63SKevin Wolf 
9785e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
9795e5c4f63SKevin Wolf         qobject_decref(options_obj);
9805e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
9815e5c4f63SKevin Wolf         return NULL;
9825e5c4f63SKevin Wolf     }
9835e5c4f63SKevin Wolf 
9845e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
9855e5c4f63SKevin Wolf     qdict_flatten(options);
9865e5c4f63SKevin Wolf 
9875e5c4f63SKevin Wolf     return options;
9885e5c4f63SKevin Wolf }
9895e5c4f63SKevin Wolf 
99057915332SKevin Wolf /*
991f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
992f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
99353a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
99453a29513SMax Reitz  * block driver has been specified explicitly.
995f54120ffSKevin Wolf  */
99653a29513SMax Reitz static int bdrv_fill_options(QDict **options, const char **pfilename,
997053e1578SMax Reitz                              int *flags, Error **errp)
998f54120ffSKevin Wolf {
9995e5c4f63SKevin Wolf     const char *filename = *pfilename;
1000f54120ffSKevin Wolf     const char *drvname;
100153a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1002f54120ffSKevin Wolf     bool parse_filename = false;
1003053e1578SMax Reitz     BlockDriver *drv = NULL;
1004f54120ffSKevin Wolf     Error *local_err = NULL;
1005f54120ffSKevin Wolf 
10065e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10075e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10085e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10095e5c4f63SKevin Wolf         if (local_err) {
10105e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10115e5c4f63SKevin Wolf             return -EINVAL;
10125e5c4f63SKevin Wolf         }
10135e5c4f63SKevin Wolf 
10145e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10155e5c4f63SKevin Wolf          * specified directly */
10165e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10175e5c4f63SKevin Wolf         QDECREF(json_options);
10185e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10195e5c4f63SKevin Wolf     }
10205e5c4f63SKevin Wolf 
102153a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1022053e1578SMax Reitz     if (drvname) {
1023053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1024053e1578SMax Reitz         if (!drv) {
1025053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1026053e1578SMax Reitz             return -ENOENT;
1027053e1578SMax Reitz         }
102853a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
102953a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1030053e1578SMax Reitz         protocol = drv->bdrv_file_open;
103153a29513SMax Reitz     }
103253a29513SMax Reitz 
103353a29513SMax Reitz     if (protocol) {
103453a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
103553a29513SMax Reitz     } else {
103653a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
103753a29513SMax Reitz     }
103853a29513SMax Reitz 
1039f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
104017b005f1SKevin Wolf     if (protocol && filename) {
1041f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1042f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1043f54120ffSKevin Wolf             parse_filename = true;
1044f54120ffSKevin Wolf         } else {
1045f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1046f54120ffSKevin Wolf                              "the same time");
1047f54120ffSKevin Wolf             return -EINVAL;
1048f54120ffSKevin Wolf         }
1049f54120ffSKevin Wolf     }
1050f54120ffSKevin Wolf 
1051f54120ffSKevin Wolf     /* Find the right block driver */
1052f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1053f54120ffSKevin Wolf 
105417b005f1SKevin Wolf     if (!drvname && protocol) {
1055f54120ffSKevin Wolf         if (filename) {
1056b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1057f54120ffSKevin Wolf             if (!drv) {
1058f54120ffSKevin Wolf                 return -EINVAL;
1059f54120ffSKevin Wolf             }
1060f54120ffSKevin Wolf 
1061f54120ffSKevin Wolf             drvname = drv->format_name;
1062f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1063f54120ffSKevin Wolf         } else {
1064f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1065f54120ffSKevin Wolf             return -EINVAL;
1066f54120ffSKevin Wolf         }
106717b005f1SKevin Wolf     }
106817b005f1SKevin Wolf 
106917b005f1SKevin Wolf     assert(drv || !protocol);
1070f54120ffSKevin Wolf 
1071f54120ffSKevin Wolf     /* Driver-specific filename parsing */
107217b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1073f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1074f54120ffSKevin Wolf         if (local_err) {
1075f54120ffSKevin Wolf             error_propagate(errp, local_err);
1076f54120ffSKevin Wolf             return -EINVAL;
1077f54120ffSKevin Wolf         }
1078f54120ffSKevin Wolf 
1079f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1080f54120ffSKevin Wolf             qdict_del(*options, "filename");
1081f54120ffSKevin Wolf         }
1082f54120ffSKevin Wolf     }
1083f54120ffSKevin Wolf 
1084f54120ffSKevin Wolf     return 0;
1085f54120ffSKevin Wolf }
1086f54120ffSKevin Wolf 
1087b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1088df581792SKevin Wolf                                     BlockDriverState *child_bs,
1089df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1090df581792SKevin Wolf {
1091df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1092df581792SKevin Wolf     *child = (BdrvChild) {
1093df581792SKevin Wolf         .bs     = child_bs,
1094df581792SKevin Wolf         .role   = child_role,
1095df581792SKevin Wolf     };
1096df581792SKevin Wolf 
1097df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1098d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1099b4b059f6SKevin Wolf 
1100b4b059f6SKevin Wolf     return child;
1101df581792SKevin Wolf }
1102df581792SKevin Wolf 
11033f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
110433a60407SKevin Wolf {
110533a60407SKevin Wolf     QLIST_REMOVE(child, next);
1106d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
110733a60407SKevin Wolf     g_free(child);
110833a60407SKevin Wolf }
110933a60407SKevin Wolf 
111033a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
111133a60407SKevin Wolf {
1112779020cbSKevin Wolf     BlockDriverState *child_bs;
1113779020cbSKevin Wolf 
1114779020cbSKevin Wolf     if (child == NULL) {
1115779020cbSKevin Wolf         return;
1116779020cbSKevin Wolf     }
111733a60407SKevin Wolf 
111833a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
111933a60407SKevin Wolf         child->bs->inherits_from = NULL;
112033a60407SKevin Wolf     }
112133a60407SKevin Wolf 
1122779020cbSKevin Wolf     child_bs = child->bs;
112333a60407SKevin Wolf     bdrv_detach_child(child);
112433a60407SKevin Wolf     bdrv_unref(child_bs);
112533a60407SKevin Wolf }
112633a60407SKevin Wolf 
11275db15a57SKevin Wolf /*
11285db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
11295db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
11305db15a57SKevin Wolf  */
11318d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11328d24cce1SFam Zheng {
11335db15a57SKevin Wolf     if (backing_hd) {
11345db15a57SKevin Wolf         bdrv_ref(backing_hd);
11355db15a57SKevin Wolf     }
11368d24cce1SFam Zheng 
1137760e0063SKevin Wolf     if (bs->backing) {
1138826b6ca0SFam Zheng         assert(bs->backing_blocker);
1139760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
11405db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1141826b6ca0SFam Zheng     } else if (backing_hd) {
1142826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
114381e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
114481e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1145826b6ca0SFam Zheng     }
1146826b6ca0SFam Zheng 
11478d24cce1SFam Zheng     if (!backing_hd) {
1148826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1149826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1150760e0063SKevin Wolf         bs->backing = NULL;
11518d24cce1SFam Zheng         goto out;
11528d24cce1SFam Zheng     }
1153760e0063SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, &child_backing);
11548d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11558d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11568d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11578d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1158826b6ca0SFam Zheng 
1159760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1160826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1161760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1162826b6ca0SFam Zheng                     bs->backing_blocker);
11638d24cce1SFam Zheng out:
11643baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11658d24cce1SFam Zheng }
11668d24cce1SFam Zheng 
116731ca6d07SKevin Wolf /*
116831ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
116931ca6d07SKevin Wolf  *
117031ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
117131ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
117231ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
117331ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
117431ca6d07SKevin Wolf  */
117534b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11769156df12SPaolo Bonzini {
11771ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1178317fc44eSKevin Wolf     int ret = 0;
11798d24cce1SFam Zheng     BlockDriverState *backing_hd;
118034b5d2c6SMax Reitz     Error *local_err = NULL;
11819156df12SPaolo Bonzini 
1182760e0063SKevin Wolf     if (bs->backing != NULL) {
118331ca6d07SKevin Wolf         QDECREF(options);
11841ba4b6a5SBenoît Canet         goto free_exit;
11859156df12SPaolo Bonzini     }
11869156df12SPaolo Bonzini 
118731ca6d07SKevin Wolf     /* NULL means an empty set of options */
118831ca6d07SKevin Wolf     if (options == NULL) {
118931ca6d07SKevin Wolf         options = qdict_new();
119031ca6d07SKevin Wolf     }
119131ca6d07SKevin Wolf 
11929156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11931cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11941cb6f506SKevin Wolf         backing_filename[0] = '\0';
11951cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
119631ca6d07SKevin Wolf         QDECREF(options);
11971ba4b6a5SBenoît Canet         goto free_exit;
1198dbecebddSFam Zheng     } else {
11999f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
12009f07429eSMax Reitz                                        &local_err);
12019f07429eSMax Reitz         if (local_err) {
12029f07429eSMax Reitz             ret = -EINVAL;
12039f07429eSMax Reitz             error_propagate(errp, local_err);
12049f07429eSMax Reitz             QDECREF(options);
12059f07429eSMax Reitz             goto free_exit;
12069f07429eSMax Reitz         }
12079156df12SPaolo Bonzini     }
12089156df12SPaolo Bonzini 
12098ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12108ee79e70SKevin Wolf         ret = -EINVAL;
12118ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12128ee79e70SKevin Wolf         QDECREF(options);
12138ee79e70SKevin Wolf         goto free_exit;
12148ee79e70SKevin Wolf     }
12158ee79e70SKevin Wolf 
1216e4e9986bSMarkus Armbruster     backing_hd = bdrv_new();
12178d24cce1SFam Zheng 
1218c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1219c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
12209156df12SPaolo Bonzini     }
12219156df12SPaolo Bonzini 
1222760e0063SKevin Wolf     assert(bs->backing == NULL);
1223f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1224f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1225ce343771SMax Reitz                             NULL, options, 0, bs, &child_backing, &local_err);
12269156df12SPaolo Bonzini     if (ret < 0) {
12278d24cce1SFam Zheng         bdrv_unref(backing_hd);
12288d24cce1SFam Zheng         backing_hd = NULL;
12299156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1230b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1231b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1232b04b6b6eSFam Zheng         error_free(local_err);
12331ba4b6a5SBenoît Canet         goto free_exit;
12349156df12SPaolo Bonzini     }
1235df581792SKevin Wolf 
12365db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
12375db15a57SKevin Wolf      * backing_hd reference now */
12388d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
12395db15a57SKevin Wolf     bdrv_unref(backing_hd);
1240d80ac658SPeter Feiner 
12411ba4b6a5SBenoît Canet free_exit:
12421ba4b6a5SBenoît Canet     g_free(backing_filename);
12431ba4b6a5SBenoît Canet     return ret;
12449156df12SPaolo Bonzini }
12459156df12SPaolo Bonzini 
1246b6ce07aaSKevin Wolf /*
1247da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1248da557aacSMax Reitz  * device's options.
1249da557aacSMax Reitz  *
1250da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1251b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1252da557aacSMax Reitz  *
1253da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1254da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1255da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1256da557aacSMax Reitz  * BlockdevRef.
1257da557aacSMax Reitz  *
1258da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1259da557aacSMax Reitz  */
1260b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1261f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1262b4b059f6SKevin Wolf                            BlockDriverState* parent,
1263b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1264f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1265da557aacSMax Reitz {
1266b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1267b4b059f6SKevin Wolf     BlockDriverState *bs;
1268da557aacSMax Reitz     QDict *image_options;
1269da557aacSMax Reitz     int ret;
1270da557aacSMax Reitz     char *bdref_key_dot;
1271da557aacSMax Reitz     const char *reference;
1272da557aacSMax Reitz 
1273df581792SKevin Wolf     assert(child_role != NULL);
1274f67503e5SMax Reitz 
1275da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1276da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1277da557aacSMax Reitz     g_free(bdref_key_dot);
1278da557aacSMax Reitz 
1279da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1280da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1281b4b059f6SKevin Wolf         if (!allow_none) {
1282da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1283da557aacSMax Reitz                        bdref_key);
1284da557aacSMax Reitz         }
1285b20e61e0SMarkus Armbruster         QDECREF(image_options);
1286da557aacSMax Reitz         goto done;
1287da557aacSMax Reitz     }
1288da557aacSMax Reitz 
1289b4b059f6SKevin Wolf     bs = NULL;
1290b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1291ce343771SMax Reitz                             parent, child_role, errp);
1292df581792SKevin Wolf     if (ret < 0) {
1293df581792SKevin Wolf         goto done;
1294df581792SKevin Wolf     }
1295df581792SKevin Wolf 
1296b4b059f6SKevin Wolf     c = bdrv_attach_child(parent, bs, child_role);
1297da557aacSMax Reitz 
1298da557aacSMax Reitz done:
1299da557aacSMax Reitz     qdict_del(options, bdref_key);
1300b4b059f6SKevin Wolf     return c;
1301b4b059f6SKevin Wolf }
1302b4b059f6SKevin Wolf 
13036b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1304b998875dSKevin Wolf {
1305b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
13061ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1307b998875dSKevin Wolf     int64_t total_size;
130883d0521aSChunyan Liu     QemuOpts *opts = NULL;
1309b998875dSKevin Wolf     QDict *snapshot_options;
1310b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1311c2e0dbbfSFam Zheng     Error *local_err = NULL;
1312b998875dSKevin Wolf     int ret;
1313b998875dSKevin Wolf 
1314b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1315b998875dSKevin Wolf        instead of opening 'filename' directly */
1316b998875dSKevin Wolf 
1317b998875dSKevin Wolf     /* Get the required size from the image */
1318f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1319f187743aSKevin Wolf     if (total_size < 0) {
13206b8aeca5SChen Gang         ret = total_size;
1321f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13221ba4b6a5SBenoît Canet         goto out;
1323f187743aSKevin Wolf     }
1324b998875dSKevin Wolf 
1325b998875dSKevin Wolf     /* Create the temporary image */
13261ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1327b998875dSKevin Wolf     if (ret < 0) {
1328b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13291ba4b6a5SBenoît Canet         goto out;
1330b998875dSKevin Wolf     }
1331b998875dSKevin Wolf 
1332ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1333c282e1fdSChunyan Liu                             &error_abort);
133439101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1335ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
133683d0521aSChunyan Liu     qemu_opts_del(opts);
1337b998875dSKevin Wolf     if (ret < 0) {
1338b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1339b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1340b998875dSKevin Wolf                          error_get_pretty(local_err));
1341b998875dSKevin Wolf         error_free(local_err);
13421ba4b6a5SBenoît Canet         goto out;
1343b998875dSKevin Wolf     }
1344b998875dSKevin Wolf 
1345b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1346b998875dSKevin Wolf     snapshot_options = qdict_new();
1347b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1348b998875dSKevin Wolf               qstring_from_str("file"));
1349b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1350b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1351e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1352e6641719SMax Reitz               qstring_from_str("qcow2"));
1353b998875dSKevin Wolf 
1354e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1355b998875dSKevin Wolf 
1356b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
13576ebf9aa2SMax Reitz                     flags, &local_err);
1358b998875dSKevin Wolf     if (ret < 0) {
1359b998875dSKevin Wolf         error_propagate(errp, local_err);
13601ba4b6a5SBenoît Canet         goto out;
1361b998875dSKevin Wolf     }
1362b998875dSKevin Wolf 
1363b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
13641ba4b6a5SBenoît Canet 
13651ba4b6a5SBenoît Canet out:
13661ba4b6a5SBenoît Canet     g_free(tmp_filename);
13676b8aeca5SChen Gang     return ret;
1368b998875dSKevin Wolf }
1369b998875dSKevin Wolf 
1370da557aacSMax Reitz /*
1371b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1372de9c0cecSKevin Wolf  *
1373de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1374de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1375de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1376de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1377f67503e5SMax Reitz  *
1378f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1379f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1380ddf5636dSMax Reitz  *
1381ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1382ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1383ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1384b6ce07aaSKevin Wolf  */
1385f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1386ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1387f3930ed0SKevin Wolf                              BlockDriverState *parent,
1388ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1389ea2384d3Sbellard {
1390b6ce07aaSKevin Wolf     int ret;
13919a4f4c31SKevin Wolf     BdrvChild *file = NULL;
13929a4f4c31SKevin Wolf     BlockDriverState *bs;
1393ce343771SMax Reitz     BlockDriver *drv = NULL;
139474fe54f2SKevin Wolf     const char *drvname;
139534b5d2c6SMax Reitz     Error *local_err = NULL;
1396b1e6fc08SKevin Wolf     int snapshot_flags = 0;
139733e3963eSbellard 
1398f67503e5SMax Reitz     assert(pbs);
1399f3930ed0SKevin Wolf     assert(!child_role || !flags);
1400f3930ed0SKevin Wolf     assert(!child_role == !parent);
1401f67503e5SMax Reitz 
1402ddf5636dSMax Reitz     if (reference) {
1403ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1404ddf5636dSMax Reitz         QDECREF(options);
1405ddf5636dSMax Reitz 
1406ddf5636dSMax Reitz         if (*pbs) {
1407ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1408ddf5636dSMax Reitz                        "another block device");
1409ddf5636dSMax Reitz             return -EINVAL;
1410ddf5636dSMax Reitz         }
1411ddf5636dSMax Reitz 
1412ddf5636dSMax Reitz         if (filename || options_non_empty) {
1413ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1414ddf5636dSMax Reitz                        "additional options or a new filename");
1415ddf5636dSMax Reitz             return -EINVAL;
1416ddf5636dSMax Reitz         }
1417ddf5636dSMax Reitz 
1418ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1419ddf5636dSMax Reitz         if (!bs) {
1420ddf5636dSMax Reitz             return -ENODEV;
1421ddf5636dSMax Reitz         }
1422ddf5636dSMax Reitz         bdrv_ref(bs);
1423ddf5636dSMax Reitz         *pbs = bs;
1424ddf5636dSMax Reitz         return 0;
1425ddf5636dSMax Reitz     }
1426ddf5636dSMax Reitz 
1427f67503e5SMax Reitz     if (*pbs) {
1428f67503e5SMax Reitz         bs = *pbs;
1429f67503e5SMax Reitz     } else {
1430e4e9986bSMarkus Armbruster         bs = bdrv_new();
1431f67503e5SMax Reitz     }
1432f67503e5SMax Reitz 
1433de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1434de9c0cecSKevin Wolf     if (options == NULL) {
1435de9c0cecSKevin Wolf         options = qdict_new();
1436de9c0cecSKevin Wolf     }
1437de9c0cecSKevin Wolf 
1438f3930ed0SKevin Wolf     if (child_role) {
1439bddcec37SKevin Wolf         bs->inherits_from = parent;
1440f3930ed0SKevin Wolf         flags = child_role->inherit_flags(parent->open_flags);
1441f3930ed0SKevin Wolf     }
1442f3930ed0SKevin Wolf 
1443053e1578SMax Reitz     ret = bdrv_fill_options(&options, &filename, &flags, &local_err);
1444462f5bcfSKevin Wolf     if (local_err) {
1445462f5bcfSKevin Wolf         goto fail;
1446462f5bcfSKevin Wolf     }
1447462f5bcfSKevin Wolf 
144876c591b0SKevin Wolf     /* Find the right image format driver */
144976c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
145076c591b0SKevin Wolf     if (drvname) {
145176c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
145276c591b0SKevin Wolf         qdict_del(options, "driver");
145376c591b0SKevin Wolf         if (!drv) {
145476c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
145576c591b0SKevin Wolf             ret = -EINVAL;
145676c591b0SKevin Wolf             goto fail;
145776c591b0SKevin Wolf         }
145876c591b0SKevin Wolf     }
145976c591b0SKevin Wolf 
146076c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
146176c591b0SKevin Wolf 
1462f3930ed0SKevin Wolf     bs->open_flags = flags;
1463de9c0cecSKevin Wolf     bs->options = options;
1464b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1465de9c0cecSKevin Wolf 
1466f500a6d3SKevin Wolf     /* Open image file without format layer */
1467f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1468be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1469be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1470be028adcSJeff Cody         }
1471b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1472b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1473b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1474b1e6fc08SKevin Wolf         }
1475be028adcSJeff Cody 
1476f3930ed0SKevin Wolf         bs->open_flags = flags;
14771fdd6933SKevin Wolf 
14789a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
14791fdd6933SKevin Wolf                                &child_file, true, &local_err);
14801fdd6933SKevin Wolf         if (local_err) {
14811fdd6933SKevin Wolf             ret = -EINVAL;
14828bfea15dSKevin Wolf             goto fail;
1483f500a6d3SKevin Wolf         }
1484f4788adcSKevin Wolf     }
1485f500a6d3SKevin Wolf 
148676c591b0SKevin Wolf     /* Image format probing */
148738f3ef57SKevin Wolf     bs->probed = !drv;
148876c591b0SKevin Wolf     if (!drv && file) {
14899a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
149017b005f1SKevin Wolf         if (ret < 0) {
149117b005f1SKevin Wolf             goto fail;
149217b005f1SKevin Wolf         }
149376c591b0SKevin Wolf     } else if (!drv) {
14942a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
14952a05cbe4SMax Reitz         ret = -EINVAL;
14968bfea15dSKevin Wolf         goto fail;
14972a05cbe4SMax Reitz     }
1498f500a6d3SKevin Wolf 
149953a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
150053a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
150153a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
150253a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
150353a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
150453a29513SMax Reitz 
1505b6ce07aaSKevin Wolf     /* Open the image */
150634b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1507b6ce07aaSKevin Wolf     if (ret < 0) {
15088bfea15dSKevin Wolf         goto fail;
15096987307cSChristoph Hellwig     }
15106987307cSChristoph Hellwig 
15112a05cbe4SMax Reitz     if (file && (bs->file != file)) {
15129a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1513f500a6d3SKevin Wolf         file = NULL;
1514f500a6d3SKevin Wolf     }
1515f500a6d3SKevin Wolf 
1516b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
15179156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
151831ca6d07SKevin Wolf         QDict *backing_options;
151931ca6d07SKevin Wolf 
15205726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
152134b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1522b6ce07aaSKevin Wolf         if (ret < 0) {
1523b6ad491aSKevin Wolf             goto close_and_fail;
1524b6ce07aaSKevin Wolf         }
1525b6ce07aaSKevin Wolf     }
1526b6ce07aaSKevin Wolf 
152791af7014SMax Reitz     bdrv_refresh_filename(bs);
152891af7014SMax Reitz 
1529b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15305acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1531b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15325acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15335acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15345acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15355acd9d81SMax Reitz         } else {
153634b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15375acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1538bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
15395acd9d81SMax Reitz         }
1540b6ad491aSKevin Wolf 
1541b6ad491aSKevin Wolf         ret = -EINVAL;
1542b6ad491aSKevin Wolf         goto close_and_fail;
1543b6ad491aSKevin Wolf     }
1544b6ad491aSKevin Wolf 
1545b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1546a7f53e26SMarkus Armbruster         if (bs->blk) {
1547a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1548a7f53e26SMarkus Armbruster         }
1549c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1550c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1551c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1552c3adb58fSMarkus Armbruster         error_setg(errp,
1553c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1554c3adb58fSMarkus Armbruster         ret = -EBUSY;
1555c3adb58fSMarkus Armbruster         goto close_and_fail;
1556b6ce07aaSKevin Wolf     }
1557b6ce07aaSKevin Wolf 
1558c3adb58fSMarkus Armbruster     QDECREF(options);
1559f67503e5SMax Reitz     *pbs = bs;
1560dd62f1caSKevin Wolf 
1561dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1562dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1563dd62f1caSKevin Wolf     if (snapshot_flags) {
1564dd62f1caSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1565dd62f1caSKevin Wolf         if (local_err) {
1566dd62f1caSKevin Wolf             goto close_and_fail;
1567dd62f1caSKevin Wolf         }
1568dd62f1caSKevin Wolf     }
1569dd62f1caSKevin Wolf 
1570b6ce07aaSKevin Wolf     return 0;
1571b6ce07aaSKevin Wolf 
15728bfea15dSKevin Wolf fail:
1573f500a6d3SKevin Wolf     if (file != NULL) {
15749a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1575f500a6d3SKevin Wolf     }
1576de9c0cecSKevin Wolf     QDECREF(bs->options);
1577b6ad491aSKevin Wolf     QDECREF(options);
1578de9c0cecSKevin Wolf     bs->options = NULL;
1579f67503e5SMax Reitz     if (!*pbs) {
1580f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1581f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1582f67503e5SMax Reitz            since it has not really been opened yet. */
1583f67503e5SMax Reitz         bdrv_unref(bs);
1584f67503e5SMax Reitz     }
158584d18f06SMarkus Armbruster     if (local_err) {
158634b5d2c6SMax Reitz         error_propagate(errp, local_err);
158734b5d2c6SMax Reitz     }
1588b6ad491aSKevin Wolf     return ret;
1589de9c0cecSKevin Wolf 
1590b6ad491aSKevin Wolf close_and_fail:
1591f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1592f67503e5SMax Reitz     if (*pbs) {
1593b6ad491aSKevin Wolf         bdrv_close(bs);
1594f67503e5SMax Reitz     } else {
1595f67503e5SMax Reitz         bdrv_unref(bs);
1596f67503e5SMax Reitz     }
1597b6ad491aSKevin Wolf     QDECREF(options);
159884d18f06SMarkus Armbruster     if (local_err) {
159934b5d2c6SMax Reitz         error_propagate(errp, local_err);
160034b5d2c6SMax Reitz     }
1601b6ce07aaSKevin Wolf     return ret;
1602b6ce07aaSKevin Wolf }
1603b6ce07aaSKevin Wolf 
1604f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
16056ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1606f3930ed0SKevin Wolf {
1607f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1608ce343771SMax Reitz                              NULL, errp);
1609f3930ed0SKevin Wolf }
1610f3930ed0SKevin Wolf 
1611e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1612e971aa12SJeff Cody      bool prepared;
1613e971aa12SJeff Cody      BDRVReopenState state;
1614e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1615e971aa12SJeff Cody } BlockReopenQueueEntry;
1616e971aa12SJeff Cody 
1617e971aa12SJeff Cody /*
1618e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1619e971aa12SJeff Cody  * reopen of multiple devices.
1620e971aa12SJeff Cody  *
1621e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1622e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1623e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1624e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1625e971aa12SJeff Cody  * atomic 'set'.
1626e971aa12SJeff Cody  *
1627e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1628e971aa12SJeff Cody  *
16294d2cb092SKevin Wolf  * options contains the changed options for the associated bs
16304d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
16314d2cb092SKevin Wolf  *
1632e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1633e971aa12SJeff Cody  *
1634e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1635e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1636e971aa12SJeff Cody  *
1637e971aa12SJeff Cody  */
1638e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
16394d2cb092SKevin Wolf                                     BlockDriverState *bs,
16404d2cb092SKevin Wolf                                     QDict *options, int flags)
1641e971aa12SJeff Cody {
1642e971aa12SJeff Cody     assert(bs != NULL);
1643e971aa12SJeff Cody 
1644e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
164567251a31SKevin Wolf     BdrvChild *child;
16464d2cb092SKevin Wolf     QDict *old_options;
164767251a31SKevin Wolf 
1648e971aa12SJeff Cody     if (bs_queue == NULL) {
1649e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1650e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1651e971aa12SJeff Cody     }
1652e971aa12SJeff Cody 
16534d2cb092SKevin Wolf     if (!options) {
16544d2cb092SKevin Wolf         options = qdict_new();
16554d2cb092SKevin Wolf     }
16564d2cb092SKevin Wolf 
16574d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
16584d2cb092SKevin Wolf     qdict_join(options, old_options, false);
16594d2cb092SKevin Wolf     QDECREF(old_options);
16604d2cb092SKevin Wolf 
1661f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1662f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1663f1f25a2eSKevin Wolf 
166467251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
166567251a31SKevin Wolf         int child_flags;
166667251a31SKevin Wolf 
166767251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
166867251a31SKevin Wolf             continue;
166967251a31SKevin Wolf         }
167067251a31SKevin Wolf 
167167251a31SKevin Wolf         child_flags = child->role->inherit_flags(flags);
16724d2cb092SKevin Wolf         /* TODO Pass down child flags (backing.*, extents.*, ...) */
16734d2cb092SKevin Wolf         bdrv_reopen_queue(bs_queue, child->bs, NULL, child_flags);
1674e971aa12SJeff Cody     }
1675e971aa12SJeff Cody 
1676e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1677e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1678e971aa12SJeff Cody 
1679e971aa12SJeff Cody     bs_entry->state.bs = bs;
16804d2cb092SKevin Wolf     bs_entry->state.options = options;
1681e971aa12SJeff Cody     bs_entry->state.flags = flags;
1682e971aa12SJeff Cody 
1683e971aa12SJeff Cody     return bs_queue;
1684e971aa12SJeff Cody }
1685e971aa12SJeff Cody 
1686e971aa12SJeff Cody /*
1687e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1688e971aa12SJeff Cody  *
1689e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1690e971aa12SJeff Cody  * via bdrv_reopen_queue().
1691e971aa12SJeff Cody  *
1692e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1693e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1694e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1695e971aa12SJeff Cody  * data cleaned up.
1696e971aa12SJeff Cody  *
1697e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1698e971aa12SJeff Cody  * to all devices.
1699e971aa12SJeff Cody  *
1700e971aa12SJeff Cody  */
1701e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1702e971aa12SJeff Cody {
1703e971aa12SJeff Cody     int ret = -1;
1704e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1705e971aa12SJeff Cody     Error *local_err = NULL;
1706e971aa12SJeff Cody 
1707e971aa12SJeff Cody     assert(bs_queue != NULL);
1708e971aa12SJeff Cody 
1709e971aa12SJeff Cody     bdrv_drain_all();
1710e971aa12SJeff Cody 
1711e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1712e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1713e971aa12SJeff Cody             error_propagate(errp, local_err);
1714e971aa12SJeff Cody             goto cleanup;
1715e971aa12SJeff Cody         }
1716e971aa12SJeff Cody         bs_entry->prepared = true;
1717e971aa12SJeff Cody     }
1718e971aa12SJeff Cody 
1719e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1720e971aa12SJeff Cody      * changes
1721e971aa12SJeff Cody      */
1722e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1723e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1724e971aa12SJeff Cody     }
1725e971aa12SJeff Cody 
1726e971aa12SJeff Cody     ret = 0;
1727e971aa12SJeff Cody 
1728e971aa12SJeff Cody cleanup:
1729e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1730e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1731e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1732e971aa12SJeff Cody         }
17334d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1734e971aa12SJeff Cody         g_free(bs_entry);
1735e971aa12SJeff Cody     }
1736e971aa12SJeff Cody     g_free(bs_queue);
1737e971aa12SJeff Cody     return ret;
1738e971aa12SJeff Cody }
1739e971aa12SJeff Cody 
1740e971aa12SJeff Cody 
1741e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1742e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1743e971aa12SJeff Cody {
1744e971aa12SJeff Cody     int ret = -1;
1745e971aa12SJeff Cody     Error *local_err = NULL;
17464d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1747e971aa12SJeff Cody 
1748e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1749e971aa12SJeff Cody     if (local_err != NULL) {
1750e971aa12SJeff Cody         error_propagate(errp, local_err);
1751e971aa12SJeff Cody     }
1752e971aa12SJeff Cody     return ret;
1753e971aa12SJeff Cody }
1754e971aa12SJeff Cody 
1755e971aa12SJeff Cody 
1756e971aa12SJeff Cody /*
1757e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1758e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1759e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1760e971aa12SJeff Cody  *
1761e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1762e971aa12SJeff Cody  * flags are the new open flags
1763e971aa12SJeff Cody  * queue is the reopen queue
1764e971aa12SJeff Cody  *
1765e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1766e971aa12SJeff Cody  * as well.
1767e971aa12SJeff Cody  *
1768e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1769e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1770e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1771e971aa12SJeff Cody  *
1772e971aa12SJeff Cody  */
1773e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1774e971aa12SJeff Cody                         Error **errp)
1775e971aa12SJeff Cody {
1776e971aa12SJeff Cody     int ret = -1;
1777e971aa12SJeff Cody     Error *local_err = NULL;
1778e971aa12SJeff Cody     BlockDriver *drv;
1779e971aa12SJeff Cody 
1780e971aa12SJeff Cody     assert(reopen_state != NULL);
1781e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1782e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1783e971aa12SJeff Cody 
1784e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1785e971aa12SJeff Cody      * to r/w */
1786e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1787e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
178881e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
178981e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1790e971aa12SJeff Cody         goto error;
1791e971aa12SJeff Cody     }
1792e971aa12SJeff Cody 
1793e971aa12SJeff Cody 
1794e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1795e971aa12SJeff Cody     if (ret) {
1796e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1797e971aa12SJeff Cody                   strerror(-ret));
1798e971aa12SJeff Cody         goto error;
1799e971aa12SJeff Cody     }
1800e971aa12SJeff Cody 
1801e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1802e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1803e971aa12SJeff Cody         if (ret) {
1804e971aa12SJeff Cody             if (local_err != NULL) {
1805e971aa12SJeff Cody                 error_propagate(errp, local_err);
1806e971aa12SJeff Cody             } else {
1807d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1808e971aa12SJeff Cody                            reopen_state->bs->filename);
1809e971aa12SJeff Cody             }
1810e971aa12SJeff Cody             goto error;
1811e971aa12SJeff Cody         }
1812e971aa12SJeff Cody     } else {
1813e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1814e971aa12SJeff Cody          * handler for each supported drv. */
181581e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
181681e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
181781e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1818e971aa12SJeff Cody         ret = -1;
1819e971aa12SJeff Cody         goto error;
1820e971aa12SJeff Cody     }
1821e971aa12SJeff Cody 
18224d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
18234d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
18244d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
18254d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
18264d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
18274d2cb092SKevin Wolf 
18284d2cb092SKevin Wolf         do {
18294d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
18304d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
18314d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
18324d2cb092SKevin Wolf                                                 entry->key);
18334d2cb092SKevin Wolf 
18344d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
18354d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
18364d2cb092SKevin Wolf                 ret = -EINVAL;
18374d2cb092SKevin Wolf                 goto error;
18384d2cb092SKevin Wolf             }
18394d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
18404d2cb092SKevin Wolf     }
18414d2cb092SKevin Wolf 
1842e971aa12SJeff Cody     ret = 0;
1843e971aa12SJeff Cody 
1844e971aa12SJeff Cody error:
1845e971aa12SJeff Cody     return ret;
1846e971aa12SJeff Cody }
1847e971aa12SJeff Cody 
1848e971aa12SJeff Cody /*
1849e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1850e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1851e971aa12SJeff Cody  * the active BlockDriverState contents.
1852e971aa12SJeff Cody  */
1853e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1854e971aa12SJeff Cody {
1855e971aa12SJeff Cody     BlockDriver *drv;
1856e971aa12SJeff Cody 
1857e971aa12SJeff Cody     assert(reopen_state != NULL);
1858e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1859e971aa12SJeff Cody     assert(drv != NULL);
1860e971aa12SJeff Cody 
1861e971aa12SJeff Cody     /* If there are any driver level actions to take */
1862e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1863e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1864e971aa12SJeff Cody     }
1865e971aa12SJeff Cody 
1866e971aa12SJeff Cody     /* set BDS specific flags now */
1867e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1868e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1869e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1870e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1871355ef4acSKevin Wolf 
18723baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1873e971aa12SJeff Cody }
1874e971aa12SJeff Cody 
1875e971aa12SJeff Cody /*
1876e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1877e971aa12SJeff Cody  * reopen_state
1878e971aa12SJeff Cody  */
1879e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1880e971aa12SJeff Cody {
1881e971aa12SJeff Cody     BlockDriver *drv;
1882e971aa12SJeff Cody 
1883e971aa12SJeff Cody     assert(reopen_state != NULL);
1884e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1885e971aa12SJeff Cody     assert(drv != NULL);
1886e971aa12SJeff Cody 
1887e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1888e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1889e971aa12SJeff Cody     }
1890e971aa12SJeff Cody }
1891e971aa12SJeff Cody 
1892e971aa12SJeff Cody 
1893fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1894fc01f7e7Sbellard {
189533384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
189633384421SMax Reitz 
18973e914655SPaolo Bonzini     if (bs->job) {
18983e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
18993e914655SPaolo Bonzini     }
190099b7e775SAlberto Garcia 
190199b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
190299b7e775SAlberto Garcia     if (bs->io_limits_enabled) {
190399b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
190499b7e775SAlberto Garcia     }
190599b7e775SAlberto Garcia 
190653ec73e2SFam Zheng     bdrv_drain(bs); /* complete I/O */
190758fda173SStefan Hajnoczi     bdrv_flush(bs);
190853ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
1909d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
19107094f12fSKevin Wolf 
19113cbc002cSPaolo Bonzini     if (bs->drv) {
19126e93e7c4SKevin Wolf         BdrvChild *child, *next;
19136e93e7c4SKevin Wolf 
19149a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
19159a4f4c31SKevin Wolf         bs->drv = NULL;
19169a7dedbcSKevin Wolf 
19179a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
19189a7dedbcSKevin Wolf 
19199a4f4c31SKevin Wolf         if (bs->file != NULL) {
19209a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
19219a4f4c31SKevin Wolf             bs->file = NULL;
19229a4f4c31SKevin Wolf         }
19239a4f4c31SKevin Wolf 
19246e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
192533a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
192633a60407SKevin Wolf              * bdrv_unref_child() here */
1927bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
1928bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
1929bddcec37SKevin Wolf             }
193033a60407SKevin Wolf             bdrv_detach_child(child);
19316e93e7c4SKevin Wolf         }
19326e93e7c4SKevin Wolf 
19337267c094SAnthony Liguori         g_free(bs->opaque);
1934ea2384d3Sbellard         bs->opaque = NULL;
193553fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1936a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1937a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
19386405875cSPaolo Bonzini         bs->total_sectors = 0;
19396405875cSPaolo Bonzini         bs->encrypted = 0;
19406405875cSPaolo Bonzini         bs->valid_key = 0;
19416405875cSPaolo Bonzini         bs->sg = 0;
19420d51b4deSAsias He         bs->zero_beyond_eof = false;
1943de9c0cecSKevin Wolf         QDECREF(bs->options);
1944de9c0cecSKevin Wolf         bs->options = NULL;
194591af7014SMax Reitz         QDECREF(bs->full_open_options);
194691af7014SMax Reitz         bs->full_open_options = NULL;
19479ca11154SPavel Hrdina     }
194866f82ceeSKevin Wolf 
1949a7f53e26SMarkus Armbruster     if (bs->blk) {
1950a7f53e26SMarkus Armbruster         blk_dev_change_media_cb(bs->blk, false);
1951a7f53e26SMarkus Armbruster     }
195298f90dbaSZhi Yong Wu 
195333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
195433384421SMax Reitz         g_free(ban);
195533384421SMax Reitz     }
195633384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1957b338082bSbellard }
1958b338082bSbellard 
19592bc93fedSMORITA Kazutaka void bdrv_close_all(void)
19602bc93fedSMORITA Kazutaka {
19612bc93fedSMORITA Kazutaka     BlockDriverState *bs;
19622bc93fedSMORITA Kazutaka 
1963dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1964ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1965ed78cda3SStefan Hajnoczi 
1966ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
19672bc93fedSMORITA Kazutaka         bdrv_close(bs);
1968ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
19692bc93fedSMORITA Kazutaka     }
19702bc93fedSMORITA Kazutaka }
19712bc93fedSMORITA Kazutaka 
1972dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1973dc364f4cSBenoît Canet  * graph_bdrv_state list.
1974d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1975d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1976d22b2f41SRyan Harper {
1977bfb197e0SMarkus Armbruster     /*
1978bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
1979bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
1980bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
1981bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
1982bfb197e0SMarkus Armbruster      * resetting it to null on remove.
1983bfb197e0SMarkus Armbruster      */
1984bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
1985dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1986bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
1987d22b2f41SRyan Harper     }
1988dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1989dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1990dc364f4cSBenoît Canet     }
1991dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1992d22b2f41SRyan Harper }
1993d22b2f41SRyan Harper 
19948e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
19954ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
19964ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
19974ddc07caSPaolo Bonzini {
19984ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
19994ddc07caSPaolo Bonzini 
20004ddc07caSPaolo Bonzini     /* dev info */
20011b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
20024ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
20034ddc07caSPaolo Bonzini 
20044ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
20054ddc07caSPaolo Bonzini 
2006dd62f1caSKevin Wolf     /* r/w error */
2007dd62f1caSKevin Wolf     bs_dest->on_read_error      = bs_src->on_read_error;
2008dd62f1caSKevin Wolf     bs_dest->on_write_error     = bs_src->on_write_error;
2009dd62f1caSKevin Wolf 
2010dd62f1caSKevin Wolf     /* i/o status */
2011dd62f1caSKevin Wolf     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
2012dd62f1caSKevin Wolf     bs_dest->iostatus           = bs_src->iostatus;
2013dd62f1caSKevin Wolf 
2014dd62f1caSKevin Wolf     /* dirty bitmap */
2015dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2016dd62f1caSKevin Wolf }
2017dd62f1caSKevin Wolf 
2018dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2019dd62f1caSKevin Wolf                                        BlockDriverState *to)
2020dd62f1caSKevin Wolf {
2021dd62f1caSKevin Wolf     BdrvChild *c, *next;
2022dd62f1caSKevin Wolf 
2023dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2024dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2025dd62f1caSKevin Wolf         c->bs = to;
2026dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2027dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2028dd62f1caSKevin Wolf         bdrv_ref(to);
2029dd62f1caSKevin Wolf         bdrv_unref(from);
2030dd62f1caSKevin Wolf     }
2031dd62f1caSKevin Wolf     if (from->blk) {
2032dd62f1caSKevin Wolf         blk_set_bs(from->blk, to);
2033dd62f1caSKevin Wolf         if (!to->device_list.tqe_prev) {
2034dd62f1caSKevin Wolf             QTAILQ_INSERT_BEFORE(from, to, device_list);
2035dd62f1caSKevin Wolf         }
2036dd62f1caSKevin Wolf         QTAILQ_REMOVE(&bdrv_states, from, device_list);
2037dd62f1caSKevin Wolf     }
2038dd62f1caSKevin Wolf }
2039dd62f1caSKevin Wolf 
2040dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2041dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2042dd62f1caSKevin Wolf {
2043dd62f1caSKevin Wolf     BlockDriverState tmp;
2044dd62f1caSKevin Wolf 
2045dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2046dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2047dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2048dd62f1caSKevin Wolf 
2049dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2050dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2051dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2052dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2053dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2054dd62f1caSKevin Wolf     }
2055dd62f1caSKevin Wolf }
2056dd62f1caSKevin Wolf 
20578802d1fdSJeff Cody /*
20588802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
20598802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
20608802d1fdSJeff Cody  *
20618802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
20628802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
20638802d1fdSJeff Cody  *
2064bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2065f6801b83SJeff Cody  *
20668802d1fdSJeff Cody  * This function does not create any image files.
2067dd62f1caSKevin Wolf  *
2068dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2069dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2070dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2071dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
20728802d1fdSJeff Cody  */
20738802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
20748802d1fdSJeff Cody {
2075dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2076dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
20778802d1fdSJeff Cody 
2078dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2079dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2080dd62f1caSKevin Wolf 
2081dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2082dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2083dd62f1caSKevin Wolf 
2084dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2085dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2086dd62f1caSKevin Wolf 
2087dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2088dd62f1caSKevin Wolf      * additional reference any more. */
2089dd62f1caSKevin Wolf     bdrv_unref(bs_new);
20908802d1fdSJeff Cody }
20918802d1fdSJeff Cody 
20923f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
20933f09bfbcSKevin Wolf {
20943f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
20953f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
20963f09bfbcSKevin Wolf 
20973f09bfbcSKevin Wolf     bdrv_ref(old);
20983f09bfbcSKevin Wolf 
20993f09bfbcSKevin Wolf     if (old->blk) {
21003f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
21013f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
21023f09bfbcSKevin Wolf          *
21033f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
21043f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
21053f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
21063f09bfbcSKevin Wolf         assert(!new->blk);
21073f09bfbcSKevin Wolf         swap_feature_fields(old, new);
21083f09bfbcSKevin Wolf     }
21093f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
21103f09bfbcSKevin Wolf 
21113f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
21123f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
21133f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
21143f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
21153f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
21163f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
21173f09bfbcSKevin Wolf     }
21183f09bfbcSKevin Wolf 
21193f09bfbcSKevin Wolf     bdrv_unref(old);
21203f09bfbcSKevin Wolf }
21213f09bfbcSKevin Wolf 
21224f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2123b338082bSbellard {
21243e914655SPaolo Bonzini     assert(!bs->job);
21253718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21264f6fd349SFam Zheng     assert(!bs->refcnt);
2127e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
212818846deeSMarkus Armbruster 
2129e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2130e1b5c52eSStefan Hajnoczi 
21311b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2132d22b2f41SRyan Harper     bdrv_make_anon(bs);
213334c6f050Saurel32 
21347267c094SAnthony Liguori     g_free(bs);
2135fc01f7e7Sbellard }
2136fc01f7e7Sbellard 
2137e97fc193Saliguori /*
2138e97fc193Saliguori  * Run consistency checks on an image
2139e97fc193Saliguori  *
2140e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2141a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2142e076f338SKevin Wolf  * check are stored in res.
2143e97fc193Saliguori  */
21444534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2145e97fc193Saliguori {
2146908bcd54SMax Reitz     if (bs->drv == NULL) {
2147908bcd54SMax Reitz         return -ENOMEDIUM;
2148908bcd54SMax Reitz     }
2149e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2150e97fc193Saliguori         return -ENOTSUP;
2151e97fc193Saliguori     }
2152e97fc193Saliguori 
2153e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21544534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2155e97fc193Saliguori }
2156e97fc193Saliguori 
21578a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21588a426614SKevin Wolf 
215933e3963eSbellard /* commit COW file into the raw image */
216033e3963eSbellard int bdrv_commit(BlockDriverState *bs)
216133e3963eSbellard {
216219cb3738Sbellard     BlockDriver *drv = bs->drv;
216372706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
21648a426614SKevin Wolf     int n, ro, open_flags;
21650bce597dSJeff Cody     int ret = 0;
216672706ea4SJeff Cody     uint8_t *buf = NULL;
216733e3963eSbellard 
216819cb3738Sbellard     if (!drv)
216919cb3738Sbellard         return -ENOMEDIUM;
217033e3963eSbellard 
2171760e0063SKevin Wolf     if (!bs->backing) {
21724dca4b63SNaphtali Sprei         return -ENOTSUP;
21734dca4b63SNaphtali Sprei     }
21744dca4b63SNaphtali Sprei 
2175bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2176760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
21772d3735d3SStefan Hajnoczi         return -EBUSY;
21782d3735d3SStefan Hajnoczi     }
21792d3735d3SStefan Hajnoczi 
2180760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2181760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
21824dca4b63SNaphtali Sprei 
21834dca4b63SNaphtali Sprei     if (ro) {
2184760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
21850bce597dSJeff Cody             return -EACCES;
21864dca4b63SNaphtali Sprei         }
2187ea2384d3Sbellard     }
2188ea2384d3Sbellard 
218972706ea4SJeff Cody     length = bdrv_getlength(bs);
219072706ea4SJeff Cody     if (length < 0) {
219172706ea4SJeff Cody         ret = length;
219272706ea4SJeff Cody         goto ro_cleanup;
219372706ea4SJeff Cody     }
219472706ea4SJeff Cody 
2195760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
219672706ea4SJeff Cody     if (backing_length < 0) {
219772706ea4SJeff Cody         ret = backing_length;
219872706ea4SJeff Cody         goto ro_cleanup;
219972706ea4SJeff Cody     }
220072706ea4SJeff Cody 
220172706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
220272706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
220372706ea4SJeff Cody      * we must return an error */
220472706ea4SJeff Cody     if (length > backing_length) {
2205760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
220672706ea4SJeff Cody         if (ret < 0) {
220772706ea4SJeff Cody             goto ro_cleanup;
220872706ea4SJeff Cody         }
220972706ea4SJeff Cody     }
221072706ea4SJeff Cody 
221172706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2212857d4f46SKevin Wolf 
2213857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2214760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2215857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2216857d4f46SKevin Wolf     if (buf == NULL) {
2217857d4f46SKevin Wolf         ret = -ENOMEM;
2218857d4f46SKevin Wolf         goto ro_cleanup;
2219857d4f46SKevin Wolf     }
22208a426614SKevin Wolf 
22218a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2222d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2223d663640cSPaolo Bonzini         if (ret < 0) {
2224d663640cSPaolo Bonzini             goto ro_cleanup;
2225d663640cSPaolo Bonzini         }
2226d663640cSPaolo Bonzini         if (ret) {
2227dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2228dabfa6ccSKevin Wolf             if (ret < 0) {
22294dca4b63SNaphtali Sprei                 goto ro_cleanup;
223033e3963eSbellard             }
223133e3963eSbellard 
2232760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2233dabfa6ccSKevin Wolf             if (ret < 0) {
22344dca4b63SNaphtali Sprei                 goto ro_cleanup;
223533e3963eSbellard             }
223633e3963eSbellard         }
223733e3963eSbellard     }
223895389c86Sbellard 
22391d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22401d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2241dabfa6ccSKevin Wolf         if (ret < 0) {
2242dabfa6ccSKevin Wolf             goto ro_cleanup;
2243dabfa6ccSKevin Wolf         }
22441d44952fSChristoph Hellwig         bdrv_flush(bs);
22451d44952fSChristoph Hellwig     }
224695389c86Sbellard 
22473f5075aeSChristoph Hellwig     /*
22483f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22493f5075aeSChristoph Hellwig      * stable on disk.
22503f5075aeSChristoph Hellwig      */
2251760e0063SKevin Wolf     if (bs->backing) {
2252760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2253dabfa6ccSKevin Wolf     }
22544dca4b63SNaphtali Sprei 
2255dabfa6ccSKevin Wolf     ret = 0;
22564dca4b63SNaphtali Sprei ro_cleanup:
2257857d4f46SKevin Wolf     qemu_vfree(buf);
22584dca4b63SNaphtali Sprei 
22594dca4b63SNaphtali Sprei     if (ro) {
22600bce597dSJeff Cody         /* ignoring error return here */
2261760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
22624dca4b63SNaphtali Sprei     }
22634dca4b63SNaphtali Sprei 
22641d44952fSChristoph Hellwig     return ret;
226533e3963eSbellard }
226633e3963eSbellard 
2267e8877497SStefan Hajnoczi int bdrv_commit_all(void)
22686ab4b5abSMarkus Armbruster {
22696ab4b5abSMarkus Armbruster     BlockDriverState *bs;
22706ab4b5abSMarkus Armbruster 
2271dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2272ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2273ed78cda3SStefan Hajnoczi 
2274ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2275760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2276e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2277e8877497SStefan Hajnoczi             if (ret < 0) {
2278ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2279e8877497SStefan Hajnoczi                 return ret;
22806ab4b5abSMarkus Armbruster             }
22816ab4b5abSMarkus Armbruster         }
2282ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2283272d2d8eSJeff Cody     }
2284e8877497SStefan Hajnoczi     return 0;
2285e8877497SStefan Hajnoczi }
22866ab4b5abSMarkus Armbruster 
2287756e6736SKevin Wolf /*
2288756e6736SKevin Wolf  * Return values:
2289756e6736SKevin Wolf  * 0        - success
2290756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2291756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2292756e6736SKevin Wolf  *            image file header
2293756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2294756e6736SKevin Wolf  */
2295756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2296756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2297756e6736SKevin Wolf {
2298756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2299469ef350SPaolo Bonzini     int ret;
2300756e6736SKevin Wolf 
23015f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23025f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23035f377794SPaolo Bonzini         return -EINVAL;
23045f377794SPaolo Bonzini     }
23055f377794SPaolo Bonzini 
2306756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2307469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2308756e6736SKevin Wolf     } else {
2309469ef350SPaolo Bonzini         ret = -ENOTSUP;
2310756e6736SKevin Wolf     }
2311469ef350SPaolo Bonzini 
2312469ef350SPaolo Bonzini     if (ret == 0) {
2313469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2314469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2315469ef350SPaolo Bonzini     }
2316469ef350SPaolo Bonzini     return ret;
2317756e6736SKevin Wolf }
2318756e6736SKevin Wolf 
23196ebdcee2SJeff Cody /*
23206ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23216ebdcee2SJeff Cody  *
23226ebdcee2SJeff Cody  * active is the current topmost image.
23236ebdcee2SJeff Cody  *
23246ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23256ebdcee2SJeff Cody  * or if active == bs.
23264caf0fcdSJeff Cody  *
23274caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
23286ebdcee2SJeff Cody  */
23296ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23306ebdcee2SJeff Cody                                     BlockDriverState *bs)
23316ebdcee2SJeff Cody {
2332760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2333760e0063SKevin Wolf         active = backing_bs(active);
23346ebdcee2SJeff Cody     }
23356ebdcee2SJeff Cody 
23364caf0fcdSJeff Cody     return active;
23376ebdcee2SJeff Cody }
23386ebdcee2SJeff Cody 
23394caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
23404caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
23414caf0fcdSJeff Cody {
23424caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
23436ebdcee2SJeff Cody }
23446ebdcee2SJeff Cody 
23456ebdcee2SJeff Cody /*
23466ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23476ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23486ebdcee2SJeff Cody  *
23496ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23506ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23516ebdcee2SJeff Cody  *
23526ebdcee2SJeff Cody  * E.g., this will convert the following chain:
23536ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
23546ebdcee2SJeff Cody  *
23556ebdcee2SJeff Cody  * to
23566ebdcee2SJeff Cody  *
23576ebdcee2SJeff Cody  * bottom <- base <- active
23586ebdcee2SJeff Cody  *
23596ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
23606ebdcee2SJeff Cody  *
23616ebdcee2SJeff Cody  * base <- intermediate <- top <- active
23626ebdcee2SJeff Cody  *
23636ebdcee2SJeff Cody  * to
23646ebdcee2SJeff Cody  *
23656ebdcee2SJeff Cody  * base <- active
23666ebdcee2SJeff Cody  *
236754e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
236854e26900SJeff Cody  * overlay image metadata.
236954e26900SJeff Cody  *
23706ebdcee2SJeff Cody  * Error conditions:
23716ebdcee2SJeff Cody  *  if active == top, that is considered an error
23726ebdcee2SJeff Cody  *
23736ebdcee2SJeff Cody  */
23746ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
237554e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
23766ebdcee2SJeff Cody {
23776ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
23786ebdcee2SJeff Cody     int ret = -EIO;
23796ebdcee2SJeff Cody 
23806ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
23816ebdcee2SJeff Cody         goto exit;
23826ebdcee2SJeff Cody     }
23836ebdcee2SJeff Cody 
23846ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
23856ebdcee2SJeff Cody 
23866ebdcee2SJeff Cody     if (new_top_bs == NULL) {
23876ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
23886ebdcee2SJeff Cody         goto exit;
23896ebdcee2SJeff Cody     }
23906ebdcee2SJeff Cody 
2391760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
23926ebdcee2SJeff Cody      * to do, no intermediate images */
2393760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
23946ebdcee2SJeff Cody         ret = 0;
23956ebdcee2SJeff Cody         goto exit;
23966ebdcee2SJeff Cody     }
23976ebdcee2SJeff Cody 
23985db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
23995db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
24006ebdcee2SJeff Cody         goto exit;
24016ebdcee2SJeff Cody     }
24026ebdcee2SJeff Cody 
24036ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
24045db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
240554e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
24065db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
24076ebdcee2SJeff Cody     if (ret) {
24086ebdcee2SJeff Cody         goto exit;
24096ebdcee2SJeff Cody     }
24105db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
24116ebdcee2SJeff Cody 
24126ebdcee2SJeff Cody     ret = 0;
24136ebdcee2SJeff Cody exit:
24146ebdcee2SJeff Cody     return ret;
24156ebdcee2SJeff Cody }
24166ebdcee2SJeff Cody 
241783f64091Sbellard /**
241883f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
241983f64091Sbellard  */
242083f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
242183f64091Sbellard {
242283f64091Sbellard     BlockDriver *drv = bs->drv;
242351762288SStefan Hajnoczi     int ret;
242483f64091Sbellard     if (!drv)
242519cb3738Sbellard         return -ENOMEDIUM;
242683f64091Sbellard     if (!drv->bdrv_truncate)
242783f64091Sbellard         return -ENOTSUP;
242859f2689dSNaphtali Sprei     if (bs->read_only)
242959f2689dSNaphtali Sprei         return -EACCES;
24309c75e168SJeff Cody 
243151762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
243251762288SStefan Hajnoczi     if (ret == 0) {
243351762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2434ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2435a7f53e26SMarkus Armbruster         if (bs->blk) {
2436a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2437a7f53e26SMarkus Armbruster         }
243851762288SStefan Hajnoczi     }
243951762288SStefan Hajnoczi     return ret;
244083f64091Sbellard }
244183f64091Sbellard 
244283f64091Sbellard /**
24434a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
24444a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
24454a1d5e1fSFam Zheng  */
24464a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
24474a1d5e1fSFam Zheng {
24484a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
24494a1d5e1fSFam Zheng     if (!drv) {
24504a1d5e1fSFam Zheng         return -ENOMEDIUM;
24514a1d5e1fSFam Zheng     }
24524a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
24534a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
24544a1d5e1fSFam Zheng     }
24554a1d5e1fSFam Zheng     if (bs->file) {
24569a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
24574a1d5e1fSFam Zheng     }
24584a1d5e1fSFam Zheng     return -ENOTSUP;
24594a1d5e1fSFam Zheng }
24604a1d5e1fSFam Zheng 
24614a1d5e1fSFam Zheng /**
246265a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
246383f64091Sbellard  */
246465a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
246583f64091Sbellard {
246683f64091Sbellard     BlockDriver *drv = bs->drv;
246765a9bb25SMarkus Armbruster 
246883f64091Sbellard     if (!drv)
246919cb3738Sbellard         return -ENOMEDIUM;
247051762288SStefan Hajnoczi 
2471b94a2610SKevin Wolf     if (drv->has_variable_length) {
2472b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2473b94a2610SKevin Wolf         if (ret < 0) {
2474b94a2610SKevin Wolf             return ret;
2475fc01f7e7Sbellard         }
247646a4e4e6SStefan Hajnoczi     }
247765a9bb25SMarkus Armbruster     return bs->total_sectors;
247865a9bb25SMarkus Armbruster }
247965a9bb25SMarkus Armbruster 
248065a9bb25SMarkus Armbruster /**
248165a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
248265a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
248365a9bb25SMarkus Armbruster  */
248465a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
248565a9bb25SMarkus Armbruster {
248665a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
248765a9bb25SMarkus Armbruster 
24884a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
248965a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
249046a4e4e6SStefan Hajnoczi }
2491fc01f7e7Sbellard 
249219cb3738Sbellard /* return 0 as number of sectors if no device present or error */
249396b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2494fc01f7e7Sbellard {
249565a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
249665a9bb25SMarkus Armbruster 
249765a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2498fc01f7e7Sbellard }
2499cf98951bSbellard 
2500ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2501ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2502abd7f68dSMarkus Armbruster {
2503abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2504abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2505abd7f68dSMarkus Armbruster }
2506abd7f68dSMarkus Armbruster 
25071ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2508abd7f68dSMarkus Armbruster {
2509abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2510abd7f68dSMarkus Armbruster }
2511abd7f68dSMarkus Armbruster 
25123e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
25133e1caa5fSPaolo Bonzini {
25143e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
25153e1caa5fSPaolo Bonzini 
25163e1caa5fSPaolo Bonzini     switch (on_err) {
25173e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
2518a589569fSWenchao Xia         return (error == ENOSPC) ?
2519a589569fSWenchao Xia                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
25203e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
2521a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_STOP;
25223e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
2523a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_REPORT;
25243e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
2525a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_IGNORE;
25263e1caa5fSPaolo Bonzini     default:
25273e1caa5fSPaolo Bonzini         abort();
25283e1caa5fSPaolo Bonzini     }
25293e1caa5fSPaolo Bonzini }
25303e1caa5fSPaolo Bonzini 
2531c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs,
2532c7c2ff0cSLuiz Capitulino                                  BlockErrorAction action,
2533c7c2ff0cSLuiz Capitulino                                  bool is_read, int error)
2534c7c2ff0cSLuiz Capitulino {
2535573742a5SPeter Maydell     IoOperationType optype;
2536c7c2ff0cSLuiz Capitulino 
2537573742a5SPeter Maydell     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
2538573742a5SPeter Maydell     qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action,
2539c7c2ff0cSLuiz Capitulino                                    bdrv_iostatus_is_enabled(bs),
2540624ff573SLuiz Capitulino                                    error == ENOSPC, strerror(error),
2541624ff573SLuiz Capitulino                                    &error_abort);
2542c7c2ff0cSLuiz Capitulino }
2543c7c2ff0cSLuiz Capitulino 
25443e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
25453e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
25463e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
25473e1caa5fSPaolo Bonzini  */
25483e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
25493e1caa5fSPaolo Bonzini                        bool is_read, int error)
25503e1caa5fSPaolo Bonzini {
25513e1caa5fSPaolo Bonzini     assert(error >= 0);
25522bd3bce8SPaolo Bonzini 
2553a589569fSWenchao Xia     if (action == BLOCK_ERROR_ACTION_STOP) {
25542bd3bce8SPaolo Bonzini         /* First set the iostatus, so that "info block" returns an iostatus
25552bd3bce8SPaolo Bonzini          * that matches the events raised so far (an additional error iostatus
25562bd3bce8SPaolo Bonzini          * is fine, but not a lost one).
25572bd3bce8SPaolo Bonzini          */
25583e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
25592bd3bce8SPaolo Bonzini 
25602bd3bce8SPaolo Bonzini         /* Then raise the request to stop the VM and the event.
25612bd3bce8SPaolo Bonzini          * qemu_system_vmstop_request_prepare has two effects.  First,
25622bd3bce8SPaolo Bonzini          * it ensures that the STOP event always comes after the
25632bd3bce8SPaolo Bonzini          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
25642bd3bce8SPaolo Bonzini          * can observe the STOP event and do a "cont" before the STOP
25652bd3bce8SPaolo Bonzini          * event is issued, the VM will not stop.  In this case, vm_start()
25662bd3bce8SPaolo Bonzini          * also ensures that the STOP/RESUME pair of events is emitted.
25672bd3bce8SPaolo Bonzini          */
25682bd3bce8SPaolo Bonzini         qemu_system_vmstop_request_prepare();
2569c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
25702bd3bce8SPaolo Bonzini         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
25712bd3bce8SPaolo Bonzini     } else {
2572c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
25733e1caa5fSPaolo Bonzini     }
25743e1caa5fSPaolo Bonzini }
25753e1caa5fSPaolo Bonzini 
2576b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2577b338082bSbellard {
2578b338082bSbellard     return bs->read_only;
2579b338082bSbellard }
2580b338082bSbellard 
2581985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2582985a03b0Sths {
2583985a03b0Sths     return bs->sg;
2584985a03b0Sths }
2585985a03b0Sths 
2586e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2587e900a7b7SChristoph Hellwig {
2588e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2589e900a7b7SChristoph Hellwig }
2590e900a7b7SChristoph Hellwig 
2591425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2592425b0148SPaolo Bonzini {
2593425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
259455b110f2SJeff Cody 
259555b110f2SJeff Cody     /* so a reopen() will preserve wce */
259655b110f2SJeff Cody     if (wce) {
259755b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
259855b110f2SJeff Cody     } else {
259955b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
260055b110f2SJeff Cody     }
2601425b0148SPaolo Bonzini }
2602425b0148SPaolo Bonzini 
2603ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2604ea2384d3Sbellard {
2605760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2606ea2384d3Sbellard         return 1;
2607760e0063SKevin Wolf     }
2608ea2384d3Sbellard     return bs->encrypted;
2609ea2384d3Sbellard }
2610ea2384d3Sbellard 
2611c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2612c0f4ce77Saliguori {
2613760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2614c0f4ce77Saliguori 
2615760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2616c0f4ce77Saliguori         return 1;
2617760e0063SKevin Wolf     }
2618c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2619c0f4ce77Saliguori }
2620c0f4ce77Saliguori 
2621ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2622ea2384d3Sbellard {
2623ea2384d3Sbellard     int ret;
2624760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2625760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2626ea2384d3Sbellard         if (ret < 0)
2627ea2384d3Sbellard             return ret;
2628ea2384d3Sbellard         if (!bs->encrypted)
2629ea2384d3Sbellard             return 0;
2630ea2384d3Sbellard     }
2631fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2632fd04a2aeSShahar Havivi         return -EINVAL;
2633fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2634fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2635fd04a2aeSShahar Havivi     }
2636c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2637bb5fc20fSaliguori     if (ret < 0) {
2638bb5fc20fSaliguori         bs->valid_key = 0;
2639bb5fc20fSaliguori     } else if (!bs->valid_key) {
2640bb5fc20fSaliguori         bs->valid_key = 1;
2641a7f53e26SMarkus Armbruster         if (bs->blk) {
2642bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2643a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2644a7f53e26SMarkus Armbruster         }
2645bb5fc20fSaliguori     }
2646c0f4ce77Saliguori     return ret;
2647ea2384d3Sbellard }
2648ea2384d3Sbellard 
26494d2855a3SMarkus Armbruster /*
26504d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
26514d2855a3SMarkus Armbruster  * If @key is non-null:
26524d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
26534d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
26544d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
26554d2855a3SMarkus Armbruster  * If @key is null:
26564d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
26574d2855a3SMarkus Armbruster  *     Else do nothing.
26584d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
26594d2855a3SMarkus Armbruster  */
26604d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
26614d2855a3SMarkus Armbruster {
26624d2855a3SMarkus Armbruster     if (key) {
26634d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
266481e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
266581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
26664d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2667c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
26684d2855a3SMarkus Armbruster         }
26694d2855a3SMarkus Armbruster     } else {
26704d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2671b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2672b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
267381e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
26744d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
26754d2855a3SMarkus Armbruster         }
26764d2855a3SMarkus Armbruster     }
26774d2855a3SMarkus Armbruster }
26784d2855a3SMarkus Armbruster 
2679f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2680ea2384d3Sbellard {
2681f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2682ea2384d3Sbellard }
2683ea2384d3Sbellard 
2684ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2685ada42401SStefan Hajnoczi {
2686ada42401SStefan Hajnoczi     return strcmp(a, b);
2687ada42401SStefan Hajnoczi }
2688ada42401SStefan Hajnoczi 
2689ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2690ea2384d3Sbellard                          void *opaque)
2691ea2384d3Sbellard {
2692ea2384d3Sbellard     BlockDriver *drv;
2693e855e4fbSJeff Cody     int count = 0;
2694ada42401SStefan Hajnoczi     int i;
2695e855e4fbSJeff Cody     const char **formats = NULL;
2696ea2384d3Sbellard 
26978a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2698e855e4fbSJeff Cody         if (drv->format_name) {
2699e855e4fbSJeff Cody             bool found = false;
2700e855e4fbSJeff Cody             int i = count;
2701e855e4fbSJeff Cody             while (formats && i && !found) {
2702e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2703e855e4fbSJeff Cody             }
2704e855e4fbSJeff Cody 
2705e855e4fbSJeff Cody             if (!found) {
27065839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2707e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2708ea2384d3Sbellard             }
2709ea2384d3Sbellard         }
2710e855e4fbSJeff Cody     }
2711ada42401SStefan Hajnoczi 
2712ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2713ada42401SStefan Hajnoczi 
2714ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2715ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2716ada42401SStefan Hajnoczi     }
2717ada42401SStefan Hajnoczi 
2718e855e4fbSJeff Cody     g_free(formats);
2719e855e4fbSJeff Cody }
2720ea2384d3Sbellard 
2721dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2722dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2723dc364f4cSBenoît Canet {
2724dc364f4cSBenoît Canet     BlockDriverState *bs;
2725dc364f4cSBenoît Canet 
2726dc364f4cSBenoît Canet     assert(node_name);
2727dc364f4cSBenoît Canet 
2728dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2729dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2730dc364f4cSBenoît Canet             return bs;
2731dc364f4cSBenoît Canet         }
2732dc364f4cSBenoît Canet     }
2733dc364f4cSBenoît Canet     return NULL;
2734dc364f4cSBenoît Canet }
2735dc364f4cSBenoît Canet 
2736c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2737d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2738c13163fbSBenoît Canet {
2739c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2740c13163fbSBenoît Canet     BlockDriverState *bs;
2741c13163fbSBenoît Canet 
2742c13163fbSBenoît Canet     list = NULL;
2743c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2744d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2745d5a8ee60SAlberto Garcia         if (!info) {
2746d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2747d5a8ee60SAlberto Garcia             return NULL;
2748d5a8ee60SAlberto Garcia         }
2749c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2750d5a8ee60SAlberto Garcia         entry->value = info;
2751c13163fbSBenoît Canet         entry->next = list;
2752c13163fbSBenoît Canet         list = entry;
2753c13163fbSBenoît Canet     }
2754c13163fbSBenoît Canet 
2755c13163fbSBenoît Canet     return list;
2756c13163fbSBenoît Canet }
2757c13163fbSBenoît Canet 
275812d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
275912d3ba82SBenoît Canet                                  const char *node_name,
276012d3ba82SBenoît Canet                                  Error **errp)
276112d3ba82SBenoît Canet {
27627f06d47eSMarkus Armbruster     BlockBackend *blk;
27637f06d47eSMarkus Armbruster     BlockDriverState *bs;
276412d3ba82SBenoît Canet 
276512d3ba82SBenoît Canet     if (device) {
27667f06d47eSMarkus Armbruster         blk = blk_by_name(device);
276712d3ba82SBenoît Canet 
27687f06d47eSMarkus Armbruster         if (blk) {
27697f06d47eSMarkus Armbruster             return blk_bs(blk);
277012d3ba82SBenoît Canet         }
2771dd67fa50SBenoît Canet     }
277212d3ba82SBenoît Canet 
2773dd67fa50SBenoît Canet     if (node_name) {
277412d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
277512d3ba82SBenoît Canet 
2776dd67fa50SBenoît Canet         if (bs) {
2777dd67fa50SBenoît Canet             return bs;
2778dd67fa50SBenoît Canet         }
277912d3ba82SBenoît Canet     }
278012d3ba82SBenoît Canet 
2781dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2782dd67fa50SBenoît Canet                      device ? device : "",
2783dd67fa50SBenoît Canet                      node_name ? node_name : "");
2784dd67fa50SBenoît Canet     return NULL;
278512d3ba82SBenoît Canet }
278612d3ba82SBenoît Canet 
27875a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
27885a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
27895a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
27905a6684d2SJeff Cody {
27915a6684d2SJeff Cody     while (top && top != base) {
2792760e0063SKevin Wolf         top = backing_bs(top);
27935a6684d2SJeff Cody     }
27945a6684d2SJeff Cody 
27955a6684d2SJeff Cody     return top != NULL;
27965a6684d2SJeff Cody }
27975a6684d2SJeff Cody 
279804df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
279904df765aSFam Zheng {
280004df765aSFam Zheng     if (!bs) {
280104df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
280204df765aSFam Zheng     }
280304df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
280404df765aSFam Zheng }
280504df765aSFam Zheng 
28062f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
28072f399b0aSMarkus Armbruster {
28082f399b0aSMarkus Armbruster     if (!bs) {
28092f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
28102f399b0aSMarkus Armbruster     }
2811dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
28122f399b0aSMarkus Armbruster }
28132f399b0aSMarkus Armbruster 
281420a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
281520a9e77dSFam Zheng {
281620a9e77dSFam Zheng     return bs->node_name;
281720a9e77dSFam Zheng }
281820a9e77dSFam Zheng 
28197f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2820bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2821ea2384d3Sbellard {
2822bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2823ea2384d3Sbellard }
2824ea2384d3Sbellard 
28259b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
28269b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
28279b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
28289b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
28299b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
28309b2aa84fSAlberto Garcia {
28319b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
28329b2aa84fSAlberto Garcia }
28339b2aa84fSAlberto Garcia 
2834c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2835c8433287SMarkus Armbruster {
2836c8433287SMarkus Armbruster     return bs->open_flags;
2837c8433287SMarkus Armbruster }
2838c8433287SMarkus Armbruster 
28393ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
28403ac21627SPeter Lieven {
28413ac21627SPeter Lieven     return 1;
28423ac21627SPeter Lieven }
28433ac21627SPeter Lieven 
2844f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2845f2feebbdSKevin Wolf {
2846f2feebbdSKevin Wolf     assert(bs->drv);
2847f2feebbdSKevin Wolf 
284811212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
284911212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2850760e0063SKevin Wolf     if (bs->backing) {
285111212d8fSPaolo Bonzini         return 0;
285211212d8fSPaolo Bonzini     }
2853336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2854336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2855f2feebbdSKevin Wolf     }
2856f2feebbdSKevin Wolf 
28573ac21627SPeter Lieven     /* safe default */
28583ac21627SPeter Lieven     return 0;
2859f2feebbdSKevin Wolf }
2860f2feebbdSKevin Wolf 
28614ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
28624ce78691SPeter Lieven {
28634ce78691SPeter Lieven     BlockDriverInfo bdi;
28644ce78691SPeter Lieven 
2865760e0063SKevin Wolf     if (bs->backing) {
28664ce78691SPeter Lieven         return false;
28674ce78691SPeter Lieven     }
28684ce78691SPeter Lieven 
28694ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28704ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
28714ce78691SPeter Lieven     }
28724ce78691SPeter Lieven 
28734ce78691SPeter Lieven     return false;
28744ce78691SPeter Lieven }
28754ce78691SPeter Lieven 
28764ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
28774ce78691SPeter Lieven {
28784ce78691SPeter Lieven     BlockDriverInfo bdi;
28794ce78691SPeter Lieven 
2880760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
28814ce78691SPeter Lieven         return false;
28824ce78691SPeter Lieven     }
28834ce78691SPeter Lieven 
28844ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
28854ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
28864ce78691SPeter Lieven     }
28874ce78691SPeter Lieven 
28884ce78691SPeter Lieven     return false;
28894ce78691SPeter Lieven }
28904ce78691SPeter Lieven 
2891045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2892045df330Saliguori {
2893760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2894045df330Saliguori         return bs->backing_file;
2895045df330Saliguori     else if (bs->encrypted)
2896045df330Saliguori         return bs->filename;
2897045df330Saliguori     else
2898045df330Saliguori         return NULL;
2899045df330Saliguori }
2900045df330Saliguori 
290183f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
290283f64091Sbellard                                char *filename, int filename_size)
290383f64091Sbellard {
290483f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
290583f64091Sbellard }
290683f64091Sbellard 
2907faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2908faea38e7Sbellard {
2909faea38e7Sbellard     BlockDriver *drv = bs->drv;
2910faea38e7Sbellard     if (!drv)
291119cb3738Sbellard         return -ENOMEDIUM;
2912faea38e7Sbellard     if (!drv->bdrv_get_info)
2913faea38e7Sbellard         return -ENOTSUP;
2914faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2915faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2916faea38e7Sbellard }
2917faea38e7Sbellard 
2918eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2919eae041feSMax Reitz {
2920eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2921eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2922eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2923eae041feSMax Reitz     }
2924eae041feSMax Reitz     return NULL;
2925eae041feSMax Reitz }
2926eae041feSMax Reitz 
29278b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
29288b9b0cc2SKevin Wolf {
2929bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
29308b9b0cc2SKevin Wolf         return;
29318b9b0cc2SKevin Wolf     }
29328b9b0cc2SKevin Wolf 
2933bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
293441c695c7SKevin Wolf }
29358b9b0cc2SKevin Wolf 
293641c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
293741c695c7SKevin Wolf                           const char *tag)
293841c695c7SKevin Wolf {
293941c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
29409a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
294141c695c7SKevin Wolf     }
294241c695c7SKevin Wolf 
294341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
294441c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
294541c695c7SKevin Wolf     }
294641c695c7SKevin Wolf 
294741c695c7SKevin Wolf     return -ENOTSUP;
294841c695c7SKevin Wolf }
294941c695c7SKevin Wolf 
29504cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
29514cc70e93SFam Zheng {
29524cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
29539a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
29544cc70e93SFam Zheng     }
29554cc70e93SFam Zheng 
29564cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
29574cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
29584cc70e93SFam Zheng     }
29594cc70e93SFam Zheng 
29604cc70e93SFam Zheng     return -ENOTSUP;
29614cc70e93SFam Zheng }
29624cc70e93SFam Zheng 
296341c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
296441c695c7SKevin Wolf {
2965938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
29669a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
296741c695c7SKevin Wolf     }
296841c695c7SKevin Wolf 
296941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
297041c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
297141c695c7SKevin Wolf     }
297241c695c7SKevin Wolf 
297341c695c7SKevin Wolf     return -ENOTSUP;
297441c695c7SKevin Wolf }
297541c695c7SKevin Wolf 
297641c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
297741c695c7SKevin Wolf {
297841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
29799a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
298041c695c7SKevin Wolf     }
298141c695c7SKevin Wolf 
298241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
298341c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
298441c695c7SKevin Wolf     }
298541c695c7SKevin Wolf 
298641c695c7SKevin Wolf     return false;
29878b9b0cc2SKevin Wolf }
29888b9b0cc2SKevin Wolf 
2989199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2990199630b6SBlue Swirl {
2991199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2992199630b6SBlue Swirl }
2993199630b6SBlue Swirl 
2994b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
2995b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
2996b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
2997b1b1d783SJeff Cody  * the CWD rather than the chain. */
2998e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2999e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3000e8a6bb9cSMarcelo Tosatti {
3001b1b1d783SJeff Cody     char *filename_full = NULL;
3002b1b1d783SJeff Cody     char *backing_file_full = NULL;
3003b1b1d783SJeff Cody     char *filename_tmp = NULL;
3004b1b1d783SJeff Cody     int is_protocol = 0;
3005b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3006b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3007b1b1d783SJeff Cody 
3008b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3009e8a6bb9cSMarcelo Tosatti         return NULL;
3010e8a6bb9cSMarcelo Tosatti     }
3011e8a6bb9cSMarcelo Tosatti 
3012b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3013b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3014b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3015b1b1d783SJeff Cody 
3016b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3017b1b1d783SJeff Cody 
3018760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3019b1b1d783SJeff Cody 
3020b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3021b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3022b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3023b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3024760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3025b1b1d783SJeff Cody                 break;
3026b1b1d783SJeff Cody             }
3027e8a6bb9cSMarcelo Tosatti         } else {
3028b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3029b1b1d783SJeff Cody              * image's filename path */
3030b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3031b1b1d783SJeff Cody                          backing_file);
3032b1b1d783SJeff Cody 
3033b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3034b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3035b1b1d783SJeff Cody                 continue;
3036b1b1d783SJeff Cody             }
3037b1b1d783SJeff Cody 
3038b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3039b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3040b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3041b1b1d783SJeff Cody                          curr_bs->backing_file);
3042b1b1d783SJeff Cody 
3043b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3044b1b1d783SJeff Cody                 continue;
3045b1b1d783SJeff Cody             }
3046b1b1d783SJeff Cody 
3047b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3048760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3049b1b1d783SJeff Cody                 break;
3050b1b1d783SJeff Cody             }
3051e8a6bb9cSMarcelo Tosatti         }
3052e8a6bb9cSMarcelo Tosatti     }
3053e8a6bb9cSMarcelo Tosatti 
3054b1b1d783SJeff Cody     g_free(filename_full);
3055b1b1d783SJeff Cody     g_free(backing_file_full);
3056b1b1d783SJeff Cody     g_free(filename_tmp);
3057b1b1d783SJeff Cody     return retval;
3058e8a6bb9cSMarcelo Tosatti }
3059e8a6bb9cSMarcelo Tosatti 
3060f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3061f198fd1cSBenoît Canet {
3062f198fd1cSBenoît Canet     if (!bs->drv) {
3063f198fd1cSBenoît Canet         return 0;
3064f198fd1cSBenoît Canet     }
3065f198fd1cSBenoît Canet 
3066760e0063SKevin Wolf     if (!bs->backing) {
3067f198fd1cSBenoît Canet         return 0;
3068f198fd1cSBenoît Canet     }
3069f198fd1cSBenoît Canet 
3070760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3071f198fd1cSBenoît Canet }
3072f198fd1cSBenoît Canet 
3073ea2384d3Sbellard void bdrv_init(void)
3074ea2384d3Sbellard {
30755efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3076ea2384d3Sbellard }
3077ce1a14dcSpbrook 
3078eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3079eb852011SMarkus Armbruster {
3080eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3081eb852011SMarkus Armbruster     bdrv_init();
3082eb852011SMarkus Armbruster }
3083eb852011SMarkus Armbruster 
30845a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
30850f15423cSAnthony Liguori {
30865a8a30dbSKevin Wolf     Error *local_err = NULL;
30875a8a30dbSKevin Wolf     int ret;
30885a8a30dbSKevin Wolf 
30893456a8d1SKevin Wolf     if (!bs->drv)  {
30903456a8d1SKevin Wolf         return;
30910f15423cSAnthony Liguori     }
30923456a8d1SKevin Wolf 
30937ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
30947ea2d269SAlexey Kardashevskiy         return;
30957ea2d269SAlexey Kardashevskiy     }
30967ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
30977ea2d269SAlexey Kardashevskiy 
30983456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
30995a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
31003456a8d1SKevin Wolf     } else if (bs->file) {
31019a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
31025a8a30dbSKevin Wolf     }
31035a8a30dbSKevin Wolf     if (local_err) {
31045a8a30dbSKevin Wolf         error_propagate(errp, local_err);
31055a8a30dbSKevin Wolf         return;
31063456a8d1SKevin Wolf     }
31073456a8d1SKevin Wolf 
31085a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
31095a8a30dbSKevin Wolf     if (ret < 0) {
31105a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
31115a8a30dbSKevin Wolf         return;
31125a8a30dbSKevin Wolf     }
31130f15423cSAnthony Liguori }
31140f15423cSAnthony Liguori 
31155a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
31160f15423cSAnthony Liguori {
31170f15423cSAnthony Liguori     BlockDriverState *bs;
31185a8a30dbSKevin Wolf     Error *local_err = NULL;
31190f15423cSAnthony Liguori 
3120dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3121ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3122ed78cda3SStefan Hajnoczi 
3123ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
31245a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3125ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
31265a8a30dbSKevin Wolf         if (local_err) {
31275a8a30dbSKevin Wolf             error_propagate(errp, local_err);
31285a8a30dbSKevin Wolf             return;
31295a8a30dbSKevin Wolf         }
31300f15423cSAnthony Liguori     }
31310f15423cSAnthony Liguori }
31320f15423cSAnthony Liguori 
3133f9f05dc5SKevin Wolf /**************************************************************/
313419cb3738Sbellard /* removable device support */
313519cb3738Sbellard 
313619cb3738Sbellard /**
313719cb3738Sbellard  * Return TRUE if the media is present
313819cb3738Sbellard  */
313919cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
314019cb3738Sbellard {
314119cb3738Sbellard     BlockDriver *drv = bs->drv;
3142a1aff5bfSMarkus Armbruster 
314319cb3738Sbellard     if (!drv)
314419cb3738Sbellard         return 0;
314519cb3738Sbellard     if (!drv->bdrv_is_inserted)
3146a1aff5bfSMarkus Armbruster         return 1;
3147a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
314819cb3738Sbellard }
314919cb3738Sbellard 
315019cb3738Sbellard /**
31518e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
31528e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
315319cb3738Sbellard  */
315419cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
315519cb3738Sbellard {
315619cb3738Sbellard     BlockDriver *drv = bs->drv;
315719cb3738Sbellard 
31588e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
31598e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
31608e49ca46SMarkus Armbruster     }
31618e49ca46SMarkus Armbruster     return -ENOTSUP;
316219cb3738Sbellard }
316319cb3738Sbellard 
316419cb3738Sbellard /**
316519cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
316619cb3738Sbellard  */
3167f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
316819cb3738Sbellard {
316919cb3738Sbellard     BlockDriver *drv = bs->drv;
3170bfb197e0SMarkus Armbruster     const char *device_name;
317119cb3738Sbellard 
3172822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3173822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
317419cb3738Sbellard     }
31756f382ed2SLuiz Capitulino 
3176bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3177bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3178bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3179a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
31806f382ed2SLuiz Capitulino     }
318119cb3738Sbellard }
318219cb3738Sbellard 
318319cb3738Sbellard /**
318419cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
318519cb3738Sbellard  * to eject it manually).
318619cb3738Sbellard  */
3187025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
318819cb3738Sbellard {
318919cb3738Sbellard     BlockDriver *drv = bs->drv;
319019cb3738Sbellard 
3191025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3192b8c6d095SStefan Hajnoczi 
3193025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3194025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
319519cb3738Sbellard     }
319619cb3738Sbellard }
3197985a03b0Sths 
31981b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
31997b6f9300SMarkus Armbruster {
32001b7fd729SPaolo Bonzini     bs->guest_block_size = align;
32017b6f9300SMarkus Armbruster }
32027cd1e32aSlirans@il.ibm.com 
32030db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
32040db6e54aSFam Zheng {
32050db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
32060db6e54aSFam Zheng 
32070db6e54aSFam Zheng     assert(name);
32080db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
32090db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
32100db6e54aSFam Zheng             return bm;
32110db6e54aSFam Zheng         }
32120db6e54aSFam Zheng     }
32130db6e54aSFam Zheng     return NULL;
32140db6e54aSFam Zheng }
32150db6e54aSFam Zheng 
321620dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
32170db6e54aSFam Zheng {
32189bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
32190db6e54aSFam Zheng     g_free(bitmap->name);
32200db6e54aSFam Zheng     bitmap->name = NULL;
32210db6e54aSFam Zheng }
32220db6e54aSFam Zheng 
32230db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
32245fba6c0eSJohn Snow                                           uint32_t granularity,
32250db6e54aSFam Zheng                                           const char *name,
3226b8afb520SFam Zheng                                           Error **errp)
32277cd1e32aSlirans@il.ibm.com {
32287cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3229e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
32305fba6c0eSJohn Snow     uint32_t sector_granularity;
3231a55eb92cSJan Kiszka 
323250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
323350717e94SPaolo Bonzini 
32340db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
32350db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
32360db6e54aSFam Zheng         return NULL;
32370db6e54aSFam Zheng     }
32385fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
32395fba6c0eSJohn Snow     assert(sector_granularity);
324057322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3241b8afb520SFam Zheng     if (bitmap_size < 0) {
3242b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3243b8afb520SFam Zheng         errno = -bitmap_size;
3244b8afb520SFam Zheng         return NULL;
3245b8afb520SFam Zheng     }
32465839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
32475fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3248e74e6b78SJohn Snow     bitmap->size = bitmap_size;
32490db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3250b8e6fb75SJohn Snow     bitmap->disabled = false;
3251e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3252e4654d2dSFam Zheng     return bitmap;
3253e4654d2dSFam Zheng }
3254e4654d2dSFam Zheng 
32559bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
32569bd2b08fSJohn Snow {
32579bd2b08fSJohn Snow     return bitmap->successor;
32589bd2b08fSJohn Snow }
32599bd2b08fSJohn Snow 
3260b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3261b8e6fb75SJohn Snow {
32629bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
32639bd2b08fSJohn Snow }
32649bd2b08fSJohn Snow 
32659abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
32669abe3bdcSJohn Snow {
32679abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
32689abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
32699abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
32709abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
32719abe3bdcSJohn Snow     } else {
32729abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
32739abe3bdcSJohn Snow     }
32749abe3bdcSJohn Snow }
32759abe3bdcSJohn Snow 
32769bd2b08fSJohn Snow /**
32779bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
32789bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
32799bd2b08fSJohn Snow  */
32809bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
32819bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
32829bd2b08fSJohn Snow {
32839bd2b08fSJohn Snow     uint64_t granularity;
32849bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
32859bd2b08fSJohn Snow 
32869bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
32879bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
32889bd2b08fSJohn Snow                    "currently frozen");
32899bd2b08fSJohn Snow         return -1;
32909bd2b08fSJohn Snow     }
32919bd2b08fSJohn Snow     assert(!bitmap->successor);
32929bd2b08fSJohn Snow 
32939bd2b08fSJohn Snow     /* Create an anonymous successor */
32949bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
32959bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
32969bd2b08fSJohn Snow     if (!child) {
32979bd2b08fSJohn Snow         return -1;
32989bd2b08fSJohn Snow     }
32999bd2b08fSJohn Snow 
33009bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
33019bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
33029bd2b08fSJohn Snow 
33039bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
33049bd2b08fSJohn Snow     bitmap->successor = child;
33059bd2b08fSJohn Snow     return 0;
33069bd2b08fSJohn Snow }
33079bd2b08fSJohn Snow 
33089bd2b08fSJohn Snow /**
33099bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
33109bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
33119bd2b08fSJohn Snow  */
33129bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
33139bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
33149bd2b08fSJohn Snow                                             Error **errp)
33159bd2b08fSJohn Snow {
33169bd2b08fSJohn Snow     char *name;
33179bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
33189bd2b08fSJohn Snow 
33199bd2b08fSJohn Snow     if (successor == NULL) {
33209bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
33219bd2b08fSJohn Snow                    "there's no successor present");
33229bd2b08fSJohn Snow         return NULL;
33239bd2b08fSJohn Snow     }
33249bd2b08fSJohn Snow 
33259bd2b08fSJohn Snow     name = bitmap->name;
33269bd2b08fSJohn Snow     bitmap->name = NULL;
33279bd2b08fSJohn Snow     successor->name = name;
33289bd2b08fSJohn Snow     bitmap->successor = NULL;
33299bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
33309bd2b08fSJohn Snow 
33319bd2b08fSJohn Snow     return successor;
33329bd2b08fSJohn Snow }
33339bd2b08fSJohn Snow 
33349bd2b08fSJohn Snow /**
33359bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
33369bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
33379bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
33389bd2b08fSJohn Snow  */
33399bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
33409bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
33419bd2b08fSJohn Snow                                            Error **errp)
33429bd2b08fSJohn Snow {
33439bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
33449bd2b08fSJohn Snow 
33459bd2b08fSJohn Snow     if (!successor) {
33469bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
33479bd2b08fSJohn Snow         return NULL;
33489bd2b08fSJohn Snow     }
33499bd2b08fSJohn Snow 
33509bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
33519bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
33529bd2b08fSJohn Snow         return NULL;
33539bd2b08fSJohn Snow     }
33549bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
33559bd2b08fSJohn Snow     parent->successor = NULL;
33569bd2b08fSJohn Snow 
33579bd2b08fSJohn Snow     return parent;
3358b8e6fb75SJohn Snow }
3359b8e6fb75SJohn Snow 
3360ce1ffea8SJohn Snow /**
3361ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3362ce1ffea8SJohn Snow  */
3363ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3364ce1ffea8SJohn Snow {
3365ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3366ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3367ce1ffea8SJohn Snow 
3368ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
336906207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3370ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
33715270b6a0SJohn Snow         bitmap->size = size;
3372ce1ffea8SJohn Snow     }
3373ce1ffea8SJohn Snow }
3374ce1ffea8SJohn Snow 
3375e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3376e4654d2dSFam Zheng {
3377e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3378e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3379e4654d2dSFam Zheng         if (bm == bitmap) {
33809bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3381e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3382e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
33830db6e54aSFam Zheng             g_free(bitmap->name);
3384e4654d2dSFam Zheng             g_free(bitmap);
3385e4654d2dSFam Zheng             return;
33867cd1e32aSlirans@il.ibm.com         }
33877cd1e32aSlirans@il.ibm.com     }
33887cd1e32aSlirans@il.ibm.com }
33897cd1e32aSlirans@il.ibm.com 
3390b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3391b8e6fb75SJohn Snow {
33929bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3393b8e6fb75SJohn Snow     bitmap->disabled = true;
3394b8e6fb75SJohn Snow }
3395b8e6fb75SJohn Snow 
3396b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3397b8e6fb75SJohn Snow {
33989bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3399b8e6fb75SJohn Snow     bitmap->disabled = false;
3400b8e6fb75SJohn Snow }
3401b8e6fb75SJohn Snow 
340221b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
340321b56835SFam Zheng {
340421b56835SFam Zheng     BdrvDirtyBitmap *bm;
340521b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
340621b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
340721b56835SFam Zheng 
340821b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
34095839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
34105839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
341120dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3412592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
34130db6e54aSFam Zheng         info->has_name = !!bm->name;
34140db6e54aSFam Zheng         info->name = g_strdup(bm->name);
34159abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
341621b56835SFam Zheng         entry->value = info;
341721b56835SFam Zheng         *plist = entry;
341821b56835SFam Zheng         plist = &entry->next;
341921b56835SFam Zheng     }
342021b56835SFam Zheng 
342121b56835SFam Zheng     return list;
342221b56835SFam Zheng }
342321b56835SFam Zheng 
3424e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
34257cd1e32aSlirans@il.ibm.com {
3426e4654d2dSFam Zheng     if (bitmap) {
3427e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
34287cd1e32aSlirans@il.ibm.com     } else {
34297cd1e32aSlirans@il.ibm.com         return 0;
34307cd1e32aSlirans@il.ibm.com     }
34317cd1e32aSlirans@il.ibm.com }
34327cd1e32aSlirans@il.ibm.com 
3433341ebc2fSJohn Snow /**
3434341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3435341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3436341ebc2fSJohn Snow  * is no cluster size information available.
3437341ebc2fSJohn Snow  */
3438341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3439341ebc2fSJohn Snow {
3440341ebc2fSJohn Snow     BlockDriverInfo bdi;
3441341ebc2fSJohn Snow     uint32_t granularity;
3442341ebc2fSJohn Snow 
3443341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3444341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3445341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3446341ebc2fSJohn Snow     } else {
3447341ebc2fSJohn Snow         granularity = 65536;
3448341ebc2fSJohn Snow     }
3449341ebc2fSJohn Snow 
3450341ebc2fSJohn Snow     return granularity;
3451341ebc2fSJohn Snow }
3452341ebc2fSJohn Snow 
3453592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3454592fdd02SJohn Snow {
3455592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3456592fdd02SJohn Snow }
3457592fdd02SJohn Snow 
345820dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
34591755da16SPaolo Bonzini {
3460e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
34611755da16SPaolo Bonzini }
34621755da16SPaolo Bonzini 
346320dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3464c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3465c4237dfaSVladimir Sementsov-Ogievskiy {
3466b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3467c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3468c4237dfaSVladimir Sementsov-Ogievskiy }
3469c4237dfaSVladimir Sementsov-Ogievskiy 
347020dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3471c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3472c4237dfaSVladimir Sementsov-Ogievskiy {
3473b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3474c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3475c4237dfaSVladimir Sementsov-Ogievskiy }
3476c4237dfaSVladimir Sementsov-Ogievskiy 
3477e74e6b78SJohn Snow void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3478e74e6b78SJohn Snow {
3479e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3480c6a8c328SWen Congyang     hbitmap_reset_all(bitmap->bitmap);
3481e74e6b78SJohn Snow }
3482e74e6b78SJohn Snow 
3483e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
34841755da16SPaolo Bonzini                     int nr_sectors)
34851755da16SPaolo Bonzini {
3486e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3487e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3488b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3489b8e6fb75SJohn Snow             continue;
3490b8e6fb75SJohn Snow         }
3491e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3492e4654d2dSFam Zheng     }
34931755da16SPaolo Bonzini }
34941755da16SPaolo Bonzini 
3495d58d8453SJohn Snow /**
3496d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3497d58d8453SJohn Snow  */
3498d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3499d58d8453SJohn Snow {
3500d58d8453SJohn Snow     assert(hbi->hb);
3501d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3502d58d8453SJohn Snow }
3503d58d8453SJohn Snow 
350420dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3505aaa0eb75SLiran Schour {
3506e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3507aaa0eb75SLiran Schour }
3508f88e1a42SJes Sorensen 
35099fcb0251SFam Zheng /* Get a reference to bs */
35109fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
35119fcb0251SFam Zheng {
35129fcb0251SFam Zheng     bs->refcnt++;
35139fcb0251SFam Zheng }
35149fcb0251SFam Zheng 
35159fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
35169fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
35179fcb0251SFam Zheng  * deleted. */
35189fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
35199fcb0251SFam Zheng {
35209a4d5ca6SJeff Cody     if (!bs) {
35219a4d5ca6SJeff Cody         return;
35229a4d5ca6SJeff Cody     }
35239fcb0251SFam Zheng     assert(bs->refcnt > 0);
35249fcb0251SFam Zheng     if (--bs->refcnt == 0) {
35259fcb0251SFam Zheng         bdrv_delete(bs);
35269fcb0251SFam Zheng     }
35279fcb0251SFam Zheng }
35289fcb0251SFam Zheng 
3529fbe40ff7SFam Zheng struct BdrvOpBlocker {
3530fbe40ff7SFam Zheng     Error *reason;
3531fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3532fbe40ff7SFam Zheng };
3533fbe40ff7SFam Zheng 
3534fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3535fbe40ff7SFam Zheng {
3536fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3537fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3538fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3539fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3540fbe40ff7SFam Zheng         if (errp) {
354181e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
354281e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3543bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3544fbe40ff7SFam Zheng         }
3545fbe40ff7SFam Zheng         return true;
3546fbe40ff7SFam Zheng     }
3547fbe40ff7SFam Zheng     return false;
3548fbe40ff7SFam Zheng }
3549fbe40ff7SFam Zheng 
3550fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3551fbe40ff7SFam Zheng {
3552fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3553fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3554fbe40ff7SFam Zheng 
35555839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3556fbe40ff7SFam Zheng     blocker->reason = reason;
3557fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3558fbe40ff7SFam Zheng }
3559fbe40ff7SFam Zheng 
3560fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3561fbe40ff7SFam Zheng {
3562fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3563fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3564fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3565fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3566fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3567fbe40ff7SFam Zheng             g_free(blocker);
3568fbe40ff7SFam Zheng         }
3569fbe40ff7SFam Zheng     }
3570fbe40ff7SFam Zheng }
3571fbe40ff7SFam Zheng 
3572fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3573fbe40ff7SFam Zheng {
3574fbe40ff7SFam Zheng     int i;
3575fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3576fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3577fbe40ff7SFam Zheng     }
3578fbe40ff7SFam Zheng }
3579fbe40ff7SFam Zheng 
3580fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3581fbe40ff7SFam Zheng {
3582fbe40ff7SFam Zheng     int i;
3583fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3584fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3585fbe40ff7SFam Zheng     }
3586fbe40ff7SFam Zheng }
3587fbe40ff7SFam Zheng 
3588fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3589fbe40ff7SFam Zheng {
3590fbe40ff7SFam Zheng     int i;
3591fbe40ff7SFam Zheng 
3592fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3593fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3594fbe40ff7SFam Zheng             return false;
3595fbe40ff7SFam Zheng         }
3596fbe40ff7SFam Zheng     }
3597fbe40ff7SFam Zheng     return true;
3598fbe40ff7SFam Zheng }
3599fbe40ff7SFam Zheng 
360028a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
360128a7282aSLuiz Capitulino {
3602d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
360358e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
360428a7282aSLuiz Capitulino }
360528a7282aSLuiz Capitulino 
360628a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
360728a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
360828a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
360928a7282aSLuiz Capitulino {
3610d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
361192aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
361292aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
361392aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
361428a7282aSLuiz Capitulino }
361528a7282aSLuiz Capitulino 
361628a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
361728a7282aSLuiz Capitulino {
3618d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
361928a7282aSLuiz Capitulino }
362028a7282aSLuiz Capitulino 
362128a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
362228a7282aSLuiz Capitulino {
362328a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
362458e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
36253bd293c3SPaolo Bonzini         if (bs->job) {
36263bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
36273bd293c3SPaolo Bonzini         }
362828a7282aSLuiz Capitulino     }
362928a7282aSLuiz Capitulino }
363028a7282aSLuiz Capitulino 
363128a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
363228a7282aSLuiz Capitulino {
36333e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
36343e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
363558e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
363658e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
363728a7282aSLuiz Capitulino     }
363828a7282aSLuiz Capitulino }
363928a7282aSLuiz Capitulino 
3640d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3641f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3642f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3643f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3644f88e1a42SJes Sorensen {
364583d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
364683d0521aSChunyan Liu     QemuOpts *opts = NULL;
364783d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
364883d0521aSChunyan Liu     int64_t size;
3649f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3650cc84d90fSMax Reitz     Error *local_err = NULL;
3651f88e1a42SJes Sorensen     int ret = 0;
3652f88e1a42SJes Sorensen 
3653f88e1a42SJes Sorensen     /* Find driver and parse its options */
3654f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3655f88e1a42SJes Sorensen     if (!drv) {
365671c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3657d92ada22SLuiz Capitulino         return;
3658f88e1a42SJes Sorensen     }
3659f88e1a42SJes Sorensen 
3660b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3661f88e1a42SJes Sorensen     if (!proto_drv) {
3662d92ada22SLuiz Capitulino         return;
3663f88e1a42SJes Sorensen     }
3664f88e1a42SJes Sorensen 
3665c6149724SMax Reitz     if (!drv->create_opts) {
3666c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3667c6149724SMax Reitz                    drv->format_name);
3668c6149724SMax Reitz         return;
3669c6149724SMax Reitz     }
3670c6149724SMax Reitz 
3671c6149724SMax Reitz     if (!proto_drv->create_opts) {
3672c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3673c6149724SMax Reitz                    proto_drv->format_name);
3674c6149724SMax Reitz         return;
3675c6149724SMax Reitz     }
3676c6149724SMax Reitz 
3677c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3678c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3679f88e1a42SJes Sorensen 
3680f88e1a42SJes Sorensen     /* Create parameter list with default values */
368183d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
368239101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3683f88e1a42SJes Sorensen 
3684f88e1a42SJes Sorensen     /* Parse -o options */
3685f88e1a42SJes Sorensen     if (options) {
3686dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3687dc523cd3SMarkus Armbruster         if (local_err) {
3688dc523cd3SMarkus Armbruster             error_report_err(local_err);
3689dc523cd3SMarkus Armbruster             local_err = NULL;
369083d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3691f88e1a42SJes Sorensen             goto out;
3692f88e1a42SJes Sorensen         }
3693f88e1a42SJes Sorensen     }
3694f88e1a42SJes Sorensen 
3695f88e1a42SJes Sorensen     if (base_filename) {
3696f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
36976be4194bSMarkus Armbruster         if (local_err) {
369871c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
369971c79813SLuiz Capitulino                        fmt);
3700f88e1a42SJes Sorensen             goto out;
3701f88e1a42SJes Sorensen         }
3702f88e1a42SJes Sorensen     }
3703f88e1a42SJes Sorensen 
3704f88e1a42SJes Sorensen     if (base_fmt) {
3705f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
37066be4194bSMarkus Armbruster         if (local_err) {
370771c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
370871c79813SLuiz Capitulino                              "format '%s'", fmt);
3709f88e1a42SJes Sorensen             goto out;
3710f88e1a42SJes Sorensen         }
3711f88e1a42SJes Sorensen     }
3712f88e1a42SJes Sorensen 
371383d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
371483d0521aSChunyan Liu     if (backing_file) {
371583d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
371671c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
371771c79813SLuiz Capitulino                              "same filename as the backing file");
3718792da93aSJes Sorensen             goto out;
3719792da93aSJes Sorensen         }
3720792da93aSJes Sorensen     }
3721792da93aSJes Sorensen 
372283d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3723f88e1a42SJes Sorensen 
3724f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3725f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
372683d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
372783d0521aSChunyan Liu     if (size == -1) {
372883d0521aSChunyan Liu         if (backing_file) {
372966f6b814SMax Reitz             BlockDriverState *bs;
373029168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
373152bf1e72SMarkus Armbruster             int64_t size;
373263090dacSPaolo Bonzini             int back_flags;
3733e6641719SMax Reitz             QDict *backing_options = NULL;
373463090dacSPaolo Bonzini 
373529168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
373629168018SMax Reitz                                                          full_backing, PATH_MAX,
373729168018SMax Reitz                                                          &local_err);
373829168018SMax Reitz             if (local_err) {
373929168018SMax Reitz                 g_free(full_backing);
374029168018SMax Reitz                 goto out;
374129168018SMax Reitz             }
374229168018SMax Reitz 
374363090dacSPaolo Bonzini             /* backing files always opened read-only */
374463090dacSPaolo Bonzini             back_flags =
374563090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3746f88e1a42SJes Sorensen 
3747e6641719SMax Reitz             if (backing_fmt) {
3748e6641719SMax Reitz                 backing_options = qdict_new();
3749e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3750e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3751e6641719SMax Reitz             }
3752e6641719SMax Reitz 
3753f67503e5SMax Reitz             bs = NULL;
3754e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
37556ebf9aa2SMax Reitz                             back_flags, &local_err);
375629168018SMax Reitz             g_free(full_backing);
3757f88e1a42SJes Sorensen             if (ret < 0) {
3758f88e1a42SJes Sorensen                 goto out;
3759f88e1a42SJes Sorensen             }
376052bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
376152bf1e72SMarkus Armbruster             if (size < 0) {
376252bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
376352bf1e72SMarkus Armbruster                                  backing_file);
376452bf1e72SMarkus Armbruster                 bdrv_unref(bs);
376552bf1e72SMarkus Armbruster                 goto out;
376652bf1e72SMarkus Armbruster             }
3767f88e1a42SJes Sorensen 
376839101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
376966f6b814SMax Reitz 
377066f6b814SMax Reitz             bdrv_unref(bs);
3771f88e1a42SJes Sorensen         } else {
377271c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3773f88e1a42SJes Sorensen             goto out;
3774f88e1a42SJes Sorensen         }
3775f88e1a42SJes Sorensen     }
3776f88e1a42SJes Sorensen 
3777f382d43aSMiroslav Rezanina     if (!quiet) {
3778f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
377943c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3780f88e1a42SJes Sorensen         puts("");
3781f382d43aSMiroslav Rezanina     }
378283d0521aSChunyan Liu 
3783c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
378483d0521aSChunyan Liu 
3785cc84d90fSMax Reitz     if (ret == -EFBIG) {
3786cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3787cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3788cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3789f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
379083d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3791f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3792f3f4d2c0SKevin Wolf         }
3793cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3794cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3795cc84d90fSMax Reitz         error_free(local_err);
3796cc84d90fSMax Reitz         local_err = NULL;
3797f88e1a42SJes Sorensen     }
3798f88e1a42SJes Sorensen 
3799f88e1a42SJes Sorensen out:
380083d0521aSChunyan Liu     qemu_opts_del(opts);
380183d0521aSChunyan Liu     qemu_opts_free(create_opts);
380284d18f06SMarkus Armbruster     if (local_err) {
3803cc84d90fSMax Reitz         error_propagate(errp, local_err);
3804cc84d90fSMax Reitz     }
3805f88e1a42SJes Sorensen }
380685d126f3SStefan Hajnoczi 
380785d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
380885d126f3SStefan Hajnoczi {
3809dcd04228SStefan Hajnoczi     return bs->aio_context;
3810dcd04228SStefan Hajnoczi }
3811dcd04228SStefan Hajnoczi 
3812dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3813dcd04228SStefan Hajnoczi {
381433384421SMax Reitz     BdrvAioNotifier *baf;
381533384421SMax Reitz 
3816dcd04228SStefan Hajnoczi     if (!bs->drv) {
3817dcd04228SStefan Hajnoczi         return;
3818dcd04228SStefan Hajnoczi     }
3819dcd04228SStefan Hajnoczi 
382033384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
382133384421SMax Reitz         baf->detach_aio_context(baf->opaque);
382233384421SMax Reitz     }
382333384421SMax Reitz 
382413af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
38250e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
382613af91ebSStefan Hajnoczi     }
3827dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3828dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3829dcd04228SStefan Hajnoczi     }
3830dcd04228SStefan Hajnoczi     if (bs->file) {
38319a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3832dcd04228SStefan Hajnoczi     }
3833760e0063SKevin Wolf     if (bs->backing) {
3834760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3835dcd04228SStefan Hajnoczi     }
3836dcd04228SStefan Hajnoczi 
3837dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3838dcd04228SStefan Hajnoczi }
3839dcd04228SStefan Hajnoczi 
3840dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3841dcd04228SStefan Hajnoczi                              AioContext *new_context)
3842dcd04228SStefan Hajnoczi {
384333384421SMax Reitz     BdrvAioNotifier *ban;
384433384421SMax Reitz 
3845dcd04228SStefan Hajnoczi     if (!bs->drv) {
3846dcd04228SStefan Hajnoczi         return;
3847dcd04228SStefan Hajnoczi     }
3848dcd04228SStefan Hajnoczi 
3849dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3850dcd04228SStefan Hajnoczi 
3851760e0063SKevin Wolf     if (bs->backing) {
3852760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3853dcd04228SStefan Hajnoczi     }
3854dcd04228SStefan Hajnoczi     if (bs->file) {
38559a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3856dcd04228SStefan Hajnoczi     }
3857dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3858dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3859dcd04228SStefan Hajnoczi     }
386013af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
38610e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
386213af91ebSStefan Hajnoczi     }
386333384421SMax Reitz 
386433384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
386533384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
386633384421SMax Reitz     }
3867dcd04228SStefan Hajnoczi }
3868dcd04228SStefan Hajnoczi 
3869dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3870dcd04228SStefan Hajnoczi {
387153ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3872dcd04228SStefan Hajnoczi 
3873dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3874dcd04228SStefan Hajnoczi 
3875dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3876dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3877dcd04228SStefan Hajnoczi      */
3878dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3879dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3880dcd04228SStefan Hajnoczi     aio_context_release(new_context);
388185d126f3SStefan Hajnoczi }
3882d616b224SStefan Hajnoczi 
388333384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
388433384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
388533384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
388633384421SMax Reitz {
388733384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
388833384421SMax Reitz     *ban = (BdrvAioNotifier){
388933384421SMax Reitz         .attached_aio_context = attached_aio_context,
389033384421SMax Reitz         .detach_aio_context   = detach_aio_context,
389133384421SMax Reitz         .opaque               = opaque
389233384421SMax Reitz     };
389333384421SMax Reitz 
389433384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
389533384421SMax Reitz }
389633384421SMax Reitz 
389733384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
389833384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
389933384421SMax Reitz                                                                    void *),
390033384421SMax Reitz                                       void (*detach_aio_context)(void *),
390133384421SMax Reitz                                       void *opaque)
390233384421SMax Reitz {
390333384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
390433384421SMax Reitz 
390533384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
390633384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
390733384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
390833384421SMax Reitz             ban->opaque               == opaque)
390933384421SMax Reitz         {
391033384421SMax Reitz             QLIST_REMOVE(ban, list);
391133384421SMax Reitz             g_free(ban);
391233384421SMax Reitz 
391333384421SMax Reitz             return;
391433384421SMax Reitz         }
391533384421SMax Reitz     }
391633384421SMax Reitz 
391733384421SMax Reitz     abort();
391833384421SMax Reitz }
391933384421SMax Reitz 
392077485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
392177485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
39226f176b48SMax Reitz {
3923c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
39246f176b48SMax Reitz         return -ENOTSUP;
39256f176b48SMax Reitz     }
392677485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
39276f176b48SMax Reitz }
3928f6186f49SBenoît Canet 
3929b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3930b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3931b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3932b5042a36SBenoît Canet  * node graph.
3933212a5a8fSBenoît Canet  */
3934212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3935212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3936f6186f49SBenoît Canet {
3937b5042a36SBenoît Canet     /* return false if basic checks fails */
3938b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3939b5042a36SBenoît Canet         return false;
3940b5042a36SBenoît Canet     }
3941b5042a36SBenoît Canet 
3942b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3943b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3944b5042a36SBenoît Canet      */
3945b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3946b5042a36SBenoît Canet         return bs == candidate;
3947b5042a36SBenoît Canet     }
3948b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3949b5042a36SBenoît Canet 
3950b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3951b5042a36SBenoît Canet      * the node graph.
3952b5042a36SBenoît Canet      */
3953b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3954212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3955212a5a8fSBenoît Canet     }
3956212a5a8fSBenoît Canet 
3957b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3958b5042a36SBenoît Canet      */
3959b5042a36SBenoît Canet     return false;
3960212a5a8fSBenoît Canet }
3961212a5a8fSBenoît Canet 
3962212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3963212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3964212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3965212a5a8fSBenoît Canet  */
3966212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3967212a5a8fSBenoît Canet {
3968212a5a8fSBenoît Canet     BlockDriverState *bs;
3969212a5a8fSBenoît Canet 
3970212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
3971212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3972212a5a8fSBenoît Canet         bool perm;
3973212a5a8fSBenoît Canet 
3974b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3975e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3976212a5a8fSBenoît Canet 
3977212a5a8fSBenoît Canet         /* candidate is the first non filter */
3978212a5a8fSBenoît Canet         if (perm) {
3979212a5a8fSBenoît Canet             return true;
3980212a5a8fSBenoît Canet         }
3981212a5a8fSBenoît Canet     }
3982212a5a8fSBenoît Canet 
3983212a5a8fSBenoît Canet     return false;
3984f6186f49SBenoît Canet }
398509158f00SBenoît Canet 
3986e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3987e12f3784SWen Congyang                                         const char *node_name, Error **errp)
398809158f00SBenoît Canet {
398909158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
39905a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
39915a7e7a0bSStefan Hajnoczi 
399209158f00SBenoît Canet     if (!to_replace_bs) {
399309158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
399409158f00SBenoît Canet         return NULL;
399509158f00SBenoît Canet     }
399609158f00SBenoît Canet 
39975a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
39985a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
39995a7e7a0bSStefan Hajnoczi 
400009158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
40015a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40025a7e7a0bSStefan Hajnoczi         goto out;
400309158f00SBenoît Canet     }
400409158f00SBenoît Canet 
400509158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
400609158f00SBenoît Canet      * most non filter in order to prevent data corruption.
400709158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
400809158f00SBenoît Canet      * blocked by the backing blockers.
400909158f00SBenoît Canet      */
4010e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
401109158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
40125a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40135a7e7a0bSStefan Hajnoczi         goto out;
401409158f00SBenoît Canet     }
401509158f00SBenoît Canet 
40165a7e7a0bSStefan Hajnoczi out:
40175a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
401809158f00SBenoît Canet     return to_replace_bs;
401909158f00SBenoît Canet }
4020448ad91dSMing Lei 
402191af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
402291af7014SMax Reitz {
402391af7014SMax Reitz     const QDictEntry *entry;
402491af7014SMax Reitz     bool found_any = false;
402591af7014SMax Reitz 
402691af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
402791af7014SMax Reitz          entry = qdict_next(bs->options, entry))
402891af7014SMax Reitz     {
402991af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
403091af7014SMax Reitz          * options */
403191af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
403291af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
403391af7014SMax Reitz         {
403491af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
403591af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
403691af7014SMax Reitz             found_any = true;
403791af7014SMax Reitz         }
403891af7014SMax Reitz     }
403991af7014SMax Reitz 
404091af7014SMax Reitz     return found_any;
404191af7014SMax Reitz }
404291af7014SMax Reitz 
404391af7014SMax Reitz /* Updates the following BDS fields:
404491af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
404591af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
404691af7014SMax Reitz  *                    other options; so reading and writing must return the same
404791af7014SMax Reitz  *                    results, but caching etc. may be different)
404891af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
404991af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
405091af7014SMax Reitz  *                       equalling the given one
405191af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
405291af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
405391af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
405491af7014SMax Reitz  */
405591af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
405691af7014SMax Reitz {
405791af7014SMax Reitz     BlockDriver *drv = bs->drv;
405891af7014SMax Reitz     QDict *opts;
405991af7014SMax Reitz 
406091af7014SMax Reitz     if (!drv) {
406191af7014SMax Reitz         return;
406291af7014SMax Reitz     }
406391af7014SMax Reitz 
406491af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
406591af7014SMax Reitz      * refresh that first */
406691af7014SMax Reitz     if (bs->file) {
40679a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
406891af7014SMax Reitz     }
406991af7014SMax Reitz 
407091af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
407191af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
407291af7014SMax Reitz          * information before refreshing it */
407391af7014SMax Reitz         bs->exact_filename[0] = '\0';
407491af7014SMax Reitz         if (bs->full_open_options) {
407591af7014SMax Reitz             QDECREF(bs->full_open_options);
407691af7014SMax Reitz             bs->full_open_options = NULL;
407791af7014SMax Reitz         }
407891af7014SMax Reitz 
407991af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
408091af7014SMax Reitz     } else if (bs->file) {
408191af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
408291af7014SMax Reitz         bool has_open_options;
408391af7014SMax Reitz 
408491af7014SMax Reitz         bs->exact_filename[0] = '\0';
408591af7014SMax Reitz         if (bs->full_open_options) {
408691af7014SMax Reitz             QDECREF(bs->full_open_options);
408791af7014SMax Reitz             bs->full_open_options = NULL;
408891af7014SMax Reitz         }
408991af7014SMax Reitz 
409091af7014SMax Reitz         opts = qdict_new();
409191af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
409291af7014SMax Reitz 
409391af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
409491af7014SMax Reitz          * the underlying file should suffice for this one as well */
40959a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
40969a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
409791af7014SMax Reitz         }
409891af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
409991af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
410091af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
410191af7014SMax Reitz          * contain a representation of the filename, therefore the following
410291af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
41039a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
410491af7014SMax Reitz             qdict_put_obj(opts, "driver",
410591af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
41069a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
41079a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
41089a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
410991af7014SMax Reitz 
411091af7014SMax Reitz             bs->full_open_options = opts;
411191af7014SMax Reitz         } else {
411291af7014SMax Reitz             QDECREF(opts);
411391af7014SMax Reitz         }
411491af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
411591af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
411691af7014SMax Reitz          * so the full options QDict should be equal to the options given
411791af7014SMax Reitz          * specifically for this block device when it was opened (plus the
411891af7014SMax Reitz          * driver specification).
411991af7014SMax Reitz          * Because those options don't change, there is no need to update
412091af7014SMax Reitz          * full_open_options when it's already set. */
412191af7014SMax Reitz 
412291af7014SMax Reitz         opts = qdict_new();
412391af7014SMax Reitz         append_open_options(opts, bs);
412491af7014SMax Reitz         qdict_put_obj(opts, "driver",
412591af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
412691af7014SMax Reitz 
412791af7014SMax Reitz         if (bs->exact_filename[0]) {
412891af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
412991af7014SMax Reitz              * require this filename to be parsed), but we have to find some
413091af7014SMax Reitz              * default solution here, so just include it. If some block driver
413191af7014SMax Reitz              * does not support pure options without any filename at all or
413291af7014SMax Reitz              * needs some special format of the options QDict, it needs to
413391af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
413491af7014SMax Reitz              */
413591af7014SMax Reitz             qdict_put_obj(opts, "filename",
413691af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
413791af7014SMax Reitz         }
413891af7014SMax Reitz 
413991af7014SMax Reitz         bs->full_open_options = opts;
414091af7014SMax Reitz     }
414191af7014SMax Reitz 
414291af7014SMax Reitz     if (bs->exact_filename[0]) {
414391af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
414491af7014SMax Reitz     } else if (bs->full_open_options) {
414591af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
414691af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
414791af7014SMax Reitz                  qstring_get_str(json));
414891af7014SMax Reitz         QDECREF(json);
414991af7014SMax Reitz     }
415091af7014SMax Reitz }
41515366d0c8SBenoît Canet 
41525366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the
41535366d0c8SBenoît Canet  * BlockAcctStats structure embedded inside a BlockDriverState without being
41545366d0c8SBenoît Canet  * aware of the BlockDriverState structure layout.
41555366d0c8SBenoît Canet  * It will go away when the BlockAcctStats structure will be moved inside
41565366d0c8SBenoît Canet  * the device models.
41575366d0c8SBenoît Canet  */
41585366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
41595366d0c8SBenoît Canet {
41605366d0c8SBenoît Canet     return &bs->stats;
41615366d0c8SBenoît Canet }
4162