xref: /openbmc/qemu/block.c (revision 760e006384ecd5b8b8b1b91b5c85ff8fdcb3a21f)
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 /*
724*760e0063SKevin 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 {
7666913c0c2SBenoît Canet     if (!node_name) {
767636ea370SKevin Wolf         return;
7686913c0c2SBenoît Canet     }
7696913c0c2SBenoît Canet 
7709aebf3b8SKevin Wolf     /* Check for empty string or invalid characters */
771f5bebbbbSMarkus Armbruster     if (!id_wellformed(node_name)) {
7729aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
773636ea370SKevin Wolf         return;
7746913c0c2SBenoît Canet     }
7756913c0c2SBenoît Canet 
7760c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
7777f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
7780c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
7790c5e94eeSBenoît Canet                    node_name);
780636ea370SKevin Wolf         return;
7810c5e94eeSBenoît Canet     }
7820c5e94eeSBenoît Canet 
7836913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
7846913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
7856913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
786636ea370SKevin Wolf         return;
7876913c0c2SBenoît Canet     }
7886913c0c2SBenoît Canet 
7896913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
7906913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
7916913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
7926913c0c2SBenoît Canet }
7936913c0c2SBenoît Canet 
79418edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
79518edf289SKevin Wolf     .name = "bdrv_common",
79618edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
79718edf289SKevin Wolf     .desc = {
79818edf289SKevin Wolf         {
79918edf289SKevin Wolf             .name = "node-name",
80018edf289SKevin Wolf             .type = QEMU_OPT_STRING,
80118edf289SKevin Wolf             .help = "Node name of the block device node",
80218edf289SKevin Wolf         },
80318edf289SKevin Wolf         { /* end of list */ }
80418edf289SKevin Wolf     },
80518edf289SKevin Wolf };
80618edf289SKevin Wolf 
807b6ce07aaSKevin Wolf /*
80857915332SKevin Wolf  * Common part for opening disk images and files
809b6ad491aSKevin Wolf  *
810b6ad491aSKevin Wolf  * Removes all processed options from *options.
81157915332SKevin Wolf  */
8129a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
81334b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
81457915332SKevin Wolf {
81557915332SKevin Wolf     int ret, open_flags;
816035fccdfSKevin Wolf     const char *filename;
8176913c0c2SBenoît Canet     const char *node_name = NULL;
81818edf289SKevin Wolf     QemuOpts *opts;
81934b5d2c6SMax Reitz     Error *local_err = NULL;
82057915332SKevin Wolf 
82157915332SKevin Wolf     assert(drv != NULL);
8226405875cSPaolo Bonzini     assert(bs->file == NULL);
823707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
82457915332SKevin Wolf 
82545673671SKevin Wolf     if (file != NULL) {
8269a4f4c31SKevin Wolf         filename = file->bs->filename;
82745673671SKevin Wolf     } else {
82845673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
82945673671SKevin Wolf     }
83045673671SKevin Wolf 
831765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
832765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
833765003dbSKevin Wolf                    drv->format_name);
834765003dbSKevin Wolf         return -EINVAL;
835765003dbSKevin Wolf     }
836765003dbSKevin Wolf 
83745673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
83828dcee10SStefan Hajnoczi 
83918edf289SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
84018edf289SKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
84118edf289SKevin Wolf     if (local_err) {
84218edf289SKevin Wolf         error_propagate(errp, local_err);
84318edf289SKevin Wolf         ret = -EINVAL;
84418edf289SKevin Wolf         goto fail_opts;
84518edf289SKevin Wolf     }
84618edf289SKevin Wolf 
84718edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
848636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8490fb6395cSMarkus Armbruster     if (local_err) {
850636ea370SKevin Wolf         error_propagate(errp, local_err);
85118edf289SKevin Wolf         ret = -EINVAL;
85218edf289SKevin Wolf         goto fail_opts;
8535d186eb0SKevin Wolf     }
8545d186eb0SKevin Wolf 
8551b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
856c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8570d51b4deSAsias He     bs->zero_beyond_eof = true;
858b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
859b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
860b64ec4e4SFam Zheng 
861b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8628f94a6e4SKevin Wolf         error_setg(errp,
8638f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8648f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8658f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8668f94a6e4SKevin Wolf                    drv->format_name);
86718edf289SKevin Wolf         ret = -ENOTSUP;
86818edf289SKevin Wolf         goto fail_opts;
869b64ec4e4SFam Zheng     }
87057915332SKevin Wolf 
87153fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8720ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8730ebd24e0SKevin Wolf         if (!bs->read_only) {
87453fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8750ebd24e0SKevin Wolf         } else {
8760ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
87718edf289SKevin Wolf             ret = -EINVAL;
87818edf289SKevin Wolf             goto fail_opts;
8790ebd24e0SKevin Wolf         }
88053fec9d3SStefan Hajnoczi     }
88153fec9d3SStefan Hajnoczi 
882c2ad1b0cSKevin Wolf     if (filename != NULL) {
88357915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
884c2ad1b0cSKevin Wolf     } else {
885c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
886c2ad1b0cSKevin Wolf     }
88791af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
88857915332SKevin Wolf 
88957915332SKevin Wolf     bs->drv = drv;
8907267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
89157915332SKevin Wolf 
89203f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
893e7c63796SStefan Hajnoczi 
89466f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
89566f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8965d186eb0SKevin Wolf         assert(file == NULL);
897030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
89834b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
899f500a6d3SKevin Wolf     } else {
9002af5ef70SKevin Wolf         if (file == NULL) {
90134b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
90234b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9032af5ef70SKevin Wolf             ret = -EINVAL;
9042af5ef70SKevin Wolf             goto free_and_fail;
9052af5ef70SKevin Wolf         }
906f500a6d3SKevin Wolf         bs->file = file;
90734b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
90866f82ceeSKevin Wolf     }
90966f82ceeSKevin Wolf 
91057915332SKevin Wolf     if (ret < 0) {
91184d18f06SMarkus Armbruster         if (local_err) {
91234b5d2c6SMax Reitz             error_propagate(errp, local_err);
9132fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9142fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
91534b5d2c6SMax Reitz         } else {
91634b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
91734b5d2c6SMax Reitz         }
91857915332SKevin Wolf         goto free_and_fail;
91957915332SKevin Wolf     }
92057915332SKevin Wolf 
921a1f688f4SMarkus Armbruster     if (bs->encrypted) {
922a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
923a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
924a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
925a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
926a1f688f4SMarkus Armbruster     }
927a1f688f4SMarkus Armbruster 
92851762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
92951762288SStefan Hajnoczi     if (ret < 0) {
93034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
93151762288SStefan Hajnoczi         goto free_and_fail;
93257915332SKevin Wolf     }
93351762288SStefan Hajnoczi 
9343baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
9353baca891SKevin Wolf     if (local_err) {
9363baca891SKevin Wolf         error_propagate(errp, local_err);
9373baca891SKevin Wolf         ret = -EINVAL;
9383baca891SKevin Wolf         goto free_and_fail;
9393baca891SKevin Wolf     }
9403baca891SKevin Wolf 
941c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9424196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
943b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
94418edf289SKevin Wolf 
94518edf289SKevin Wolf     qemu_opts_del(opts);
94657915332SKevin Wolf     return 0;
94757915332SKevin Wolf 
94857915332SKevin Wolf free_and_fail:
94966f82ceeSKevin Wolf     bs->file = NULL;
9507267c094SAnthony Liguori     g_free(bs->opaque);
95157915332SKevin Wolf     bs->opaque = NULL;
95257915332SKevin Wolf     bs->drv = NULL;
95318edf289SKevin Wolf fail_opts:
95418edf289SKevin Wolf     qemu_opts_del(opts);
95557915332SKevin Wolf     return ret;
95657915332SKevin Wolf }
95757915332SKevin Wolf 
9585e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9595e5c4f63SKevin Wolf {
9605e5c4f63SKevin Wolf     QObject *options_obj;
9615e5c4f63SKevin Wolf     QDict *options;
9625e5c4f63SKevin Wolf     int ret;
9635e5c4f63SKevin Wolf 
9645e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
9655e5c4f63SKevin Wolf     assert(ret);
9665e5c4f63SKevin Wolf 
9675e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
9685e5c4f63SKevin Wolf     if (!options_obj) {
9695e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
9705e5c4f63SKevin Wolf         return NULL;
9715e5c4f63SKevin Wolf     }
9725e5c4f63SKevin Wolf 
9735e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
9745e5c4f63SKevin Wolf         qobject_decref(options_obj);
9755e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
9765e5c4f63SKevin Wolf         return NULL;
9775e5c4f63SKevin Wolf     }
9785e5c4f63SKevin Wolf 
9795e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
9805e5c4f63SKevin Wolf     qdict_flatten(options);
9815e5c4f63SKevin Wolf 
9825e5c4f63SKevin Wolf     return options;
9835e5c4f63SKevin Wolf }
9845e5c4f63SKevin Wolf 
98557915332SKevin Wolf /*
986f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
987f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
98853a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
98953a29513SMax Reitz  * block driver has been specified explicitly.
990f54120ffSKevin Wolf  */
99153a29513SMax Reitz static int bdrv_fill_options(QDict **options, const char **pfilename,
992053e1578SMax Reitz                              int *flags, Error **errp)
993f54120ffSKevin Wolf {
9945e5c4f63SKevin Wolf     const char *filename = *pfilename;
995f54120ffSKevin Wolf     const char *drvname;
99653a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
997f54120ffSKevin Wolf     bool parse_filename = false;
998053e1578SMax Reitz     BlockDriver *drv = NULL;
999f54120ffSKevin Wolf     Error *local_err = NULL;
1000f54120ffSKevin Wolf 
10015e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10025e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10035e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10045e5c4f63SKevin Wolf         if (local_err) {
10055e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10065e5c4f63SKevin Wolf             return -EINVAL;
10075e5c4f63SKevin Wolf         }
10085e5c4f63SKevin Wolf 
10095e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10105e5c4f63SKevin Wolf          * specified directly */
10115e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10125e5c4f63SKevin Wolf         QDECREF(json_options);
10135e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10145e5c4f63SKevin Wolf     }
10155e5c4f63SKevin Wolf 
101653a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1017053e1578SMax Reitz     if (drvname) {
1018053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1019053e1578SMax Reitz         if (!drv) {
1020053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1021053e1578SMax Reitz             return -ENOENT;
1022053e1578SMax Reitz         }
102353a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
102453a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1025053e1578SMax Reitz         protocol = drv->bdrv_file_open;
102653a29513SMax Reitz     }
102753a29513SMax Reitz 
102853a29513SMax Reitz     if (protocol) {
102953a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
103053a29513SMax Reitz     } else {
103153a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
103253a29513SMax Reitz     }
103353a29513SMax Reitz 
1034f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
103517b005f1SKevin Wolf     if (protocol && filename) {
1036f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1037f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1038f54120ffSKevin Wolf             parse_filename = true;
1039f54120ffSKevin Wolf         } else {
1040f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1041f54120ffSKevin Wolf                              "the same time");
1042f54120ffSKevin Wolf             return -EINVAL;
1043f54120ffSKevin Wolf         }
1044f54120ffSKevin Wolf     }
1045f54120ffSKevin Wolf 
1046f54120ffSKevin Wolf     /* Find the right block driver */
1047f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1048f54120ffSKevin Wolf 
104917b005f1SKevin Wolf     if (!drvname && protocol) {
1050f54120ffSKevin Wolf         if (filename) {
1051b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1052f54120ffSKevin Wolf             if (!drv) {
1053f54120ffSKevin Wolf                 return -EINVAL;
1054f54120ffSKevin Wolf             }
1055f54120ffSKevin Wolf 
1056f54120ffSKevin Wolf             drvname = drv->format_name;
1057f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1058f54120ffSKevin Wolf         } else {
1059f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1060f54120ffSKevin Wolf             return -EINVAL;
1061f54120ffSKevin Wolf         }
106217b005f1SKevin Wolf     }
106317b005f1SKevin Wolf 
106417b005f1SKevin Wolf     assert(drv || !protocol);
1065f54120ffSKevin Wolf 
1066f54120ffSKevin Wolf     /* Driver-specific filename parsing */
106717b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1068f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1069f54120ffSKevin Wolf         if (local_err) {
1070f54120ffSKevin Wolf             error_propagate(errp, local_err);
1071f54120ffSKevin Wolf             return -EINVAL;
1072f54120ffSKevin Wolf         }
1073f54120ffSKevin Wolf 
1074f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1075f54120ffSKevin Wolf             qdict_del(*options, "filename");
1076f54120ffSKevin Wolf         }
1077f54120ffSKevin Wolf     }
1078f54120ffSKevin Wolf 
1079f54120ffSKevin Wolf     return 0;
1080f54120ffSKevin Wolf }
1081f54120ffSKevin Wolf 
1082b4b059f6SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1083df581792SKevin Wolf                                     BlockDriverState *child_bs,
1084df581792SKevin Wolf                                     const BdrvChildRole *child_role)
1085df581792SKevin Wolf {
1086df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1087df581792SKevin Wolf     *child = (BdrvChild) {
1088df581792SKevin Wolf         .bs     = child_bs,
1089df581792SKevin Wolf         .role   = child_role,
1090df581792SKevin Wolf     };
1091df581792SKevin Wolf 
1092df581792SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1093b4b059f6SKevin Wolf 
1094b4b059f6SKevin Wolf     return child;
1095df581792SKevin Wolf }
1096df581792SKevin Wolf 
109733a60407SKevin Wolf static void bdrv_detach_child(BdrvChild *child)
109833a60407SKevin Wolf {
109933a60407SKevin Wolf     QLIST_REMOVE(child, next);
110033a60407SKevin Wolf     g_free(child);
110133a60407SKevin Wolf }
110233a60407SKevin Wolf 
110333a60407SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
110433a60407SKevin Wolf {
110533a60407SKevin Wolf     BlockDriverState *child_bs = child->bs;
110633a60407SKevin Wolf 
110733a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
110833a60407SKevin Wolf         child->bs->inherits_from = NULL;
110933a60407SKevin Wolf     }
111033a60407SKevin Wolf 
111133a60407SKevin Wolf     bdrv_detach_child(child);
111233a60407SKevin Wolf     bdrv_unref(child_bs);
111333a60407SKevin Wolf }
111433a60407SKevin Wolf 
11158d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11168d24cce1SFam Zheng {
11178d24cce1SFam Zheng 
1118*760e0063SKevin Wolf     if (bs->backing) {
1119826b6ca0SFam Zheng         assert(bs->backing_blocker);
1120*760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
1121*760e0063SKevin Wolf         bdrv_detach_child(bs->backing);
1122826b6ca0SFam Zheng     } else if (backing_hd) {
1123826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
112481e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
112581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1126826b6ca0SFam Zheng     }
1127826b6ca0SFam Zheng 
11288d24cce1SFam Zheng     if (!backing_hd) {
1129826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1130826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1131*760e0063SKevin Wolf         bs->backing = NULL;
11328d24cce1SFam Zheng         goto out;
11338d24cce1SFam Zheng     }
1134*760e0063SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, &child_backing);
11358d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11368d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11378d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11388d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1139826b6ca0SFam Zheng 
1140*760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1141826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1142*760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1143826b6ca0SFam Zheng                     bs->backing_blocker);
11448d24cce1SFam Zheng out:
11453baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11468d24cce1SFam Zheng }
11478d24cce1SFam Zheng 
114831ca6d07SKevin Wolf /*
114931ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
115031ca6d07SKevin Wolf  *
115131ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
115231ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
115331ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
115431ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
115531ca6d07SKevin Wolf  */
115634b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11579156df12SPaolo Bonzini {
11581ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1159317fc44eSKevin Wolf     int ret = 0;
11608d24cce1SFam Zheng     BlockDriverState *backing_hd;
116134b5d2c6SMax Reitz     Error *local_err = NULL;
11629156df12SPaolo Bonzini 
1163*760e0063SKevin Wolf     if (bs->backing != NULL) {
116431ca6d07SKevin Wolf         QDECREF(options);
11651ba4b6a5SBenoît Canet         goto free_exit;
11669156df12SPaolo Bonzini     }
11679156df12SPaolo Bonzini 
116831ca6d07SKevin Wolf     /* NULL means an empty set of options */
116931ca6d07SKevin Wolf     if (options == NULL) {
117031ca6d07SKevin Wolf         options = qdict_new();
117131ca6d07SKevin Wolf     }
117231ca6d07SKevin Wolf 
11739156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
11741cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
11751cb6f506SKevin Wolf         backing_filename[0] = '\0';
11761cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
117731ca6d07SKevin Wolf         QDECREF(options);
11781ba4b6a5SBenoît Canet         goto free_exit;
1179dbecebddSFam Zheng     } else {
11809f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
11819f07429eSMax Reitz                                        &local_err);
11829f07429eSMax Reitz         if (local_err) {
11839f07429eSMax Reitz             ret = -EINVAL;
11849f07429eSMax Reitz             error_propagate(errp, local_err);
11859f07429eSMax Reitz             QDECREF(options);
11869f07429eSMax Reitz             goto free_exit;
11879f07429eSMax Reitz         }
11889156df12SPaolo Bonzini     }
11899156df12SPaolo Bonzini 
11908ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
11918ee79e70SKevin Wolf         ret = -EINVAL;
11928ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
11938ee79e70SKevin Wolf         QDECREF(options);
11948ee79e70SKevin Wolf         goto free_exit;
11958ee79e70SKevin Wolf     }
11968ee79e70SKevin Wolf 
1197e4e9986bSMarkus Armbruster     backing_hd = bdrv_new();
11988d24cce1SFam Zheng 
1199c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1200c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
12019156df12SPaolo Bonzini     }
12029156df12SPaolo Bonzini 
1203*760e0063SKevin Wolf     assert(bs->backing == NULL);
1204f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1205f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1206ce343771SMax Reitz                             NULL, options, 0, bs, &child_backing, &local_err);
12079156df12SPaolo Bonzini     if (ret < 0) {
12088d24cce1SFam Zheng         bdrv_unref(backing_hd);
12098d24cce1SFam Zheng         backing_hd = NULL;
12109156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1211b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1212b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1213b04b6b6eSFam Zheng         error_free(local_err);
12141ba4b6a5SBenoît Canet         goto free_exit;
12159156df12SPaolo Bonzini     }
1216df581792SKevin Wolf 
12178d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
1218d80ac658SPeter Feiner 
12191ba4b6a5SBenoît Canet free_exit:
12201ba4b6a5SBenoît Canet     g_free(backing_filename);
12211ba4b6a5SBenoît Canet     return ret;
12229156df12SPaolo Bonzini }
12239156df12SPaolo Bonzini 
1224b6ce07aaSKevin Wolf /*
1225da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1226da557aacSMax Reitz  * device's options.
1227da557aacSMax Reitz  *
1228da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1229b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1230da557aacSMax Reitz  *
1231da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1232da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1233da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1234da557aacSMax Reitz  * BlockdevRef.
1235da557aacSMax Reitz  *
1236da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1237da557aacSMax Reitz  */
1238b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1239f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1240b4b059f6SKevin Wolf                            BlockDriverState* parent,
1241b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1242f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1243da557aacSMax Reitz {
1244b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1245b4b059f6SKevin Wolf     BlockDriverState *bs;
1246da557aacSMax Reitz     QDict *image_options;
1247da557aacSMax Reitz     int ret;
1248da557aacSMax Reitz     char *bdref_key_dot;
1249da557aacSMax Reitz     const char *reference;
1250da557aacSMax Reitz 
1251df581792SKevin Wolf     assert(child_role != NULL);
1252f67503e5SMax Reitz 
1253da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1254da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1255da557aacSMax Reitz     g_free(bdref_key_dot);
1256da557aacSMax Reitz 
1257da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1258da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1259b4b059f6SKevin Wolf         if (!allow_none) {
1260da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1261da557aacSMax Reitz                        bdref_key);
1262da557aacSMax Reitz         }
1263b20e61e0SMarkus Armbruster         QDECREF(image_options);
1264da557aacSMax Reitz         goto done;
1265da557aacSMax Reitz     }
1266da557aacSMax Reitz 
1267b4b059f6SKevin Wolf     bs = NULL;
1268b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1269ce343771SMax Reitz                             parent, child_role, errp);
1270df581792SKevin Wolf     if (ret < 0) {
1271df581792SKevin Wolf         goto done;
1272df581792SKevin Wolf     }
1273df581792SKevin Wolf 
1274b4b059f6SKevin Wolf     c = bdrv_attach_child(parent, bs, child_role);
1275da557aacSMax Reitz 
1276da557aacSMax Reitz done:
1277da557aacSMax Reitz     qdict_del(options, bdref_key);
1278b4b059f6SKevin Wolf     return c;
1279b4b059f6SKevin Wolf }
1280b4b059f6SKevin Wolf 
12816b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1282b998875dSKevin Wolf {
1283b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
12841ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1285b998875dSKevin Wolf     int64_t total_size;
128683d0521aSChunyan Liu     QemuOpts *opts = NULL;
1287b998875dSKevin Wolf     QDict *snapshot_options;
1288b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1289c2e0dbbfSFam Zheng     Error *local_err = NULL;
1290b998875dSKevin Wolf     int ret;
1291b998875dSKevin Wolf 
1292b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1293b998875dSKevin Wolf        instead of opening 'filename' directly */
1294b998875dSKevin Wolf 
1295b998875dSKevin Wolf     /* Get the required size from the image */
1296f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1297f187743aSKevin Wolf     if (total_size < 0) {
12986b8aeca5SChen Gang         ret = total_size;
1299f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13001ba4b6a5SBenoît Canet         goto out;
1301f187743aSKevin Wolf     }
1302b998875dSKevin Wolf 
1303b998875dSKevin Wolf     /* Create the temporary image */
13041ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1305b998875dSKevin Wolf     if (ret < 0) {
1306b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13071ba4b6a5SBenoît Canet         goto out;
1308b998875dSKevin Wolf     }
1309b998875dSKevin Wolf 
1310ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1311c282e1fdSChunyan Liu                             &error_abort);
131239101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1313ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
131483d0521aSChunyan Liu     qemu_opts_del(opts);
1315b998875dSKevin Wolf     if (ret < 0) {
1316b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1317b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1318b998875dSKevin Wolf                          error_get_pretty(local_err));
1319b998875dSKevin Wolf         error_free(local_err);
13201ba4b6a5SBenoît Canet         goto out;
1321b998875dSKevin Wolf     }
1322b998875dSKevin Wolf 
1323b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1324b998875dSKevin Wolf     snapshot_options = qdict_new();
1325b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1326b998875dSKevin Wolf               qstring_from_str("file"));
1327b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1328b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1329e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1330e6641719SMax Reitz               qstring_from_str("qcow2"));
1331b998875dSKevin Wolf 
1332e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1333b998875dSKevin Wolf 
1334b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
13356ebf9aa2SMax Reitz                     flags, &local_err);
1336b998875dSKevin Wolf     if (ret < 0) {
1337b998875dSKevin Wolf         error_propagate(errp, local_err);
13381ba4b6a5SBenoît Canet         goto out;
1339b998875dSKevin Wolf     }
1340b998875dSKevin Wolf 
1341b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
13421ba4b6a5SBenoît Canet 
13431ba4b6a5SBenoît Canet out:
13441ba4b6a5SBenoît Canet     g_free(tmp_filename);
13456b8aeca5SChen Gang     return ret;
1346b998875dSKevin Wolf }
1347b998875dSKevin Wolf 
1348da557aacSMax Reitz /*
1349b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1350de9c0cecSKevin Wolf  *
1351de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1352de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1353de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1354de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1355f67503e5SMax Reitz  *
1356f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1357f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1358ddf5636dSMax Reitz  *
1359ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1360ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1361ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1362b6ce07aaSKevin Wolf  */
1363f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1364ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1365f3930ed0SKevin Wolf                              BlockDriverState *parent,
1366ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1367ea2384d3Sbellard {
1368b6ce07aaSKevin Wolf     int ret;
13699a4f4c31SKevin Wolf     BdrvChild *file = NULL;
13709a4f4c31SKevin Wolf     BlockDriverState *bs;
1371ce343771SMax Reitz     BlockDriver *drv = NULL;
137274fe54f2SKevin Wolf     const char *drvname;
137334b5d2c6SMax Reitz     Error *local_err = NULL;
1374b1e6fc08SKevin Wolf     int snapshot_flags = 0;
137533e3963eSbellard 
1376f67503e5SMax Reitz     assert(pbs);
1377f3930ed0SKevin Wolf     assert(!child_role || !flags);
1378f3930ed0SKevin Wolf     assert(!child_role == !parent);
1379f67503e5SMax Reitz 
1380ddf5636dSMax Reitz     if (reference) {
1381ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1382ddf5636dSMax Reitz         QDECREF(options);
1383ddf5636dSMax Reitz 
1384ddf5636dSMax Reitz         if (*pbs) {
1385ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1386ddf5636dSMax Reitz                        "another block device");
1387ddf5636dSMax Reitz             return -EINVAL;
1388ddf5636dSMax Reitz         }
1389ddf5636dSMax Reitz 
1390ddf5636dSMax Reitz         if (filename || options_non_empty) {
1391ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1392ddf5636dSMax Reitz                        "additional options or a new filename");
1393ddf5636dSMax Reitz             return -EINVAL;
1394ddf5636dSMax Reitz         }
1395ddf5636dSMax Reitz 
1396ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1397ddf5636dSMax Reitz         if (!bs) {
1398ddf5636dSMax Reitz             return -ENODEV;
1399ddf5636dSMax Reitz         }
1400ddf5636dSMax Reitz         bdrv_ref(bs);
1401ddf5636dSMax Reitz         *pbs = bs;
1402ddf5636dSMax Reitz         return 0;
1403ddf5636dSMax Reitz     }
1404ddf5636dSMax Reitz 
1405f67503e5SMax Reitz     if (*pbs) {
1406f67503e5SMax Reitz         bs = *pbs;
1407f67503e5SMax Reitz     } else {
1408e4e9986bSMarkus Armbruster         bs = bdrv_new();
1409f67503e5SMax Reitz     }
1410f67503e5SMax Reitz 
1411de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1412de9c0cecSKevin Wolf     if (options == NULL) {
1413de9c0cecSKevin Wolf         options = qdict_new();
1414de9c0cecSKevin Wolf     }
1415de9c0cecSKevin Wolf 
1416f3930ed0SKevin Wolf     if (child_role) {
1417bddcec37SKevin Wolf         bs->inherits_from = parent;
1418f3930ed0SKevin Wolf         flags = child_role->inherit_flags(parent->open_flags);
1419f3930ed0SKevin Wolf     }
1420f3930ed0SKevin Wolf 
1421053e1578SMax Reitz     ret = bdrv_fill_options(&options, &filename, &flags, &local_err);
1422462f5bcfSKevin Wolf     if (local_err) {
1423462f5bcfSKevin Wolf         goto fail;
1424462f5bcfSKevin Wolf     }
1425462f5bcfSKevin Wolf 
142676c591b0SKevin Wolf     /* Find the right image format driver */
142776c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
142876c591b0SKevin Wolf     if (drvname) {
142976c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
143076c591b0SKevin Wolf         qdict_del(options, "driver");
143176c591b0SKevin Wolf         if (!drv) {
143276c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
143376c591b0SKevin Wolf             ret = -EINVAL;
143476c591b0SKevin Wolf             goto fail;
143576c591b0SKevin Wolf         }
143676c591b0SKevin Wolf     }
143776c591b0SKevin Wolf 
143876c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
143976c591b0SKevin Wolf 
1440f3930ed0SKevin Wolf     bs->open_flags = flags;
1441de9c0cecSKevin Wolf     bs->options = options;
1442b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1443de9c0cecSKevin Wolf 
1444f500a6d3SKevin Wolf     /* Open image file without format layer */
1445f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1446be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1447be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1448be028adcSJeff Cody         }
1449b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1450b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1451b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1452b1e6fc08SKevin Wolf         }
1453be028adcSJeff Cody 
1454f3930ed0SKevin Wolf         bs->open_flags = flags;
14551fdd6933SKevin Wolf 
14569a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
14571fdd6933SKevin Wolf                                &child_file, true, &local_err);
14581fdd6933SKevin Wolf         if (local_err) {
14591fdd6933SKevin Wolf             ret = -EINVAL;
14608bfea15dSKevin Wolf             goto fail;
1461f500a6d3SKevin Wolf         }
1462f4788adcSKevin Wolf     }
1463f500a6d3SKevin Wolf 
146476c591b0SKevin Wolf     /* Image format probing */
146538f3ef57SKevin Wolf     bs->probed = !drv;
146676c591b0SKevin Wolf     if (!drv && file) {
14679a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
146817b005f1SKevin Wolf         if (ret < 0) {
146917b005f1SKevin Wolf             goto fail;
147017b005f1SKevin Wolf         }
147176c591b0SKevin Wolf     } else if (!drv) {
14722a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
14732a05cbe4SMax Reitz         ret = -EINVAL;
14748bfea15dSKevin Wolf         goto fail;
14752a05cbe4SMax Reitz     }
1476f500a6d3SKevin Wolf 
147753a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
147853a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
147953a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
148053a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
148153a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
148253a29513SMax Reitz 
1483b6ce07aaSKevin Wolf     /* Open the image */
148434b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1485b6ce07aaSKevin Wolf     if (ret < 0) {
14868bfea15dSKevin Wolf         goto fail;
14876987307cSChristoph Hellwig     }
14886987307cSChristoph Hellwig 
14892a05cbe4SMax Reitz     if (file && (bs->file != file)) {
14909a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1491f500a6d3SKevin Wolf         file = NULL;
1492f500a6d3SKevin Wolf     }
1493f500a6d3SKevin Wolf 
1494b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
14959156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
149631ca6d07SKevin Wolf         QDict *backing_options;
149731ca6d07SKevin Wolf 
14985726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
149934b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1500b6ce07aaSKevin Wolf         if (ret < 0) {
1501b6ad491aSKevin Wolf             goto close_and_fail;
1502b6ce07aaSKevin Wolf         }
1503b6ce07aaSKevin Wolf     }
1504b6ce07aaSKevin Wolf 
150591af7014SMax Reitz     bdrv_refresh_filename(bs);
150691af7014SMax Reitz 
1507b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1508b998875dSKevin Wolf      * temporary snapshot afterwards. */
1509b1e6fc08SKevin Wolf     if (snapshot_flags) {
15106b8aeca5SChen Gang         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1511b998875dSKevin Wolf         if (local_err) {
1512b998875dSKevin Wolf             goto close_and_fail;
1513b998875dSKevin Wolf         }
1514b998875dSKevin Wolf     }
1515b998875dSKevin Wolf 
1516b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15175acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1518b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15195acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15205acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15215acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15225acd9d81SMax Reitz         } else {
152334b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15245acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1525bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
15265acd9d81SMax Reitz         }
1527b6ad491aSKevin Wolf 
1528b6ad491aSKevin Wolf         ret = -EINVAL;
1529b6ad491aSKevin Wolf         goto close_and_fail;
1530b6ad491aSKevin Wolf     }
1531b6ad491aSKevin Wolf 
1532b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1533a7f53e26SMarkus Armbruster         if (bs->blk) {
1534a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1535a7f53e26SMarkus Armbruster         }
1536c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1537c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1538c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1539c3adb58fSMarkus Armbruster         error_setg(errp,
1540c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1541c3adb58fSMarkus Armbruster         ret = -EBUSY;
1542c3adb58fSMarkus Armbruster         goto close_and_fail;
1543b6ce07aaSKevin Wolf     }
1544b6ce07aaSKevin Wolf 
1545c3adb58fSMarkus Armbruster     QDECREF(options);
1546f67503e5SMax Reitz     *pbs = bs;
1547b6ce07aaSKevin Wolf     return 0;
1548b6ce07aaSKevin Wolf 
15498bfea15dSKevin Wolf fail:
1550f500a6d3SKevin Wolf     if (file != NULL) {
15519a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1552f500a6d3SKevin Wolf     }
1553de9c0cecSKevin Wolf     QDECREF(bs->options);
1554b6ad491aSKevin Wolf     QDECREF(options);
1555de9c0cecSKevin Wolf     bs->options = NULL;
1556f67503e5SMax Reitz     if (!*pbs) {
1557f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1558f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1559f67503e5SMax Reitz            since it has not really been opened yet. */
1560f67503e5SMax Reitz         bdrv_unref(bs);
1561f67503e5SMax Reitz     }
156284d18f06SMarkus Armbruster     if (local_err) {
156334b5d2c6SMax Reitz         error_propagate(errp, local_err);
156434b5d2c6SMax Reitz     }
1565b6ad491aSKevin Wolf     return ret;
1566de9c0cecSKevin Wolf 
1567b6ad491aSKevin Wolf close_and_fail:
1568f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1569f67503e5SMax Reitz     if (*pbs) {
1570b6ad491aSKevin Wolf         bdrv_close(bs);
1571f67503e5SMax Reitz     } else {
1572f67503e5SMax Reitz         bdrv_unref(bs);
1573f67503e5SMax Reitz     }
1574b6ad491aSKevin Wolf     QDECREF(options);
157584d18f06SMarkus Armbruster     if (local_err) {
157634b5d2c6SMax Reitz         error_propagate(errp, local_err);
157734b5d2c6SMax Reitz     }
1578b6ce07aaSKevin Wolf     return ret;
1579b6ce07aaSKevin Wolf }
1580b6ce07aaSKevin Wolf 
1581f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
15826ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1583f3930ed0SKevin Wolf {
1584f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1585ce343771SMax Reitz                              NULL, errp);
1586f3930ed0SKevin Wolf }
1587f3930ed0SKevin Wolf 
1588e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1589e971aa12SJeff Cody      bool prepared;
1590e971aa12SJeff Cody      BDRVReopenState state;
1591e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1592e971aa12SJeff Cody } BlockReopenQueueEntry;
1593e971aa12SJeff Cody 
1594e971aa12SJeff Cody /*
1595e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1596e971aa12SJeff Cody  * reopen of multiple devices.
1597e971aa12SJeff Cody  *
1598e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1599e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1600e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1601e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1602e971aa12SJeff Cody  * atomic 'set'.
1603e971aa12SJeff Cody  *
1604e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1605e971aa12SJeff Cody  *
16064d2cb092SKevin Wolf  * options contains the changed options for the associated bs
16074d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
16084d2cb092SKevin Wolf  *
1609e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1610e971aa12SJeff Cody  *
1611e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1612e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1613e971aa12SJeff Cody  *
1614e971aa12SJeff Cody  */
1615e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
16164d2cb092SKevin Wolf                                     BlockDriverState *bs,
16174d2cb092SKevin Wolf                                     QDict *options, int flags)
1618e971aa12SJeff Cody {
1619e971aa12SJeff Cody     assert(bs != NULL);
1620e971aa12SJeff Cody 
1621e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
162267251a31SKevin Wolf     BdrvChild *child;
16234d2cb092SKevin Wolf     QDict *old_options;
162467251a31SKevin Wolf 
1625e971aa12SJeff Cody     if (bs_queue == NULL) {
1626e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1627e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1628e971aa12SJeff Cody     }
1629e971aa12SJeff Cody 
16304d2cb092SKevin Wolf     if (!options) {
16314d2cb092SKevin Wolf         options = qdict_new();
16324d2cb092SKevin Wolf     }
16334d2cb092SKevin Wolf 
16344d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
16354d2cb092SKevin Wolf     qdict_join(options, old_options, false);
16364d2cb092SKevin Wolf     QDECREF(old_options);
16374d2cb092SKevin Wolf 
1638f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1639f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1640f1f25a2eSKevin Wolf 
164167251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
164267251a31SKevin Wolf         int child_flags;
164367251a31SKevin Wolf 
164467251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
164567251a31SKevin Wolf             continue;
164667251a31SKevin Wolf         }
164767251a31SKevin Wolf 
164867251a31SKevin Wolf         child_flags = child->role->inherit_flags(flags);
16494d2cb092SKevin Wolf         /* TODO Pass down child flags (backing.*, extents.*, ...) */
16504d2cb092SKevin Wolf         bdrv_reopen_queue(bs_queue, child->bs, NULL, child_flags);
1651e971aa12SJeff Cody     }
1652e971aa12SJeff Cody 
1653e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1654e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1655e971aa12SJeff Cody 
1656e971aa12SJeff Cody     bs_entry->state.bs = bs;
16574d2cb092SKevin Wolf     bs_entry->state.options = options;
1658e971aa12SJeff Cody     bs_entry->state.flags = flags;
1659e971aa12SJeff Cody 
1660e971aa12SJeff Cody     return bs_queue;
1661e971aa12SJeff Cody }
1662e971aa12SJeff Cody 
1663e971aa12SJeff Cody /*
1664e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1665e971aa12SJeff Cody  *
1666e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1667e971aa12SJeff Cody  * via bdrv_reopen_queue().
1668e971aa12SJeff Cody  *
1669e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1670e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1671e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1672e971aa12SJeff Cody  * data cleaned up.
1673e971aa12SJeff Cody  *
1674e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1675e971aa12SJeff Cody  * to all devices.
1676e971aa12SJeff Cody  *
1677e971aa12SJeff Cody  */
1678e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1679e971aa12SJeff Cody {
1680e971aa12SJeff Cody     int ret = -1;
1681e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1682e971aa12SJeff Cody     Error *local_err = NULL;
1683e971aa12SJeff Cody 
1684e971aa12SJeff Cody     assert(bs_queue != NULL);
1685e971aa12SJeff Cody 
1686e971aa12SJeff Cody     bdrv_drain_all();
1687e971aa12SJeff Cody 
1688e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1689e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1690e971aa12SJeff Cody             error_propagate(errp, local_err);
1691e971aa12SJeff Cody             goto cleanup;
1692e971aa12SJeff Cody         }
1693e971aa12SJeff Cody         bs_entry->prepared = true;
1694e971aa12SJeff Cody     }
1695e971aa12SJeff Cody 
1696e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1697e971aa12SJeff Cody      * changes
1698e971aa12SJeff Cody      */
1699e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1700e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1701e971aa12SJeff Cody     }
1702e971aa12SJeff Cody 
1703e971aa12SJeff Cody     ret = 0;
1704e971aa12SJeff Cody 
1705e971aa12SJeff Cody cleanup:
1706e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1707e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1708e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1709e971aa12SJeff Cody         }
17104d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1711e971aa12SJeff Cody         g_free(bs_entry);
1712e971aa12SJeff Cody     }
1713e971aa12SJeff Cody     g_free(bs_queue);
1714e971aa12SJeff Cody     return ret;
1715e971aa12SJeff Cody }
1716e971aa12SJeff Cody 
1717e971aa12SJeff Cody 
1718e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1719e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1720e971aa12SJeff Cody {
1721e971aa12SJeff Cody     int ret = -1;
1722e971aa12SJeff Cody     Error *local_err = NULL;
17234d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1724e971aa12SJeff Cody 
1725e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1726e971aa12SJeff Cody     if (local_err != NULL) {
1727e971aa12SJeff Cody         error_propagate(errp, local_err);
1728e971aa12SJeff Cody     }
1729e971aa12SJeff Cody     return ret;
1730e971aa12SJeff Cody }
1731e971aa12SJeff Cody 
1732e971aa12SJeff Cody 
1733e971aa12SJeff Cody /*
1734e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1735e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1736e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1737e971aa12SJeff Cody  *
1738e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1739e971aa12SJeff Cody  * flags are the new open flags
1740e971aa12SJeff Cody  * queue is the reopen queue
1741e971aa12SJeff Cody  *
1742e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1743e971aa12SJeff Cody  * as well.
1744e971aa12SJeff Cody  *
1745e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1746e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1747e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1748e971aa12SJeff Cody  *
1749e971aa12SJeff Cody  */
1750e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1751e971aa12SJeff Cody                         Error **errp)
1752e971aa12SJeff Cody {
1753e971aa12SJeff Cody     int ret = -1;
1754e971aa12SJeff Cody     Error *local_err = NULL;
1755e971aa12SJeff Cody     BlockDriver *drv;
1756e971aa12SJeff Cody 
1757e971aa12SJeff Cody     assert(reopen_state != NULL);
1758e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1759e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1760e971aa12SJeff Cody 
1761e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1762e971aa12SJeff Cody      * to r/w */
1763e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1764e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
176581e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
176681e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1767e971aa12SJeff Cody         goto error;
1768e971aa12SJeff Cody     }
1769e971aa12SJeff Cody 
1770e971aa12SJeff Cody 
1771e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1772e971aa12SJeff Cody     if (ret) {
1773e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1774e971aa12SJeff Cody                   strerror(-ret));
1775e971aa12SJeff Cody         goto error;
1776e971aa12SJeff Cody     }
1777e971aa12SJeff Cody 
1778e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1779e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1780e971aa12SJeff Cody         if (ret) {
1781e971aa12SJeff Cody             if (local_err != NULL) {
1782e971aa12SJeff Cody                 error_propagate(errp, local_err);
1783e971aa12SJeff Cody             } else {
1784d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1785e971aa12SJeff Cody                            reopen_state->bs->filename);
1786e971aa12SJeff Cody             }
1787e971aa12SJeff Cody             goto error;
1788e971aa12SJeff Cody         }
1789e971aa12SJeff Cody     } else {
1790e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1791e971aa12SJeff Cody          * handler for each supported drv. */
179281e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
179381e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
179481e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1795e971aa12SJeff Cody         ret = -1;
1796e971aa12SJeff Cody         goto error;
1797e971aa12SJeff Cody     }
1798e971aa12SJeff Cody 
17994d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
18004d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
18014d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
18024d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
18034d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
18044d2cb092SKevin Wolf 
18054d2cb092SKevin Wolf         do {
18064d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
18074d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
18084d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
18094d2cb092SKevin Wolf                                                 entry->key);
18104d2cb092SKevin Wolf 
18114d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
18124d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
18134d2cb092SKevin Wolf                 ret = -EINVAL;
18144d2cb092SKevin Wolf                 goto error;
18154d2cb092SKevin Wolf             }
18164d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
18174d2cb092SKevin Wolf     }
18184d2cb092SKevin Wolf 
1819e971aa12SJeff Cody     ret = 0;
1820e971aa12SJeff Cody 
1821e971aa12SJeff Cody error:
1822e971aa12SJeff Cody     return ret;
1823e971aa12SJeff Cody }
1824e971aa12SJeff Cody 
1825e971aa12SJeff Cody /*
1826e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1827e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1828e971aa12SJeff Cody  * the active BlockDriverState contents.
1829e971aa12SJeff Cody  */
1830e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1831e971aa12SJeff Cody {
1832e971aa12SJeff Cody     BlockDriver *drv;
1833e971aa12SJeff Cody 
1834e971aa12SJeff Cody     assert(reopen_state != NULL);
1835e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1836e971aa12SJeff Cody     assert(drv != NULL);
1837e971aa12SJeff Cody 
1838e971aa12SJeff Cody     /* If there are any driver level actions to take */
1839e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1840e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1841e971aa12SJeff Cody     }
1842e971aa12SJeff Cody 
1843e971aa12SJeff Cody     /* set BDS specific flags now */
1844e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1845e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1846e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1847e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1848355ef4acSKevin Wolf 
18493baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1850e971aa12SJeff Cody }
1851e971aa12SJeff Cody 
1852e971aa12SJeff Cody /*
1853e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1854e971aa12SJeff Cody  * reopen_state
1855e971aa12SJeff Cody  */
1856e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1857e971aa12SJeff Cody {
1858e971aa12SJeff Cody     BlockDriver *drv;
1859e971aa12SJeff Cody 
1860e971aa12SJeff Cody     assert(reopen_state != NULL);
1861e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1862e971aa12SJeff Cody     assert(drv != NULL);
1863e971aa12SJeff Cody 
1864e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1865e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1866e971aa12SJeff Cody     }
1867e971aa12SJeff Cody }
1868e971aa12SJeff Cody 
1869e971aa12SJeff Cody 
1870fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1871fc01f7e7Sbellard {
187233384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
187333384421SMax Reitz 
18743e914655SPaolo Bonzini     if (bs->job) {
18753e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
18763e914655SPaolo Bonzini     }
187799b7e775SAlberto Garcia 
187899b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
187999b7e775SAlberto Garcia     if (bs->io_limits_enabled) {
188099b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
188199b7e775SAlberto Garcia     }
188299b7e775SAlberto Garcia 
188353ec73e2SFam Zheng     bdrv_drain(bs); /* complete I/O */
188458fda173SStefan Hajnoczi     bdrv_flush(bs);
188553ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
1886d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
18877094f12fSKevin Wolf 
18883cbc002cSPaolo Bonzini     if (bs->drv) {
18896e93e7c4SKevin Wolf         BdrvChild *child, *next;
18906e93e7c4SKevin Wolf 
18919a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
18929a4f4c31SKevin Wolf         bs->drv = NULL;
18939a7dedbcSKevin Wolf 
1894*760e0063SKevin Wolf         if (bs->backing) {
1895*760e0063SKevin Wolf             BlockDriverState *backing_hd = bs->backing->bs;
18969a7dedbcSKevin Wolf             bdrv_set_backing_hd(bs, NULL);
18979a7dedbcSKevin Wolf             bdrv_unref(backing_hd);
18989a7dedbcSKevin Wolf         }
18999a7dedbcSKevin Wolf 
19009a4f4c31SKevin Wolf         if (bs->file != NULL) {
19019a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
19029a4f4c31SKevin Wolf             bs->file = NULL;
19039a4f4c31SKevin Wolf         }
19049a4f4c31SKevin Wolf 
19056e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
190633a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
190733a60407SKevin Wolf              * bdrv_unref_child() here */
1908bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
1909bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
1910bddcec37SKevin Wolf             }
191133a60407SKevin Wolf             bdrv_detach_child(child);
19126e93e7c4SKevin Wolf         }
19136e93e7c4SKevin Wolf 
19147267c094SAnthony Liguori         g_free(bs->opaque);
1915ea2384d3Sbellard         bs->opaque = NULL;
191653fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1917a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1918a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
19196405875cSPaolo Bonzini         bs->total_sectors = 0;
19206405875cSPaolo Bonzini         bs->encrypted = 0;
19216405875cSPaolo Bonzini         bs->valid_key = 0;
19226405875cSPaolo Bonzini         bs->sg = 0;
19230d51b4deSAsias He         bs->zero_beyond_eof = false;
1924de9c0cecSKevin Wolf         QDECREF(bs->options);
1925de9c0cecSKevin Wolf         bs->options = NULL;
192691af7014SMax Reitz         QDECREF(bs->full_open_options);
192791af7014SMax Reitz         bs->full_open_options = NULL;
19289ca11154SPavel Hrdina     }
192966f82ceeSKevin Wolf 
1930a7f53e26SMarkus Armbruster     if (bs->blk) {
1931a7f53e26SMarkus Armbruster         blk_dev_change_media_cb(bs->blk, false);
1932a7f53e26SMarkus Armbruster     }
193398f90dbaSZhi Yong Wu 
193433384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
193533384421SMax Reitz         g_free(ban);
193633384421SMax Reitz     }
193733384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1938b338082bSbellard }
1939b338082bSbellard 
19402bc93fedSMORITA Kazutaka void bdrv_close_all(void)
19412bc93fedSMORITA Kazutaka {
19422bc93fedSMORITA Kazutaka     BlockDriverState *bs;
19432bc93fedSMORITA Kazutaka 
1944dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1945ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1946ed78cda3SStefan Hajnoczi 
1947ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
19482bc93fedSMORITA Kazutaka         bdrv_close(bs);
1949ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
19502bc93fedSMORITA Kazutaka     }
19512bc93fedSMORITA Kazutaka }
19522bc93fedSMORITA Kazutaka 
1953dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1954dc364f4cSBenoît Canet  * graph_bdrv_state list.
1955d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1956d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1957d22b2f41SRyan Harper {
1958bfb197e0SMarkus Armbruster     /*
1959bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
1960bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
1961bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
1962bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
1963bfb197e0SMarkus Armbruster      * resetting it to null on remove.
1964bfb197e0SMarkus Armbruster      */
1965bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
1966dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1967bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
1968d22b2f41SRyan Harper     }
1969dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1970dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1971dc364f4cSBenoît Canet     }
1972dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1973d22b2f41SRyan Harper }
1974d22b2f41SRyan Harper 
1975e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1976e023b2e2SPaolo Bonzini {
1977e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1978e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1979e023b2e2SPaolo Bonzini     }
1980e023b2e2SPaolo Bonzini }
1981e023b2e2SPaolo Bonzini 
19824ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
19834ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
19844ddc07caSPaolo Bonzini {
19854ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
19864ddc07caSPaolo Bonzini 
19874ddc07caSPaolo Bonzini     /* dev info */
19881b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
19894ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
19904ddc07caSPaolo Bonzini 
19914ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
19924ddc07caSPaolo Bonzini 
1993cc0681c4SBenoît Canet     /* i/o throttled req */
199476f4afb4SAlberto Garcia     bs_dest->throttle_state     = bs_src->throttle_state,
199576f4afb4SAlberto Garcia     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
199676f4afb4SAlberto Garcia     bs_dest->pending_reqs[0]    = bs_src->pending_reqs[0];
199776f4afb4SAlberto Garcia     bs_dest->pending_reqs[1]    = bs_src->pending_reqs[1];
199876f4afb4SAlberto Garcia     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
199976f4afb4SAlberto Garcia     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
200076f4afb4SAlberto Garcia     memcpy(&bs_dest->round_robin,
200176f4afb4SAlberto Garcia            &bs_src->round_robin,
200276f4afb4SAlberto Garcia            sizeof(bs_dest->round_robin));
20030e5b0a2dSBenoît Canet     memcpy(&bs_dest->throttle_timers,
20040e5b0a2dSBenoît Canet            &bs_src->throttle_timers,
20050e5b0a2dSBenoît Canet            sizeof(ThrottleTimers));
20064ddc07caSPaolo Bonzini 
20074ddc07caSPaolo Bonzini     /* r/w error */
20084ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
20094ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
20104ddc07caSPaolo Bonzini 
20114ddc07caSPaolo Bonzini     /* i/o status */
20124ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
20134ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
20144ddc07caSPaolo Bonzini 
20154ddc07caSPaolo Bonzini     /* dirty bitmap */
2016e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
20174ddc07caSPaolo Bonzini 
20189fcb0251SFam Zheng     /* reference count */
20199fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
20209fcb0251SFam Zheng 
20214ddc07caSPaolo Bonzini     /* job */
20224ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
20234ddc07caSPaolo Bonzini 
20244ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
2025dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
20267e7d56d9SMarkus Armbruster     bs_dest->blk = bs_src->blk;
20277e7d56d9SMarkus Armbruster 
2028fbe40ff7SFam Zheng     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
2029fbe40ff7SFam Zheng            sizeof(bs_dest->op_blockers));
20304ddc07caSPaolo Bonzini }
20314ddc07caSPaolo Bonzini 
20324ddc07caSPaolo Bonzini /*
20334ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
20344ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
20354ddc07caSPaolo Bonzini  * actually attached to a device.
20364ddc07caSPaolo Bonzini  *
20374ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
20384ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
20394ddc07caSPaolo Bonzini  *
2040bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
20414ddc07caSPaolo Bonzini  *
20424ddc07caSPaolo Bonzini  * This function does not create any image files.
20434ddc07caSPaolo Bonzini  */
20444ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
20454ddc07caSPaolo Bonzini {
20464ddc07caSPaolo Bonzini     BlockDriverState tmp;
2047bddcec37SKevin Wolf     BdrvChild *child;
20484ddc07caSPaolo Bonzini 
20496ee4ce1eSKevin Wolf     bdrv_drain(bs_new);
20506ee4ce1eSKevin Wolf     bdrv_drain(bs_old);
20514ddc07caSPaolo Bonzini 
205290ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
205390ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
205490ce8a06SBenoît Canet      * insert them back if needed.
205590ce8a06SBenoît Canet      */
205690ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
205790ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
205890ce8a06SBenoît Canet     }
205990ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
206090ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
206190ce8a06SBenoît Canet     }
206290ce8a06SBenoît Canet 
2063db628338SAlberto Garcia     /* If the BlockDriverState is part of a throttling group acquire
2064db628338SAlberto Garcia      * its lock since we're going to mess with the protected fields.
2065db628338SAlberto Garcia      * Otherwise there's no need to worry since no one else can touch
2066db628338SAlberto Garcia      * them. */
2067db628338SAlberto Garcia     if (bs_old->throttle_state) {
2068db628338SAlberto Garcia         throttle_group_lock(bs_old);
2069db628338SAlberto Garcia     }
2070db628338SAlberto Garcia 
2071bfb197e0SMarkus Armbruster     /* bs_new must be unattached and shouldn't have anything fancy enabled */
20727e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
2073e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
20744ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20754ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2076db628338SAlberto Garcia     assert(bs_new->throttle_state == NULL);
20770e5b0a2dSBenoît Canet     assert(!throttle_timers_are_initialized(&bs_new->throttle_timers));
20784ddc07caSPaolo Bonzini 
20794ddc07caSPaolo Bonzini     tmp = *bs_new;
20804ddc07caSPaolo Bonzini     *bs_new = *bs_old;
20814ddc07caSPaolo Bonzini     *bs_old = tmp;
20824ddc07caSPaolo Bonzini 
20834ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
20844ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
20854ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
20864ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
20874ddc07caSPaolo Bonzini 
2088bfb197e0SMarkus Armbruster     /* bs_new must remain unattached */
20897e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
20904ddc07caSPaolo Bonzini 
20914ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
20924ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20934ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2094db628338SAlberto Garcia     assert(bs_new->throttle_state == NULL);
20950e5b0a2dSBenoît Canet     assert(!throttle_timers_are_initialized(&bs_new->throttle_timers));
20964ddc07caSPaolo Bonzini 
2097db628338SAlberto Garcia     /* Release the ThrottleGroup lock */
2098db628338SAlberto Garcia     if (bs_old->throttle_state) {
2099db628338SAlberto Garcia         throttle_group_unlock(bs_old);
2100db628338SAlberto Garcia     }
2101db628338SAlberto Garcia 
210290ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
210390ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
210490ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
210590ce8a06SBenoît Canet     }
210690ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
210790ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
210890ce8a06SBenoît Canet     }
210990ce8a06SBenoît Canet 
21106e93e7c4SKevin Wolf     /*
21116e93e7c4SKevin Wolf      * Update lh_first.le_prev for non-empty lists.
21126e93e7c4SKevin Wolf      *
21136e93e7c4SKevin Wolf      * The head of the op blocker list doesn't change because it is moved back
21146e93e7c4SKevin Wolf      * in bdrv_move_feature_fields().
21156e93e7c4SKevin Wolf      */
21166ee4ce1eSKevin Wolf     assert(QLIST_EMPTY(&bs_old->tracked_requests));
21176ee4ce1eSKevin Wolf     assert(QLIST_EMPTY(&bs_new->tracked_requests));
21186ee4ce1eSKevin Wolf 
21196e93e7c4SKevin Wolf     QLIST_FIX_HEAD_PTR(&bs_new->children, next);
21206e93e7c4SKevin Wolf     QLIST_FIX_HEAD_PTR(&bs_old->children, next);
21216e93e7c4SKevin Wolf 
2122bddcec37SKevin Wolf     /* Update references in bs->opaque and children */
2123bddcec37SKevin Wolf     QLIST_FOREACH(child, &bs_old->children, next) {
2124bddcec37SKevin Wolf         if (child->bs->inherits_from == bs_new) {
2125bddcec37SKevin Wolf             child->bs->inherits_from = bs_old;
2126bddcec37SKevin Wolf         }
2127bddcec37SKevin Wolf     }
2128bddcec37SKevin Wolf     QLIST_FOREACH(child, &bs_new->children, next) {
2129bddcec37SKevin Wolf         if (child->bs->inherits_from == bs_old) {
2130bddcec37SKevin Wolf             child->bs->inherits_from = bs_new;
2131bddcec37SKevin Wolf         }
2132bddcec37SKevin Wolf     }
2133bddcec37SKevin Wolf 
21344ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
21354ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
21364ddc07caSPaolo Bonzini }
21374ddc07caSPaolo Bonzini 
21388802d1fdSJeff Cody /*
21398802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
21408802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
21418802d1fdSJeff Cody  *
21428802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
21438802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
21448802d1fdSJeff Cody  *
2145bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2146f6801b83SJeff Cody  *
21478802d1fdSJeff Cody  * This function does not create any image files.
21488802d1fdSJeff Cody  */
21498802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
21508802d1fdSJeff Cody {
21514ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
21528802d1fdSJeff Cody 
21538802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
21548802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
21558d24cce1SFam Zheng     bdrv_set_backing_hd(bs_top, bs_new);
21568802d1fdSJeff Cody }
21578802d1fdSJeff Cody 
21584f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2159b338082bSbellard {
21603e914655SPaolo Bonzini     assert(!bs->job);
21613718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21624f6fd349SFam Zheng     assert(!bs->refcnt);
2163e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
216418846deeSMarkus Armbruster 
2165e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2166e1b5c52eSStefan Hajnoczi 
21671b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2168d22b2f41SRyan Harper     bdrv_make_anon(bs);
216934c6f050Saurel32 
21707267c094SAnthony Liguori     g_free(bs);
2171fc01f7e7Sbellard }
2172fc01f7e7Sbellard 
2173e97fc193Saliguori /*
2174e97fc193Saliguori  * Run consistency checks on an image
2175e97fc193Saliguori  *
2176e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2177a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2178e076f338SKevin Wolf  * check are stored in res.
2179e97fc193Saliguori  */
21804534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2181e97fc193Saliguori {
2182908bcd54SMax Reitz     if (bs->drv == NULL) {
2183908bcd54SMax Reitz         return -ENOMEDIUM;
2184908bcd54SMax Reitz     }
2185e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2186e97fc193Saliguori         return -ENOTSUP;
2187e97fc193Saliguori     }
2188e97fc193Saliguori 
2189e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
21904534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2191e97fc193Saliguori }
2192e97fc193Saliguori 
21938a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
21948a426614SKevin Wolf 
219533e3963eSbellard /* commit COW file into the raw image */
219633e3963eSbellard int bdrv_commit(BlockDriverState *bs)
219733e3963eSbellard {
219819cb3738Sbellard     BlockDriver *drv = bs->drv;
219972706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
22008a426614SKevin Wolf     int n, ro, open_flags;
22010bce597dSJeff Cody     int ret = 0;
220272706ea4SJeff Cody     uint8_t *buf = NULL;
220333e3963eSbellard 
220419cb3738Sbellard     if (!drv)
220519cb3738Sbellard         return -ENOMEDIUM;
220633e3963eSbellard 
2207*760e0063SKevin Wolf     if (!bs->backing) {
22084dca4b63SNaphtali Sprei         return -ENOTSUP;
22094dca4b63SNaphtali Sprei     }
22104dca4b63SNaphtali Sprei 
2211bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2212*760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
22132d3735d3SStefan Hajnoczi         return -EBUSY;
22142d3735d3SStefan Hajnoczi     }
22152d3735d3SStefan Hajnoczi 
2216*760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2217*760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
22184dca4b63SNaphtali Sprei 
22194dca4b63SNaphtali Sprei     if (ro) {
2220*760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
22210bce597dSJeff Cody             return -EACCES;
22224dca4b63SNaphtali Sprei         }
2223ea2384d3Sbellard     }
2224ea2384d3Sbellard 
222572706ea4SJeff Cody     length = bdrv_getlength(bs);
222672706ea4SJeff Cody     if (length < 0) {
222772706ea4SJeff Cody         ret = length;
222872706ea4SJeff Cody         goto ro_cleanup;
222972706ea4SJeff Cody     }
223072706ea4SJeff Cody 
2231*760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
223272706ea4SJeff Cody     if (backing_length < 0) {
223372706ea4SJeff Cody         ret = backing_length;
223472706ea4SJeff Cody         goto ro_cleanup;
223572706ea4SJeff Cody     }
223672706ea4SJeff Cody 
223772706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
223872706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
223972706ea4SJeff Cody      * we must return an error */
224072706ea4SJeff Cody     if (length > backing_length) {
2241*760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
224272706ea4SJeff Cody         if (ret < 0) {
224372706ea4SJeff Cody             goto ro_cleanup;
224472706ea4SJeff Cody         }
224572706ea4SJeff Cody     }
224672706ea4SJeff Cody 
224772706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2248857d4f46SKevin Wolf 
2249857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2250*760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2251857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2252857d4f46SKevin Wolf     if (buf == NULL) {
2253857d4f46SKevin Wolf         ret = -ENOMEM;
2254857d4f46SKevin Wolf         goto ro_cleanup;
2255857d4f46SKevin Wolf     }
22568a426614SKevin Wolf 
22578a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2258d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2259d663640cSPaolo Bonzini         if (ret < 0) {
2260d663640cSPaolo Bonzini             goto ro_cleanup;
2261d663640cSPaolo Bonzini         }
2262d663640cSPaolo Bonzini         if (ret) {
2263dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2264dabfa6ccSKevin Wolf             if (ret < 0) {
22654dca4b63SNaphtali Sprei                 goto ro_cleanup;
226633e3963eSbellard             }
226733e3963eSbellard 
2268*760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2269dabfa6ccSKevin Wolf             if (ret < 0) {
22704dca4b63SNaphtali Sprei                 goto ro_cleanup;
227133e3963eSbellard             }
227233e3963eSbellard         }
227333e3963eSbellard     }
227495389c86Sbellard 
22751d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
22761d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2277dabfa6ccSKevin Wolf         if (ret < 0) {
2278dabfa6ccSKevin Wolf             goto ro_cleanup;
2279dabfa6ccSKevin Wolf         }
22801d44952fSChristoph Hellwig         bdrv_flush(bs);
22811d44952fSChristoph Hellwig     }
228295389c86Sbellard 
22833f5075aeSChristoph Hellwig     /*
22843f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
22853f5075aeSChristoph Hellwig      * stable on disk.
22863f5075aeSChristoph Hellwig      */
2287*760e0063SKevin Wolf     if (bs->backing) {
2288*760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2289dabfa6ccSKevin Wolf     }
22904dca4b63SNaphtali Sprei 
2291dabfa6ccSKevin Wolf     ret = 0;
22924dca4b63SNaphtali Sprei ro_cleanup:
2293857d4f46SKevin Wolf     qemu_vfree(buf);
22944dca4b63SNaphtali Sprei 
22954dca4b63SNaphtali Sprei     if (ro) {
22960bce597dSJeff Cody         /* ignoring error return here */
2297*760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
22984dca4b63SNaphtali Sprei     }
22994dca4b63SNaphtali Sprei 
23001d44952fSChristoph Hellwig     return ret;
230133e3963eSbellard }
230233e3963eSbellard 
2303e8877497SStefan Hajnoczi int bdrv_commit_all(void)
23046ab4b5abSMarkus Armbruster {
23056ab4b5abSMarkus Armbruster     BlockDriverState *bs;
23066ab4b5abSMarkus Armbruster 
2307dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2308ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2309ed78cda3SStefan Hajnoczi 
2310ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2311*760e0063SKevin Wolf         if (bs->drv && bs->backing) {
2312e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2313e8877497SStefan Hajnoczi             if (ret < 0) {
2314ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2315e8877497SStefan Hajnoczi                 return ret;
23166ab4b5abSMarkus Armbruster             }
23176ab4b5abSMarkus Armbruster         }
2318ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2319272d2d8eSJeff Cody     }
2320e8877497SStefan Hajnoczi     return 0;
2321e8877497SStefan Hajnoczi }
23226ab4b5abSMarkus Armbruster 
2323756e6736SKevin Wolf /*
2324756e6736SKevin Wolf  * Return values:
2325756e6736SKevin Wolf  * 0        - success
2326756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2327756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2328756e6736SKevin Wolf  *            image file header
2329756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2330756e6736SKevin Wolf  */
2331756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2332756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2333756e6736SKevin Wolf {
2334756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2335469ef350SPaolo Bonzini     int ret;
2336756e6736SKevin Wolf 
23375f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
23385f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
23395f377794SPaolo Bonzini         return -EINVAL;
23405f377794SPaolo Bonzini     }
23415f377794SPaolo Bonzini 
2342756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2343469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2344756e6736SKevin Wolf     } else {
2345469ef350SPaolo Bonzini         ret = -ENOTSUP;
2346756e6736SKevin Wolf     }
2347469ef350SPaolo Bonzini 
2348469ef350SPaolo Bonzini     if (ret == 0) {
2349469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2350469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2351469ef350SPaolo Bonzini     }
2352469ef350SPaolo Bonzini     return ret;
2353756e6736SKevin Wolf }
2354756e6736SKevin Wolf 
23556ebdcee2SJeff Cody /*
23566ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
23576ebdcee2SJeff Cody  *
23586ebdcee2SJeff Cody  * active is the current topmost image.
23596ebdcee2SJeff Cody  *
23606ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
23616ebdcee2SJeff Cody  * or if active == bs.
23624caf0fcdSJeff Cody  *
23634caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
23646ebdcee2SJeff Cody  */
23656ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
23666ebdcee2SJeff Cody                                     BlockDriverState *bs)
23676ebdcee2SJeff Cody {
2368*760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2369*760e0063SKevin Wolf         active = backing_bs(active);
23706ebdcee2SJeff Cody     }
23716ebdcee2SJeff Cody 
23724caf0fcdSJeff Cody     return active;
23736ebdcee2SJeff Cody }
23746ebdcee2SJeff Cody 
23754caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
23764caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
23774caf0fcdSJeff Cody {
23784caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
23796ebdcee2SJeff Cody }
23806ebdcee2SJeff Cody 
23816ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
23826ebdcee2SJeff Cody     BlockDriverState *bs;
23836ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
23846ebdcee2SJeff Cody } BlkIntermediateStates;
23856ebdcee2SJeff Cody 
23866ebdcee2SJeff Cody 
23876ebdcee2SJeff Cody /*
23886ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
23896ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
23906ebdcee2SJeff Cody  *
23916ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
23926ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
23936ebdcee2SJeff Cody  *
23946ebdcee2SJeff Cody  * E.g., this will convert the following chain:
23956ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
23966ebdcee2SJeff Cody  *
23976ebdcee2SJeff Cody  * to
23986ebdcee2SJeff Cody  *
23996ebdcee2SJeff Cody  * bottom <- base <- active
24006ebdcee2SJeff Cody  *
24016ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
24026ebdcee2SJeff Cody  *
24036ebdcee2SJeff Cody  * base <- intermediate <- top <- active
24046ebdcee2SJeff Cody  *
24056ebdcee2SJeff Cody  * to
24066ebdcee2SJeff Cody  *
24076ebdcee2SJeff Cody  * base <- active
24086ebdcee2SJeff Cody  *
240954e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
241054e26900SJeff Cody  * overlay image metadata.
241154e26900SJeff Cody  *
24126ebdcee2SJeff Cody  * Error conditions:
24136ebdcee2SJeff Cody  *  if active == top, that is considered an error
24146ebdcee2SJeff Cody  *
24156ebdcee2SJeff Cody  */
24166ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
241754e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
24186ebdcee2SJeff Cody {
24196ebdcee2SJeff Cody     BlockDriverState *intermediate;
24206ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
24216ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
24226ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
24236ebdcee2SJeff Cody     int ret = -EIO;
24246ebdcee2SJeff Cody 
24256ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
24266ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
24276ebdcee2SJeff Cody 
24286ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
24296ebdcee2SJeff Cody         goto exit;
24306ebdcee2SJeff Cody     }
24316ebdcee2SJeff Cody 
24326ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
24336ebdcee2SJeff Cody 
24346ebdcee2SJeff Cody     if (new_top_bs == NULL) {
24356ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
24366ebdcee2SJeff Cody         goto exit;
24376ebdcee2SJeff Cody     }
24386ebdcee2SJeff Cody 
2439*760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
24406ebdcee2SJeff Cody      * to do, no intermediate images */
2441*760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
24426ebdcee2SJeff Cody         ret = 0;
24436ebdcee2SJeff Cody         goto exit;
24446ebdcee2SJeff Cody     }
24456ebdcee2SJeff Cody 
24466ebdcee2SJeff Cody     intermediate = top;
24476ebdcee2SJeff Cody 
24486ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
24496ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
24506ebdcee2SJeff Cody      */
24516ebdcee2SJeff Cody     while (intermediate) {
24525839e53bSMarkus Armbruster         intermediate_state = g_new0(BlkIntermediateStates, 1);
24536ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
24546ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
24556ebdcee2SJeff Cody 
2456*760e0063SKevin Wolf         if (backing_bs(intermediate) == base) {
2457*760e0063SKevin Wolf             base_bs = backing_bs(intermediate);
24586ebdcee2SJeff Cody             break;
24596ebdcee2SJeff Cody         }
2460*760e0063SKevin Wolf         intermediate = backing_bs(intermediate);
24616ebdcee2SJeff Cody     }
24626ebdcee2SJeff Cody     if (base_bs == NULL) {
24636ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
24646ebdcee2SJeff Cody          * unravel everything, and exit with error */
24656ebdcee2SJeff Cody         goto exit;
24666ebdcee2SJeff Cody     }
24676ebdcee2SJeff Cody 
24686ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
246954e26900SJeff Cody     backing_file_str = backing_file_str ? backing_file_str : base_bs->filename;
247054e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
24716ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
24726ebdcee2SJeff Cody     if (ret) {
24736ebdcee2SJeff Cody         goto exit;
24746ebdcee2SJeff Cody     }
2475920beae1SFam Zheng     bdrv_set_backing_hd(new_top_bs, base_bs);
24766ebdcee2SJeff Cody 
24776ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
24786ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
2479920beae1SFam Zheng         bdrv_set_backing_hd(intermediate_state->bs, NULL);
24804f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
24816ebdcee2SJeff Cody     }
24826ebdcee2SJeff Cody     ret = 0;
24836ebdcee2SJeff Cody 
24846ebdcee2SJeff Cody exit:
24856ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
24866ebdcee2SJeff Cody         g_free(intermediate_state);
24876ebdcee2SJeff Cody     }
24886ebdcee2SJeff Cody     return ret;
24896ebdcee2SJeff Cody }
24906ebdcee2SJeff Cody 
249183f64091Sbellard /**
249283f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
249383f64091Sbellard  */
249483f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
249583f64091Sbellard {
249683f64091Sbellard     BlockDriver *drv = bs->drv;
249751762288SStefan Hajnoczi     int ret;
249883f64091Sbellard     if (!drv)
249919cb3738Sbellard         return -ENOMEDIUM;
250083f64091Sbellard     if (!drv->bdrv_truncate)
250183f64091Sbellard         return -ENOTSUP;
250259f2689dSNaphtali Sprei     if (bs->read_only)
250359f2689dSNaphtali Sprei         return -EACCES;
25049c75e168SJeff Cody 
250551762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
250651762288SStefan Hajnoczi     if (ret == 0) {
250751762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2508ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2509a7f53e26SMarkus Armbruster         if (bs->blk) {
2510a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2511a7f53e26SMarkus Armbruster         }
251251762288SStefan Hajnoczi     }
251351762288SStefan Hajnoczi     return ret;
251483f64091Sbellard }
251583f64091Sbellard 
251683f64091Sbellard /**
25174a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
25184a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
25194a1d5e1fSFam Zheng  */
25204a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
25214a1d5e1fSFam Zheng {
25224a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
25234a1d5e1fSFam Zheng     if (!drv) {
25244a1d5e1fSFam Zheng         return -ENOMEDIUM;
25254a1d5e1fSFam Zheng     }
25264a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
25274a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
25284a1d5e1fSFam Zheng     }
25294a1d5e1fSFam Zheng     if (bs->file) {
25309a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
25314a1d5e1fSFam Zheng     }
25324a1d5e1fSFam Zheng     return -ENOTSUP;
25334a1d5e1fSFam Zheng }
25344a1d5e1fSFam Zheng 
25354a1d5e1fSFam Zheng /**
253665a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
253783f64091Sbellard  */
253865a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
253983f64091Sbellard {
254083f64091Sbellard     BlockDriver *drv = bs->drv;
254165a9bb25SMarkus Armbruster 
254283f64091Sbellard     if (!drv)
254319cb3738Sbellard         return -ENOMEDIUM;
254451762288SStefan Hajnoczi 
2545b94a2610SKevin Wolf     if (drv->has_variable_length) {
2546b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2547b94a2610SKevin Wolf         if (ret < 0) {
2548b94a2610SKevin Wolf             return ret;
2549fc01f7e7Sbellard         }
255046a4e4e6SStefan Hajnoczi     }
255165a9bb25SMarkus Armbruster     return bs->total_sectors;
255265a9bb25SMarkus Armbruster }
255365a9bb25SMarkus Armbruster 
255465a9bb25SMarkus Armbruster /**
255565a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
255665a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
255765a9bb25SMarkus Armbruster  */
255865a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
255965a9bb25SMarkus Armbruster {
256065a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
256165a9bb25SMarkus Armbruster 
25624a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
256365a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
256446a4e4e6SStefan Hajnoczi }
2565fc01f7e7Sbellard 
256619cb3738Sbellard /* return 0 as number of sectors if no device present or error */
256796b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2568fc01f7e7Sbellard {
256965a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
257065a9bb25SMarkus Armbruster 
257165a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2572fc01f7e7Sbellard }
2573cf98951bSbellard 
2574ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2575ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2576abd7f68dSMarkus Armbruster {
2577abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2578abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2579abd7f68dSMarkus Armbruster }
2580abd7f68dSMarkus Armbruster 
25811ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2582abd7f68dSMarkus Armbruster {
2583abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2584abd7f68dSMarkus Armbruster }
2585abd7f68dSMarkus Armbruster 
25863e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
25873e1caa5fSPaolo Bonzini {
25883e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
25893e1caa5fSPaolo Bonzini 
25903e1caa5fSPaolo Bonzini     switch (on_err) {
25913e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
2592a589569fSWenchao Xia         return (error == ENOSPC) ?
2593a589569fSWenchao Xia                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
25943e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
2595a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_STOP;
25963e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
2597a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_REPORT;
25983e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
2599a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_IGNORE;
26003e1caa5fSPaolo Bonzini     default:
26013e1caa5fSPaolo Bonzini         abort();
26023e1caa5fSPaolo Bonzini     }
26033e1caa5fSPaolo Bonzini }
26043e1caa5fSPaolo Bonzini 
2605c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs,
2606c7c2ff0cSLuiz Capitulino                                  BlockErrorAction action,
2607c7c2ff0cSLuiz Capitulino                                  bool is_read, int error)
2608c7c2ff0cSLuiz Capitulino {
2609573742a5SPeter Maydell     IoOperationType optype;
2610c7c2ff0cSLuiz Capitulino 
2611573742a5SPeter Maydell     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
2612573742a5SPeter Maydell     qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action,
2613c7c2ff0cSLuiz Capitulino                                    bdrv_iostatus_is_enabled(bs),
2614624ff573SLuiz Capitulino                                    error == ENOSPC, strerror(error),
2615624ff573SLuiz Capitulino                                    &error_abort);
2616c7c2ff0cSLuiz Capitulino }
2617c7c2ff0cSLuiz Capitulino 
26183e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
26193e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
26203e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
26213e1caa5fSPaolo Bonzini  */
26223e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
26233e1caa5fSPaolo Bonzini                        bool is_read, int error)
26243e1caa5fSPaolo Bonzini {
26253e1caa5fSPaolo Bonzini     assert(error >= 0);
26262bd3bce8SPaolo Bonzini 
2627a589569fSWenchao Xia     if (action == BLOCK_ERROR_ACTION_STOP) {
26282bd3bce8SPaolo Bonzini         /* First set the iostatus, so that "info block" returns an iostatus
26292bd3bce8SPaolo Bonzini          * that matches the events raised so far (an additional error iostatus
26302bd3bce8SPaolo Bonzini          * is fine, but not a lost one).
26312bd3bce8SPaolo Bonzini          */
26323e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
26332bd3bce8SPaolo Bonzini 
26342bd3bce8SPaolo Bonzini         /* Then raise the request to stop the VM and the event.
26352bd3bce8SPaolo Bonzini          * qemu_system_vmstop_request_prepare has two effects.  First,
26362bd3bce8SPaolo Bonzini          * it ensures that the STOP event always comes after the
26372bd3bce8SPaolo Bonzini          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
26382bd3bce8SPaolo Bonzini          * can observe the STOP event and do a "cont" before the STOP
26392bd3bce8SPaolo Bonzini          * event is issued, the VM will not stop.  In this case, vm_start()
26402bd3bce8SPaolo Bonzini          * also ensures that the STOP/RESUME pair of events is emitted.
26412bd3bce8SPaolo Bonzini          */
26422bd3bce8SPaolo Bonzini         qemu_system_vmstop_request_prepare();
2643c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
26442bd3bce8SPaolo Bonzini         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
26452bd3bce8SPaolo Bonzini     } else {
2646c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
26473e1caa5fSPaolo Bonzini     }
26483e1caa5fSPaolo Bonzini }
26493e1caa5fSPaolo Bonzini 
2650b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2651b338082bSbellard {
2652b338082bSbellard     return bs->read_only;
2653b338082bSbellard }
2654b338082bSbellard 
2655985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2656985a03b0Sths {
2657985a03b0Sths     return bs->sg;
2658985a03b0Sths }
2659985a03b0Sths 
2660e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2661e900a7b7SChristoph Hellwig {
2662e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2663e900a7b7SChristoph Hellwig }
2664e900a7b7SChristoph Hellwig 
2665425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2666425b0148SPaolo Bonzini {
2667425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
266855b110f2SJeff Cody 
266955b110f2SJeff Cody     /* so a reopen() will preserve wce */
267055b110f2SJeff Cody     if (wce) {
267155b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
267255b110f2SJeff Cody     } else {
267355b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
267455b110f2SJeff Cody     }
2675425b0148SPaolo Bonzini }
2676425b0148SPaolo Bonzini 
2677ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2678ea2384d3Sbellard {
2679*760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2680ea2384d3Sbellard         return 1;
2681*760e0063SKevin Wolf     }
2682ea2384d3Sbellard     return bs->encrypted;
2683ea2384d3Sbellard }
2684ea2384d3Sbellard 
2685c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2686c0f4ce77Saliguori {
2687*760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2688c0f4ce77Saliguori 
2689*760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2690c0f4ce77Saliguori         return 1;
2691*760e0063SKevin Wolf     }
2692c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2693c0f4ce77Saliguori }
2694c0f4ce77Saliguori 
2695ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2696ea2384d3Sbellard {
2697ea2384d3Sbellard     int ret;
2698*760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2699*760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2700ea2384d3Sbellard         if (ret < 0)
2701ea2384d3Sbellard             return ret;
2702ea2384d3Sbellard         if (!bs->encrypted)
2703ea2384d3Sbellard             return 0;
2704ea2384d3Sbellard     }
2705fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2706fd04a2aeSShahar Havivi         return -EINVAL;
2707fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2708fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2709fd04a2aeSShahar Havivi     }
2710c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2711bb5fc20fSaliguori     if (ret < 0) {
2712bb5fc20fSaliguori         bs->valid_key = 0;
2713bb5fc20fSaliguori     } else if (!bs->valid_key) {
2714bb5fc20fSaliguori         bs->valid_key = 1;
2715a7f53e26SMarkus Armbruster         if (bs->blk) {
2716bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2717a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2718a7f53e26SMarkus Armbruster         }
2719bb5fc20fSaliguori     }
2720c0f4ce77Saliguori     return ret;
2721ea2384d3Sbellard }
2722ea2384d3Sbellard 
27234d2855a3SMarkus Armbruster /*
27244d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
27254d2855a3SMarkus Armbruster  * If @key is non-null:
27264d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
27274d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
27284d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
27294d2855a3SMarkus Armbruster  * If @key is null:
27304d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
27314d2855a3SMarkus Armbruster  *     Else do nothing.
27324d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
27334d2855a3SMarkus Armbruster  */
27344d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
27354d2855a3SMarkus Armbruster {
27364d2855a3SMarkus Armbruster     if (key) {
27374d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
273881e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
273981e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
27404d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2741c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
27424d2855a3SMarkus Armbruster         }
27434d2855a3SMarkus Armbruster     } else {
27444d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2745b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2746b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
274781e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
27484d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
27494d2855a3SMarkus Armbruster         }
27504d2855a3SMarkus Armbruster     }
27514d2855a3SMarkus Armbruster }
27524d2855a3SMarkus Armbruster 
2753f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2754ea2384d3Sbellard {
2755f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2756ea2384d3Sbellard }
2757ea2384d3Sbellard 
2758ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2759ada42401SStefan Hajnoczi {
2760ada42401SStefan Hajnoczi     return strcmp(a, b);
2761ada42401SStefan Hajnoczi }
2762ada42401SStefan Hajnoczi 
2763ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2764ea2384d3Sbellard                          void *opaque)
2765ea2384d3Sbellard {
2766ea2384d3Sbellard     BlockDriver *drv;
2767e855e4fbSJeff Cody     int count = 0;
2768ada42401SStefan Hajnoczi     int i;
2769e855e4fbSJeff Cody     const char **formats = NULL;
2770ea2384d3Sbellard 
27718a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2772e855e4fbSJeff Cody         if (drv->format_name) {
2773e855e4fbSJeff Cody             bool found = false;
2774e855e4fbSJeff Cody             int i = count;
2775e855e4fbSJeff Cody             while (formats && i && !found) {
2776e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2777e855e4fbSJeff Cody             }
2778e855e4fbSJeff Cody 
2779e855e4fbSJeff Cody             if (!found) {
27805839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2781e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2782ea2384d3Sbellard             }
2783ea2384d3Sbellard         }
2784e855e4fbSJeff Cody     }
2785ada42401SStefan Hajnoczi 
2786ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2787ada42401SStefan Hajnoczi 
2788ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2789ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2790ada42401SStefan Hajnoczi     }
2791ada42401SStefan Hajnoczi 
2792e855e4fbSJeff Cody     g_free(formats);
2793e855e4fbSJeff Cody }
2794ea2384d3Sbellard 
2795dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2796dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2797dc364f4cSBenoît Canet {
2798dc364f4cSBenoît Canet     BlockDriverState *bs;
2799dc364f4cSBenoît Canet 
2800dc364f4cSBenoît Canet     assert(node_name);
2801dc364f4cSBenoît Canet 
2802dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2803dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2804dc364f4cSBenoît Canet             return bs;
2805dc364f4cSBenoît Canet         }
2806dc364f4cSBenoît Canet     }
2807dc364f4cSBenoît Canet     return NULL;
2808dc364f4cSBenoît Canet }
2809dc364f4cSBenoît Canet 
2810c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2811d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2812c13163fbSBenoît Canet {
2813c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2814c13163fbSBenoît Canet     BlockDriverState *bs;
2815c13163fbSBenoît Canet 
2816c13163fbSBenoît Canet     list = NULL;
2817c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2818d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2819d5a8ee60SAlberto Garcia         if (!info) {
2820d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2821d5a8ee60SAlberto Garcia             return NULL;
2822d5a8ee60SAlberto Garcia         }
2823c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2824d5a8ee60SAlberto Garcia         entry->value = info;
2825c13163fbSBenoît Canet         entry->next = list;
2826c13163fbSBenoît Canet         list = entry;
2827c13163fbSBenoît Canet     }
2828c13163fbSBenoît Canet 
2829c13163fbSBenoît Canet     return list;
2830c13163fbSBenoît Canet }
2831c13163fbSBenoît Canet 
283212d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
283312d3ba82SBenoît Canet                                  const char *node_name,
283412d3ba82SBenoît Canet                                  Error **errp)
283512d3ba82SBenoît Canet {
28367f06d47eSMarkus Armbruster     BlockBackend *blk;
28377f06d47eSMarkus Armbruster     BlockDriverState *bs;
283812d3ba82SBenoît Canet 
283912d3ba82SBenoît Canet     if (device) {
28407f06d47eSMarkus Armbruster         blk = blk_by_name(device);
284112d3ba82SBenoît Canet 
28427f06d47eSMarkus Armbruster         if (blk) {
28437f06d47eSMarkus Armbruster             return blk_bs(blk);
284412d3ba82SBenoît Canet         }
2845dd67fa50SBenoît Canet     }
284612d3ba82SBenoît Canet 
2847dd67fa50SBenoît Canet     if (node_name) {
284812d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
284912d3ba82SBenoît Canet 
2850dd67fa50SBenoît Canet         if (bs) {
2851dd67fa50SBenoît Canet             return bs;
2852dd67fa50SBenoît Canet         }
285312d3ba82SBenoît Canet     }
285412d3ba82SBenoît Canet 
2855dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2856dd67fa50SBenoît Canet                      device ? device : "",
2857dd67fa50SBenoît Canet                      node_name ? node_name : "");
2858dd67fa50SBenoît Canet     return NULL;
285912d3ba82SBenoît Canet }
286012d3ba82SBenoît Canet 
28615a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
28625a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
28635a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
28645a6684d2SJeff Cody {
28655a6684d2SJeff Cody     while (top && top != base) {
2866*760e0063SKevin Wolf         top = backing_bs(top);
28675a6684d2SJeff Cody     }
28685a6684d2SJeff Cody 
28695a6684d2SJeff Cody     return top != NULL;
28705a6684d2SJeff Cody }
28715a6684d2SJeff Cody 
287204df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
287304df765aSFam Zheng {
287404df765aSFam Zheng     if (!bs) {
287504df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
287604df765aSFam Zheng     }
287704df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
287804df765aSFam Zheng }
287904df765aSFam Zheng 
28802f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
28812f399b0aSMarkus Armbruster {
28822f399b0aSMarkus Armbruster     if (!bs) {
28832f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
28842f399b0aSMarkus Armbruster     }
2885dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
28862f399b0aSMarkus Armbruster }
28872f399b0aSMarkus Armbruster 
288820a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
288920a9e77dSFam Zheng {
289020a9e77dSFam Zheng     return bs->node_name;
289120a9e77dSFam Zheng }
289220a9e77dSFam Zheng 
28937f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2894bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2895ea2384d3Sbellard {
2896bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2897ea2384d3Sbellard }
2898ea2384d3Sbellard 
28999b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29009b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29019b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29029b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29039b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29049b2aa84fSAlberto Garcia {
29059b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
29069b2aa84fSAlberto Garcia }
29079b2aa84fSAlberto Garcia 
2908c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2909c8433287SMarkus Armbruster {
2910c8433287SMarkus Armbruster     return bs->open_flags;
2911c8433287SMarkus Armbruster }
2912c8433287SMarkus Armbruster 
29133ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
29143ac21627SPeter Lieven {
29153ac21627SPeter Lieven     return 1;
29163ac21627SPeter Lieven }
29173ac21627SPeter Lieven 
2918f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2919f2feebbdSKevin Wolf {
2920f2feebbdSKevin Wolf     assert(bs->drv);
2921f2feebbdSKevin Wolf 
292211212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
292311212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
2924*760e0063SKevin Wolf     if (bs->backing) {
292511212d8fSPaolo Bonzini         return 0;
292611212d8fSPaolo Bonzini     }
2927336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2928336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2929f2feebbdSKevin Wolf     }
2930f2feebbdSKevin Wolf 
29313ac21627SPeter Lieven     /* safe default */
29323ac21627SPeter Lieven     return 0;
2933f2feebbdSKevin Wolf }
2934f2feebbdSKevin Wolf 
29354ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
29364ce78691SPeter Lieven {
29374ce78691SPeter Lieven     BlockDriverInfo bdi;
29384ce78691SPeter Lieven 
2939*760e0063SKevin Wolf     if (bs->backing) {
29404ce78691SPeter Lieven         return false;
29414ce78691SPeter Lieven     }
29424ce78691SPeter Lieven 
29434ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29444ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
29454ce78691SPeter Lieven     }
29464ce78691SPeter Lieven 
29474ce78691SPeter Lieven     return false;
29484ce78691SPeter Lieven }
29494ce78691SPeter Lieven 
29504ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
29514ce78691SPeter Lieven {
29524ce78691SPeter Lieven     BlockDriverInfo bdi;
29534ce78691SPeter Lieven 
2954*760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
29554ce78691SPeter Lieven         return false;
29564ce78691SPeter Lieven     }
29574ce78691SPeter Lieven 
29584ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
29594ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
29604ce78691SPeter Lieven     }
29614ce78691SPeter Lieven 
29624ce78691SPeter Lieven     return false;
29634ce78691SPeter Lieven }
29644ce78691SPeter Lieven 
2965045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2966045df330Saliguori {
2967*760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
2968045df330Saliguori         return bs->backing_file;
2969045df330Saliguori     else if (bs->encrypted)
2970045df330Saliguori         return bs->filename;
2971045df330Saliguori     else
2972045df330Saliguori         return NULL;
2973045df330Saliguori }
2974045df330Saliguori 
297583f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
297683f64091Sbellard                                char *filename, int filename_size)
297783f64091Sbellard {
297883f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
297983f64091Sbellard }
298083f64091Sbellard 
2981faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2982faea38e7Sbellard {
2983faea38e7Sbellard     BlockDriver *drv = bs->drv;
2984faea38e7Sbellard     if (!drv)
298519cb3738Sbellard         return -ENOMEDIUM;
2986faea38e7Sbellard     if (!drv->bdrv_get_info)
2987faea38e7Sbellard         return -ENOTSUP;
2988faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2989faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2990faea38e7Sbellard }
2991faea38e7Sbellard 
2992eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2993eae041feSMax Reitz {
2994eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2995eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2996eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2997eae041feSMax Reitz     }
2998eae041feSMax Reitz     return NULL;
2999eae041feSMax Reitz }
3000eae041feSMax Reitz 
30018b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
30028b9b0cc2SKevin Wolf {
3003bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30048b9b0cc2SKevin Wolf         return;
30058b9b0cc2SKevin Wolf     }
30068b9b0cc2SKevin Wolf 
3007bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
300841c695c7SKevin Wolf }
30098b9b0cc2SKevin Wolf 
301041c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
301141c695c7SKevin Wolf                           const char *tag)
301241c695c7SKevin Wolf {
301341c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
30149a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
301541c695c7SKevin Wolf     }
301641c695c7SKevin Wolf 
301741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
301841c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
301941c695c7SKevin Wolf     }
302041c695c7SKevin Wolf 
302141c695c7SKevin Wolf     return -ENOTSUP;
302241c695c7SKevin Wolf }
302341c695c7SKevin Wolf 
30244cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
30254cc70e93SFam Zheng {
30264cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
30279a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
30284cc70e93SFam Zheng     }
30294cc70e93SFam Zheng 
30304cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
30314cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
30324cc70e93SFam Zheng     }
30334cc70e93SFam Zheng 
30344cc70e93SFam Zheng     return -ENOTSUP;
30354cc70e93SFam Zheng }
30364cc70e93SFam Zheng 
303741c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
303841c695c7SKevin Wolf {
3039938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
30409a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
304141c695c7SKevin Wolf     }
304241c695c7SKevin Wolf 
304341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
304441c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
304541c695c7SKevin Wolf     }
304641c695c7SKevin Wolf 
304741c695c7SKevin Wolf     return -ENOTSUP;
304841c695c7SKevin Wolf }
304941c695c7SKevin Wolf 
305041c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
305141c695c7SKevin Wolf {
305241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
30539a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
305441c695c7SKevin Wolf     }
305541c695c7SKevin Wolf 
305641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
305741c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
305841c695c7SKevin Wolf     }
305941c695c7SKevin Wolf 
306041c695c7SKevin Wolf     return false;
30618b9b0cc2SKevin Wolf }
30628b9b0cc2SKevin Wolf 
3063199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3064199630b6SBlue Swirl {
3065199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3066199630b6SBlue Swirl }
3067199630b6SBlue Swirl 
3068b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3069b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3070b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3071b1b1d783SJeff Cody  * the CWD rather than the chain. */
3072e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3073e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3074e8a6bb9cSMarcelo Tosatti {
3075b1b1d783SJeff Cody     char *filename_full = NULL;
3076b1b1d783SJeff Cody     char *backing_file_full = NULL;
3077b1b1d783SJeff Cody     char *filename_tmp = NULL;
3078b1b1d783SJeff Cody     int is_protocol = 0;
3079b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3080b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3081b1b1d783SJeff Cody 
3082b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3083e8a6bb9cSMarcelo Tosatti         return NULL;
3084e8a6bb9cSMarcelo Tosatti     }
3085e8a6bb9cSMarcelo Tosatti 
3086b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3087b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3088b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3089b1b1d783SJeff Cody 
3090b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3091b1b1d783SJeff Cody 
3092*760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3093b1b1d783SJeff Cody 
3094b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3095b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3096b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3097b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3098*760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3099b1b1d783SJeff Cody                 break;
3100b1b1d783SJeff Cody             }
3101e8a6bb9cSMarcelo Tosatti         } else {
3102b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3103b1b1d783SJeff Cody              * image's filename path */
3104b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3105b1b1d783SJeff Cody                          backing_file);
3106b1b1d783SJeff Cody 
3107b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3108b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3109b1b1d783SJeff Cody                 continue;
3110b1b1d783SJeff Cody             }
3111b1b1d783SJeff Cody 
3112b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3113b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3114b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3115b1b1d783SJeff Cody                          curr_bs->backing_file);
3116b1b1d783SJeff Cody 
3117b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3118b1b1d783SJeff Cody                 continue;
3119b1b1d783SJeff Cody             }
3120b1b1d783SJeff Cody 
3121b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3122*760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3123b1b1d783SJeff Cody                 break;
3124b1b1d783SJeff Cody             }
3125e8a6bb9cSMarcelo Tosatti         }
3126e8a6bb9cSMarcelo Tosatti     }
3127e8a6bb9cSMarcelo Tosatti 
3128b1b1d783SJeff Cody     g_free(filename_full);
3129b1b1d783SJeff Cody     g_free(backing_file_full);
3130b1b1d783SJeff Cody     g_free(filename_tmp);
3131b1b1d783SJeff Cody     return retval;
3132e8a6bb9cSMarcelo Tosatti }
3133e8a6bb9cSMarcelo Tosatti 
3134f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3135f198fd1cSBenoît Canet {
3136f198fd1cSBenoît Canet     if (!bs->drv) {
3137f198fd1cSBenoît Canet         return 0;
3138f198fd1cSBenoît Canet     }
3139f198fd1cSBenoît Canet 
3140*760e0063SKevin Wolf     if (!bs->backing) {
3141f198fd1cSBenoît Canet         return 0;
3142f198fd1cSBenoît Canet     }
3143f198fd1cSBenoît Canet 
3144*760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3145f198fd1cSBenoît Canet }
3146f198fd1cSBenoît Canet 
3147ea2384d3Sbellard void bdrv_init(void)
3148ea2384d3Sbellard {
31495efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3150ea2384d3Sbellard }
3151ce1a14dcSpbrook 
3152eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3153eb852011SMarkus Armbruster {
3154eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3155eb852011SMarkus Armbruster     bdrv_init();
3156eb852011SMarkus Armbruster }
3157eb852011SMarkus Armbruster 
31585a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
31590f15423cSAnthony Liguori {
31605a8a30dbSKevin Wolf     Error *local_err = NULL;
31615a8a30dbSKevin Wolf     int ret;
31625a8a30dbSKevin Wolf 
31633456a8d1SKevin Wolf     if (!bs->drv)  {
31643456a8d1SKevin Wolf         return;
31650f15423cSAnthony Liguori     }
31663456a8d1SKevin Wolf 
31677ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
31687ea2d269SAlexey Kardashevskiy         return;
31697ea2d269SAlexey Kardashevskiy     }
31707ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
31717ea2d269SAlexey Kardashevskiy 
31723456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
31735a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
31743456a8d1SKevin Wolf     } else if (bs->file) {
31759a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
31765a8a30dbSKevin Wolf     }
31775a8a30dbSKevin Wolf     if (local_err) {
31785a8a30dbSKevin Wolf         error_propagate(errp, local_err);
31795a8a30dbSKevin Wolf         return;
31803456a8d1SKevin Wolf     }
31813456a8d1SKevin Wolf 
31825a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
31835a8a30dbSKevin Wolf     if (ret < 0) {
31845a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
31855a8a30dbSKevin Wolf         return;
31865a8a30dbSKevin Wolf     }
31870f15423cSAnthony Liguori }
31880f15423cSAnthony Liguori 
31895a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
31900f15423cSAnthony Liguori {
31910f15423cSAnthony Liguori     BlockDriverState *bs;
31925a8a30dbSKevin Wolf     Error *local_err = NULL;
31930f15423cSAnthony Liguori 
3194dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3195ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3196ed78cda3SStefan Hajnoczi 
3197ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
31985a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3199ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32005a8a30dbSKevin Wolf         if (local_err) {
32015a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32025a8a30dbSKevin Wolf             return;
32035a8a30dbSKevin Wolf         }
32040f15423cSAnthony Liguori     }
32050f15423cSAnthony Liguori }
32060f15423cSAnthony Liguori 
3207f9f05dc5SKevin Wolf /**************************************************************/
320819cb3738Sbellard /* removable device support */
320919cb3738Sbellard 
321019cb3738Sbellard /**
321119cb3738Sbellard  * Return TRUE if the media is present
321219cb3738Sbellard  */
321319cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
321419cb3738Sbellard {
321519cb3738Sbellard     BlockDriver *drv = bs->drv;
3216a1aff5bfSMarkus Armbruster 
321719cb3738Sbellard     if (!drv)
321819cb3738Sbellard         return 0;
321919cb3738Sbellard     if (!drv->bdrv_is_inserted)
3220a1aff5bfSMarkus Armbruster         return 1;
3221a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
322219cb3738Sbellard }
322319cb3738Sbellard 
322419cb3738Sbellard /**
32258e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
32268e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
322719cb3738Sbellard  */
322819cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
322919cb3738Sbellard {
323019cb3738Sbellard     BlockDriver *drv = bs->drv;
323119cb3738Sbellard 
32328e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
32338e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
32348e49ca46SMarkus Armbruster     }
32358e49ca46SMarkus Armbruster     return -ENOTSUP;
323619cb3738Sbellard }
323719cb3738Sbellard 
323819cb3738Sbellard /**
323919cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
324019cb3738Sbellard  */
3241f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
324219cb3738Sbellard {
324319cb3738Sbellard     BlockDriver *drv = bs->drv;
3244bfb197e0SMarkus Armbruster     const char *device_name;
324519cb3738Sbellard 
3246822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3247822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
324819cb3738Sbellard     }
32496f382ed2SLuiz Capitulino 
3250bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3251bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3252bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3253a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
32546f382ed2SLuiz Capitulino     }
325519cb3738Sbellard }
325619cb3738Sbellard 
325719cb3738Sbellard /**
325819cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
325919cb3738Sbellard  * to eject it manually).
326019cb3738Sbellard  */
3261025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
326219cb3738Sbellard {
326319cb3738Sbellard     BlockDriver *drv = bs->drv;
326419cb3738Sbellard 
3265025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3266b8c6d095SStefan Hajnoczi 
3267025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3268025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
326919cb3738Sbellard     }
327019cb3738Sbellard }
3271985a03b0Sths 
32721b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
32737b6f9300SMarkus Armbruster {
32741b7fd729SPaolo Bonzini     bs->guest_block_size = align;
32757b6f9300SMarkus Armbruster }
32767cd1e32aSlirans@il.ibm.com 
32770db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
32780db6e54aSFam Zheng {
32790db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
32800db6e54aSFam Zheng 
32810db6e54aSFam Zheng     assert(name);
32820db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
32830db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
32840db6e54aSFam Zheng             return bm;
32850db6e54aSFam Zheng         }
32860db6e54aSFam Zheng     }
32870db6e54aSFam Zheng     return NULL;
32880db6e54aSFam Zheng }
32890db6e54aSFam Zheng 
329020dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
32910db6e54aSFam Zheng {
32929bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
32930db6e54aSFam Zheng     g_free(bitmap->name);
32940db6e54aSFam Zheng     bitmap->name = NULL;
32950db6e54aSFam Zheng }
32960db6e54aSFam Zheng 
32970db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
32985fba6c0eSJohn Snow                                           uint32_t granularity,
32990db6e54aSFam Zheng                                           const char *name,
3300b8afb520SFam Zheng                                           Error **errp)
33017cd1e32aSlirans@il.ibm.com {
33027cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3303e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
33045fba6c0eSJohn Snow     uint32_t sector_granularity;
3305a55eb92cSJan Kiszka 
330650717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
330750717e94SPaolo Bonzini 
33080db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
33090db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
33100db6e54aSFam Zheng         return NULL;
33110db6e54aSFam Zheng     }
33125fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
33135fba6c0eSJohn Snow     assert(sector_granularity);
331457322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3315b8afb520SFam Zheng     if (bitmap_size < 0) {
3316b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3317b8afb520SFam Zheng         errno = -bitmap_size;
3318b8afb520SFam Zheng         return NULL;
3319b8afb520SFam Zheng     }
33205839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
33215fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3322e74e6b78SJohn Snow     bitmap->size = bitmap_size;
33230db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3324b8e6fb75SJohn Snow     bitmap->disabled = false;
3325e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3326e4654d2dSFam Zheng     return bitmap;
3327e4654d2dSFam Zheng }
3328e4654d2dSFam Zheng 
33299bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
33309bd2b08fSJohn Snow {
33319bd2b08fSJohn Snow     return bitmap->successor;
33329bd2b08fSJohn Snow }
33339bd2b08fSJohn Snow 
3334b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3335b8e6fb75SJohn Snow {
33369bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
33379bd2b08fSJohn Snow }
33389bd2b08fSJohn Snow 
33399abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
33409abe3bdcSJohn Snow {
33419abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
33429abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
33439abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
33449abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
33459abe3bdcSJohn Snow     } else {
33469abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
33479abe3bdcSJohn Snow     }
33489abe3bdcSJohn Snow }
33499abe3bdcSJohn Snow 
33509bd2b08fSJohn Snow /**
33519bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
33529bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
33539bd2b08fSJohn Snow  */
33549bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
33559bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
33569bd2b08fSJohn Snow {
33579bd2b08fSJohn Snow     uint64_t granularity;
33589bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
33599bd2b08fSJohn Snow 
33609bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
33619bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
33629bd2b08fSJohn Snow                    "currently frozen");
33639bd2b08fSJohn Snow         return -1;
33649bd2b08fSJohn Snow     }
33659bd2b08fSJohn Snow     assert(!bitmap->successor);
33669bd2b08fSJohn Snow 
33679bd2b08fSJohn Snow     /* Create an anonymous successor */
33689bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
33699bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
33709bd2b08fSJohn Snow     if (!child) {
33719bd2b08fSJohn Snow         return -1;
33729bd2b08fSJohn Snow     }
33739bd2b08fSJohn Snow 
33749bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
33759bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
33769bd2b08fSJohn Snow 
33779bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
33789bd2b08fSJohn Snow     bitmap->successor = child;
33799bd2b08fSJohn Snow     return 0;
33809bd2b08fSJohn Snow }
33819bd2b08fSJohn Snow 
33829bd2b08fSJohn Snow /**
33839bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
33849bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
33859bd2b08fSJohn Snow  */
33869bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
33879bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
33889bd2b08fSJohn Snow                                             Error **errp)
33899bd2b08fSJohn Snow {
33909bd2b08fSJohn Snow     char *name;
33919bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
33929bd2b08fSJohn Snow 
33939bd2b08fSJohn Snow     if (successor == NULL) {
33949bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
33959bd2b08fSJohn Snow                    "there's no successor present");
33969bd2b08fSJohn Snow         return NULL;
33979bd2b08fSJohn Snow     }
33989bd2b08fSJohn Snow 
33999bd2b08fSJohn Snow     name = bitmap->name;
34009bd2b08fSJohn Snow     bitmap->name = NULL;
34019bd2b08fSJohn Snow     successor->name = name;
34029bd2b08fSJohn Snow     bitmap->successor = NULL;
34039bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
34049bd2b08fSJohn Snow 
34059bd2b08fSJohn Snow     return successor;
34069bd2b08fSJohn Snow }
34079bd2b08fSJohn Snow 
34089bd2b08fSJohn Snow /**
34099bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
34109bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
34119bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
34129bd2b08fSJohn Snow  */
34139bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
34149bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
34159bd2b08fSJohn Snow                                            Error **errp)
34169bd2b08fSJohn Snow {
34179bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
34189bd2b08fSJohn Snow 
34199bd2b08fSJohn Snow     if (!successor) {
34209bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
34219bd2b08fSJohn Snow         return NULL;
34229bd2b08fSJohn Snow     }
34239bd2b08fSJohn Snow 
34249bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
34259bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
34269bd2b08fSJohn Snow         return NULL;
34279bd2b08fSJohn Snow     }
34289bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
34299bd2b08fSJohn Snow     parent->successor = NULL;
34309bd2b08fSJohn Snow 
34319bd2b08fSJohn Snow     return parent;
3432b8e6fb75SJohn Snow }
3433b8e6fb75SJohn Snow 
3434ce1ffea8SJohn Snow /**
3435ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3436ce1ffea8SJohn Snow  */
3437ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3438ce1ffea8SJohn Snow {
3439ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3440ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3441ce1ffea8SJohn Snow 
3442ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
344306207b0fSJohn Snow         assert(!bdrv_dirty_bitmap_frozen(bitmap));
3444ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
34455270b6a0SJohn Snow         bitmap->size = size;
3446ce1ffea8SJohn Snow     }
3447ce1ffea8SJohn Snow }
3448ce1ffea8SJohn Snow 
3449e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3450e4654d2dSFam Zheng {
3451e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3452e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3453e4654d2dSFam Zheng         if (bm == bitmap) {
34549bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3455e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3456e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
34570db6e54aSFam Zheng             g_free(bitmap->name);
3458e4654d2dSFam Zheng             g_free(bitmap);
3459e4654d2dSFam Zheng             return;
34607cd1e32aSlirans@il.ibm.com         }
34617cd1e32aSlirans@il.ibm.com     }
34627cd1e32aSlirans@il.ibm.com }
34637cd1e32aSlirans@il.ibm.com 
3464b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3465b8e6fb75SJohn Snow {
34669bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3467b8e6fb75SJohn Snow     bitmap->disabled = true;
3468b8e6fb75SJohn Snow }
3469b8e6fb75SJohn Snow 
3470b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3471b8e6fb75SJohn Snow {
34729bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3473b8e6fb75SJohn Snow     bitmap->disabled = false;
3474b8e6fb75SJohn Snow }
3475b8e6fb75SJohn Snow 
347621b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
347721b56835SFam Zheng {
347821b56835SFam Zheng     BdrvDirtyBitmap *bm;
347921b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
348021b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
348121b56835SFam Zheng 
348221b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
34835839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
34845839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
348520dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3486592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
34870db6e54aSFam Zheng         info->has_name = !!bm->name;
34880db6e54aSFam Zheng         info->name = g_strdup(bm->name);
34899abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
349021b56835SFam Zheng         entry->value = info;
349121b56835SFam Zheng         *plist = entry;
349221b56835SFam Zheng         plist = &entry->next;
349321b56835SFam Zheng     }
349421b56835SFam Zheng 
349521b56835SFam Zheng     return list;
349621b56835SFam Zheng }
349721b56835SFam Zheng 
3498e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
34997cd1e32aSlirans@il.ibm.com {
3500e4654d2dSFam Zheng     if (bitmap) {
3501e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
35027cd1e32aSlirans@il.ibm.com     } else {
35037cd1e32aSlirans@il.ibm.com         return 0;
35047cd1e32aSlirans@il.ibm.com     }
35057cd1e32aSlirans@il.ibm.com }
35067cd1e32aSlirans@il.ibm.com 
3507341ebc2fSJohn Snow /**
3508341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3509341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3510341ebc2fSJohn Snow  * is no cluster size information available.
3511341ebc2fSJohn Snow  */
3512341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3513341ebc2fSJohn Snow {
3514341ebc2fSJohn Snow     BlockDriverInfo bdi;
3515341ebc2fSJohn Snow     uint32_t granularity;
3516341ebc2fSJohn Snow 
3517341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3518341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3519341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3520341ebc2fSJohn Snow     } else {
3521341ebc2fSJohn Snow         granularity = 65536;
3522341ebc2fSJohn Snow     }
3523341ebc2fSJohn Snow 
3524341ebc2fSJohn Snow     return granularity;
3525341ebc2fSJohn Snow }
3526341ebc2fSJohn Snow 
3527592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3528592fdd02SJohn Snow {
3529592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3530592fdd02SJohn Snow }
3531592fdd02SJohn Snow 
353220dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
35331755da16SPaolo Bonzini {
3534e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
35351755da16SPaolo Bonzini }
35361755da16SPaolo Bonzini 
353720dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3538c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3539c4237dfaSVladimir Sementsov-Ogievskiy {
3540b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3541c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3542c4237dfaSVladimir Sementsov-Ogievskiy }
3543c4237dfaSVladimir Sementsov-Ogievskiy 
354420dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3545c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3546c4237dfaSVladimir Sementsov-Ogievskiy {
3547b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3548c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3549c4237dfaSVladimir Sementsov-Ogievskiy }
3550c4237dfaSVladimir Sementsov-Ogievskiy 
3551e74e6b78SJohn Snow void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3552e74e6b78SJohn Snow {
3553e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3554c6a8c328SWen Congyang     hbitmap_reset_all(bitmap->bitmap);
3555e74e6b78SJohn Snow }
3556e74e6b78SJohn Snow 
3557e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
35581755da16SPaolo Bonzini                     int nr_sectors)
35591755da16SPaolo Bonzini {
3560e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3561e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3562b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3563b8e6fb75SJohn Snow             continue;
3564b8e6fb75SJohn Snow         }
3565e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3566e4654d2dSFam Zheng     }
35671755da16SPaolo Bonzini }
35681755da16SPaolo Bonzini 
3569d58d8453SJohn Snow /**
3570d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3571d58d8453SJohn Snow  */
3572d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3573d58d8453SJohn Snow {
3574d58d8453SJohn Snow     assert(hbi->hb);
3575d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3576d58d8453SJohn Snow }
3577d58d8453SJohn Snow 
357820dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3579aaa0eb75SLiran Schour {
3580e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3581aaa0eb75SLiran Schour }
3582f88e1a42SJes Sorensen 
35839fcb0251SFam Zheng /* Get a reference to bs */
35849fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
35859fcb0251SFam Zheng {
35869fcb0251SFam Zheng     bs->refcnt++;
35879fcb0251SFam Zheng }
35889fcb0251SFam Zheng 
35899fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
35909fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
35919fcb0251SFam Zheng  * deleted. */
35929fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
35939fcb0251SFam Zheng {
35949a4d5ca6SJeff Cody     if (!bs) {
35959a4d5ca6SJeff Cody         return;
35969a4d5ca6SJeff Cody     }
35979fcb0251SFam Zheng     assert(bs->refcnt > 0);
35989fcb0251SFam Zheng     if (--bs->refcnt == 0) {
35999fcb0251SFam Zheng         bdrv_delete(bs);
36009fcb0251SFam Zheng     }
36019fcb0251SFam Zheng }
36029fcb0251SFam Zheng 
3603fbe40ff7SFam Zheng struct BdrvOpBlocker {
3604fbe40ff7SFam Zheng     Error *reason;
3605fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3606fbe40ff7SFam Zheng };
3607fbe40ff7SFam Zheng 
3608fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3609fbe40ff7SFam Zheng {
3610fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3611fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3612fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3613fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3614fbe40ff7SFam Zheng         if (errp) {
361581e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
361681e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3617bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3618fbe40ff7SFam Zheng         }
3619fbe40ff7SFam Zheng         return true;
3620fbe40ff7SFam Zheng     }
3621fbe40ff7SFam Zheng     return false;
3622fbe40ff7SFam Zheng }
3623fbe40ff7SFam Zheng 
3624fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3625fbe40ff7SFam Zheng {
3626fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3627fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3628fbe40ff7SFam Zheng 
36295839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3630fbe40ff7SFam Zheng     blocker->reason = reason;
3631fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3632fbe40ff7SFam Zheng }
3633fbe40ff7SFam Zheng 
3634fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3635fbe40ff7SFam Zheng {
3636fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3637fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3638fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3639fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3640fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3641fbe40ff7SFam Zheng             g_free(blocker);
3642fbe40ff7SFam Zheng         }
3643fbe40ff7SFam Zheng     }
3644fbe40ff7SFam Zheng }
3645fbe40ff7SFam Zheng 
3646fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3647fbe40ff7SFam Zheng {
3648fbe40ff7SFam Zheng     int i;
3649fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3650fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3651fbe40ff7SFam Zheng     }
3652fbe40ff7SFam Zheng }
3653fbe40ff7SFam Zheng 
3654fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3655fbe40ff7SFam Zheng {
3656fbe40ff7SFam Zheng     int i;
3657fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3658fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3659fbe40ff7SFam Zheng     }
3660fbe40ff7SFam Zheng }
3661fbe40ff7SFam Zheng 
3662fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3663fbe40ff7SFam Zheng {
3664fbe40ff7SFam Zheng     int i;
3665fbe40ff7SFam Zheng 
3666fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3667fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3668fbe40ff7SFam Zheng             return false;
3669fbe40ff7SFam Zheng         }
3670fbe40ff7SFam Zheng     }
3671fbe40ff7SFam Zheng     return true;
3672fbe40ff7SFam Zheng }
3673fbe40ff7SFam Zheng 
367428a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
367528a7282aSLuiz Capitulino {
3676d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
367758e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
367828a7282aSLuiz Capitulino }
367928a7282aSLuiz Capitulino 
368028a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
368128a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
368228a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
368328a7282aSLuiz Capitulino {
3684d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
368592aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
368692aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
368792aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
368828a7282aSLuiz Capitulino }
368928a7282aSLuiz Capitulino 
369028a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
369128a7282aSLuiz Capitulino {
3692d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
369328a7282aSLuiz Capitulino }
369428a7282aSLuiz Capitulino 
369528a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
369628a7282aSLuiz Capitulino {
369728a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
369858e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
36993bd293c3SPaolo Bonzini         if (bs->job) {
37003bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
37013bd293c3SPaolo Bonzini         }
370228a7282aSLuiz Capitulino     }
370328a7282aSLuiz Capitulino }
370428a7282aSLuiz Capitulino 
370528a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
370628a7282aSLuiz Capitulino {
37073e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
37083e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
370958e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
371058e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
371128a7282aSLuiz Capitulino     }
371228a7282aSLuiz Capitulino }
371328a7282aSLuiz Capitulino 
3714d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3715f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3716f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3717f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3718f88e1a42SJes Sorensen {
371983d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
372083d0521aSChunyan Liu     QemuOpts *opts = NULL;
372183d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
372283d0521aSChunyan Liu     int64_t size;
3723f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3724cc84d90fSMax Reitz     Error *local_err = NULL;
3725f88e1a42SJes Sorensen     int ret = 0;
3726f88e1a42SJes Sorensen 
3727f88e1a42SJes Sorensen     /* Find driver and parse its options */
3728f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3729f88e1a42SJes Sorensen     if (!drv) {
373071c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3731d92ada22SLuiz Capitulino         return;
3732f88e1a42SJes Sorensen     }
3733f88e1a42SJes Sorensen 
3734b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3735f88e1a42SJes Sorensen     if (!proto_drv) {
3736d92ada22SLuiz Capitulino         return;
3737f88e1a42SJes Sorensen     }
3738f88e1a42SJes Sorensen 
3739c6149724SMax Reitz     if (!drv->create_opts) {
3740c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3741c6149724SMax Reitz                    drv->format_name);
3742c6149724SMax Reitz         return;
3743c6149724SMax Reitz     }
3744c6149724SMax Reitz 
3745c6149724SMax Reitz     if (!proto_drv->create_opts) {
3746c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3747c6149724SMax Reitz                    proto_drv->format_name);
3748c6149724SMax Reitz         return;
3749c6149724SMax Reitz     }
3750c6149724SMax Reitz 
3751c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3752c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3753f88e1a42SJes Sorensen 
3754f88e1a42SJes Sorensen     /* Create parameter list with default values */
375583d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
375639101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3757f88e1a42SJes Sorensen 
3758f88e1a42SJes Sorensen     /* Parse -o options */
3759f88e1a42SJes Sorensen     if (options) {
3760dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3761dc523cd3SMarkus Armbruster         if (local_err) {
3762dc523cd3SMarkus Armbruster             error_report_err(local_err);
3763dc523cd3SMarkus Armbruster             local_err = NULL;
376483d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3765f88e1a42SJes Sorensen             goto out;
3766f88e1a42SJes Sorensen         }
3767f88e1a42SJes Sorensen     }
3768f88e1a42SJes Sorensen 
3769f88e1a42SJes Sorensen     if (base_filename) {
3770f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
37716be4194bSMarkus Armbruster         if (local_err) {
377271c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
377371c79813SLuiz Capitulino                        fmt);
3774f88e1a42SJes Sorensen             goto out;
3775f88e1a42SJes Sorensen         }
3776f88e1a42SJes Sorensen     }
3777f88e1a42SJes Sorensen 
3778f88e1a42SJes Sorensen     if (base_fmt) {
3779f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
37806be4194bSMarkus Armbruster         if (local_err) {
378171c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
378271c79813SLuiz Capitulino                              "format '%s'", fmt);
3783f88e1a42SJes Sorensen             goto out;
3784f88e1a42SJes Sorensen         }
3785f88e1a42SJes Sorensen     }
3786f88e1a42SJes Sorensen 
378783d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
378883d0521aSChunyan Liu     if (backing_file) {
378983d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
379071c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
379171c79813SLuiz Capitulino                              "same filename as the backing file");
3792792da93aSJes Sorensen             goto out;
3793792da93aSJes Sorensen         }
3794792da93aSJes Sorensen     }
3795792da93aSJes Sorensen 
379683d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3797f88e1a42SJes Sorensen 
3798f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3799f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
380083d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
380183d0521aSChunyan Liu     if (size == -1) {
380283d0521aSChunyan Liu         if (backing_file) {
380366f6b814SMax Reitz             BlockDriverState *bs;
380429168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
380552bf1e72SMarkus Armbruster             int64_t size;
380663090dacSPaolo Bonzini             int back_flags;
3807e6641719SMax Reitz             QDict *backing_options = NULL;
380863090dacSPaolo Bonzini 
380929168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
381029168018SMax Reitz                                                          full_backing, PATH_MAX,
381129168018SMax Reitz                                                          &local_err);
381229168018SMax Reitz             if (local_err) {
381329168018SMax Reitz                 g_free(full_backing);
381429168018SMax Reitz                 goto out;
381529168018SMax Reitz             }
381629168018SMax Reitz 
381763090dacSPaolo Bonzini             /* backing files always opened read-only */
381863090dacSPaolo Bonzini             back_flags =
381963090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3820f88e1a42SJes Sorensen 
3821e6641719SMax Reitz             if (backing_fmt) {
3822e6641719SMax Reitz                 backing_options = qdict_new();
3823e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3824e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3825e6641719SMax Reitz             }
3826e6641719SMax Reitz 
3827f67503e5SMax Reitz             bs = NULL;
3828e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
38296ebf9aa2SMax Reitz                             back_flags, &local_err);
383029168018SMax Reitz             g_free(full_backing);
3831f88e1a42SJes Sorensen             if (ret < 0) {
3832f88e1a42SJes Sorensen                 goto out;
3833f88e1a42SJes Sorensen             }
383452bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
383552bf1e72SMarkus Armbruster             if (size < 0) {
383652bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
383752bf1e72SMarkus Armbruster                                  backing_file);
383852bf1e72SMarkus Armbruster                 bdrv_unref(bs);
383952bf1e72SMarkus Armbruster                 goto out;
384052bf1e72SMarkus Armbruster             }
3841f88e1a42SJes Sorensen 
384239101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
384366f6b814SMax Reitz 
384466f6b814SMax Reitz             bdrv_unref(bs);
3845f88e1a42SJes Sorensen         } else {
384671c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3847f88e1a42SJes Sorensen             goto out;
3848f88e1a42SJes Sorensen         }
3849f88e1a42SJes Sorensen     }
3850f88e1a42SJes Sorensen 
3851f382d43aSMiroslav Rezanina     if (!quiet) {
3852f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
385343c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3854f88e1a42SJes Sorensen         puts("");
3855f382d43aSMiroslav Rezanina     }
385683d0521aSChunyan Liu 
3857c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
385883d0521aSChunyan Liu 
3859cc84d90fSMax Reitz     if (ret == -EFBIG) {
3860cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3861cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3862cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3863f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
386483d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3865f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3866f3f4d2c0SKevin Wolf         }
3867cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3868cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3869cc84d90fSMax Reitz         error_free(local_err);
3870cc84d90fSMax Reitz         local_err = NULL;
3871f88e1a42SJes Sorensen     }
3872f88e1a42SJes Sorensen 
3873f88e1a42SJes Sorensen out:
387483d0521aSChunyan Liu     qemu_opts_del(opts);
387583d0521aSChunyan Liu     qemu_opts_free(create_opts);
387684d18f06SMarkus Armbruster     if (local_err) {
3877cc84d90fSMax Reitz         error_propagate(errp, local_err);
3878cc84d90fSMax Reitz     }
3879f88e1a42SJes Sorensen }
388085d126f3SStefan Hajnoczi 
388185d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
388285d126f3SStefan Hajnoczi {
3883dcd04228SStefan Hajnoczi     return bs->aio_context;
3884dcd04228SStefan Hajnoczi }
3885dcd04228SStefan Hajnoczi 
3886dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3887dcd04228SStefan Hajnoczi {
388833384421SMax Reitz     BdrvAioNotifier *baf;
388933384421SMax Reitz 
3890dcd04228SStefan Hajnoczi     if (!bs->drv) {
3891dcd04228SStefan Hajnoczi         return;
3892dcd04228SStefan Hajnoczi     }
3893dcd04228SStefan Hajnoczi 
389433384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
389533384421SMax Reitz         baf->detach_aio_context(baf->opaque);
389633384421SMax Reitz     }
389733384421SMax Reitz 
389813af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
38990e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
390013af91ebSStefan Hajnoczi     }
3901dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3902dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3903dcd04228SStefan Hajnoczi     }
3904dcd04228SStefan Hajnoczi     if (bs->file) {
39059a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3906dcd04228SStefan Hajnoczi     }
3907*760e0063SKevin Wolf     if (bs->backing) {
3908*760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3909dcd04228SStefan Hajnoczi     }
3910dcd04228SStefan Hajnoczi 
3911dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3912dcd04228SStefan Hajnoczi }
3913dcd04228SStefan Hajnoczi 
3914dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3915dcd04228SStefan Hajnoczi                              AioContext *new_context)
3916dcd04228SStefan Hajnoczi {
391733384421SMax Reitz     BdrvAioNotifier *ban;
391833384421SMax Reitz 
3919dcd04228SStefan Hajnoczi     if (!bs->drv) {
3920dcd04228SStefan Hajnoczi         return;
3921dcd04228SStefan Hajnoczi     }
3922dcd04228SStefan Hajnoczi 
3923dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3924dcd04228SStefan Hajnoczi 
3925*760e0063SKevin Wolf     if (bs->backing) {
3926*760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3927dcd04228SStefan Hajnoczi     }
3928dcd04228SStefan Hajnoczi     if (bs->file) {
39299a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3930dcd04228SStefan Hajnoczi     }
3931dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3932dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3933dcd04228SStefan Hajnoczi     }
393413af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
39350e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
393613af91ebSStefan Hajnoczi     }
393733384421SMax Reitz 
393833384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
393933384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
394033384421SMax Reitz     }
3941dcd04228SStefan Hajnoczi }
3942dcd04228SStefan Hajnoczi 
3943dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3944dcd04228SStefan Hajnoczi {
394553ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3946dcd04228SStefan Hajnoczi 
3947dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3948dcd04228SStefan Hajnoczi 
3949dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3950dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3951dcd04228SStefan Hajnoczi      */
3952dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3953dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3954dcd04228SStefan Hajnoczi     aio_context_release(new_context);
395585d126f3SStefan Hajnoczi }
3956d616b224SStefan Hajnoczi 
395733384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
395833384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
395933384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
396033384421SMax Reitz {
396133384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
396233384421SMax Reitz     *ban = (BdrvAioNotifier){
396333384421SMax Reitz         .attached_aio_context = attached_aio_context,
396433384421SMax Reitz         .detach_aio_context   = detach_aio_context,
396533384421SMax Reitz         .opaque               = opaque
396633384421SMax Reitz     };
396733384421SMax Reitz 
396833384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
396933384421SMax Reitz }
397033384421SMax Reitz 
397133384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
397233384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
397333384421SMax Reitz                                                                    void *),
397433384421SMax Reitz                                       void (*detach_aio_context)(void *),
397533384421SMax Reitz                                       void *opaque)
397633384421SMax Reitz {
397733384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
397833384421SMax Reitz 
397933384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
398033384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
398133384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
398233384421SMax Reitz             ban->opaque               == opaque)
398333384421SMax Reitz         {
398433384421SMax Reitz             QLIST_REMOVE(ban, list);
398533384421SMax Reitz             g_free(ban);
398633384421SMax Reitz 
398733384421SMax Reitz             return;
398833384421SMax Reitz         }
398933384421SMax Reitz     }
399033384421SMax Reitz 
399133384421SMax Reitz     abort();
399233384421SMax Reitz }
399333384421SMax Reitz 
399477485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
399577485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
39966f176b48SMax Reitz {
3997c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
39986f176b48SMax Reitz         return -ENOTSUP;
39996f176b48SMax Reitz     }
400077485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
40016f176b48SMax Reitz }
4002f6186f49SBenoît Canet 
4003b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
4004b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
4005b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
4006b5042a36SBenoît Canet  * node graph.
4007212a5a8fSBenoît Canet  */
4008212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
4009212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
4010f6186f49SBenoît Canet {
4011b5042a36SBenoît Canet     /* return false if basic checks fails */
4012b5042a36SBenoît Canet     if (!bs || !bs->drv) {
4013b5042a36SBenoît Canet         return false;
4014b5042a36SBenoît Canet     }
4015b5042a36SBenoît Canet 
4016b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
4017b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
4018b5042a36SBenoît Canet      */
4019b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
4020b5042a36SBenoît Canet         return bs == candidate;
4021b5042a36SBenoît Canet     }
4022b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
4023b5042a36SBenoît Canet 
4024b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
4025b5042a36SBenoît Canet      * the node graph.
4026b5042a36SBenoît Canet      */
4027b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
4028212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
4029212a5a8fSBenoît Canet     }
4030212a5a8fSBenoît Canet 
4031b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
4032b5042a36SBenoît Canet      */
4033b5042a36SBenoît Canet     return false;
4034212a5a8fSBenoît Canet }
4035212a5a8fSBenoît Canet 
4036212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
4037212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
4038212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
4039212a5a8fSBenoît Canet  */
4040212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
4041212a5a8fSBenoît Canet {
4042212a5a8fSBenoît Canet     BlockDriverState *bs;
4043212a5a8fSBenoît Canet 
4044212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
4045212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
4046212a5a8fSBenoît Canet         bool perm;
4047212a5a8fSBenoît Canet 
4048b5042a36SBenoît Canet         /* try to recurse in this top level bs */
4049e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
4050212a5a8fSBenoît Canet 
4051212a5a8fSBenoît Canet         /* candidate is the first non filter */
4052212a5a8fSBenoît Canet         if (perm) {
4053212a5a8fSBenoît Canet             return true;
4054212a5a8fSBenoît Canet         }
4055212a5a8fSBenoît Canet     }
4056212a5a8fSBenoît Canet 
4057212a5a8fSBenoît Canet     return false;
4058f6186f49SBenoît Canet }
405909158f00SBenoît Canet 
4060e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
4061e12f3784SWen Congyang                                         const char *node_name, Error **errp)
406209158f00SBenoît Canet {
406309158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
40645a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
40655a7e7a0bSStefan Hajnoczi 
406609158f00SBenoît Canet     if (!to_replace_bs) {
406709158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
406809158f00SBenoît Canet         return NULL;
406909158f00SBenoît Canet     }
407009158f00SBenoît Canet 
40715a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
40725a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
40735a7e7a0bSStefan Hajnoczi 
407409158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
40755a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40765a7e7a0bSStefan Hajnoczi         goto out;
407709158f00SBenoît Canet     }
407809158f00SBenoît Canet 
407909158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
408009158f00SBenoît Canet      * most non filter in order to prevent data corruption.
408109158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
408209158f00SBenoît Canet      * blocked by the backing blockers.
408309158f00SBenoît Canet      */
4084e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
408509158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
40865a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
40875a7e7a0bSStefan Hajnoczi         goto out;
408809158f00SBenoît Canet     }
408909158f00SBenoît Canet 
40905a7e7a0bSStefan Hajnoczi out:
40915a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
409209158f00SBenoît Canet     return to_replace_bs;
409309158f00SBenoît Canet }
4094448ad91dSMing Lei 
409591af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
409691af7014SMax Reitz {
409791af7014SMax Reitz     const QDictEntry *entry;
409891af7014SMax Reitz     bool found_any = false;
409991af7014SMax Reitz 
410091af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
410191af7014SMax Reitz          entry = qdict_next(bs->options, entry))
410291af7014SMax Reitz     {
410391af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
410491af7014SMax Reitz          * options */
410591af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
410691af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
410791af7014SMax Reitz         {
410891af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
410991af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
411091af7014SMax Reitz             found_any = true;
411191af7014SMax Reitz         }
411291af7014SMax Reitz     }
411391af7014SMax Reitz 
411491af7014SMax Reitz     return found_any;
411591af7014SMax Reitz }
411691af7014SMax Reitz 
411791af7014SMax Reitz /* Updates the following BDS fields:
411891af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
411991af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
412091af7014SMax Reitz  *                    other options; so reading and writing must return the same
412191af7014SMax Reitz  *                    results, but caching etc. may be different)
412291af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
412391af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
412491af7014SMax Reitz  *                       equalling the given one
412591af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
412691af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
412791af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
412891af7014SMax Reitz  */
412991af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
413091af7014SMax Reitz {
413191af7014SMax Reitz     BlockDriver *drv = bs->drv;
413291af7014SMax Reitz     QDict *opts;
413391af7014SMax Reitz 
413491af7014SMax Reitz     if (!drv) {
413591af7014SMax Reitz         return;
413691af7014SMax Reitz     }
413791af7014SMax Reitz 
413891af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
413991af7014SMax Reitz      * refresh that first */
414091af7014SMax Reitz     if (bs->file) {
41419a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
414291af7014SMax Reitz     }
414391af7014SMax Reitz 
414491af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
414591af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
414691af7014SMax Reitz          * information before refreshing it */
414791af7014SMax Reitz         bs->exact_filename[0] = '\0';
414891af7014SMax Reitz         if (bs->full_open_options) {
414991af7014SMax Reitz             QDECREF(bs->full_open_options);
415091af7014SMax Reitz             bs->full_open_options = NULL;
415191af7014SMax Reitz         }
415291af7014SMax Reitz 
415391af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
415491af7014SMax Reitz     } else if (bs->file) {
415591af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
415691af7014SMax Reitz         bool has_open_options;
415791af7014SMax Reitz 
415891af7014SMax Reitz         bs->exact_filename[0] = '\0';
415991af7014SMax Reitz         if (bs->full_open_options) {
416091af7014SMax Reitz             QDECREF(bs->full_open_options);
416191af7014SMax Reitz             bs->full_open_options = NULL;
416291af7014SMax Reitz         }
416391af7014SMax Reitz 
416491af7014SMax Reitz         opts = qdict_new();
416591af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
416691af7014SMax Reitz 
416791af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
416891af7014SMax Reitz          * the underlying file should suffice for this one as well */
41699a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
41709a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
417191af7014SMax Reitz         }
417291af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
417391af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
417491af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
417591af7014SMax Reitz          * contain a representation of the filename, therefore the following
417691af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
41779a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
417891af7014SMax Reitz             qdict_put_obj(opts, "driver",
417991af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
41809a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
41819a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
41829a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
418391af7014SMax Reitz 
418491af7014SMax Reitz             bs->full_open_options = opts;
418591af7014SMax Reitz         } else {
418691af7014SMax Reitz             QDECREF(opts);
418791af7014SMax Reitz         }
418891af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
418991af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
419091af7014SMax Reitz          * so the full options QDict should be equal to the options given
419191af7014SMax Reitz          * specifically for this block device when it was opened (plus the
419291af7014SMax Reitz          * driver specification).
419391af7014SMax Reitz          * Because those options don't change, there is no need to update
419491af7014SMax Reitz          * full_open_options when it's already set. */
419591af7014SMax Reitz 
419691af7014SMax Reitz         opts = qdict_new();
419791af7014SMax Reitz         append_open_options(opts, bs);
419891af7014SMax Reitz         qdict_put_obj(opts, "driver",
419991af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
420091af7014SMax Reitz 
420191af7014SMax Reitz         if (bs->exact_filename[0]) {
420291af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
420391af7014SMax Reitz              * require this filename to be parsed), but we have to find some
420491af7014SMax Reitz              * default solution here, so just include it. If some block driver
420591af7014SMax Reitz              * does not support pure options without any filename at all or
420691af7014SMax Reitz              * needs some special format of the options QDict, it needs to
420791af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
420891af7014SMax Reitz              */
420991af7014SMax Reitz             qdict_put_obj(opts, "filename",
421091af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
421191af7014SMax Reitz         }
421291af7014SMax Reitz 
421391af7014SMax Reitz         bs->full_open_options = opts;
421491af7014SMax Reitz     }
421591af7014SMax Reitz 
421691af7014SMax Reitz     if (bs->exact_filename[0]) {
421791af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
421891af7014SMax Reitz     } else if (bs->full_open_options) {
421991af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
422091af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
422191af7014SMax Reitz                  qstring_get_str(json));
422291af7014SMax Reitz         QDECREF(json);
422391af7014SMax Reitz     }
422491af7014SMax Reitz }
42255366d0c8SBenoît Canet 
42265366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the
42275366d0c8SBenoît Canet  * BlockAcctStats structure embedded inside a BlockDriverState without being
42285366d0c8SBenoît Canet  * aware of the BlockDriverState structure layout.
42295366d0c8SBenoît Canet  * It will go away when the BlockAcctStats structure will be moved inside
42305366d0c8SBenoît Canet  * the device models.
42315366d0c8SBenoît Canet  */
42325366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
42335366d0c8SBenoît Canet {
42345366d0c8SBenoît Canet     return &bs->stats;
42355366d0c8SBenoît Canet }
4236