xref: /openbmc/qemu/block.c (revision 76f4afb40fa076ed23fe0ab42c7a768ddb71123f)
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"
291de7afc9SPaolo Bonzini #include "qemu/module.h"
307b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
31bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
329c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35c13163fbSBenoît Canet #include "block/qapi.h"
36b2023818SLuiz Capitulino #include "qmp-commands.h"
371de7afc9SPaolo Bonzini #include "qemu/timer.h"
38a5ee7bd4SWenchao Xia #include "qapi-event.h"
39fc01f7e7Sbellard 
4071e72a19SJuan Quintela #ifdef CONFIG_BSD
417674e7bfSbellard #include <sys/types.h>
427674e7bfSbellard #include <sys/stat.h>
437674e7bfSbellard #include <sys/ioctl.h>
4472cf2d4fSBlue Swirl #include <sys/queue.h>
45c5e97233Sblueswir1 #ifndef __DragonFly__
467674e7bfSbellard #include <sys/disk.h>
477674e7bfSbellard #endif
48c5e97233Sblueswir1 #endif
497674e7bfSbellard 
5049dc768dSaliguori #ifdef _WIN32
5149dc768dSaliguori #include <windows.h>
5249dc768dSaliguori #endif
5349dc768dSaliguori 
549bd2b08fSJohn Snow /**
559bd2b08fSJohn Snow  * A BdrvDirtyBitmap can be in three possible states:
569bd2b08fSJohn Snow  * (1) successor is NULL and disabled is false: full r/w mode
579bd2b08fSJohn Snow  * (2) successor is NULL and disabled is true: read only mode ("disabled")
589bd2b08fSJohn Snow  * (3) successor is set: frozen mode.
599bd2b08fSJohn Snow  *     A frozen bitmap cannot be renamed, deleted, anonymized, cleared, set,
609bd2b08fSJohn Snow  *     or enabled. A frozen bitmap can only abdicate() or reclaim().
619bd2b08fSJohn Snow  */
62e4654d2dSFam Zheng struct BdrvDirtyBitmap {
63aa0c7ca5SJohn Snow     HBitmap *bitmap;            /* Dirty sector bitmap implementation */
64aa0c7ca5SJohn Snow     BdrvDirtyBitmap *successor; /* Anonymous child; implies frozen status */
65aa0c7ca5SJohn Snow     char *name;                 /* Optional non-empty unique ID */
66aa0c7ca5SJohn Snow     int64_t size;               /* Size of the bitmap (Number of sectors) */
67aa0c7ca5SJohn Snow     bool disabled;              /* Bitmap is read-only */
68e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
69e4654d2dSFam Zheng };
70e4654d2dSFam Zheng 
711c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
721c9805a3SStefan Hajnoczi 
731b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
741b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
757ee930d0Sblueswir1 
76dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
77dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
78dc364f4cSBenoît Canet 
798a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
808a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
81ea2384d3Sbellard 
82ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs);
83eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
84eb852011SMarkus Armbruster static int use_bdrv_whitelist;
85eb852011SMarkus Armbruster 
869e0b22f4SStefan Hajnoczi #ifdef _WIN32
879e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
889e0b22f4SStefan Hajnoczi {
899e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
909e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
919e0b22f4SStefan Hajnoczi             filename[1] == ':');
929e0b22f4SStefan Hajnoczi }
939e0b22f4SStefan Hajnoczi 
949e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
959e0b22f4SStefan Hajnoczi {
969e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
979e0b22f4SStefan Hajnoczi         filename[2] == '\0')
989e0b22f4SStefan Hajnoczi         return 1;
999e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1009e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1019e0b22f4SStefan Hajnoczi         return 1;
1029e0b22f4SStefan Hajnoczi     return 0;
1039e0b22f4SStefan Hajnoczi }
1049e0b22f4SStefan Hajnoczi #endif
1059e0b22f4SStefan Hajnoczi 
106339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
107339064d5SKevin Wolf {
108339064d5SKevin Wolf     if (!bs || !bs->drv) {
109459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
110459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
111339064d5SKevin Wolf     }
112339064d5SKevin Wolf 
113339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
114339064d5SKevin Wolf }
115339064d5SKevin Wolf 
1164196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1174196d2f0SDenis V. Lunev {
1184196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
119459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
120459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1214196d2f0SDenis V. Lunev     }
1224196d2f0SDenis V. Lunev 
1234196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1244196d2f0SDenis V. Lunev }
1254196d2f0SDenis V. Lunev 
1269e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1275c98415bSMax Reitz int path_has_protocol(const char *path)
1289e0b22f4SStefan Hajnoczi {
129947995c0SPaolo Bonzini     const char *p;
130947995c0SPaolo Bonzini 
1319e0b22f4SStefan Hajnoczi #ifdef _WIN32
1329e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1339e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1349e0b22f4SStefan Hajnoczi         return 0;
1359e0b22f4SStefan Hajnoczi     }
136947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
137947995c0SPaolo Bonzini #else
138947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1399e0b22f4SStefan Hajnoczi #endif
1409e0b22f4SStefan Hajnoczi 
141947995c0SPaolo Bonzini     return *p == ':';
1429e0b22f4SStefan Hajnoczi }
1439e0b22f4SStefan Hajnoczi 
14483f64091Sbellard int path_is_absolute(const char *path)
14583f64091Sbellard {
14621664424Sbellard #ifdef _WIN32
14721664424Sbellard     /* specific case for names like: "\\.\d:" */
148f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
14921664424Sbellard         return 1;
150f53f4da9SPaolo Bonzini     }
151f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1523b9f94e1Sbellard #else
153f53f4da9SPaolo Bonzini     return (*path == '/');
1543b9f94e1Sbellard #endif
15583f64091Sbellard }
15683f64091Sbellard 
15783f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
15883f64091Sbellard    path to it by considering it is relative to base_path. URL are
15983f64091Sbellard    supported. */
16083f64091Sbellard void path_combine(char *dest, int dest_size,
16183f64091Sbellard                   const char *base_path,
16283f64091Sbellard                   const char *filename)
16383f64091Sbellard {
16483f64091Sbellard     const char *p, *p1;
16583f64091Sbellard     int len;
16683f64091Sbellard 
16783f64091Sbellard     if (dest_size <= 0)
16883f64091Sbellard         return;
16983f64091Sbellard     if (path_is_absolute(filename)) {
17083f64091Sbellard         pstrcpy(dest, dest_size, filename);
17183f64091Sbellard     } else {
17283f64091Sbellard         p = strchr(base_path, ':');
17383f64091Sbellard         if (p)
17483f64091Sbellard             p++;
17583f64091Sbellard         else
17683f64091Sbellard             p = base_path;
1773b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1783b9f94e1Sbellard #ifdef _WIN32
1793b9f94e1Sbellard         {
1803b9f94e1Sbellard             const char *p2;
1813b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1823b9f94e1Sbellard             if (!p1 || p2 > p1)
1833b9f94e1Sbellard                 p1 = p2;
1843b9f94e1Sbellard         }
1853b9f94e1Sbellard #endif
18683f64091Sbellard         if (p1)
18783f64091Sbellard             p1++;
18883f64091Sbellard         else
18983f64091Sbellard             p1 = base_path;
19083f64091Sbellard         if (p1 > p)
19183f64091Sbellard             p = p1;
19283f64091Sbellard         len = p - base_path;
19383f64091Sbellard         if (len > dest_size - 1)
19483f64091Sbellard             len = dest_size - 1;
19583f64091Sbellard         memcpy(dest, base_path, len);
19683f64091Sbellard         dest[len] = '\0';
19783f64091Sbellard         pstrcat(dest, dest_size, filename);
19883f64091Sbellard     }
19983f64091Sbellard }
20083f64091Sbellard 
2010a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
2020a82855aSMax Reitz                                                   const char *backing,
2039f07429eSMax Reitz                                                   char *dest, size_t sz,
2049f07429eSMax Reitz                                                   Error **errp)
2050a82855aSMax Reitz {
2069f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
2079f07429eSMax Reitz         path_is_absolute(backing))
2089f07429eSMax Reitz     {
2090a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2109f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2119f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2129f07429eSMax Reitz                    backed);
2130a82855aSMax Reitz     } else {
2140a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2150a82855aSMax Reitz     }
2160a82855aSMax Reitz }
2170a82855aSMax Reitz 
2189f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2199f07429eSMax Reitz                                     Error **errp)
220dc5a1371SPaolo Bonzini {
2219f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2229f07429eSMax Reitz 
2239f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2249f07429eSMax Reitz                                                  dest, sz, errp);
225dc5a1371SPaolo Bonzini }
226dc5a1371SPaolo Bonzini 
2270eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2280eb7217eSStefan Hajnoczi {
2290eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
230b2e12bc6SChristoph Hellwig 
2318a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
232ea2384d3Sbellard }
233b338082bSbellard 
2347f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
235fc01f7e7Sbellard {
2367f06d47eSMarkus Armbruster     BlockDriverState *bs = bdrv_new();
237e4e9986bSMarkus Armbruster 
238e4e9986bSMarkus Armbruster     QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
239e4e9986bSMarkus Armbruster     return bs;
240e4e9986bSMarkus Armbruster }
241e4e9986bSMarkus Armbruster 
242e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
243e4e9986bSMarkus Armbruster {
244e4e9986bSMarkus Armbruster     BlockDriverState *bs;
245e4e9986bSMarkus Armbruster     int i;
246e4e9986bSMarkus Armbruster 
2475839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
248e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
249fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
250fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
251fbe40ff7SFam Zheng     }
25228a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
253d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
254d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
255cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
256cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2579fcb0251SFam Zheng     bs->refcnt = 1;
258dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
259d7d512f6SPaolo Bonzini 
260b338082bSbellard     return bs;
261b338082bSbellard }
262b338082bSbellard 
263d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
264d7d512f6SPaolo Bonzini {
265d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
266d7d512f6SPaolo Bonzini }
267d7d512f6SPaolo Bonzini 
268ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
269ea2384d3Sbellard {
270ea2384d3Sbellard     BlockDriver *drv1;
2718a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2728a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
273ea2384d3Sbellard             return drv1;
274ea2384d3Sbellard         }
2758a22f02aSStefan Hajnoczi     }
276ea2384d3Sbellard     return NULL;
277ea2384d3Sbellard }
278ea2384d3Sbellard 
279b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
280eb852011SMarkus Armbruster {
281b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
282b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
283b64ec4e4SFam Zheng     };
284b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
285b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
286eb852011SMarkus Armbruster     };
287eb852011SMarkus Armbruster     const char **p;
288eb852011SMarkus Armbruster 
289b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
290eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
291b64ec4e4SFam Zheng     }
292eb852011SMarkus Armbruster 
293b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
294eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
295eb852011SMarkus Armbruster             return 1;
296eb852011SMarkus Armbruster         }
297eb852011SMarkus Armbruster     }
298b64ec4e4SFam Zheng     if (read_only) {
299b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
300b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
301b64ec4e4SFam Zheng                 return 1;
302b64ec4e4SFam Zheng             }
303b64ec4e4SFam Zheng         }
304b64ec4e4SFam Zheng     }
305eb852011SMarkus Armbruster     return 0;
306eb852011SMarkus Armbruster }
307eb852011SMarkus Armbruster 
308b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
309b64ec4e4SFam Zheng                                           bool read_only)
310eb852011SMarkus Armbruster {
311eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
312b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
313eb852011SMarkus Armbruster }
314eb852011SMarkus Armbruster 
3155b7e1542SZhi Yong Wu typedef struct CreateCo {
3165b7e1542SZhi Yong Wu     BlockDriver *drv;
3175b7e1542SZhi Yong Wu     char *filename;
31883d0521aSChunyan Liu     QemuOpts *opts;
3195b7e1542SZhi Yong Wu     int ret;
320cc84d90fSMax Reitz     Error *err;
3215b7e1542SZhi Yong Wu } CreateCo;
3225b7e1542SZhi Yong Wu 
3235b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3245b7e1542SZhi Yong Wu {
325cc84d90fSMax Reitz     Error *local_err = NULL;
326cc84d90fSMax Reitz     int ret;
327cc84d90fSMax Reitz 
3285b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3295b7e1542SZhi Yong Wu     assert(cco->drv);
3305b7e1542SZhi Yong Wu 
331c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
33284d18f06SMarkus Armbruster     if (local_err) {
333cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
334cc84d90fSMax Reitz     }
335cc84d90fSMax Reitz     cco->ret = ret;
3365b7e1542SZhi Yong Wu }
3375b7e1542SZhi Yong Wu 
3380e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
33983d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
340ea2384d3Sbellard {
3415b7e1542SZhi Yong Wu     int ret;
3420e7e1989SKevin Wolf 
3435b7e1542SZhi Yong Wu     Coroutine *co;
3445b7e1542SZhi Yong Wu     CreateCo cco = {
3455b7e1542SZhi Yong Wu         .drv = drv,
3465b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
34783d0521aSChunyan Liu         .opts = opts,
3485b7e1542SZhi Yong Wu         .ret = NOT_DONE,
349cc84d90fSMax Reitz         .err = NULL,
3505b7e1542SZhi Yong Wu     };
3515b7e1542SZhi Yong Wu 
352c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
353cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
35480168bffSLuiz Capitulino         ret = -ENOTSUP;
35580168bffSLuiz Capitulino         goto out;
3565b7e1542SZhi Yong Wu     }
3575b7e1542SZhi Yong Wu 
3585b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3595b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3605b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3615b7e1542SZhi Yong Wu     } else {
3625b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3635b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3645b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
365b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3665b7e1542SZhi Yong Wu         }
3675b7e1542SZhi Yong Wu     }
3685b7e1542SZhi Yong Wu 
3695b7e1542SZhi Yong Wu     ret = cco.ret;
370cc84d90fSMax Reitz     if (ret < 0) {
37184d18f06SMarkus Armbruster         if (cco.err) {
372cc84d90fSMax Reitz             error_propagate(errp, cco.err);
373cc84d90fSMax Reitz         } else {
374cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
375cc84d90fSMax Reitz         }
376cc84d90fSMax Reitz     }
3775b7e1542SZhi Yong Wu 
37880168bffSLuiz Capitulino out:
37980168bffSLuiz Capitulino     g_free(cco.filename);
3805b7e1542SZhi Yong Wu     return ret;
381ea2384d3Sbellard }
382ea2384d3Sbellard 
383c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
38484a12e66SChristoph Hellwig {
38584a12e66SChristoph Hellwig     BlockDriver *drv;
386cc84d90fSMax Reitz     Error *local_err = NULL;
387cc84d90fSMax Reitz     int ret;
38884a12e66SChristoph Hellwig 
389b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
39084a12e66SChristoph Hellwig     if (drv == NULL) {
39116905d71SStefan Hajnoczi         return -ENOENT;
39284a12e66SChristoph Hellwig     }
39384a12e66SChristoph Hellwig 
394c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
39584d18f06SMarkus Armbruster     if (local_err) {
396cc84d90fSMax Reitz         error_propagate(errp, local_err);
397cc84d90fSMax Reitz     }
398cc84d90fSMax Reitz     return ret;
39984a12e66SChristoph Hellwig }
40084a12e66SChristoph Hellwig 
401892b7de8SEkaterina Tumanova /**
402892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
403892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
404892b7de8SEkaterina Tumanova  * On failure return -errno.
405892b7de8SEkaterina Tumanova  * @bs must not be empty.
406892b7de8SEkaterina Tumanova  */
407892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
408892b7de8SEkaterina Tumanova {
409892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
410892b7de8SEkaterina Tumanova 
411892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
412892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
413892b7de8SEkaterina Tumanova     }
414892b7de8SEkaterina Tumanova 
415892b7de8SEkaterina Tumanova     return -ENOTSUP;
416892b7de8SEkaterina Tumanova }
417892b7de8SEkaterina Tumanova 
418892b7de8SEkaterina Tumanova /**
419892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
420892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
421892b7de8SEkaterina Tumanova  * On failure return -errno.
422892b7de8SEkaterina Tumanova  * @bs must not be empty.
423892b7de8SEkaterina Tumanova  */
424892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
425892b7de8SEkaterina Tumanova {
426892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
427892b7de8SEkaterina Tumanova 
428892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
429892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
430892b7de8SEkaterina Tumanova     }
431892b7de8SEkaterina Tumanova 
432892b7de8SEkaterina Tumanova     return -ENOTSUP;
433892b7de8SEkaterina Tumanova }
434892b7de8SEkaterina Tumanova 
435eba25057SJim Meyering /*
436eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
437eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
438eba25057SJim Meyering  */
439eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
440eba25057SJim Meyering {
441d5249393Sbellard #ifdef _WIN32
4423b9f94e1Sbellard     char temp_dir[MAX_PATH];
443eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
444eba25057SJim Meyering        have length MAX_PATH or greater.  */
445eba25057SJim Meyering     assert(size >= MAX_PATH);
446eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
447eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
448eba25057SJim Meyering             ? 0 : -GetLastError());
449d5249393Sbellard #else
450ea2384d3Sbellard     int fd;
4517ccfb2ebSblueswir1     const char *tmpdir;
4520badc1eeSaurel32     tmpdir = getenv("TMPDIR");
45369bef793SAmit Shah     if (!tmpdir) {
45469bef793SAmit Shah         tmpdir = "/var/tmp";
45569bef793SAmit Shah     }
456eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
457eba25057SJim Meyering         return -EOVERFLOW;
458ea2384d3Sbellard     }
459eba25057SJim Meyering     fd = mkstemp(filename);
460fe235a06SDunrong Huang     if (fd < 0) {
461fe235a06SDunrong Huang         return -errno;
462fe235a06SDunrong Huang     }
463fe235a06SDunrong Huang     if (close(fd) != 0) {
464fe235a06SDunrong Huang         unlink(filename);
465eba25057SJim Meyering         return -errno;
466eba25057SJim Meyering     }
467eba25057SJim Meyering     return 0;
468d5249393Sbellard #endif
469eba25057SJim Meyering }
470ea2384d3Sbellard 
471f3a5d3f8SChristoph Hellwig /*
472f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
473f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
474f3a5d3f8SChristoph Hellwig  */
475f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
476f3a5d3f8SChristoph Hellwig {
477508c7cb3SChristoph Hellwig     int score_max = 0, score;
478508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
479f3a5d3f8SChristoph Hellwig 
4808a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
481508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
482508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
483508c7cb3SChristoph Hellwig             if (score > score_max) {
484508c7cb3SChristoph Hellwig                 score_max = score;
485508c7cb3SChristoph Hellwig                 drv = d;
486f3a5d3f8SChristoph Hellwig             }
487508c7cb3SChristoph Hellwig         }
488f3a5d3f8SChristoph Hellwig     }
489f3a5d3f8SChristoph Hellwig 
490508c7cb3SChristoph Hellwig     return drv;
491f3a5d3f8SChristoph Hellwig }
492f3a5d3f8SChristoph Hellwig 
49398289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
494b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
495b65a5e12SMax Reitz                                 Error **errp)
49684a12e66SChristoph Hellwig {
49784a12e66SChristoph Hellwig     BlockDriver *drv1;
49884a12e66SChristoph Hellwig     char protocol[128];
49984a12e66SChristoph Hellwig     int len;
50084a12e66SChristoph Hellwig     const char *p;
50184a12e66SChristoph Hellwig 
50266f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
50366f82ceeSKevin Wolf 
50439508e7aSChristoph Hellwig     /*
50539508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
50639508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
50739508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
50839508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
50939508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
51039508e7aSChristoph Hellwig      */
51184a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
51239508e7aSChristoph Hellwig     if (drv1) {
51384a12e66SChristoph Hellwig         return drv1;
51484a12e66SChristoph Hellwig     }
51539508e7aSChristoph Hellwig 
51698289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
517ef810437SMax Reitz         return &bdrv_file;
51839508e7aSChristoph Hellwig     }
51998289620SKevin Wolf 
5209e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
5219e0b22f4SStefan Hajnoczi     assert(p != NULL);
52284a12e66SChristoph Hellwig     len = p - filename;
52384a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
52484a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
52584a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
52684a12e66SChristoph Hellwig     protocol[len] = '\0';
52784a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
52884a12e66SChristoph Hellwig         if (drv1->protocol_name &&
52984a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
53084a12e66SChristoph Hellwig             return drv1;
53184a12e66SChristoph Hellwig         }
53284a12e66SChristoph Hellwig     }
533b65a5e12SMax Reitz 
534b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
53584a12e66SChristoph Hellwig     return NULL;
53684a12e66SChristoph Hellwig }
53784a12e66SChristoph Hellwig 
538c6684249SMarkus Armbruster /*
539c6684249SMarkus Armbruster  * Guess image format by probing its contents.
540c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
541c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
542c6684249SMarkus Armbruster  *
543c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5447cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5457cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
546c6684249SMarkus Armbruster  * @filename    is its filename.
547c6684249SMarkus Armbruster  *
548c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
549c6684249SMarkus Armbruster  * probing score.
550c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
551c6684249SMarkus Armbruster  */
55238f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
553c6684249SMarkus Armbruster                             const char *filename)
554c6684249SMarkus Armbruster {
555c6684249SMarkus Armbruster     int score_max = 0, score;
556c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
557c6684249SMarkus Armbruster 
558c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
559c6684249SMarkus Armbruster         if (d->bdrv_probe) {
560c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
561c6684249SMarkus Armbruster             if (score > score_max) {
562c6684249SMarkus Armbruster                 score_max = score;
563c6684249SMarkus Armbruster                 drv = d;
564c6684249SMarkus Armbruster             }
565c6684249SMarkus Armbruster         }
566c6684249SMarkus Armbruster     }
567c6684249SMarkus Armbruster 
568c6684249SMarkus Armbruster     return drv;
569c6684249SMarkus Armbruster }
570c6684249SMarkus Armbruster 
571f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
57234b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
573ea2384d3Sbellard {
574c6684249SMarkus Armbruster     BlockDriver *drv;
5757cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
576f500a6d3SKevin Wolf     int ret = 0;
577f8ea0b00SNicholas Bellinger 
57808a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
5798e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
580ef810437SMax Reitz         *pdrv = &bdrv_raw;
581c98ac35dSStefan Weil         return ret;
5821a396859SNicholas A. Bellinger     }
583f8ea0b00SNicholas Bellinger 
58483f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
585ea2384d3Sbellard     if (ret < 0) {
58634b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
58734b5d2c6SMax Reitz                          "format");
588c98ac35dSStefan Weil         *pdrv = NULL;
589c98ac35dSStefan Weil         return ret;
590ea2384d3Sbellard     }
591ea2384d3Sbellard 
592c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
593c98ac35dSStefan Weil     if (!drv) {
59434b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
59534b5d2c6SMax Reitz                    "driver found");
596c98ac35dSStefan Weil         ret = -ENOENT;
597c98ac35dSStefan Weil     }
598c98ac35dSStefan Weil     *pdrv = drv;
599c98ac35dSStefan Weil     return ret;
600ea2384d3Sbellard }
601ea2384d3Sbellard 
60251762288SStefan Hajnoczi /**
60351762288SStefan Hajnoczi  * Set the current 'total_sectors' value
60465a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
60551762288SStefan Hajnoczi  */
60651762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
60751762288SStefan Hajnoczi {
60851762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
60951762288SStefan Hajnoczi 
610396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
611396759adSNicholas Bellinger     if (bs->sg)
612396759adSNicholas Bellinger         return 0;
613396759adSNicholas Bellinger 
61451762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
61551762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
61651762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
61751762288SStefan Hajnoczi         if (length < 0) {
61851762288SStefan Hajnoczi             return length;
61951762288SStefan Hajnoczi         }
6207e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
62151762288SStefan Hajnoczi     }
62251762288SStefan Hajnoczi 
62351762288SStefan Hajnoczi     bs->total_sectors = hint;
62451762288SStefan Hajnoczi     return 0;
62551762288SStefan Hajnoczi }
62651762288SStefan Hajnoczi 
627c3993cdcSStefan Hajnoczi /**
6289e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6299e8f1835SPaolo Bonzini  *
6309e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6319e8f1835SPaolo Bonzini  */
6329e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6339e8f1835SPaolo Bonzini {
6349e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6359e8f1835SPaolo Bonzini 
6369e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6379e8f1835SPaolo Bonzini         /* do nothing */
6389e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6399e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6409e8f1835SPaolo Bonzini     } else {
6419e8f1835SPaolo Bonzini         return -1;
6429e8f1835SPaolo Bonzini     }
6439e8f1835SPaolo Bonzini 
6449e8f1835SPaolo Bonzini     return 0;
6459e8f1835SPaolo Bonzini }
6469e8f1835SPaolo Bonzini 
6479e8f1835SPaolo Bonzini /**
648c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
649c3993cdcSStefan Hajnoczi  *
650c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
651c3993cdcSStefan Hajnoczi  */
652c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
653c3993cdcSStefan Hajnoczi {
654c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
655c3993cdcSStefan Hajnoczi 
656c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
657c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
65892196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
65992196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
660c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
661c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
662c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
663c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
664c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
665c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
666c3993cdcSStefan Hajnoczi         /* this is the default */
667c3993cdcSStefan Hajnoczi     } else {
668c3993cdcSStefan Hajnoczi         return -1;
669c3993cdcSStefan Hajnoczi     }
670c3993cdcSStefan Hajnoczi 
671c3993cdcSStefan Hajnoczi     return 0;
672c3993cdcSStefan Hajnoczi }
673c3993cdcSStefan Hajnoczi 
6740b50cc88SKevin Wolf /*
675b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
676b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
677b1e6fc08SKevin Wolf  * like a backing file)
678b1e6fc08SKevin Wolf  */
679b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
680b1e6fc08SKevin Wolf {
681b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
682b1e6fc08SKevin Wolf }
683b1e6fc08SKevin Wolf 
684b1e6fc08SKevin Wolf /*
6850b50cc88SKevin Wolf  * Returns the flags that bs->file should get, based on the given flags for
6860b50cc88SKevin Wolf  * the parent BDS
6870b50cc88SKevin Wolf  */
6880b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
6890b50cc88SKevin Wolf {
6900b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6910b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
6920b50cc88SKevin Wolf 
6930b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
6940b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
6950b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
6960b50cc88SKevin Wolf 
6970b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
6985669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
6990b50cc88SKevin Wolf 
7000b50cc88SKevin Wolf     return flags;
7010b50cc88SKevin Wolf }
7020b50cc88SKevin Wolf 
703317fc44eSKevin Wolf /*
704317fc44eSKevin Wolf  * Returns the flags that bs->backing_hd should get, based on the given flags
705317fc44eSKevin Wolf  * for the parent BDS
706317fc44eSKevin Wolf  */
707317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
708317fc44eSKevin Wolf {
709317fc44eSKevin Wolf     /* backing files always opened read-only */
710317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
711317fc44eSKevin Wolf 
712317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7138bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
714317fc44eSKevin Wolf 
715317fc44eSKevin Wolf     return flags;
716317fc44eSKevin Wolf }
717317fc44eSKevin Wolf 
7187b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7197b272452SKevin Wolf {
7207b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7217b272452SKevin Wolf 
7227b272452SKevin Wolf     /*
7237b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7247b272452SKevin Wolf      * image.
7257b272452SKevin Wolf      */
72620cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7277b272452SKevin Wolf 
7287b272452SKevin Wolf     /*
7297b272452SKevin Wolf      * Snapshots should be writable.
7307b272452SKevin Wolf      */
7318bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7327b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7337b272452SKevin Wolf     }
7347b272452SKevin Wolf 
7357b272452SKevin Wolf     return open_flags;
7367b272452SKevin Wolf }
7377b272452SKevin Wolf 
738636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
7396913c0c2SBenoît Canet                                   const char *node_name,
7406913c0c2SBenoît Canet                                   Error **errp)
7416913c0c2SBenoît Canet {
7426913c0c2SBenoît Canet     if (!node_name) {
743636ea370SKevin Wolf         return;
7446913c0c2SBenoît Canet     }
7456913c0c2SBenoît Canet 
7469aebf3b8SKevin Wolf     /* Check for empty string or invalid characters */
747f5bebbbbSMarkus Armbruster     if (!id_wellformed(node_name)) {
7489aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
749636ea370SKevin Wolf         return;
7506913c0c2SBenoît Canet     }
7516913c0c2SBenoît Canet 
7520c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
7537f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
7540c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
7550c5e94eeSBenoît Canet                    node_name);
756636ea370SKevin Wolf         return;
7570c5e94eeSBenoît Canet     }
7580c5e94eeSBenoît Canet 
7596913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
7606913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
7616913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
762636ea370SKevin Wolf         return;
7636913c0c2SBenoît Canet     }
7646913c0c2SBenoît Canet 
7656913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
7666913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
7676913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
7686913c0c2SBenoît Canet }
7696913c0c2SBenoît Canet 
770b6ce07aaSKevin Wolf /*
77157915332SKevin Wolf  * Common part for opening disk images and files
772b6ad491aSKevin Wolf  *
773b6ad491aSKevin Wolf  * Removes all processed options from *options.
77457915332SKevin Wolf  */
775f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
77634b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
77757915332SKevin Wolf {
77857915332SKevin Wolf     int ret, open_flags;
779035fccdfSKevin Wolf     const char *filename;
7806913c0c2SBenoît Canet     const char *node_name = NULL;
78134b5d2c6SMax Reitz     Error *local_err = NULL;
78257915332SKevin Wolf 
78357915332SKevin Wolf     assert(drv != NULL);
7846405875cSPaolo Bonzini     assert(bs->file == NULL);
785707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
78657915332SKevin Wolf 
78745673671SKevin Wolf     if (file != NULL) {
78845673671SKevin Wolf         filename = file->filename;
78945673671SKevin Wolf     } else {
79045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
79145673671SKevin Wolf     }
79245673671SKevin Wolf 
793765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
794765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
795765003dbSKevin Wolf                    drv->format_name);
796765003dbSKevin Wolf         return -EINVAL;
797765003dbSKevin Wolf     }
798765003dbSKevin Wolf 
79945673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
80028dcee10SStefan Hajnoczi 
8016913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
802636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
8030fb6395cSMarkus Armbruster     if (local_err) {
804636ea370SKevin Wolf         error_propagate(errp, local_err);
805636ea370SKevin Wolf         return -EINVAL;
8066913c0c2SBenoît Canet     }
8076913c0c2SBenoît Canet     qdict_del(options, "node-name");
8086913c0c2SBenoît Canet 
8095d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
8105d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
8115d186eb0SKevin Wolf      * and return immediately. */
8125d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
8135d186eb0SKevin Wolf         bdrv_swap(file, bs);
8145d186eb0SKevin Wolf         return 0;
8155d186eb0SKevin Wolf     }
8165d186eb0SKevin Wolf 
81757915332SKevin Wolf     bs->open_flags = flags;
8181b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
819c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
8200d51b4deSAsias He     bs->zero_beyond_eof = true;
821b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
822b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
823b64ec4e4SFam Zheng 
824b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
8258f94a6e4SKevin Wolf         error_setg(errp,
8268f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
8278f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
8288f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
8298f94a6e4SKevin Wolf                    drv->format_name);
830b64ec4e4SFam Zheng         return -ENOTSUP;
831b64ec4e4SFam Zheng     }
83257915332SKevin Wolf 
83353fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
8340ebd24e0SKevin Wolf     if (flags & BDRV_O_COPY_ON_READ) {
8350ebd24e0SKevin Wolf         if (!bs->read_only) {
83653fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
8370ebd24e0SKevin Wolf         } else {
8380ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
8390ebd24e0SKevin Wolf             return -EINVAL;
8400ebd24e0SKevin Wolf         }
84153fec9d3SStefan Hajnoczi     }
84253fec9d3SStefan Hajnoczi 
843c2ad1b0cSKevin Wolf     if (filename != NULL) {
84457915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
845c2ad1b0cSKevin Wolf     } else {
846c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
847c2ad1b0cSKevin Wolf     }
84891af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
84957915332SKevin Wolf 
85057915332SKevin Wolf     bs->drv = drv;
8517267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
85257915332SKevin Wolf 
85303f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
854e7c63796SStefan Hajnoczi 
85566f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
85666f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
8575d186eb0SKevin Wolf         assert(file == NULL);
858030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
85934b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
860f500a6d3SKevin Wolf     } else {
8612af5ef70SKevin Wolf         if (file == NULL) {
86234b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
86334b5d2c6SMax Reitz                        "protocol level", drv->format_name);
8642af5ef70SKevin Wolf             ret = -EINVAL;
8652af5ef70SKevin Wolf             goto free_and_fail;
8662af5ef70SKevin Wolf         }
867f500a6d3SKevin Wolf         bs->file = file;
86834b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
86966f82ceeSKevin Wolf     }
87066f82ceeSKevin Wolf 
87157915332SKevin Wolf     if (ret < 0) {
87284d18f06SMarkus Armbruster         if (local_err) {
87334b5d2c6SMax Reitz             error_propagate(errp, local_err);
8742fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
8752fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
87634b5d2c6SMax Reitz         } else {
87734b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
87834b5d2c6SMax Reitz         }
87957915332SKevin Wolf         goto free_and_fail;
88057915332SKevin Wolf     }
88157915332SKevin Wolf 
882a1f688f4SMarkus Armbruster     if (bs->encrypted) {
883a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
884a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
885a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
886a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
887a1f688f4SMarkus Armbruster     }
888a1f688f4SMarkus Armbruster 
88951762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
89051762288SStefan Hajnoczi     if (ret < 0) {
89134b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
89251762288SStefan Hajnoczi         goto free_and_fail;
89357915332SKevin Wolf     }
89451762288SStefan Hajnoczi 
8953baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
8963baca891SKevin Wolf     if (local_err) {
8973baca891SKevin Wolf         error_propagate(errp, local_err);
8983baca891SKevin Wolf         ret = -EINVAL;
8993baca891SKevin Wolf         goto free_and_fail;
9003baca891SKevin Wolf     }
9013baca891SKevin Wolf 
902c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
9034196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
90447ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
90557915332SKevin Wolf     return 0;
90657915332SKevin Wolf 
90757915332SKevin Wolf free_and_fail:
90866f82ceeSKevin Wolf     bs->file = NULL;
9097267c094SAnthony Liguori     g_free(bs->opaque);
91057915332SKevin Wolf     bs->opaque = NULL;
91157915332SKevin Wolf     bs->drv = NULL;
91257915332SKevin Wolf     return ret;
91357915332SKevin Wolf }
91457915332SKevin Wolf 
9155e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
9165e5c4f63SKevin Wolf {
9175e5c4f63SKevin Wolf     QObject *options_obj;
9185e5c4f63SKevin Wolf     QDict *options;
9195e5c4f63SKevin Wolf     int ret;
9205e5c4f63SKevin Wolf 
9215e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
9225e5c4f63SKevin Wolf     assert(ret);
9235e5c4f63SKevin Wolf 
9245e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
9255e5c4f63SKevin Wolf     if (!options_obj) {
9265e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
9275e5c4f63SKevin Wolf         return NULL;
9285e5c4f63SKevin Wolf     }
9295e5c4f63SKevin Wolf 
9305e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
9315e5c4f63SKevin Wolf         qobject_decref(options_obj);
9325e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
9335e5c4f63SKevin Wolf         return NULL;
9345e5c4f63SKevin Wolf     }
9355e5c4f63SKevin Wolf 
9365e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
9375e5c4f63SKevin Wolf     qdict_flatten(options);
9385e5c4f63SKevin Wolf 
9395e5c4f63SKevin Wolf     return options;
9405e5c4f63SKevin Wolf }
9415e5c4f63SKevin Wolf 
94257915332SKevin Wolf /*
943f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
944f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
945f54120ffSKevin Wolf  */
9465e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags,
94717b005f1SKevin Wolf                              BlockDriver *drv, Error **errp)
948f54120ffSKevin Wolf {
9495e5c4f63SKevin Wolf     const char *filename = *pfilename;
950f54120ffSKevin Wolf     const char *drvname;
951462f5bcfSKevin Wolf     bool protocol = flags & BDRV_O_PROTOCOL;
952f54120ffSKevin Wolf     bool parse_filename = false;
953f54120ffSKevin Wolf     Error *local_err = NULL;
954f54120ffSKevin Wolf 
9555e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
9565e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
9575e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
9585e5c4f63SKevin Wolf         if (local_err) {
9595e5c4f63SKevin Wolf             error_propagate(errp, local_err);
9605e5c4f63SKevin Wolf             return -EINVAL;
9615e5c4f63SKevin Wolf         }
9625e5c4f63SKevin Wolf 
9635e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
9645e5c4f63SKevin Wolf          * specified directly */
9655e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
9665e5c4f63SKevin Wolf         QDECREF(json_options);
9675e5c4f63SKevin Wolf         *pfilename = filename = NULL;
9685e5c4f63SKevin Wolf     }
9695e5c4f63SKevin Wolf 
970f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
97117b005f1SKevin Wolf     if (protocol && filename) {
972f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
973f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
974f54120ffSKevin Wolf             parse_filename = true;
975f54120ffSKevin Wolf         } else {
976f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
977f54120ffSKevin Wolf                              "the same time");
978f54120ffSKevin Wolf             return -EINVAL;
979f54120ffSKevin Wolf         }
980f54120ffSKevin Wolf     }
981f54120ffSKevin Wolf 
982f54120ffSKevin Wolf     /* Find the right block driver */
983f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
984f54120ffSKevin Wolf     drvname = qdict_get_try_str(*options, "driver");
985f54120ffSKevin Wolf 
98617b005f1SKevin Wolf     if (drv) {
98717b005f1SKevin Wolf         if (drvname) {
98817b005f1SKevin Wolf             error_setg(errp, "Driver specified twice");
98917b005f1SKevin Wolf             return -EINVAL;
99017b005f1SKevin Wolf         }
99117b005f1SKevin Wolf         drvname = drv->format_name;
99217b005f1SKevin Wolf         qdict_put(*options, "driver", qstring_from_str(drvname));
99317b005f1SKevin Wolf     } else {
99417b005f1SKevin Wolf         if (!drvname && protocol) {
995f54120ffSKevin Wolf             if (filename) {
996b65a5e12SMax Reitz                 drv = bdrv_find_protocol(filename, parse_filename, errp);
997f54120ffSKevin Wolf                 if (!drv) {
998f54120ffSKevin Wolf                     return -EINVAL;
999f54120ffSKevin Wolf                 }
1000f54120ffSKevin Wolf 
1001f54120ffSKevin Wolf                 drvname = drv->format_name;
1002f54120ffSKevin Wolf                 qdict_put(*options, "driver", qstring_from_str(drvname));
1003f54120ffSKevin Wolf             } else {
1004f54120ffSKevin Wolf                 error_setg(errp, "Must specify either driver or file");
1005f54120ffSKevin Wolf                 return -EINVAL;
1006f54120ffSKevin Wolf             }
100717b005f1SKevin Wolf         } else if (drvname) {
1008f54120ffSKevin Wolf             drv = bdrv_find_format(drvname);
1009f54120ffSKevin Wolf             if (!drv) {
1010f54120ffSKevin Wolf                 error_setg(errp, "Unknown driver '%s'", drvname);
1011f54120ffSKevin Wolf                 return -ENOENT;
1012f54120ffSKevin Wolf             }
101317b005f1SKevin Wolf         }
101417b005f1SKevin Wolf     }
101517b005f1SKevin Wolf 
101617b005f1SKevin Wolf     assert(drv || !protocol);
1017f54120ffSKevin Wolf 
1018f54120ffSKevin Wolf     /* Driver-specific filename parsing */
101917b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1020f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1021f54120ffSKevin Wolf         if (local_err) {
1022f54120ffSKevin Wolf             error_propagate(errp, local_err);
1023f54120ffSKevin Wolf             return -EINVAL;
1024f54120ffSKevin Wolf         }
1025f54120ffSKevin Wolf 
1026f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1027f54120ffSKevin Wolf             qdict_del(*options, "filename");
1028f54120ffSKevin Wolf         }
1029f54120ffSKevin Wolf     }
1030f54120ffSKevin Wolf 
1031f54120ffSKevin Wolf     return 0;
1032f54120ffSKevin Wolf }
1033f54120ffSKevin Wolf 
10348d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
10358d24cce1SFam Zheng {
10368d24cce1SFam Zheng 
1037826b6ca0SFam Zheng     if (bs->backing_hd) {
1038826b6ca0SFam Zheng         assert(bs->backing_blocker);
1039826b6ca0SFam Zheng         bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker);
1040826b6ca0SFam Zheng     } else if (backing_hd) {
1041826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
104281e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
104381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1044826b6ca0SFam Zheng     }
1045826b6ca0SFam Zheng 
10468d24cce1SFam Zheng     bs->backing_hd = backing_hd;
10478d24cce1SFam Zheng     if (!backing_hd) {
1048826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1049826b6ca0SFam Zheng         bs->backing_blocker = NULL;
10508d24cce1SFam Zheng         goto out;
10518d24cce1SFam Zheng     }
10528d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
10538d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
10548d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
10558d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1056826b6ca0SFam Zheng 
1057826b6ca0SFam Zheng     bdrv_op_block_all(bs->backing_hd, bs->backing_blocker);
1058826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1059bb00021dSFam Zheng     bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1060826b6ca0SFam Zheng                     bs->backing_blocker);
10618d24cce1SFam Zheng out:
10623baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
10638d24cce1SFam Zheng }
10648d24cce1SFam Zheng 
106531ca6d07SKevin Wolf /*
106631ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
106731ca6d07SKevin Wolf  *
106831ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
106931ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
107031ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
107131ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
107231ca6d07SKevin Wolf  */
107334b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
10749156df12SPaolo Bonzini {
10751ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1076317fc44eSKevin Wolf     int ret = 0;
10778d24cce1SFam Zheng     BlockDriverState *backing_hd;
107834b5d2c6SMax Reitz     Error *local_err = NULL;
10799156df12SPaolo Bonzini 
10809156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
108131ca6d07SKevin Wolf         QDECREF(options);
10821ba4b6a5SBenoît Canet         goto free_exit;
10839156df12SPaolo Bonzini     }
10849156df12SPaolo Bonzini 
108531ca6d07SKevin Wolf     /* NULL means an empty set of options */
108631ca6d07SKevin Wolf     if (options == NULL) {
108731ca6d07SKevin Wolf         options = qdict_new();
108831ca6d07SKevin Wolf     }
108931ca6d07SKevin Wolf 
10909156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
10911cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
10921cb6f506SKevin Wolf         backing_filename[0] = '\0';
10931cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
109431ca6d07SKevin Wolf         QDECREF(options);
10951ba4b6a5SBenoît Canet         goto free_exit;
1096dbecebddSFam Zheng     } else {
10979f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
10989f07429eSMax Reitz                                        &local_err);
10999f07429eSMax Reitz         if (local_err) {
11009f07429eSMax Reitz             ret = -EINVAL;
11019f07429eSMax Reitz             error_propagate(errp, local_err);
11029f07429eSMax Reitz             QDECREF(options);
11039f07429eSMax Reitz             goto free_exit;
11049f07429eSMax Reitz         }
11059156df12SPaolo Bonzini     }
11069156df12SPaolo Bonzini 
11078ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
11088ee79e70SKevin Wolf         ret = -EINVAL;
11098ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
11108ee79e70SKevin Wolf         QDECREF(options);
11118ee79e70SKevin Wolf         goto free_exit;
11128ee79e70SKevin Wolf     }
11138ee79e70SKevin Wolf 
1114e4e9986bSMarkus Armbruster     backing_hd = bdrv_new();
11158d24cce1SFam Zheng 
1116c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1117c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
11189156df12SPaolo Bonzini     }
11199156df12SPaolo Bonzini 
1120f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
11218d24cce1SFam Zheng     ret = bdrv_open(&backing_hd,
1122ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
1123c5f6e493SKevin Wolf                     bdrv_backing_flags(bs->open_flags), NULL, &local_err);
11249156df12SPaolo Bonzini     if (ret < 0) {
11258d24cce1SFam Zheng         bdrv_unref(backing_hd);
11268d24cce1SFam Zheng         backing_hd = NULL;
11279156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1128b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1129b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1130b04b6b6eSFam Zheng         error_free(local_err);
11311ba4b6a5SBenoît Canet         goto free_exit;
11329156df12SPaolo Bonzini     }
11338d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
1134d80ac658SPeter Feiner 
11351ba4b6a5SBenoît Canet free_exit:
11361ba4b6a5SBenoît Canet     g_free(backing_filename);
11371ba4b6a5SBenoît Canet     return ret;
11389156df12SPaolo Bonzini }
11399156df12SPaolo Bonzini 
1140b6ce07aaSKevin Wolf /*
1141da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1142da557aacSMax Reitz  * device's options.
1143da557aacSMax Reitz  *
1144da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1145da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1146da557aacSMax Reitz  *
1147da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1148da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1149da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1150da557aacSMax Reitz  * BlockdevRef.
1151da557aacSMax Reitz  *
1152da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1153f67503e5SMax Reitz  *
1154f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1155da557aacSMax Reitz  */
1156da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1157da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1158f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1159da557aacSMax Reitz {
1160da557aacSMax Reitz     QDict *image_options;
1161da557aacSMax Reitz     int ret;
1162da557aacSMax Reitz     char *bdref_key_dot;
1163da557aacSMax Reitz     const char *reference;
1164da557aacSMax Reitz 
1165f67503e5SMax Reitz     assert(pbs);
1166f67503e5SMax Reitz     assert(*pbs == NULL);
1167f67503e5SMax Reitz 
1168da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1169da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1170da557aacSMax Reitz     g_free(bdref_key_dot);
1171da557aacSMax Reitz 
1172da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1173da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1174da557aacSMax Reitz         if (allow_none) {
1175da557aacSMax Reitz             ret = 0;
1176da557aacSMax Reitz         } else {
1177da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1178da557aacSMax Reitz                        bdref_key);
1179da557aacSMax Reitz             ret = -EINVAL;
1180da557aacSMax Reitz         }
1181b20e61e0SMarkus Armbruster         QDECREF(image_options);
1182da557aacSMax Reitz         goto done;
1183da557aacSMax Reitz     }
1184da557aacSMax Reitz 
1185f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1186da557aacSMax Reitz 
1187da557aacSMax Reitz done:
1188da557aacSMax Reitz     qdict_del(options, bdref_key);
1189da557aacSMax Reitz     return ret;
1190da557aacSMax Reitz }
1191da557aacSMax Reitz 
11926b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1193b998875dSKevin Wolf {
1194b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
11951ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1196b998875dSKevin Wolf     int64_t total_size;
119783d0521aSChunyan Liu     QemuOpts *opts = NULL;
1198b998875dSKevin Wolf     QDict *snapshot_options;
1199b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1200b998875dSKevin Wolf     Error *local_err;
1201b998875dSKevin Wolf     int ret;
1202b998875dSKevin Wolf 
1203b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1204b998875dSKevin Wolf        instead of opening 'filename' directly */
1205b998875dSKevin Wolf 
1206b998875dSKevin Wolf     /* Get the required size from the image */
1207f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1208f187743aSKevin Wolf     if (total_size < 0) {
12096b8aeca5SChen Gang         ret = total_size;
1210f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
12111ba4b6a5SBenoît Canet         goto out;
1212f187743aSKevin Wolf     }
1213b998875dSKevin Wolf 
1214b998875dSKevin Wolf     /* Create the temporary image */
12151ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1216b998875dSKevin Wolf     if (ret < 0) {
1217b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
12181ba4b6a5SBenoît Canet         goto out;
1219b998875dSKevin Wolf     }
1220b998875dSKevin Wolf 
1221ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1222c282e1fdSChunyan Liu                             &error_abort);
122339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1224ef810437SMax Reitz     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, &local_err);
122583d0521aSChunyan Liu     qemu_opts_del(opts);
1226b998875dSKevin Wolf     if (ret < 0) {
1227b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1228b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1229b998875dSKevin Wolf                          error_get_pretty(local_err));
1230b998875dSKevin Wolf         error_free(local_err);
12311ba4b6a5SBenoît Canet         goto out;
1232b998875dSKevin Wolf     }
1233b998875dSKevin Wolf 
1234b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1235b998875dSKevin Wolf     snapshot_options = qdict_new();
1236b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1237b998875dSKevin Wolf               qstring_from_str("file"));
1238b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1239b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1240b998875dSKevin Wolf 
1241e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1242b998875dSKevin Wolf 
1243b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1244ef810437SMax Reitz                     flags, &bdrv_qcow2, &local_err);
1245b998875dSKevin Wolf     if (ret < 0) {
1246b998875dSKevin Wolf         error_propagate(errp, local_err);
12471ba4b6a5SBenoît Canet         goto out;
1248b998875dSKevin Wolf     }
1249b998875dSKevin Wolf 
1250b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
12511ba4b6a5SBenoît Canet 
12521ba4b6a5SBenoît Canet out:
12531ba4b6a5SBenoît Canet     g_free(tmp_filename);
12546b8aeca5SChen Gang     return ret;
1255b998875dSKevin Wolf }
1256b998875dSKevin Wolf 
1257da557aacSMax Reitz /*
1258b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1259de9c0cecSKevin Wolf  *
1260de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1261de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1262de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1263de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1264f67503e5SMax Reitz  *
1265f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1266f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1267ddf5636dSMax Reitz  *
1268ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1269ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1270ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1271b6ce07aaSKevin Wolf  */
1272ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1273ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1274ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1275ea2384d3Sbellard {
1276b6ce07aaSKevin Wolf     int ret;
1277f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
127874fe54f2SKevin Wolf     const char *drvname;
127934b5d2c6SMax Reitz     Error *local_err = NULL;
1280b1e6fc08SKevin Wolf     int snapshot_flags = 0;
128133e3963eSbellard 
1282f67503e5SMax Reitz     assert(pbs);
1283f67503e5SMax Reitz 
1284ddf5636dSMax Reitz     if (reference) {
1285ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1286ddf5636dSMax Reitz         QDECREF(options);
1287ddf5636dSMax Reitz 
1288ddf5636dSMax Reitz         if (*pbs) {
1289ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1290ddf5636dSMax Reitz                        "another block device");
1291ddf5636dSMax Reitz             return -EINVAL;
1292ddf5636dSMax Reitz         }
1293ddf5636dSMax Reitz 
1294ddf5636dSMax Reitz         if (filename || options_non_empty) {
1295ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1296ddf5636dSMax Reitz                        "additional options or a new filename");
1297ddf5636dSMax Reitz             return -EINVAL;
1298ddf5636dSMax Reitz         }
1299ddf5636dSMax Reitz 
1300ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1301ddf5636dSMax Reitz         if (!bs) {
1302ddf5636dSMax Reitz             return -ENODEV;
1303ddf5636dSMax Reitz         }
1304ddf5636dSMax Reitz         bdrv_ref(bs);
1305ddf5636dSMax Reitz         *pbs = bs;
1306ddf5636dSMax Reitz         return 0;
1307ddf5636dSMax Reitz     }
1308ddf5636dSMax Reitz 
1309f67503e5SMax Reitz     if (*pbs) {
1310f67503e5SMax Reitz         bs = *pbs;
1311f67503e5SMax Reitz     } else {
1312e4e9986bSMarkus Armbruster         bs = bdrv_new();
1313f67503e5SMax Reitz     }
1314f67503e5SMax Reitz 
1315de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1316de9c0cecSKevin Wolf     if (options == NULL) {
1317de9c0cecSKevin Wolf         options = qdict_new();
1318de9c0cecSKevin Wolf     }
1319de9c0cecSKevin Wolf 
132017b005f1SKevin Wolf     ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err);
1321462f5bcfSKevin Wolf     if (local_err) {
1322462f5bcfSKevin Wolf         goto fail;
1323462f5bcfSKevin Wolf     }
1324462f5bcfSKevin Wolf 
132576c591b0SKevin Wolf     /* Find the right image format driver */
132676c591b0SKevin Wolf     drv = NULL;
132776c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
132876c591b0SKevin Wolf     if (drvname) {
132976c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
133076c591b0SKevin Wolf         qdict_del(options, "driver");
133176c591b0SKevin Wolf         if (!drv) {
133276c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
133376c591b0SKevin Wolf             ret = -EINVAL;
133476c591b0SKevin Wolf             goto fail;
133576c591b0SKevin Wolf         }
133676c591b0SKevin Wolf     }
133776c591b0SKevin Wolf 
133876c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
133976c591b0SKevin Wolf     if (drv && !drv->bdrv_file_open) {
134076c591b0SKevin Wolf         /* If the user explicitly wants a format driver here, we'll need to add
134176c591b0SKevin Wolf          * another layer for the protocol in bs->file */
134276c591b0SKevin Wolf         flags &= ~BDRV_O_PROTOCOL;
134376c591b0SKevin Wolf     }
134476c591b0SKevin Wolf 
1345de9c0cecSKevin Wolf     bs->options = options;
1346b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1347de9c0cecSKevin Wolf 
1348f500a6d3SKevin Wolf     /* Open image file without format layer */
1349f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1350be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1351be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1352be028adcSJeff Cody         }
1353b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1354b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1355b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1356b1e6fc08SKevin Wolf         }
1357be028adcSJeff Cody 
1358f67503e5SMax Reitz         assert(file == NULL);
1359054963f8SMax Reitz         ret = bdrv_open_image(&file, filename, options, "file",
13600b50cc88SKevin Wolf                               bdrv_inherited_flags(flags),
13610b50cc88SKevin Wolf                               true, &local_err);
1362f500a6d3SKevin Wolf         if (ret < 0) {
13638bfea15dSKevin Wolf             goto fail;
1364f500a6d3SKevin Wolf         }
1365f4788adcSKevin Wolf     }
1366f500a6d3SKevin Wolf 
136776c591b0SKevin Wolf     /* Image format probing */
136838f3ef57SKevin Wolf     bs->probed = !drv;
136976c591b0SKevin Wolf     if (!drv && file) {
137034b5d2c6SMax Reitz         ret = find_image_format(file, filename, &drv, &local_err);
137117b005f1SKevin Wolf         if (ret < 0) {
137217b005f1SKevin Wolf             goto fail;
137317b005f1SKevin Wolf         }
137476c591b0SKevin Wolf     } else if (!drv) {
13752a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
13762a05cbe4SMax Reitz         ret = -EINVAL;
13778bfea15dSKevin Wolf         goto fail;
13782a05cbe4SMax Reitz     }
1379f500a6d3SKevin Wolf 
1380b6ce07aaSKevin Wolf     /* Open the image */
138134b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1382b6ce07aaSKevin Wolf     if (ret < 0) {
13838bfea15dSKevin Wolf         goto fail;
13846987307cSChristoph Hellwig     }
13856987307cSChristoph Hellwig 
13862a05cbe4SMax Reitz     if (file && (bs->file != file)) {
13874f6fd349SFam Zheng         bdrv_unref(file);
1388f500a6d3SKevin Wolf         file = NULL;
1389f500a6d3SKevin Wolf     }
1390f500a6d3SKevin Wolf 
1391b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
13929156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
139331ca6d07SKevin Wolf         QDict *backing_options;
139431ca6d07SKevin Wolf 
13955726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
139634b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1397b6ce07aaSKevin Wolf         if (ret < 0) {
1398b6ad491aSKevin Wolf             goto close_and_fail;
1399b6ce07aaSKevin Wolf         }
1400b6ce07aaSKevin Wolf     }
1401b6ce07aaSKevin Wolf 
140291af7014SMax Reitz     bdrv_refresh_filename(bs);
140391af7014SMax Reitz 
1404b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1405b998875dSKevin Wolf      * temporary snapshot afterwards. */
1406b1e6fc08SKevin Wolf     if (snapshot_flags) {
14076b8aeca5SChen Gang         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1408b998875dSKevin Wolf         if (local_err) {
1409b998875dSKevin Wolf             goto close_and_fail;
1410b998875dSKevin Wolf         }
1411b998875dSKevin Wolf     }
1412b998875dSKevin Wolf 
1413b6ad491aSKevin Wolf     /* Check if any unknown options were used */
14145acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1415b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
14165acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
14175acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
14185acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
14195acd9d81SMax Reitz         } else {
142034b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
14215acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
1422bfb197e0SMarkus Armbruster                        bdrv_get_device_name(bs), entry->key);
14235acd9d81SMax Reitz         }
1424b6ad491aSKevin Wolf 
1425b6ad491aSKevin Wolf         ret = -EINVAL;
1426b6ad491aSKevin Wolf         goto close_and_fail;
1427b6ad491aSKevin Wolf     }
1428b6ad491aSKevin Wolf 
1429b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1430a7f53e26SMarkus Armbruster         if (bs->blk) {
1431a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1432a7f53e26SMarkus Armbruster         }
1433c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1434c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1435c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1436c3adb58fSMarkus Armbruster         error_setg(errp,
1437c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1438c3adb58fSMarkus Armbruster         ret = -EBUSY;
1439c3adb58fSMarkus Armbruster         goto close_and_fail;
1440b6ce07aaSKevin Wolf     }
1441b6ce07aaSKevin Wolf 
1442c3adb58fSMarkus Armbruster     QDECREF(options);
1443f67503e5SMax Reitz     *pbs = bs;
1444b6ce07aaSKevin Wolf     return 0;
1445b6ce07aaSKevin Wolf 
14468bfea15dSKevin Wolf fail:
1447f500a6d3SKevin Wolf     if (file != NULL) {
14484f6fd349SFam Zheng         bdrv_unref(file);
1449f500a6d3SKevin Wolf     }
1450de9c0cecSKevin Wolf     QDECREF(bs->options);
1451b6ad491aSKevin Wolf     QDECREF(options);
1452de9c0cecSKevin Wolf     bs->options = NULL;
1453f67503e5SMax Reitz     if (!*pbs) {
1454f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1455f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1456f67503e5SMax Reitz            since it has not really been opened yet. */
1457f67503e5SMax Reitz         bdrv_unref(bs);
1458f67503e5SMax Reitz     }
145984d18f06SMarkus Armbruster     if (local_err) {
146034b5d2c6SMax Reitz         error_propagate(errp, local_err);
146134b5d2c6SMax Reitz     }
1462b6ad491aSKevin Wolf     return ret;
1463de9c0cecSKevin Wolf 
1464b6ad491aSKevin Wolf close_and_fail:
1465f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1466f67503e5SMax Reitz     if (*pbs) {
1467b6ad491aSKevin Wolf         bdrv_close(bs);
1468f67503e5SMax Reitz     } else {
1469f67503e5SMax Reitz         bdrv_unref(bs);
1470f67503e5SMax Reitz     }
1471b6ad491aSKevin Wolf     QDECREF(options);
147284d18f06SMarkus Armbruster     if (local_err) {
147334b5d2c6SMax Reitz         error_propagate(errp, local_err);
147434b5d2c6SMax Reitz     }
1475b6ce07aaSKevin Wolf     return ret;
1476b6ce07aaSKevin Wolf }
1477b6ce07aaSKevin Wolf 
1478e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1479e971aa12SJeff Cody      bool prepared;
1480e971aa12SJeff Cody      BDRVReopenState state;
1481e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1482e971aa12SJeff Cody } BlockReopenQueueEntry;
1483e971aa12SJeff Cody 
1484e971aa12SJeff Cody /*
1485e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1486e971aa12SJeff Cody  * reopen of multiple devices.
1487e971aa12SJeff Cody  *
1488e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1489e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1490e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1491e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1492e971aa12SJeff Cody  * atomic 'set'.
1493e971aa12SJeff Cody  *
1494e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1495e971aa12SJeff Cody  *
1496e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1497e971aa12SJeff Cody  *
1498e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1499e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1500e971aa12SJeff Cody  *
1501e971aa12SJeff Cody  */
1502e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1503e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1504e971aa12SJeff Cody {
1505e971aa12SJeff Cody     assert(bs != NULL);
1506e971aa12SJeff Cody 
1507e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1508e971aa12SJeff Cody     if (bs_queue == NULL) {
1509e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1510e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1511e971aa12SJeff Cody     }
1512e971aa12SJeff Cody 
1513f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1514f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1515f1f25a2eSKevin Wolf 
1516e971aa12SJeff Cody     if (bs->file) {
1517f1f25a2eSKevin Wolf         bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
1518e971aa12SJeff Cody     }
1519e971aa12SJeff Cody 
1520e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1521e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1522e971aa12SJeff Cody 
1523e971aa12SJeff Cody     bs_entry->state.bs = bs;
1524e971aa12SJeff Cody     bs_entry->state.flags = flags;
1525e971aa12SJeff Cody 
1526e971aa12SJeff Cody     return bs_queue;
1527e971aa12SJeff Cody }
1528e971aa12SJeff Cody 
1529e971aa12SJeff Cody /*
1530e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1531e971aa12SJeff Cody  *
1532e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1533e971aa12SJeff Cody  * via bdrv_reopen_queue().
1534e971aa12SJeff Cody  *
1535e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1536e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1537e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1538e971aa12SJeff Cody  * data cleaned up.
1539e971aa12SJeff Cody  *
1540e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1541e971aa12SJeff Cody  * to all devices.
1542e971aa12SJeff Cody  *
1543e971aa12SJeff Cody  */
1544e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1545e971aa12SJeff Cody {
1546e971aa12SJeff Cody     int ret = -1;
1547e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1548e971aa12SJeff Cody     Error *local_err = NULL;
1549e971aa12SJeff Cody 
1550e971aa12SJeff Cody     assert(bs_queue != NULL);
1551e971aa12SJeff Cody 
1552e971aa12SJeff Cody     bdrv_drain_all();
1553e971aa12SJeff Cody 
1554e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1555e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1556e971aa12SJeff Cody             error_propagate(errp, local_err);
1557e971aa12SJeff Cody             goto cleanup;
1558e971aa12SJeff Cody         }
1559e971aa12SJeff Cody         bs_entry->prepared = true;
1560e971aa12SJeff Cody     }
1561e971aa12SJeff Cody 
1562e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1563e971aa12SJeff Cody      * changes
1564e971aa12SJeff Cody      */
1565e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1566e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1567e971aa12SJeff Cody     }
1568e971aa12SJeff Cody 
1569e971aa12SJeff Cody     ret = 0;
1570e971aa12SJeff Cody 
1571e971aa12SJeff Cody cleanup:
1572e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1573e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1574e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1575e971aa12SJeff Cody         }
1576e971aa12SJeff Cody         g_free(bs_entry);
1577e971aa12SJeff Cody     }
1578e971aa12SJeff Cody     g_free(bs_queue);
1579e971aa12SJeff Cody     return ret;
1580e971aa12SJeff Cody }
1581e971aa12SJeff Cody 
1582e971aa12SJeff Cody 
1583e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1584e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1585e971aa12SJeff Cody {
1586e971aa12SJeff Cody     int ret = -1;
1587e971aa12SJeff Cody     Error *local_err = NULL;
1588e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1589e971aa12SJeff Cody 
1590e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1591e971aa12SJeff Cody     if (local_err != NULL) {
1592e971aa12SJeff Cody         error_propagate(errp, local_err);
1593e971aa12SJeff Cody     }
1594e971aa12SJeff Cody     return ret;
1595e971aa12SJeff Cody }
1596e971aa12SJeff Cody 
1597e971aa12SJeff Cody 
1598e971aa12SJeff Cody /*
1599e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1600e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1601e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1602e971aa12SJeff Cody  *
1603e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1604e971aa12SJeff Cody  * flags are the new open flags
1605e971aa12SJeff Cody  * queue is the reopen queue
1606e971aa12SJeff Cody  *
1607e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1608e971aa12SJeff Cody  * as well.
1609e971aa12SJeff Cody  *
1610e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1611e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1612e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1613e971aa12SJeff Cody  *
1614e971aa12SJeff Cody  */
1615e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1616e971aa12SJeff Cody                         Error **errp)
1617e971aa12SJeff Cody {
1618e971aa12SJeff Cody     int ret = -1;
1619e971aa12SJeff Cody     Error *local_err = NULL;
1620e971aa12SJeff Cody     BlockDriver *drv;
1621e971aa12SJeff Cody 
1622e971aa12SJeff Cody     assert(reopen_state != NULL);
1623e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1624e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1625e971aa12SJeff Cody 
1626e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1627e971aa12SJeff Cody      * to r/w */
1628e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1629e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
163081e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
163181e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1632e971aa12SJeff Cody         goto error;
1633e971aa12SJeff Cody     }
1634e971aa12SJeff Cody 
1635e971aa12SJeff Cody 
1636e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1637e971aa12SJeff Cody     if (ret) {
1638e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1639e971aa12SJeff Cody                   strerror(-ret));
1640e971aa12SJeff Cody         goto error;
1641e971aa12SJeff Cody     }
1642e971aa12SJeff Cody 
1643e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1644e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1645e971aa12SJeff Cody         if (ret) {
1646e971aa12SJeff Cody             if (local_err != NULL) {
1647e971aa12SJeff Cody                 error_propagate(errp, local_err);
1648e971aa12SJeff Cody             } else {
1649d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1650e971aa12SJeff Cody                            reopen_state->bs->filename);
1651e971aa12SJeff Cody             }
1652e971aa12SJeff Cody             goto error;
1653e971aa12SJeff Cody         }
1654e971aa12SJeff Cody     } else {
1655e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1656e971aa12SJeff Cody          * handler for each supported drv. */
165781e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
165881e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
165981e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
1660e971aa12SJeff Cody         ret = -1;
1661e971aa12SJeff Cody         goto error;
1662e971aa12SJeff Cody     }
1663e971aa12SJeff Cody 
1664e971aa12SJeff Cody     ret = 0;
1665e971aa12SJeff Cody 
1666e971aa12SJeff Cody error:
1667e971aa12SJeff Cody     return ret;
1668e971aa12SJeff Cody }
1669e971aa12SJeff Cody 
1670e971aa12SJeff Cody /*
1671e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1672e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1673e971aa12SJeff Cody  * the active BlockDriverState contents.
1674e971aa12SJeff Cody  */
1675e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1676e971aa12SJeff Cody {
1677e971aa12SJeff Cody     BlockDriver *drv;
1678e971aa12SJeff Cody 
1679e971aa12SJeff Cody     assert(reopen_state != NULL);
1680e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1681e971aa12SJeff Cody     assert(drv != NULL);
1682e971aa12SJeff Cody 
1683e971aa12SJeff Cody     /* If there are any driver level actions to take */
1684e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1685e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1686e971aa12SJeff Cody     }
1687e971aa12SJeff Cody 
1688e971aa12SJeff Cody     /* set BDS specific flags now */
1689e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1690e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1691e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1692e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1693355ef4acSKevin Wolf 
16943baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1695e971aa12SJeff Cody }
1696e971aa12SJeff Cody 
1697e971aa12SJeff Cody /*
1698e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1699e971aa12SJeff Cody  * reopen_state
1700e971aa12SJeff Cody  */
1701e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1702e971aa12SJeff Cody {
1703e971aa12SJeff Cody     BlockDriver *drv;
1704e971aa12SJeff Cody 
1705e971aa12SJeff Cody     assert(reopen_state != NULL);
1706e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1707e971aa12SJeff Cody     assert(drv != NULL);
1708e971aa12SJeff Cody 
1709e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1710e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1711e971aa12SJeff Cody     }
1712e971aa12SJeff Cody }
1713e971aa12SJeff Cody 
1714e971aa12SJeff Cody 
1715fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1716fc01f7e7Sbellard {
171733384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
171833384421SMax Reitz 
17193e914655SPaolo Bonzini     if (bs->job) {
17203e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
17213e914655SPaolo Bonzini     }
172258fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
172358fda173SStefan Hajnoczi     bdrv_flush(bs);
172458fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1725d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
17267094f12fSKevin Wolf 
17273cbc002cSPaolo Bonzini     if (bs->drv) {
1728557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1729826b6ca0SFam Zheng             BlockDriverState *backing_hd = bs->backing_hd;
1730826b6ca0SFam Zheng             bdrv_set_backing_hd(bs, NULL);
1731826b6ca0SFam Zheng             bdrv_unref(backing_hd);
1732557df6acSStefan Hajnoczi         }
1733ea2384d3Sbellard         bs->drv->bdrv_close(bs);
17347267c094SAnthony Liguori         g_free(bs->opaque);
1735ea2384d3Sbellard         bs->opaque = NULL;
1736ea2384d3Sbellard         bs->drv = NULL;
173753fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1738a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1739a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
17406405875cSPaolo Bonzini         bs->total_sectors = 0;
17416405875cSPaolo Bonzini         bs->encrypted = 0;
17426405875cSPaolo Bonzini         bs->valid_key = 0;
17436405875cSPaolo Bonzini         bs->sg = 0;
17440d51b4deSAsias He         bs->zero_beyond_eof = false;
1745de9c0cecSKevin Wolf         QDECREF(bs->options);
1746de9c0cecSKevin Wolf         bs->options = NULL;
174791af7014SMax Reitz         QDECREF(bs->full_open_options);
174891af7014SMax Reitz         bs->full_open_options = NULL;
1749b338082bSbellard 
175066f82ceeSKevin Wolf         if (bs->file != NULL) {
17514f6fd349SFam Zheng             bdrv_unref(bs->file);
17520ac9377dSPaolo Bonzini             bs->file = NULL;
175366f82ceeSKevin Wolf         }
17549ca11154SPavel Hrdina     }
175566f82ceeSKevin Wolf 
1756a7f53e26SMarkus Armbruster     if (bs->blk) {
1757a7f53e26SMarkus Armbruster         blk_dev_change_media_cb(bs->blk, false);
1758a7f53e26SMarkus Armbruster     }
175998f90dbaSZhi Yong Wu 
176098f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
176198f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
176298f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
176398f90dbaSZhi Yong Wu     }
176433384421SMax Reitz 
176533384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
176633384421SMax Reitz         g_free(ban);
176733384421SMax Reitz     }
176833384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1769b338082bSbellard }
1770b338082bSbellard 
17712bc93fedSMORITA Kazutaka void bdrv_close_all(void)
17722bc93fedSMORITA Kazutaka {
17732bc93fedSMORITA Kazutaka     BlockDriverState *bs;
17742bc93fedSMORITA Kazutaka 
1775dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1776ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1777ed78cda3SStefan Hajnoczi 
1778ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
17792bc93fedSMORITA Kazutaka         bdrv_close(bs);
1780ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
17812bc93fedSMORITA Kazutaka     }
17822bc93fedSMORITA Kazutaka }
17832bc93fedSMORITA Kazutaka 
1784dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1785dc364f4cSBenoît Canet  * graph_bdrv_state list.
1786d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1787d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1788d22b2f41SRyan Harper {
1789bfb197e0SMarkus Armbruster     /*
1790bfb197e0SMarkus Armbruster      * Take care to remove bs from bdrv_states only when it's actually
1791bfb197e0SMarkus Armbruster      * in it.  Note that bs->device_list.tqe_prev is initially null,
1792bfb197e0SMarkus Armbruster      * and gets set to non-null by QTAILQ_INSERT_TAIL().  Establish
1793bfb197e0SMarkus Armbruster      * the useful invariant "bs in bdrv_states iff bs->tqe_prev" by
1794bfb197e0SMarkus Armbruster      * resetting it to null on remove.
1795bfb197e0SMarkus Armbruster      */
1796bfb197e0SMarkus Armbruster     if (bs->device_list.tqe_prev) {
1797dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1798bfb197e0SMarkus Armbruster         bs->device_list.tqe_prev = NULL;
1799d22b2f41SRyan Harper     }
1800dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1801dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1802dc364f4cSBenoît Canet     }
1803dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1804d22b2f41SRyan Harper }
1805d22b2f41SRyan Harper 
1806e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1807e023b2e2SPaolo Bonzini {
1808e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1809e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1810e023b2e2SPaolo Bonzini     }
1811e023b2e2SPaolo Bonzini }
1812e023b2e2SPaolo Bonzini 
18134ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
18144ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
18154ddc07caSPaolo Bonzini {
18164ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
18174ddc07caSPaolo Bonzini 
18184ddc07caSPaolo Bonzini     /* dev info */
18191b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
18204ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
18214ddc07caSPaolo Bonzini 
18224ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
18234ddc07caSPaolo Bonzini 
1824cc0681c4SBenoît Canet     /* i/o throttled req */
1825*76f4afb4SAlberto Garcia     bs_dest->throttle_state     = bs_src->throttle_state,
1826*76f4afb4SAlberto Garcia     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
1827*76f4afb4SAlberto Garcia     bs_dest->pending_reqs[0]    = bs_src->pending_reqs[0];
1828*76f4afb4SAlberto Garcia     bs_dest->pending_reqs[1]    = bs_src->pending_reqs[1];
1829*76f4afb4SAlberto Garcia     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1830*76f4afb4SAlberto Garcia     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
1831*76f4afb4SAlberto Garcia     memcpy(&bs_dest->round_robin,
1832*76f4afb4SAlberto Garcia            &bs_src->round_robin,
1833*76f4afb4SAlberto Garcia            sizeof(bs_dest->round_robin));
18340e5b0a2dSBenoît Canet     memcpy(&bs_dest->throttle_timers,
18350e5b0a2dSBenoît Canet            &bs_src->throttle_timers,
18360e5b0a2dSBenoît Canet            sizeof(ThrottleTimers));
18374ddc07caSPaolo Bonzini 
18384ddc07caSPaolo Bonzini     /* r/w error */
18394ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
18404ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
18414ddc07caSPaolo Bonzini 
18424ddc07caSPaolo Bonzini     /* i/o status */
18434ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
18444ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
18454ddc07caSPaolo Bonzini 
18464ddc07caSPaolo Bonzini     /* dirty bitmap */
1847e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
18484ddc07caSPaolo Bonzini 
18499fcb0251SFam Zheng     /* reference count */
18509fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
18519fcb0251SFam Zheng 
18524ddc07caSPaolo Bonzini     /* job */
18534ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
18544ddc07caSPaolo Bonzini 
18554ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
1856dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
18577e7d56d9SMarkus Armbruster     bs_dest->blk = bs_src->blk;
18587e7d56d9SMarkus Armbruster 
1859fbe40ff7SFam Zheng     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
1860fbe40ff7SFam Zheng            sizeof(bs_dest->op_blockers));
18614ddc07caSPaolo Bonzini }
18624ddc07caSPaolo Bonzini 
18634ddc07caSPaolo Bonzini /*
18644ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
18654ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
18664ddc07caSPaolo Bonzini  * actually attached to a device.
18674ddc07caSPaolo Bonzini  *
18684ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
18694ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
18704ddc07caSPaolo Bonzini  *
1871bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
18724ddc07caSPaolo Bonzini  *
18734ddc07caSPaolo Bonzini  * This function does not create any image files.
18744ddc07caSPaolo Bonzini  */
18754ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
18764ddc07caSPaolo Bonzini {
18774ddc07caSPaolo Bonzini     BlockDriverState tmp;
18784ddc07caSPaolo Bonzini 
187990ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
188090ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
188190ce8a06SBenoît Canet      * insert them back if needed.
188290ce8a06SBenoît Canet      */
188390ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
188490ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
188590ce8a06SBenoît Canet     }
188690ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
188790ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
188890ce8a06SBenoît Canet     }
188990ce8a06SBenoît Canet 
1890bfb197e0SMarkus Armbruster     /* bs_new must be unattached and shouldn't have anything fancy enabled */
18917e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
1892e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
18934ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
18944ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
18950e5b0a2dSBenoît Canet     assert(!throttle_timers_are_initialized(&bs_new->throttle_timers));
18964ddc07caSPaolo Bonzini 
18974ddc07caSPaolo Bonzini     tmp = *bs_new;
18984ddc07caSPaolo Bonzini     *bs_new = *bs_old;
18994ddc07caSPaolo Bonzini     *bs_old = tmp;
19004ddc07caSPaolo Bonzini 
19014ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
19024ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
19034ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
19044ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
19054ddc07caSPaolo Bonzini 
1906bfb197e0SMarkus Armbruster     /* bs_new must remain unattached */
19077e7d56d9SMarkus Armbruster     assert(!bs_new->blk);
19084ddc07caSPaolo Bonzini 
19094ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
19104ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
19114ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
19120e5b0a2dSBenoît Canet     assert(!throttle_timers_are_initialized(&bs_new->throttle_timers));
19134ddc07caSPaolo Bonzini 
191490ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
191590ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
191690ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
191790ce8a06SBenoît Canet     }
191890ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
191990ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
192090ce8a06SBenoît Canet     }
192190ce8a06SBenoît Canet 
19224ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
19234ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
19244ddc07caSPaolo Bonzini }
19254ddc07caSPaolo Bonzini 
19268802d1fdSJeff Cody /*
19278802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
19288802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
19298802d1fdSJeff Cody  *
19308802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
19318802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
19328802d1fdSJeff Cody  *
1933bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
1934f6801b83SJeff Cody  *
19358802d1fdSJeff Cody  * This function does not create any image files.
19368802d1fdSJeff Cody  */
19378802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
19388802d1fdSJeff Cody {
19394ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
19408802d1fdSJeff Cody 
19418802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
19428802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
19438d24cce1SFam Zheng     bdrv_set_backing_hd(bs_top, bs_new);
19448802d1fdSJeff Cody }
19458802d1fdSJeff Cody 
19464f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
1947b338082bSbellard {
19483e914655SPaolo Bonzini     assert(!bs->job);
19493718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
19504f6fd349SFam Zheng     assert(!bs->refcnt);
1951e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
195218846deeSMarkus Armbruster 
1953e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
1954e1b5c52eSStefan Hajnoczi 
19551b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
1956d22b2f41SRyan Harper     bdrv_make_anon(bs);
195734c6f050Saurel32 
19587267c094SAnthony Liguori     g_free(bs);
1959fc01f7e7Sbellard }
1960fc01f7e7Sbellard 
1961e97fc193Saliguori /*
1962e97fc193Saliguori  * Run consistency checks on an image
1963e97fc193Saliguori  *
1964e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
1965a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
1966e076f338SKevin Wolf  * check are stored in res.
1967e97fc193Saliguori  */
19684534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
1969e97fc193Saliguori {
1970908bcd54SMax Reitz     if (bs->drv == NULL) {
1971908bcd54SMax Reitz         return -ENOMEDIUM;
1972908bcd54SMax Reitz     }
1973e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
1974e97fc193Saliguori         return -ENOTSUP;
1975e97fc193Saliguori     }
1976e97fc193Saliguori 
1977e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
19784534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
1979e97fc193Saliguori }
1980e97fc193Saliguori 
19818a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
19828a426614SKevin Wolf 
198333e3963eSbellard /* commit COW file into the raw image */
198433e3963eSbellard int bdrv_commit(BlockDriverState *bs)
198533e3963eSbellard {
198619cb3738Sbellard     BlockDriver *drv = bs->drv;
198772706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
19888a426614SKevin Wolf     int n, ro, open_flags;
19890bce597dSJeff Cody     int ret = 0;
199072706ea4SJeff Cody     uint8_t *buf = NULL;
199133e3963eSbellard 
199219cb3738Sbellard     if (!drv)
199319cb3738Sbellard         return -ENOMEDIUM;
199433e3963eSbellard 
19954dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
19964dca4b63SNaphtali Sprei         return -ENOTSUP;
19974dca4b63SNaphtali Sprei     }
19984dca4b63SNaphtali Sprei 
1999bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2000bb00021dSFam Zheng         bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
20012d3735d3SStefan Hajnoczi         return -EBUSY;
20022d3735d3SStefan Hajnoczi     }
20032d3735d3SStefan Hajnoczi 
20044dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
20054dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
20064dca4b63SNaphtali Sprei 
20074dca4b63SNaphtali Sprei     if (ro) {
20080bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
20090bce597dSJeff Cody             return -EACCES;
20104dca4b63SNaphtali Sprei         }
2011ea2384d3Sbellard     }
2012ea2384d3Sbellard 
201372706ea4SJeff Cody     length = bdrv_getlength(bs);
201472706ea4SJeff Cody     if (length < 0) {
201572706ea4SJeff Cody         ret = length;
201672706ea4SJeff Cody         goto ro_cleanup;
201772706ea4SJeff Cody     }
201872706ea4SJeff Cody 
201972706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
202072706ea4SJeff Cody     if (backing_length < 0) {
202172706ea4SJeff Cody         ret = backing_length;
202272706ea4SJeff Cody         goto ro_cleanup;
202372706ea4SJeff Cody     }
202472706ea4SJeff Cody 
202572706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
202672706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
202772706ea4SJeff Cody      * we must return an error */
202872706ea4SJeff Cody     if (length > backing_length) {
202972706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
203072706ea4SJeff Cody         if (ret < 0) {
203172706ea4SJeff Cody             goto ro_cleanup;
203272706ea4SJeff Cody         }
203372706ea4SJeff Cody     }
203472706ea4SJeff Cody 
203572706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2036857d4f46SKevin Wolf 
2037857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2038857d4f46SKevin Wolf      * bs->backing_hd as well, so no need to compare the alignment manually. */
2039857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2040857d4f46SKevin Wolf     if (buf == NULL) {
2041857d4f46SKevin Wolf         ret = -ENOMEM;
2042857d4f46SKevin Wolf         goto ro_cleanup;
2043857d4f46SKevin Wolf     }
20448a426614SKevin Wolf 
20458a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2046d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2047d663640cSPaolo Bonzini         if (ret < 0) {
2048d663640cSPaolo Bonzini             goto ro_cleanup;
2049d663640cSPaolo Bonzini         }
2050d663640cSPaolo Bonzini         if (ret) {
2051dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2052dabfa6ccSKevin Wolf             if (ret < 0) {
20534dca4b63SNaphtali Sprei                 goto ro_cleanup;
205433e3963eSbellard             }
205533e3963eSbellard 
2056dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2057dabfa6ccSKevin Wolf             if (ret < 0) {
20584dca4b63SNaphtali Sprei                 goto ro_cleanup;
205933e3963eSbellard             }
206033e3963eSbellard         }
206133e3963eSbellard     }
206295389c86Sbellard 
20631d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
20641d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2065dabfa6ccSKevin Wolf         if (ret < 0) {
2066dabfa6ccSKevin Wolf             goto ro_cleanup;
2067dabfa6ccSKevin Wolf         }
20681d44952fSChristoph Hellwig         bdrv_flush(bs);
20691d44952fSChristoph Hellwig     }
207095389c86Sbellard 
20713f5075aeSChristoph Hellwig     /*
20723f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
20733f5075aeSChristoph Hellwig      * stable on disk.
20743f5075aeSChristoph Hellwig      */
2075dabfa6ccSKevin Wolf     if (bs->backing_hd) {
20763f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2077dabfa6ccSKevin Wolf     }
20784dca4b63SNaphtali Sprei 
2079dabfa6ccSKevin Wolf     ret = 0;
20804dca4b63SNaphtali Sprei ro_cleanup:
2081857d4f46SKevin Wolf     qemu_vfree(buf);
20824dca4b63SNaphtali Sprei 
20834dca4b63SNaphtali Sprei     if (ro) {
20840bce597dSJeff Cody         /* ignoring error return here */
20850bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
20864dca4b63SNaphtali Sprei     }
20874dca4b63SNaphtali Sprei 
20881d44952fSChristoph Hellwig     return ret;
208933e3963eSbellard }
209033e3963eSbellard 
2091e8877497SStefan Hajnoczi int bdrv_commit_all(void)
20926ab4b5abSMarkus Armbruster {
20936ab4b5abSMarkus Armbruster     BlockDriverState *bs;
20946ab4b5abSMarkus Armbruster 
2095dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2096ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2097ed78cda3SStefan Hajnoczi 
2098ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2099272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2100e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2101e8877497SStefan Hajnoczi             if (ret < 0) {
2102ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2103e8877497SStefan Hajnoczi                 return ret;
21046ab4b5abSMarkus Armbruster             }
21056ab4b5abSMarkus Armbruster         }
2106ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2107272d2d8eSJeff Cody     }
2108e8877497SStefan Hajnoczi     return 0;
2109e8877497SStefan Hajnoczi }
21106ab4b5abSMarkus Armbruster 
2111756e6736SKevin Wolf /*
2112756e6736SKevin Wolf  * Return values:
2113756e6736SKevin Wolf  * 0        - success
2114756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2115756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2116756e6736SKevin Wolf  *            image file header
2117756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2118756e6736SKevin Wolf  */
2119756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2120756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2121756e6736SKevin Wolf {
2122756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2123469ef350SPaolo Bonzini     int ret;
2124756e6736SKevin Wolf 
21255f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
21265f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
21275f377794SPaolo Bonzini         return -EINVAL;
21285f377794SPaolo Bonzini     }
21295f377794SPaolo Bonzini 
2130756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2131469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2132756e6736SKevin Wolf     } else {
2133469ef350SPaolo Bonzini         ret = -ENOTSUP;
2134756e6736SKevin Wolf     }
2135469ef350SPaolo Bonzini 
2136469ef350SPaolo Bonzini     if (ret == 0) {
2137469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2138469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2139469ef350SPaolo Bonzini     }
2140469ef350SPaolo Bonzini     return ret;
2141756e6736SKevin Wolf }
2142756e6736SKevin Wolf 
21436ebdcee2SJeff Cody /*
21446ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
21456ebdcee2SJeff Cody  *
21466ebdcee2SJeff Cody  * active is the current topmost image.
21476ebdcee2SJeff Cody  *
21486ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
21496ebdcee2SJeff Cody  * or if active == bs.
21504caf0fcdSJeff Cody  *
21514caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
21526ebdcee2SJeff Cody  */
21536ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
21546ebdcee2SJeff Cody                                     BlockDriverState *bs)
21556ebdcee2SJeff Cody {
21564caf0fcdSJeff Cody     while (active && bs != active->backing_hd) {
21574caf0fcdSJeff Cody         active = active->backing_hd;
21586ebdcee2SJeff Cody     }
21596ebdcee2SJeff Cody 
21604caf0fcdSJeff Cody     return active;
21616ebdcee2SJeff Cody }
21626ebdcee2SJeff Cody 
21634caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
21644caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
21654caf0fcdSJeff Cody {
21664caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
21676ebdcee2SJeff Cody }
21686ebdcee2SJeff Cody 
21696ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
21706ebdcee2SJeff Cody     BlockDriverState *bs;
21716ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
21726ebdcee2SJeff Cody } BlkIntermediateStates;
21736ebdcee2SJeff Cody 
21746ebdcee2SJeff Cody 
21756ebdcee2SJeff Cody /*
21766ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
21776ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
21786ebdcee2SJeff Cody  *
21796ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
21806ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
21816ebdcee2SJeff Cody  *
21826ebdcee2SJeff Cody  * E.g., this will convert the following chain:
21836ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
21846ebdcee2SJeff Cody  *
21856ebdcee2SJeff Cody  * to
21866ebdcee2SJeff Cody  *
21876ebdcee2SJeff Cody  * bottom <- base <- active
21886ebdcee2SJeff Cody  *
21896ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
21906ebdcee2SJeff Cody  *
21916ebdcee2SJeff Cody  * base <- intermediate <- top <- active
21926ebdcee2SJeff Cody  *
21936ebdcee2SJeff Cody  * to
21946ebdcee2SJeff Cody  *
21956ebdcee2SJeff Cody  * base <- active
21966ebdcee2SJeff Cody  *
219754e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
219854e26900SJeff Cody  * overlay image metadata.
219954e26900SJeff Cody  *
22006ebdcee2SJeff Cody  * Error conditions:
22016ebdcee2SJeff Cody  *  if active == top, that is considered an error
22026ebdcee2SJeff Cody  *
22036ebdcee2SJeff Cody  */
22046ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
220554e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
22066ebdcee2SJeff Cody {
22076ebdcee2SJeff Cody     BlockDriverState *intermediate;
22086ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
22096ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
22106ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
22116ebdcee2SJeff Cody     int ret = -EIO;
22126ebdcee2SJeff Cody 
22136ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
22146ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
22156ebdcee2SJeff Cody 
22166ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
22176ebdcee2SJeff Cody         goto exit;
22186ebdcee2SJeff Cody     }
22196ebdcee2SJeff Cody 
22206ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
22216ebdcee2SJeff Cody 
22226ebdcee2SJeff Cody     if (new_top_bs == NULL) {
22236ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
22246ebdcee2SJeff Cody         goto exit;
22256ebdcee2SJeff Cody     }
22266ebdcee2SJeff Cody 
22276ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
22286ebdcee2SJeff Cody      * to do, no intermediate images */
22296ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
22306ebdcee2SJeff Cody         ret = 0;
22316ebdcee2SJeff Cody         goto exit;
22326ebdcee2SJeff Cody     }
22336ebdcee2SJeff Cody 
22346ebdcee2SJeff Cody     intermediate = top;
22356ebdcee2SJeff Cody 
22366ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
22376ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
22386ebdcee2SJeff Cody      */
22396ebdcee2SJeff Cody     while (intermediate) {
22405839e53bSMarkus Armbruster         intermediate_state = g_new0(BlkIntermediateStates, 1);
22416ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
22426ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
22436ebdcee2SJeff Cody 
22446ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
22456ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
22466ebdcee2SJeff Cody             break;
22476ebdcee2SJeff Cody         }
22486ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
22496ebdcee2SJeff Cody     }
22506ebdcee2SJeff Cody     if (base_bs == NULL) {
22516ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
22526ebdcee2SJeff Cody          * unravel everything, and exit with error */
22536ebdcee2SJeff Cody         goto exit;
22546ebdcee2SJeff Cody     }
22556ebdcee2SJeff Cody 
22566ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
225754e26900SJeff Cody     backing_file_str = backing_file_str ? backing_file_str : base_bs->filename;
225854e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
22596ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
22606ebdcee2SJeff Cody     if (ret) {
22616ebdcee2SJeff Cody         goto exit;
22626ebdcee2SJeff Cody     }
2263920beae1SFam Zheng     bdrv_set_backing_hd(new_top_bs, base_bs);
22646ebdcee2SJeff Cody 
22656ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
22666ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
2267920beae1SFam Zheng         bdrv_set_backing_hd(intermediate_state->bs, NULL);
22684f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
22696ebdcee2SJeff Cody     }
22706ebdcee2SJeff Cody     ret = 0;
22716ebdcee2SJeff Cody 
22726ebdcee2SJeff Cody exit:
22736ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
22746ebdcee2SJeff Cody         g_free(intermediate_state);
22756ebdcee2SJeff Cody     }
22766ebdcee2SJeff Cody     return ret;
22776ebdcee2SJeff Cody }
22786ebdcee2SJeff Cody 
227983f64091Sbellard /**
228083f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
228183f64091Sbellard  */
228283f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
228383f64091Sbellard {
228483f64091Sbellard     BlockDriver *drv = bs->drv;
228551762288SStefan Hajnoczi     int ret;
228683f64091Sbellard     if (!drv)
228719cb3738Sbellard         return -ENOMEDIUM;
228883f64091Sbellard     if (!drv->bdrv_truncate)
228983f64091Sbellard         return -ENOTSUP;
229059f2689dSNaphtali Sprei     if (bs->read_only)
229159f2689dSNaphtali Sprei         return -EACCES;
22929c75e168SJeff Cody 
229351762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
229451762288SStefan Hajnoczi     if (ret == 0) {
229551762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2296ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2297a7f53e26SMarkus Armbruster         if (bs->blk) {
2298a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2299a7f53e26SMarkus Armbruster         }
230051762288SStefan Hajnoczi     }
230151762288SStefan Hajnoczi     return ret;
230283f64091Sbellard }
230383f64091Sbellard 
230483f64091Sbellard /**
23054a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
23064a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
23074a1d5e1fSFam Zheng  */
23084a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
23094a1d5e1fSFam Zheng {
23104a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
23114a1d5e1fSFam Zheng     if (!drv) {
23124a1d5e1fSFam Zheng         return -ENOMEDIUM;
23134a1d5e1fSFam Zheng     }
23144a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
23154a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
23164a1d5e1fSFam Zheng     }
23174a1d5e1fSFam Zheng     if (bs->file) {
23184a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
23194a1d5e1fSFam Zheng     }
23204a1d5e1fSFam Zheng     return -ENOTSUP;
23214a1d5e1fSFam Zheng }
23224a1d5e1fSFam Zheng 
23234a1d5e1fSFam Zheng /**
232465a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
232583f64091Sbellard  */
232665a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
232783f64091Sbellard {
232883f64091Sbellard     BlockDriver *drv = bs->drv;
232965a9bb25SMarkus Armbruster 
233083f64091Sbellard     if (!drv)
233119cb3738Sbellard         return -ENOMEDIUM;
233251762288SStefan Hajnoczi 
2333b94a2610SKevin Wolf     if (drv->has_variable_length) {
2334b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2335b94a2610SKevin Wolf         if (ret < 0) {
2336b94a2610SKevin Wolf             return ret;
2337fc01f7e7Sbellard         }
233846a4e4e6SStefan Hajnoczi     }
233965a9bb25SMarkus Armbruster     return bs->total_sectors;
234065a9bb25SMarkus Armbruster }
234165a9bb25SMarkus Armbruster 
234265a9bb25SMarkus Armbruster /**
234365a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
234465a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
234565a9bb25SMarkus Armbruster  */
234665a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
234765a9bb25SMarkus Armbruster {
234865a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
234965a9bb25SMarkus Armbruster 
23504a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
235165a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
235246a4e4e6SStefan Hajnoczi }
2353fc01f7e7Sbellard 
235419cb3738Sbellard /* return 0 as number of sectors if no device present or error */
235596b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2356fc01f7e7Sbellard {
235765a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
235865a9bb25SMarkus Armbruster 
235965a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2360fc01f7e7Sbellard }
2361cf98951bSbellard 
2362ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
2363ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
2364abd7f68dSMarkus Armbruster {
2365abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
2366abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
2367abd7f68dSMarkus Armbruster }
2368abd7f68dSMarkus Armbruster 
23691ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
2370abd7f68dSMarkus Armbruster {
2371abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
2372abd7f68dSMarkus Armbruster }
2373abd7f68dSMarkus Armbruster 
23743e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
23753e1caa5fSPaolo Bonzini {
23763e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
23773e1caa5fSPaolo Bonzini 
23783e1caa5fSPaolo Bonzini     switch (on_err) {
23793e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
2380a589569fSWenchao Xia         return (error == ENOSPC) ?
2381a589569fSWenchao Xia                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
23823e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
2383a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_STOP;
23843e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
2385a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_REPORT;
23863e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
2387a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_IGNORE;
23883e1caa5fSPaolo Bonzini     default:
23893e1caa5fSPaolo Bonzini         abort();
23903e1caa5fSPaolo Bonzini     }
23913e1caa5fSPaolo Bonzini }
23923e1caa5fSPaolo Bonzini 
2393c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs,
2394c7c2ff0cSLuiz Capitulino                                  BlockErrorAction action,
2395c7c2ff0cSLuiz Capitulino                                  bool is_read, int error)
2396c7c2ff0cSLuiz Capitulino {
2397573742a5SPeter Maydell     IoOperationType optype;
2398c7c2ff0cSLuiz Capitulino 
2399573742a5SPeter Maydell     optype = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
2400573742a5SPeter Maydell     qapi_event_send_block_io_error(bdrv_get_device_name(bs), optype, action,
2401c7c2ff0cSLuiz Capitulino                                    bdrv_iostatus_is_enabled(bs),
2402624ff573SLuiz Capitulino                                    error == ENOSPC, strerror(error),
2403624ff573SLuiz Capitulino                                    &error_abort);
2404c7c2ff0cSLuiz Capitulino }
2405c7c2ff0cSLuiz Capitulino 
24063e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
24073e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
24083e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
24093e1caa5fSPaolo Bonzini  */
24103e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
24113e1caa5fSPaolo Bonzini                        bool is_read, int error)
24123e1caa5fSPaolo Bonzini {
24133e1caa5fSPaolo Bonzini     assert(error >= 0);
24142bd3bce8SPaolo Bonzini 
2415a589569fSWenchao Xia     if (action == BLOCK_ERROR_ACTION_STOP) {
24162bd3bce8SPaolo Bonzini         /* First set the iostatus, so that "info block" returns an iostatus
24172bd3bce8SPaolo Bonzini          * that matches the events raised so far (an additional error iostatus
24182bd3bce8SPaolo Bonzini          * is fine, but not a lost one).
24192bd3bce8SPaolo Bonzini          */
24203e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
24212bd3bce8SPaolo Bonzini 
24222bd3bce8SPaolo Bonzini         /* Then raise the request to stop the VM and the event.
24232bd3bce8SPaolo Bonzini          * qemu_system_vmstop_request_prepare has two effects.  First,
24242bd3bce8SPaolo Bonzini          * it ensures that the STOP event always comes after the
24252bd3bce8SPaolo Bonzini          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
24262bd3bce8SPaolo Bonzini          * can observe the STOP event and do a "cont" before the STOP
24272bd3bce8SPaolo Bonzini          * event is issued, the VM will not stop.  In this case, vm_start()
24282bd3bce8SPaolo Bonzini          * also ensures that the STOP/RESUME pair of events is emitted.
24292bd3bce8SPaolo Bonzini          */
24302bd3bce8SPaolo Bonzini         qemu_system_vmstop_request_prepare();
2431c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
24322bd3bce8SPaolo Bonzini         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
24332bd3bce8SPaolo Bonzini     } else {
2434c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
24353e1caa5fSPaolo Bonzini     }
24363e1caa5fSPaolo Bonzini }
24373e1caa5fSPaolo Bonzini 
2438b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2439b338082bSbellard {
2440b338082bSbellard     return bs->read_only;
2441b338082bSbellard }
2442b338082bSbellard 
2443985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2444985a03b0Sths {
2445985a03b0Sths     return bs->sg;
2446985a03b0Sths }
2447985a03b0Sths 
2448e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2449e900a7b7SChristoph Hellwig {
2450e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2451e900a7b7SChristoph Hellwig }
2452e900a7b7SChristoph Hellwig 
2453425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2454425b0148SPaolo Bonzini {
2455425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
245655b110f2SJeff Cody 
245755b110f2SJeff Cody     /* so a reopen() will preserve wce */
245855b110f2SJeff Cody     if (wce) {
245955b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
246055b110f2SJeff Cody     } else {
246155b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
246255b110f2SJeff Cody     }
2463425b0148SPaolo Bonzini }
2464425b0148SPaolo Bonzini 
2465ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2466ea2384d3Sbellard {
2467ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
2468ea2384d3Sbellard         return 1;
2469ea2384d3Sbellard     return bs->encrypted;
2470ea2384d3Sbellard }
2471ea2384d3Sbellard 
2472c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2473c0f4ce77Saliguori {
2474c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
2475c0f4ce77Saliguori 
2476c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
2477c0f4ce77Saliguori         return 1;
2478c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2479c0f4ce77Saliguori }
2480c0f4ce77Saliguori 
2481ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2482ea2384d3Sbellard {
2483ea2384d3Sbellard     int ret;
2484ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
2485ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
2486ea2384d3Sbellard         if (ret < 0)
2487ea2384d3Sbellard             return ret;
2488ea2384d3Sbellard         if (!bs->encrypted)
2489ea2384d3Sbellard             return 0;
2490ea2384d3Sbellard     }
2491fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2492fd04a2aeSShahar Havivi         return -EINVAL;
2493fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2494fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2495fd04a2aeSShahar Havivi     }
2496c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2497bb5fc20fSaliguori     if (ret < 0) {
2498bb5fc20fSaliguori         bs->valid_key = 0;
2499bb5fc20fSaliguori     } else if (!bs->valid_key) {
2500bb5fc20fSaliguori         bs->valid_key = 1;
2501a7f53e26SMarkus Armbruster         if (bs->blk) {
2502bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2503a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2504a7f53e26SMarkus Armbruster         }
2505bb5fc20fSaliguori     }
2506c0f4ce77Saliguori     return ret;
2507ea2384d3Sbellard }
2508ea2384d3Sbellard 
25094d2855a3SMarkus Armbruster /*
25104d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
25114d2855a3SMarkus Armbruster  * If @key is non-null:
25124d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
25134d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
25144d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
25154d2855a3SMarkus Armbruster  * If @key is null:
25164d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
25174d2855a3SMarkus Armbruster  *     Else do nothing.
25184d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
25194d2855a3SMarkus Armbruster  */
25204d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
25214d2855a3SMarkus Armbruster {
25224d2855a3SMarkus Armbruster     if (key) {
25234d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
252481e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
252581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
25264d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
25274d2855a3SMarkus Armbruster             error_set(errp, QERR_INVALID_PASSWORD);
25284d2855a3SMarkus Armbruster         }
25294d2855a3SMarkus Armbruster     } else {
25304d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2531b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2532b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
253381e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
25344d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
25354d2855a3SMarkus Armbruster         }
25364d2855a3SMarkus Armbruster     }
25374d2855a3SMarkus Armbruster }
25384d2855a3SMarkus Armbruster 
2539f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2540ea2384d3Sbellard {
2541f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2542ea2384d3Sbellard }
2543ea2384d3Sbellard 
2544ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2545ada42401SStefan Hajnoczi {
2546ada42401SStefan Hajnoczi     return strcmp(a, b);
2547ada42401SStefan Hajnoczi }
2548ada42401SStefan Hajnoczi 
2549ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2550ea2384d3Sbellard                          void *opaque)
2551ea2384d3Sbellard {
2552ea2384d3Sbellard     BlockDriver *drv;
2553e855e4fbSJeff Cody     int count = 0;
2554ada42401SStefan Hajnoczi     int i;
2555e855e4fbSJeff Cody     const char **formats = NULL;
2556ea2384d3Sbellard 
25578a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2558e855e4fbSJeff Cody         if (drv->format_name) {
2559e855e4fbSJeff Cody             bool found = false;
2560e855e4fbSJeff Cody             int i = count;
2561e855e4fbSJeff Cody             while (formats && i && !found) {
2562e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2563e855e4fbSJeff Cody             }
2564e855e4fbSJeff Cody 
2565e855e4fbSJeff Cody             if (!found) {
25665839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2567e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2568ea2384d3Sbellard             }
2569ea2384d3Sbellard         }
2570e855e4fbSJeff Cody     }
2571ada42401SStefan Hajnoczi 
2572ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2573ada42401SStefan Hajnoczi 
2574ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2575ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2576ada42401SStefan Hajnoczi     }
2577ada42401SStefan Hajnoczi 
2578e855e4fbSJeff Cody     g_free(formats);
2579e855e4fbSJeff Cody }
2580ea2384d3Sbellard 
2581dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2582dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2583dc364f4cSBenoît Canet {
2584dc364f4cSBenoît Canet     BlockDriverState *bs;
2585dc364f4cSBenoît Canet 
2586dc364f4cSBenoît Canet     assert(node_name);
2587dc364f4cSBenoît Canet 
2588dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2589dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2590dc364f4cSBenoît Canet             return bs;
2591dc364f4cSBenoît Canet         }
2592dc364f4cSBenoît Canet     }
2593dc364f4cSBenoît Canet     return NULL;
2594dc364f4cSBenoît Canet }
2595dc364f4cSBenoît Canet 
2596c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2597d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2598c13163fbSBenoît Canet {
2599c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2600c13163fbSBenoît Canet     BlockDriverState *bs;
2601c13163fbSBenoît Canet 
2602c13163fbSBenoît Canet     list = NULL;
2603c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2604d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2605d5a8ee60SAlberto Garcia         if (!info) {
2606d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2607d5a8ee60SAlberto Garcia             return NULL;
2608d5a8ee60SAlberto Garcia         }
2609c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2610d5a8ee60SAlberto Garcia         entry->value = info;
2611c13163fbSBenoît Canet         entry->next = list;
2612c13163fbSBenoît Canet         list = entry;
2613c13163fbSBenoît Canet     }
2614c13163fbSBenoît Canet 
2615c13163fbSBenoît Canet     return list;
2616c13163fbSBenoît Canet }
2617c13163fbSBenoît Canet 
261812d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
261912d3ba82SBenoît Canet                                  const char *node_name,
262012d3ba82SBenoît Canet                                  Error **errp)
262112d3ba82SBenoît Canet {
26227f06d47eSMarkus Armbruster     BlockBackend *blk;
26237f06d47eSMarkus Armbruster     BlockDriverState *bs;
262412d3ba82SBenoît Canet 
262512d3ba82SBenoît Canet     if (device) {
26267f06d47eSMarkus Armbruster         blk = blk_by_name(device);
262712d3ba82SBenoît Canet 
26287f06d47eSMarkus Armbruster         if (blk) {
26297f06d47eSMarkus Armbruster             return blk_bs(blk);
263012d3ba82SBenoît Canet         }
2631dd67fa50SBenoît Canet     }
263212d3ba82SBenoît Canet 
2633dd67fa50SBenoît Canet     if (node_name) {
263412d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
263512d3ba82SBenoît Canet 
2636dd67fa50SBenoît Canet         if (bs) {
2637dd67fa50SBenoît Canet             return bs;
2638dd67fa50SBenoît Canet         }
263912d3ba82SBenoît Canet     }
264012d3ba82SBenoît Canet 
2641dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2642dd67fa50SBenoît Canet                      device ? device : "",
2643dd67fa50SBenoît Canet                      node_name ? node_name : "");
2644dd67fa50SBenoît Canet     return NULL;
264512d3ba82SBenoît Canet }
264612d3ba82SBenoît Canet 
26475a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
26485a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
26495a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
26505a6684d2SJeff Cody {
26515a6684d2SJeff Cody     while (top && top != base) {
26525a6684d2SJeff Cody         top = top->backing_hd;
26535a6684d2SJeff Cody     }
26545a6684d2SJeff Cody 
26555a6684d2SJeff Cody     return top != NULL;
26565a6684d2SJeff Cody }
26575a6684d2SJeff Cody 
265804df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
265904df765aSFam Zheng {
266004df765aSFam Zheng     if (!bs) {
266104df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
266204df765aSFam Zheng     }
266304df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
266404df765aSFam Zheng }
266504df765aSFam Zheng 
26662f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
26672f399b0aSMarkus Armbruster {
26682f399b0aSMarkus Armbruster     if (!bs) {
26692f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
26702f399b0aSMarkus Armbruster     }
2671dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
26722f399b0aSMarkus Armbruster }
26732f399b0aSMarkus Armbruster 
267420a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
267520a9e77dSFam Zheng {
267620a9e77dSFam Zheng     return bs->node_name;
267720a9e77dSFam Zheng }
267820a9e77dSFam Zheng 
26797f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2680bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2681ea2384d3Sbellard {
2682bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2683ea2384d3Sbellard }
2684ea2384d3Sbellard 
26859b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
26869b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
26879b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
26889b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
26899b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
26909b2aa84fSAlberto Garcia {
26919b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
26929b2aa84fSAlberto Garcia }
26939b2aa84fSAlberto Garcia 
2694c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
2695c8433287SMarkus Armbruster {
2696c8433287SMarkus Armbruster     return bs->open_flags;
2697c8433287SMarkus Armbruster }
2698c8433287SMarkus Armbruster 
26993ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
27003ac21627SPeter Lieven {
27013ac21627SPeter Lieven     return 1;
27023ac21627SPeter Lieven }
27033ac21627SPeter Lieven 
2704f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
2705f2feebbdSKevin Wolf {
2706f2feebbdSKevin Wolf     assert(bs->drv);
2707f2feebbdSKevin Wolf 
270811212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
270911212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
271011212d8fSPaolo Bonzini     if (bs->backing_hd) {
271111212d8fSPaolo Bonzini         return 0;
271211212d8fSPaolo Bonzini     }
2713336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
2714336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
2715f2feebbdSKevin Wolf     }
2716f2feebbdSKevin Wolf 
27173ac21627SPeter Lieven     /* safe default */
27183ac21627SPeter Lieven     return 0;
2719f2feebbdSKevin Wolf }
2720f2feebbdSKevin Wolf 
27214ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
27224ce78691SPeter Lieven {
27234ce78691SPeter Lieven     BlockDriverInfo bdi;
27244ce78691SPeter Lieven 
27254ce78691SPeter Lieven     if (bs->backing_hd) {
27264ce78691SPeter Lieven         return false;
27274ce78691SPeter Lieven     }
27284ce78691SPeter Lieven 
27294ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
27304ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
27314ce78691SPeter Lieven     }
27324ce78691SPeter Lieven 
27334ce78691SPeter Lieven     return false;
27344ce78691SPeter Lieven }
27354ce78691SPeter Lieven 
27364ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
27374ce78691SPeter Lieven {
27384ce78691SPeter Lieven     BlockDriverInfo bdi;
27394ce78691SPeter Lieven 
27404ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
27414ce78691SPeter Lieven         return false;
27424ce78691SPeter Lieven     }
27434ce78691SPeter Lieven 
27444ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
27454ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
27464ce78691SPeter Lieven     }
27474ce78691SPeter Lieven 
27484ce78691SPeter Lieven     return false;
27494ce78691SPeter Lieven }
27504ce78691SPeter Lieven 
2751045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
2752045df330Saliguori {
2753045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
2754045df330Saliguori         return bs->backing_file;
2755045df330Saliguori     else if (bs->encrypted)
2756045df330Saliguori         return bs->filename;
2757045df330Saliguori     else
2758045df330Saliguori         return NULL;
2759045df330Saliguori }
2760045df330Saliguori 
276183f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
276283f64091Sbellard                                char *filename, int filename_size)
276383f64091Sbellard {
276483f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
276583f64091Sbellard }
276683f64091Sbellard 
2767faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
2768faea38e7Sbellard {
2769faea38e7Sbellard     BlockDriver *drv = bs->drv;
2770faea38e7Sbellard     if (!drv)
277119cb3738Sbellard         return -ENOMEDIUM;
2772faea38e7Sbellard     if (!drv->bdrv_get_info)
2773faea38e7Sbellard         return -ENOTSUP;
2774faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
2775faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
2776faea38e7Sbellard }
2777faea38e7Sbellard 
2778eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
2779eae041feSMax Reitz {
2780eae041feSMax Reitz     BlockDriver *drv = bs->drv;
2781eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
2782eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
2783eae041feSMax Reitz     }
2784eae041feSMax Reitz     return NULL;
2785eae041feSMax Reitz }
2786eae041feSMax Reitz 
27878b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
27888b9b0cc2SKevin Wolf {
2789bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
27908b9b0cc2SKevin Wolf         return;
27918b9b0cc2SKevin Wolf     }
27928b9b0cc2SKevin Wolf 
2793bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
279441c695c7SKevin Wolf }
27958b9b0cc2SKevin Wolf 
279641c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
279741c695c7SKevin Wolf                           const char *tag)
279841c695c7SKevin Wolf {
279941c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
280041c695c7SKevin Wolf         bs = bs->file;
280141c695c7SKevin Wolf     }
280241c695c7SKevin Wolf 
280341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
280441c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
280541c695c7SKevin Wolf     }
280641c695c7SKevin Wolf 
280741c695c7SKevin Wolf     return -ENOTSUP;
280841c695c7SKevin Wolf }
280941c695c7SKevin Wolf 
28104cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
28114cc70e93SFam Zheng {
28124cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
28134cc70e93SFam Zheng         bs = bs->file;
28144cc70e93SFam Zheng     }
28154cc70e93SFam Zheng 
28164cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
28174cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
28184cc70e93SFam Zheng     }
28194cc70e93SFam Zheng 
28204cc70e93SFam Zheng     return -ENOTSUP;
28214cc70e93SFam Zheng }
28224cc70e93SFam Zheng 
282341c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
282441c695c7SKevin Wolf {
2825938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
282641c695c7SKevin Wolf         bs = bs->file;
282741c695c7SKevin Wolf     }
282841c695c7SKevin Wolf 
282941c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
283041c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
283141c695c7SKevin Wolf     }
283241c695c7SKevin Wolf 
283341c695c7SKevin Wolf     return -ENOTSUP;
283441c695c7SKevin Wolf }
283541c695c7SKevin Wolf 
283641c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
283741c695c7SKevin Wolf {
283841c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
283941c695c7SKevin Wolf         bs = bs->file;
284041c695c7SKevin Wolf     }
284141c695c7SKevin Wolf 
284241c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
284341c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
284441c695c7SKevin Wolf     }
284541c695c7SKevin Wolf 
284641c695c7SKevin Wolf     return false;
28478b9b0cc2SKevin Wolf }
28488b9b0cc2SKevin Wolf 
2849199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
2850199630b6SBlue Swirl {
2851199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
2852199630b6SBlue Swirl }
2853199630b6SBlue Swirl 
2854b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
2855b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
2856b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
2857b1b1d783SJeff Cody  * the CWD rather than the chain. */
2858e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
2859e8a6bb9cSMarcelo Tosatti         const char *backing_file)
2860e8a6bb9cSMarcelo Tosatti {
2861b1b1d783SJeff Cody     char *filename_full = NULL;
2862b1b1d783SJeff Cody     char *backing_file_full = NULL;
2863b1b1d783SJeff Cody     char *filename_tmp = NULL;
2864b1b1d783SJeff Cody     int is_protocol = 0;
2865b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
2866b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
2867b1b1d783SJeff Cody 
2868b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
2869e8a6bb9cSMarcelo Tosatti         return NULL;
2870e8a6bb9cSMarcelo Tosatti     }
2871e8a6bb9cSMarcelo Tosatti 
2872b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
2873b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
2874b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
2875b1b1d783SJeff Cody 
2876b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
2877b1b1d783SJeff Cody 
2878b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
2879b1b1d783SJeff Cody 
2880b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
2881b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
2882b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
2883b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
2884b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
2885b1b1d783SJeff Cody                 break;
2886b1b1d783SJeff Cody             }
2887e8a6bb9cSMarcelo Tosatti         } else {
2888b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
2889b1b1d783SJeff Cody              * image's filename path */
2890b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2891b1b1d783SJeff Cody                          backing_file);
2892b1b1d783SJeff Cody 
2893b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
2894b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
2895b1b1d783SJeff Cody                 continue;
2896b1b1d783SJeff Cody             }
2897b1b1d783SJeff Cody 
2898b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
2899b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
2900b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
2901b1b1d783SJeff Cody                          curr_bs->backing_file);
2902b1b1d783SJeff Cody 
2903b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
2904b1b1d783SJeff Cody                 continue;
2905b1b1d783SJeff Cody             }
2906b1b1d783SJeff Cody 
2907b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
2908b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
2909b1b1d783SJeff Cody                 break;
2910b1b1d783SJeff Cody             }
2911e8a6bb9cSMarcelo Tosatti         }
2912e8a6bb9cSMarcelo Tosatti     }
2913e8a6bb9cSMarcelo Tosatti 
2914b1b1d783SJeff Cody     g_free(filename_full);
2915b1b1d783SJeff Cody     g_free(backing_file_full);
2916b1b1d783SJeff Cody     g_free(filename_tmp);
2917b1b1d783SJeff Cody     return retval;
2918e8a6bb9cSMarcelo Tosatti }
2919e8a6bb9cSMarcelo Tosatti 
2920f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
2921f198fd1cSBenoît Canet {
2922f198fd1cSBenoît Canet     if (!bs->drv) {
2923f198fd1cSBenoît Canet         return 0;
2924f198fd1cSBenoît Canet     }
2925f198fd1cSBenoît Canet 
2926f198fd1cSBenoît Canet     if (!bs->backing_hd) {
2927f198fd1cSBenoît Canet         return 0;
2928f198fd1cSBenoît Canet     }
2929f198fd1cSBenoît Canet 
2930f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
2931f198fd1cSBenoît Canet }
2932f198fd1cSBenoît Canet 
2933ea2384d3Sbellard void bdrv_init(void)
2934ea2384d3Sbellard {
29355efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
2936ea2384d3Sbellard }
2937ce1a14dcSpbrook 
2938eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
2939eb852011SMarkus Armbruster {
2940eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
2941eb852011SMarkus Armbruster     bdrv_init();
2942eb852011SMarkus Armbruster }
2943eb852011SMarkus Armbruster 
29445a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
29450f15423cSAnthony Liguori {
29465a8a30dbSKevin Wolf     Error *local_err = NULL;
29475a8a30dbSKevin Wolf     int ret;
29485a8a30dbSKevin Wolf 
29493456a8d1SKevin Wolf     if (!bs->drv)  {
29503456a8d1SKevin Wolf         return;
29510f15423cSAnthony Liguori     }
29523456a8d1SKevin Wolf 
29537ea2d269SAlexey Kardashevskiy     if (!(bs->open_flags & BDRV_O_INCOMING)) {
29547ea2d269SAlexey Kardashevskiy         return;
29557ea2d269SAlexey Kardashevskiy     }
29567ea2d269SAlexey Kardashevskiy     bs->open_flags &= ~BDRV_O_INCOMING;
29577ea2d269SAlexey Kardashevskiy 
29583456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
29595a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
29603456a8d1SKevin Wolf     } else if (bs->file) {
29615a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
29625a8a30dbSKevin Wolf     }
29635a8a30dbSKevin Wolf     if (local_err) {
29645a8a30dbSKevin Wolf         error_propagate(errp, local_err);
29655a8a30dbSKevin Wolf         return;
29663456a8d1SKevin Wolf     }
29673456a8d1SKevin Wolf 
29685a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
29695a8a30dbSKevin Wolf     if (ret < 0) {
29705a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
29715a8a30dbSKevin Wolf         return;
29725a8a30dbSKevin Wolf     }
29730f15423cSAnthony Liguori }
29740f15423cSAnthony Liguori 
29755a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
29760f15423cSAnthony Liguori {
29770f15423cSAnthony Liguori     BlockDriverState *bs;
29785a8a30dbSKevin Wolf     Error *local_err = NULL;
29790f15423cSAnthony Liguori 
2980dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2981ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2982ed78cda3SStefan Hajnoczi 
2983ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
29845a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
2985ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
29865a8a30dbSKevin Wolf         if (local_err) {
29875a8a30dbSKevin Wolf             error_propagate(errp, local_err);
29885a8a30dbSKevin Wolf             return;
29895a8a30dbSKevin Wolf         }
29900f15423cSAnthony Liguori     }
29910f15423cSAnthony Liguori }
29920f15423cSAnthony Liguori 
2993f9f05dc5SKevin Wolf /**************************************************************/
299419cb3738Sbellard /* removable device support */
299519cb3738Sbellard 
299619cb3738Sbellard /**
299719cb3738Sbellard  * Return TRUE if the media is present
299819cb3738Sbellard  */
299919cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
300019cb3738Sbellard {
300119cb3738Sbellard     BlockDriver *drv = bs->drv;
3002a1aff5bfSMarkus Armbruster 
300319cb3738Sbellard     if (!drv)
300419cb3738Sbellard         return 0;
300519cb3738Sbellard     if (!drv->bdrv_is_inserted)
3006a1aff5bfSMarkus Armbruster         return 1;
3007a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
300819cb3738Sbellard }
300919cb3738Sbellard 
301019cb3738Sbellard /**
30118e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
30128e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
301319cb3738Sbellard  */
301419cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
301519cb3738Sbellard {
301619cb3738Sbellard     BlockDriver *drv = bs->drv;
301719cb3738Sbellard 
30188e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
30198e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
30208e49ca46SMarkus Armbruster     }
30218e49ca46SMarkus Armbruster     return -ENOTSUP;
302219cb3738Sbellard }
302319cb3738Sbellard 
302419cb3738Sbellard /**
302519cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
302619cb3738Sbellard  */
3027f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
302819cb3738Sbellard {
302919cb3738Sbellard     BlockDriver *drv = bs->drv;
3030bfb197e0SMarkus Armbruster     const char *device_name;
303119cb3738Sbellard 
3032822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3033822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
303419cb3738Sbellard     }
30356f382ed2SLuiz Capitulino 
3036bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3037bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3038bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3039a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
30406f382ed2SLuiz Capitulino     }
304119cb3738Sbellard }
304219cb3738Sbellard 
304319cb3738Sbellard /**
304419cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
304519cb3738Sbellard  * to eject it manually).
304619cb3738Sbellard  */
3047025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
304819cb3738Sbellard {
304919cb3738Sbellard     BlockDriver *drv = bs->drv;
305019cb3738Sbellard 
3051025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3052b8c6d095SStefan Hajnoczi 
3053025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3054025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
305519cb3738Sbellard     }
305619cb3738Sbellard }
3057985a03b0Sths 
30581b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
30597b6f9300SMarkus Armbruster {
30601b7fd729SPaolo Bonzini     bs->guest_block_size = align;
30617b6f9300SMarkus Armbruster }
30627cd1e32aSlirans@il.ibm.com 
30630db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_find_dirty_bitmap(BlockDriverState *bs, const char *name)
30640db6e54aSFam Zheng {
30650db6e54aSFam Zheng     BdrvDirtyBitmap *bm;
30660db6e54aSFam Zheng 
30670db6e54aSFam Zheng     assert(name);
30680db6e54aSFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
30690db6e54aSFam Zheng         if (bm->name && !strcmp(name, bm->name)) {
30700db6e54aSFam Zheng             return bm;
30710db6e54aSFam Zheng         }
30720db6e54aSFam Zheng     }
30730db6e54aSFam Zheng     return NULL;
30740db6e54aSFam Zheng }
30750db6e54aSFam Zheng 
307620dca810SJohn Snow void bdrv_dirty_bitmap_make_anon(BdrvDirtyBitmap *bitmap)
30770db6e54aSFam Zheng {
30789bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
30790db6e54aSFam Zheng     g_free(bitmap->name);
30800db6e54aSFam Zheng     bitmap->name = NULL;
30810db6e54aSFam Zheng }
30820db6e54aSFam Zheng 
30830db6e54aSFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs,
30845fba6c0eSJohn Snow                                           uint32_t granularity,
30850db6e54aSFam Zheng                                           const char *name,
3086b8afb520SFam Zheng                                           Error **errp)
30877cd1e32aSlirans@il.ibm.com {
30887cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
3089e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
30905fba6c0eSJohn Snow     uint32_t sector_granularity;
3091a55eb92cSJan Kiszka 
309250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
309350717e94SPaolo Bonzini 
30940db6e54aSFam Zheng     if (name && bdrv_find_dirty_bitmap(bs, name)) {
30950db6e54aSFam Zheng         error_setg(errp, "Bitmap already exists: %s", name);
30960db6e54aSFam Zheng         return NULL;
30970db6e54aSFam Zheng     }
30985fba6c0eSJohn Snow     sector_granularity = granularity >> BDRV_SECTOR_BITS;
30995fba6c0eSJohn Snow     assert(sector_granularity);
310057322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
3101b8afb520SFam Zheng     if (bitmap_size < 0) {
3102b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
3103b8afb520SFam Zheng         errno = -bitmap_size;
3104b8afb520SFam Zheng         return NULL;
3105b8afb520SFam Zheng     }
31065839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
31075fba6c0eSJohn Snow     bitmap->bitmap = hbitmap_alloc(bitmap_size, ctz32(sector_granularity));
3108e74e6b78SJohn Snow     bitmap->size = bitmap_size;
31090db6e54aSFam Zheng     bitmap->name = g_strdup(name);
3110b8e6fb75SJohn Snow     bitmap->disabled = false;
3111e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
3112e4654d2dSFam Zheng     return bitmap;
3113e4654d2dSFam Zheng }
3114e4654d2dSFam Zheng 
31159bd2b08fSJohn Snow bool bdrv_dirty_bitmap_frozen(BdrvDirtyBitmap *bitmap)
31169bd2b08fSJohn Snow {
31179bd2b08fSJohn Snow     return bitmap->successor;
31189bd2b08fSJohn Snow }
31199bd2b08fSJohn Snow 
3120b8e6fb75SJohn Snow bool bdrv_dirty_bitmap_enabled(BdrvDirtyBitmap *bitmap)
3121b8e6fb75SJohn Snow {
31229bd2b08fSJohn Snow     return !(bitmap->disabled || bitmap->successor);
31239bd2b08fSJohn Snow }
31249bd2b08fSJohn Snow 
31259abe3bdcSJohn Snow DirtyBitmapStatus bdrv_dirty_bitmap_status(BdrvDirtyBitmap *bitmap)
31269abe3bdcSJohn Snow {
31279abe3bdcSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
31289abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_FROZEN;
31299abe3bdcSJohn Snow     } else if (!bdrv_dirty_bitmap_enabled(bitmap)) {
31309abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_DISABLED;
31319abe3bdcSJohn Snow     } else {
31329abe3bdcSJohn Snow         return DIRTY_BITMAP_STATUS_ACTIVE;
31339abe3bdcSJohn Snow     }
31349abe3bdcSJohn Snow }
31359abe3bdcSJohn Snow 
31369bd2b08fSJohn Snow /**
31379bd2b08fSJohn Snow  * Create a successor bitmap destined to replace this bitmap after an operation.
31389bd2b08fSJohn Snow  * Requires that the bitmap is not frozen and has no successor.
31399bd2b08fSJohn Snow  */
31409bd2b08fSJohn Snow int bdrv_dirty_bitmap_create_successor(BlockDriverState *bs,
31419bd2b08fSJohn Snow                                        BdrvDirtyBitmap *bitmap, Error **errp)
31429bd2b08fSJohn Snow {
31439bd2b08fSJohn Snow     uint64_t granularity;
31449bd2b08fSJohn Snow     BdrvDirtyBitmap *child;
31459bd2b08fSJohn Snow 
31469bd2b08fSJohn Snow     if (bdrv_dirty_bitmap_frozen(bitmap)) {
31479bd2b08fSJohn Snow         error_setg(errp, "Cannot create a successor for a bitmap that is "
31489bd2b08fSJohn Snow                    "currently frozen");
31499bd2b08fSJohn Snow         return -1;
31509bd2b08fSJohn Snow     }
31519bd2b08fSJohn Snow     assert(!bitmap->successor);
31529bd2b08fSJohn Snow 
31539bd2b08fSJohn Snow     /* Create an anonymous successor */
31549bd2b08fSJohn Snow     granularity = bdrv_dirty_bitmap_granularity(bitmap);
31559bd2b08fSJohn Snow     child = bdrv_create_dirty_bitmap(bs, granularity, NULL, errp);
31569bd2b08fSJohn Snow     if (!child) {
31579bd2b08fSJohn Snow         return -1;
31589bd2b08fSJohn Snow     }
31599bd2b08fSJohn Snow 
31609bd2b08fSJohn Snow     /* Successor will be on or off based on our current state. */
31619bd2b08fSJohn Snow     child->disabled = bitmap->disabled;
31629bd2b08fSJohn Snow 
31639bd2b08fSJohn Snow     /* Install the successor and freeze the parent */
31649bd2b08fSJohn Snow     bitmap->successor = child;
31659bd2b08fSJohn Snow     return 0;
31669bd2b08fSJohn Snow }
31679bd2b08fSJohn Snow 
31689bd2b08fSJohn Snow /**
31699bd2b08fSJohn Snow  * For a bitmap with a successor, yield our name to the successor,
31709bd2b08fSJohn Snow  * delete the old bitmap, and return a handle to the new bitmap.
31719bd2b08fSJohn Snow  */
31729bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_dirty_bitmap_abdicate(BlockDriverState *bs,
31739bd2b08fSJohn Snow                                             BdrvDirtyBitmap *bitmap,
31749bd2b08fSJohn Snow                                             Error **errp)
31759bd2b08fSJohn Snow {
31769bd2b08fSJohn Snow     char *name;
31779bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = bitmap->successor;
31789bd2b08fSJohn Snow 
31799bd2b08fSJohn Snow     if (successor == NULL) {
31809bd2b08fSJohn Snow         error_setg(errp, "Cannot relinquish control if "
31819bd2b08fSJohn Snow                    "there's no successor present");
31829bd2b08fSJohn Snow         return NULL;
31839bd2b08fSJohn Snow     }
31849bd2b08fSJohn Snow 
31859bd2b08fSJohn Snow     name = bitmap->name;
31869bd2b08fSJohn Snow     bitmap->name = NULL;
31879bd2b08fSJohn Snow     successor->name = name;
31889bd2b08fSJohn Snow     bitmap->successor = NULL;
31899bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, bitmap);
31909bd2b08fSJohn Snow 
31919bd2b08fSJohn Snow     return successor;
31929bd2b08fSJohn Snow }
31939bd2b08fSJohn Snow 
31949bd2b08fSJohn Snow /**
31959bd2b08fSJohn Snow  * In cases of failure where we can no longer safely delete the parent,
31969bd2b08fSJohn Snow  * we may wish to re-join the parent and child/successor.
31979bd2b08fSJohn Snow  * The merged parent will be un-frozen, but not explicitly re-enabled.
31989bd2b08fSJohn Snow  */
31999bd2b08fSJohn Snow BdrvDirtyBitmap *bdrv_reclaim_dirty_bitmap(BlockDriverState *bs,
32009bd2b08fSJohn Snow                                            BdrvDirtyBitmap *parent,
32019bd2b08fSJohn Snow                                            Error **errp)
32029bd2b08fSJohn Snow {
32039bd2b08fSJohn Snow     BdrvDirtyBitmap *successor = parent->successor;
32049bd2b08fSJohn Snow 
32059bd2b08fSJohn Snow     if (!successor) {
32069bd2b08fSJohn Snow         error_setg(errp, "Cannot reclaim a successor when none is present");
32079bd2b08fSJohn Snow         return NULL;
32089bd2b08fSJohn Snow     }
32099bd2b08fSJohn Snow 
32109bd2b08fSJohn Snow     if (!hbitmap_merge(parent->bitmap, successor->bitmap)) {
32119bd2b08fSJohn Snow         error_setg(errp, "Merging of parent and successor bitmap failed");
32129bd2b08fSJohn Snow         return NULL;
32139bd2b08fSJohn Snow     }
32149bd2b08fSJohn Snow     bdrv_release_dirty_bitmap(bs, successor);
32159bd2b08fSJohn Snow     parent->successor = NULL;
32169bd2b08fSJohn Snow 
32179bd2b08fSJohn Snow     return parent;
3218b8e6fb75SJohn Snow }
3219b8e6fb75SJohn Snow 
3220ce1ffea8SJohn Snow /**
3221ce1ffea8SJohn Snow  * Truncates _all_ bitmaps attached to a BDS.
3222ce1ffea8SJohn Snow  */
3223ce1ffea8SJohn Snow static void bdrv_dirty_bitmap_truncate(BlockDriverState *bs)
3224ce1ffea8SJohn Snow {
3225ce1ffea8SJohn Snow     BdrvDirtyBitmap *bitmap;
3226ce1ffea8SJohn Snow     uint64_t size = bdrv_nb_sectors(bs);
3227ce1ffea8SJohn Snow 
3228ce1ffea8SJohn Snow     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3229ce1ffea8SJohn Snow         if (bdrv_dirty_bitmap_frozen(bitmap)) {
3230ce1ffea8SJohn Snow             continue;
3231ce1ffea8SJohn Snow         }
3232ce1ffea8SJohn Snow         hbitmap_truncate(bitmap->bitmap, size);
3233ce1ffea8SJohn Snow     }
3234ce1ffea8SJohn Snow }
3235ce1ffea8SJohn Snow 
3236e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
3237e4654d2dSFam Zheng {
3238e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
3239e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
3240e4654d2dSFam Zheng         if (bm == bitmap) {
32419bd2b08fSJohn Snow             assert(!bdrv_dirty_bitmap_frozen(bm));
3242e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
3243e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
32440db6e54aSFam Zheng             g_free(bitmap->name);
3245e4654d2dSFam Zheng             g_free(bitmap);
3246e4654d2dSFam Zheng             return;
32477cd1e32aSlirans@il.ibm.com         }
32487cd1e32aSlirans@il.ibm.com     }
32497cd1e32aSlirans@il.ibm.com }
32507cd1e32aSlirans@il.ibm.com 
3251b8e6fb75SJohn Snow void bdrv_disable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3252b8e6fb75SJohn Snow {
32539bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3254b8e6fb75SJohn Snow     bitmap->disabled = true;
3255b8e6fb75SJohn Snow }
3256b8e6fb75SJohn Snow 
3257b8e6fb75SJohn Snow void bdrv_enable_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3258b8e6fb75SJohn Snow {
32599bd2b08fSJohn Snow     assert(!bdrv_dirty_bitmap_frozen(bitmap));
3260b8e6fb75SJohn Snow     bitmap->disabled = false;
3261b8e6fb75SJohn Snow }
3262b8e6fb75SJohn Snow 
326321b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
326421b56835SFam Zheng {
326521b56835SFam Zheng     BdrvDirtyBitmap *bm;
326621b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
326721b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
326821b56835SFam Zheng 
326921b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
32705839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
32715839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
327220dca810SJohn Snow         info->count = bdrv_get_dirty_count(bm);
3273592fdd02SJohn Snow         info->granularity = bdrv_dirty_bitmap_granularity(bm);
32740db6e54aSFam Zheng         info->has_name = !!bm->name;
32750db6e54aSFam Zheng         info->name = g_strdup(bm->name);
32769abe3bdcSJohn Snow         info->status = bdrv_dirty_bitmap_status(bm);
327721b56835SFam Zheng         entry->value = info;
327821b56835SFam Zheng         *plist = entry;
327921b56835SFam Zheng         plist = &entry->next;
328021b56835SFam Zheng     }
328121b56835SFam Zheng 
328221b56835SFam Zheng     return list;
328321b56835SFam Zheng }
328421b56835SFam Zheng 
3285e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
32867cd1e32aSlirans@il.ibm.com {
3287e4654d2dSFam Zheng     if (bitmap) {
3288e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
32897cd1e32aSlirans@il.ibm.com     } else {
32907cd1e32aSlirans@il.ibm.com         return 0;
32917cd1e32aSlirans@il.ibm.com     }
32927cd1e32aSlirans@il.ibm.com }
32937cd1e32aSlirans@il.ibm.com 
3294341ebc2fSJohn Snow /**
3295341ebc2fSJohn Snow  * Chooses a default granularity based on the existing cluster size,
3296341ebc2fSJohn Snow  * but clamped between [4K, 64K]. Defaults to 64K in the case that there
3297341ebc2fSJohn Snow  * is no cluster size information available.
3298341ebc2fSJohn Snow  */
3299341ebc2fSJohn Snow uint32_t bdrv_get_default_bitmap_granularity(BlockDriverState *bs)
3300341ebc2fSJohn Snow {
3301341ebc2fSJohn Snow     BlockDriverInfo bdi;
3302341ebc2fSJohn Snow     uint32_t granularity;
3303341ebc2fSJohn Snow 
3304341ebc2fSJohn Snow     if (bdrv_get_info(bs, &bdi) >= 0 && bdi.cluster_size > 0) {
3305341ebc2fSJohn Snow         granularity = MAX(4096, bdi.cluster_size);
3306341ebc2fSJohn Snow         granularity = MIN(65536, granularity);
3307341ebc2fSJohn Snow     } else {
3308341ebc2fSJohn Snow         granularity = 65536;
3309341ebc2fSJohn Snow     }
3310341ebc2fSJohn Snow 
3311341ebc2fSJohn Snow     return granularity;
3312341ebc2fSJohn Snow }
3313341ebc2fSJohn Snow 
3314592fdd02SJohn Snow uint32_t bdrv_dirty_bitmap_granularity(BdrvDirtyBitmap *bitmap)
3315592fdd02SJohn Snow {
3316592fdd02SJohn Snow     return BDRV_SECTOR_SIZE << hbitmap_granularity(bitmap->bitmap);
3317592fdd02SJohn Snow }
3318592fdd02SJohn Snow 
331920dca810SJohn Snow void bdrv_dirty_iter_init(BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
33201755da16SPaolo Bonzini {
3321e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
33221755da16SPaolo Bonzini }
33231755da16SPaolo Bonzini 
332420dca810SJohn Snow void bdrv_set_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3325c4237dfaSVladimir Sementsov-Ogievskiy                            int64_t cur_sector, int nr_sectors)
3326c4237dfaSVladimir Sementsov-Ogievskiy {
3327b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3328c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3329c4237dfaSVladimir Sementsov-Ogievskiy }
3330c4237dfaSVladimir Sementsov-Ogievskiy 
333120dca810SJohn Snow void bdrv_reset_dirty_bitmap(BdrvDirtyBitmap *bitmap,
3332c4237dfaSVladimir Sementsov-Ogievskiy                              int64_t cur_sector, int nr_sectors)
3333c4237dfaSVladimir Sementsov-Ogievskiy {
3334b8e6fb75SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3335c4237dfaSVladimir Sementsov-Ogievskiy     hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3336c4237dfaSVladimir Sementsov-Ogievskiy }
3337c4237dfaSVladimir Sementsov-Ogievskiy 
3338e74e6b78SJohn Snow void bdrv_clear_dirty_bitmap(BdrvDirtyBitmap *bitmap)
3339e74e6b78SJohn Snow {
3340e74e6b78SJohn Snow     assert(bdrv_dirty_bitmap_enabled(bitmap));
3341e74e6b78SJohn Snow     hbitmap_reset(bitmap->bitmap, 0, bitmap->size);
3342e74e6b78SJohn Snow }
3343e74e6b78SJohn Snow 
3344e0c47b6cSStefan Hajnoczi void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
33451755da16SPaolo Bonzini                     int nr_sectors)
33461755da16SPaolo Bonzini {
3347e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3348e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3349b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3350b8e6fb75SJohn Snow             continue;
3351b8e6fb75SJohn Snow         }
3352e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
3353e4654d2dSFam Zheng     }
33541755da16SPaolo Bonzini }
33551755da16SPaolo Bonzini 
3356e0c47b6cSStefan Hajnoczi void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector,
3357c4237dfaSVladimir Sementsov-Ogievskiy                       int nr_sectors)
33587cd1e32aSlirans@il.ibm.com {
3359e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
3360e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
3361b8e6fb75SJohn Snow         if (!bdrv_dirty_bitmap_enabled(bitmap)) {
3362b8e6fb75SJohn Snow             continue;
3363b8e6fb75SJohn Snow         }
3364e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
3365e4654d2dSFam Zheng     }
33667cd1e32aSlirans@il.ibm.com }
3367aaa0eb75SLiran Schour 
3368d58d8453SJohn Snow /**
3369d58d8453SJohn Snow  * Advance an HBitmapIter to an arbitrary offset.
3370d58d8453SJohn Snow  */
3371d58d8453SJohn Snow void bdrv_set_dirty_iter(HBitmapIter *hbi, int64_t offset)
3372d58d8453SJohn Snow {
3373d58d8453SJohn Snow     assert(hbi->hb);
3374d58d8453SJohn Snow     hbitmap_iter_init(hbi, hbi->hb, offset);
3375d58d8453SJohn Snow }
3376d58d8453SJohn Snow 
337720dca810SJohn Snow int64_t bdrv_get_dirty_count(BdrvDirtyBitmap *bitmap)
3378aaa0eb75SLiran Schour {
3379e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
3380aaa0eb75SLiran Schour }
3381f88e1a42SJes Sorensen 
33829fcb0251SFam Zheng /* Get a reference to bs */
33839fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
33849fcb0251SFam Zheng {
33859fcb0251SFam Zheng     bs->refcnt++;
33869fcb0251SFam Zheng }
33879fcb0251SFam Zheng 
33889fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
33899fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
33909fcb0251SFam Zheng  * deleted. */
33919fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
33929fcb0251SFam Zheng {
33939a4d5ca6SJeff Cody     if (!bs) {
33949a4d5ca6SJeff Cody         return;
33959a4d5ca6SJeff Cody     }
33969fcb0251SFam Zheng     assert(bs->refcnt > 0);
33979fcb0251SFam Zheng     if (--bs->refcnt == 0) {
33989fcb0251SFam Zheng         bdrv_delete(bs);
33999fcb0251SFam Zheng     }
34009fcb0251SFam Zheng }
34019fcb0251SFam Zheng 
3402fbe40ff7SFam Zheng struct BdrvOpBlocker {
3403fbe40ff7SFam Zheng     Error *reason;
3404fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3405fbe40ff7SFam Zheng };
3406fbe40ff7SFam Zheng 
3407fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3408fbe40ff7SFam Zheng {
3409fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3410fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3411fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3412fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3413fbe40ff7SFam Zheng         if (errp) {
341481e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is busy: %s",
341581e5f78aSAlberto Garcia                        bdrv_get_device_or_node_name(bs),
3416bfb197e0SMarkus Armbruster                        error_get_pretty(blocker->reason));
3417fbe40ff7SFam Zheng         }
3418fbe40ff7SFam Zheng         return true;
3419fbe40ff7SFam Zheng     }
3420fbe40ff7SFam Zheng     return false;
3421fbe40ff7SFam Zheng }
3422fbe40ff7SFam Zheng 
3423fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3424fbe40ff7SFam Zheng {
3425fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3426fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3427fbe40ff7SFam Zheng 
34285839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3429fbe40ff7SFam Zheng     blocker->reason = reason;
3430fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3431fbe40ff7SFam Zheng }
3432fbe40ff7SFam Zheng 
3433fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3434fbe40ff7SFam Zheng {
3435fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3436fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3437fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3438fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3439fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3440fbe40ff7SFam Zheng             g_free(blocker);
3441fbe40ff7SFam Zheng         }
3442fbe40ff7SFam Zheng     }
3443fbe40ff7SFam Zheng }
3444fbe40ff7SFam Zheng 
3445fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3446fbe40ff7SFam Zheng {
3447fbe40ff7SFam Zheng     int i;
3448fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3449fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3450fbe40ff7SFam Zheng     }
3451fbe40ff7SFam Zheng }
3452fbe40ff7SFam Zheng 
3453fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3454fbe40ff7SFam Zheng {
3455fbe40ff7SFam Zheng     int i;
3456fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3457fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3458fbe40ff7SFam Zheng     }
3459fbe40ff7SFam Zheng }
3460fbe40ff7SFam Zheng 
3461fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3462fbe40ff7SFam Zheng {
3463fbe40ff7SFam Zheng     int i;
3464fbe40ff7SFam Zheng 
3465fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3466fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3467fbe40ff7SFam Zheng             return false;
3468fbe40ff7SFam Zheng         }
3469fbe40ff7SFam Zheng     }
3470fbe40ff7SFam Zheng     return true;
3471fbe40ff7SFam Zheng }
3472fbe40ff7SFam Zheng 
347328a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
347428a7282aSLuiz Capitulino {
3475d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
347658e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
347728a7282aSLuiz Capitulino }
347828a7282aSLuiz Capitulino 
347928a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
348028a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
348128a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
348228a7282aSLuiz Capitulino {
3483d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
348492aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
348592aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
348692aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
348728a7282aSLuiz Capitulino }
348828a7282aSLuiz Capitulino 
348928a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
349028a7282aSLuiz Capitulino {
3491d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
349228a7282aSLuiz Capitulino }
349328a7282aSLuiz Capitulino 
349428a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
349528a7282aSLuiz Capitulino {
349628a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
349758e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
34983bd293c3SPaolo Bonzini         if (bs->job) {
34993bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
35003bd293c3SPaolo Bonzini         }
350128a7282aSLuiz Capitulino     }
350228a7282aSLuiz Capitulino }
350328a7282aSLuiz Capitulino 
350428a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
350528a7282aSLuiz Capitulino {
35063e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
35073e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
350858e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
350958e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
351028a7282aSLuiz Capitulino     }
351128a7282aSLuiz Capitulino }
351228a7282aSLuiz Capitulino 
3513d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3514f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3515f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3516f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3517f88e1a42SJes Sorensen {
351883d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
351983d0521aSChunyan Liu     QemuOpts *opts = NULL;
352083d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
352183d0521aSChunyan Liu     int64_t size;
3522f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
352396df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
3524cc84d90fSMax Reitz     Error *local_err = NULL;
3525f88e1a42SJes Sorensen     int ret = 0;
3526f88e1a42SJes Sorensen 
3527f88e1a42SJes Sorensen     /* Find driver and parse its options */
3528f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3529f88e1a42SJes Sorensen     if (!drv) {
353071c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3531d92ada22SLuiz Capitulino         return;
3532f88e1a42SJes Sorensen     }
3533f88e1a42SJes Sorensen 
3534b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3535f88e1a42SJes Sorensen     if (!proto_drv) {
3536d92ada22SLuiz Capitulino         return;
3537f88e1a42SJes Sorensen     }
3538f88e1a42SJes Sorensen 
3539c6149724SMax Reitz     if (!drv->create_opts) {
3540c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3541c6149724SMax Reitz                    drv->format_name);
3542c6149724SMax Reitz         return;
3543c6149724SMax Reitz     }
3544c6149724SMax Reitz 
3545c6149724SMax Reitz     if (!proto_drv->create_opts) {
3546c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3547c6149724SMax Reitz                    proto_drv->format_name);
3548c6149724SMax Reitz         return;
3549c6149724SMax Reitz     }
3550c6149724SMax Reitz 
3551c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3552c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3553f88e1a42SJes Sorensen 
3554f88e1a42SJes Sorensen     /* Create parameter list with default values */
355583d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
355639101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3557f88e1a42SJes Sorensen 
3558f88e1a42SJes Sorensen     /* Parse -o options */
3559f88e1a42SJes Sorensen     if (options) {
3560dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3561dc523cd3SMarkus Armbruster         if (local_err) {
3562dc523cd3SMarkus Armbruster             error_report_err(local_err);
3563dc523cd3SMarkus Armbruster             local_err = NULL;
356483d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3565f88e1a42SJes Sorensen             goto out;
3566f88e1a42SJes Sorensen         }
3567f88e1a42SJes Sorensen     }
3568f88e1a42SJes Sorensen 
3569f88e1a42SJes Sorensen     if (base_filename) {
3570f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35716be4194bSMarkus Armbruster         if (local_err) {
357271c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
357371c79813SLuiz Capitulino                        fmt);
3574f88e1a42SJes Sorensen             goto out;
3575f88e1a42SJes Sorensen         }
3576f88e1a42SJes Sorensen     }
3577f88e1a42SJes Sorensen 
3578f88e1a42SJes Sorensen     if (base_fmt) {
3579f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35806be4194bSMarkus Armbruster         if (local_err) {
358171c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
358271c79813SLuiz Capitulino                              "format '%s'", fmt);
3583f88e1a42SJes Sorensen             goto out;
3584f88e1a42SJes Sorensen         }
3585f88e1a42SJes Sorensen     }
3586f88e1a42SJes Sorensen 
358783d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
358883d0521aSChunyan Liu     if (backing_file) {
358983d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
359071c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
359171c79813SLuiz Capitulino                              "same filename as the backing file");
3592792da93aSJes Sorensen             goto out;
3593792da93aSJes Sorensen         }
3594792da93aSJes Sorensen     }
3595792da93aSJes Sorensen 
359683d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
359783d0521aSChunyan Liu     if (backing_fmt) {
359883d0521aSChunyan Liu         backing_drv = bdrv_find_format(backing_fmt);
359996df67d1SStefan Hajnoczi         if (!backing_drv) {
360071c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
360183d0521aSChunyan Liu                        backing_fmt);
3602f88e1a42SJes Sorensen             goto out;
3603f88e1a42SJes Sorensen         }
3604f88e1a42SJes Sorensen     }
3605f88e1a42SJes Sorensen 
3606f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3607f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
360883d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
360983d0521aSChunyan Liu     if (size == -1) {
361083d0521aSChunyan Liu         if (backing_file) {
361166f6b814SMax Reitz             BlockDriverState *bs;
361229168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
361352bf1e72SMarkus Armbruster             int64_t size;
361463090dacSPaolo Bonzini             int back_flags;
361563090dacSPaolo Bonzini 
361629168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
361729168018SMax Reitz                                                          full_backing, PATH_MAX,
361829168018SMax Reitz                                                          &local_err);
361929168018SMax Reitz             if (local_err) {
362029168018SMax Reitz                 g_free(full_backing);
362129168018SMax Reitz                 goto out;
362229168018SMax Reitz             }
362329168018SMax Reitz 
362463090dacSPaolo Bonzini             /* backing files always opened read-only */
362563090dacSPaolo Bonzini             back_flags =
362663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3627f88e1a42SJes Sorensen 
3628f67503e5SMax Reitz             bs = NULL;
362929168018SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, NULL, back_flags,
3630cc84d90fSMax Reitz                             backing_drv, &local_err);
363129168018SMax Reitz             g_free(full_backing);
3632f88e1a42SJes Sorensen             if (ret < 0) {
3633f88e1a42SJes Sorensen                 goto out;
3634f88e1a42SJes Sorensen             }
363552bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
363652bf1e72SMarkus Armbruster             if (size < 0) {
363752bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
363852bf1e72SMarkus Armbruster                                  backing_file);
363952bf1e72SMarkus Armbruster                 bdrv_unref(bs);
364052bf1e72SMarkus Armbruster                 goto out;
364152bf1e72SMarkus Armbruster             }
3642f88e1a42SJes Sorensen 
364339101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
364466f6b814SMax Reitz 
364566f6b814SMax Reitz             bdrv_unref(bs);
3646f88e1a42SJes Sorensen         } else {
364771c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3648f88e1a42SJes Sorensen             goto out;
3649f88e1a42SJes Sorensen         }
3650f88e1a42SJes Sorensen     }
3651f88e1a42SJes Sorensen 
3652f382d43aSMiroslav Rezanina     if (!quiet) {
3653f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s", filename, fmt);
365443c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3655f88e1a42SJes Sorensen         puts("");
3656f382d43aSMiroslav Rezanina     }
365783d0521aSChunyan Liu 
3658c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
365983d0521aSChunyan Liu 
3660cc84d90fSMax Reitz     if (ret == -EFBIG) {
3661cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3662cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3663cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3664f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
366583d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3666f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3667f3f4d2c0SKevin Wolf         }
3668cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3669cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3670cc84d90fSMax Reitz         error_free(local_err);
3671cc84d90fSMax Reitz         local_err = NULL;
3672f88e1a42SJes Sorensen     }
3673f88e1a42SJes Sorensen 
3674f88e1a42SJes Sorensen out:
367583d0521aSChunyan Liu     qemu_opts_del(opts);
367683d0521aSChunyan Liu     qemu_opts_free(create_opts);
367784d18f06SMarkus Armbruster     if (local_err) {
3678cc84d90fSMax Reitz         error_propagate(errp, local_err);
3679cc84d90fSMax Reitz     }
3680f88e1a42SJes Sorensen }
368185d126f3SStefan Hajnoczi 
368285d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
368385d126f3SStefan Hajnoczi {
3684dcd04228SStefan Hajnoczi     return bs->aio_context;
3685dcd04228SStefan Hajnoczi }
3686dcd04228SStefan Hajnoczi 
3687dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3688dcd04228SStefan Hajnoczi {
368933384421SMax Reitz     BdrvAioNotifier *baf;
369033384421SMax Reitz 
3691dcd04228SStefan Hajnoczi     if (!bs->drv) {
3692dcd04228SStefan Hajnoczi         return;
3693dcd04228SStefan Hajnoczi     }
3694dcd04228SStefan Hajnoczi 
369533384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
369633384421SMax Reitz         baf->detach_aio_context(baf->opaque);
369733384421SMax Reitz     }
369833384421SMax Reitz 
369913af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
37000e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
370113af91ebSStefan Hajnoczi     }
3702dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3703dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3704dcd04228SStefan Hajnoczi     }
3705dcd04228SStefan Hajnoczi     if (bs->file) {
3706dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->file);
3707dcd04228SStefan Hajnoczi     }
3708dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
3709dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->backing_hd);
3710dcd04228SStefan Hajnoczi     }
3711dcd04228SStefan Hajnoczi 
3712dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3713dcd04228SStefan Hajnoczi }
3714dcd04228SStefan Hajnoczi 
3715dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3716dcd04228SStefan Hajnoczi                              AioContext *new_context)
3717dcd04228SStefan Hajnoczi {
371833384421SMax Reitz     BdrvAioNotifier *ban;
371933384421SMax Reitz 
3720dcd04228SStefan Hajnoczi     if (!bs->drv) {
3721dcd04228SStefan Hajnoczi         return;
3722dcd04228SStefan Hajnoczi     }
3723dcd04228SStefan Hajnoczi 
3724dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3725dcd04228SStefan Hajnoczi 
3726dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
3727dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->backing_hd, new_context);
3728dcd04228SStefan Hajnoczi     }
3729dcd04228SStefan Hajnoczi     if (bs->file) {
3730dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->file, new_context);
3731dcd04228SStefan Hajnoczi     }
3732dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3733dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3734dcd04228SStefan Hajnoczi     }
373513af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
37360e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
373713af91ebSStefan Hajnoczi     }
373833384421SMax Reitz 
373933384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
374033384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
374133384421SMax Reitz     }
3742dcd04228SStefan Hajnoczi }
3743dcd04228SStefan Hajnoczi 
3744dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3745dcd04228SStefan Hajnoczi {
3746dcd04228SStefan Hajnoczi     bdrv_drain_all(); /* ensure there are no in-flight requests */
3747dcd04228SStefan Hajnoczi 
3748dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3749dcd04228SStefan Hajnoczi 
3750dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3751dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3752dcd04228SStefan Hajnoczi      */
3753dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3754dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3755dcd04228SStefan Hajnoczi     aio_context_release(new_context);
375685d126f3SStefan Hajnoczi }
3757d616b224SStefan Hajnoczi 
375833384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
375933384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
376033384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
376133384421SMax Reitz {
376233384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
376333384421SMax Reitz     *ban = (BdrvAioNotifier){
376433384421SMax Reitz         .attached_aio_context = attached_aio_context,
376533384421SMax Reitz         .detach_aio_context   = detach_aio_context,
376633384421SMax Reitz         .opaque               = opaque
376733384421SMax Reitz     };
376833384421SMax Reitz 
376933384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
377033384421SMax Reitz }
377133384421SMax Reitz 
377233384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
377333384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
377433384421SMax Reitz                                                                    void *),
377533384421SMax Reitz                                       void (*detach_aio_context)(void *),
377633384421SMax Reitz                                       void *opaque)
377733384421SMax Reitz {
377833384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
377933384421SMax Reitz 
378033384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
378133384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
378233384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
378333384421SMax Reitz             ban->opaque               == opaque)
378433384421SMax Reitz         {
378533384421SMax Reitz             QLIST_REMOVE(ban, list);
378633384421SMax Reitz             g_free(ban);
378733384421SMax Reitz 
378833384421SMax Reitz             return;
378933384421SMax Reitz         }
379033384421SMax Reitz     }
379133384421SMax Reitz 
379233384421SMax Reitz     abort();
379333384421SMax Reitz }
379433384421SMax Reitz 
379577485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
379677485434SMax Reitz                        BlockDriverAmendStatusCB *status_cb)
37976f176b48SMax Reitz {
3798c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
37996f176b48SMax Reitz         return -ENOTSUP;
38006f176b48SMax Reitz     }
380177485434SMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb);
38026f176b48SMax Reitz }
3803f6186f49SBenoît Canet 
3804b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3805b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3806b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3807b5042a36SBenoît Canet  * node graph.
3808212a5a8fSBenoît Canet  */
3809212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3810212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3811f6186f49SBenoît Canet {
3812b5042a36SBenoît Canet     /* return false if basic checks fails */
3813b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3814b5042a36SBenoît Canet         return false;
3815b5042a36SBenoît Canet     }
3816b5042a36SBenoît Canet 
3817b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3818b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3819b5042a36SBenoît Canet      */
3820b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3821b5042a36SBenoît Canet         return bs == candidate;
3822b5042a36SBenoît Canet     }
3823b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3824b5042a36SBenoît Canet 
3825b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3826b5042a36SBenoît Canet      * the node graph.
3827b5042a36SBenoît Canet      */
3828b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3829212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3830212a5a8fSBenoît Canet     }
3831212a5a8fSBenoît Canet 
3832b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3833b5042a36SBenoît Canet      */
3834b5042a36SBenoît Canet     return false;
3835212a5a8fSBenoît Canet }
3836212a5a8fSBenoît Canet 
3837212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3838212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3839212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3840212a5a8fSBenoît Canet  */
3841212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3842212a5a8fSBenoît Canet {
3843212a5a8fSBenoît Canet     BlockDriverState *bs;
3844212a5a8fSBenoît Canet 
3845212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
3846212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3847212a5a8fSBenoît Canet         bool perm;
3848212a5a8fSBenoît Canet 
3849b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3850e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3851212a5a8fSBenoît Canet 
3852212a5a8fSBenoît Canet         /* candidate is the first non filter */
3853212a5a8fSBenoît Canet         if (perm) {
3854212a5a8fSBenoît Canet             return true;
3855212a5a8fSBenoît Canet         }
3856212a5a8fSBenoît Canet     }
3857212a5a8fSBenoît Canet 
3858212a5a8fSBenoît Canet     return false;
3859f6186f49SBenoît Canet }
386009158f00SBenoît Canet 
386109158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp)
386209158f00SBenoît Canet {
386309158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38645a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38655a7e7a0bSStefan Hajnoczi 
386609158f00SBenoît Canet     if (!to_replace_bs) {
386709158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
386809158f00SBenoît Canet         return NULL;
386909158f00SBenoît Canet     }
387009158f00SBenoît Canet 
38715a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38725a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38735a7e7a0bSStefan Hajnoczi 
387409158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38755a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38765a7e7a0bSStefan Hajnoczi         goto out;
387709158f00SBenoît Canet     }
387809158f00SBenoît Canet 
387909158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
388009158f00SBenoît Canet      * most non filter in order to prevent data corruption.
388109158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
388209158f00SBenoît Canet      * blocked by the backing blockers.
388309158f00SBenoît Canet      */
388409158f00SBenoît Canet     if (!bdrv_is_first_non_filter(to_replace_bs)) {
388509158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
38865a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38875a7e7a0bSStefan Hajnoczi         goto out;
388809158f00SBenoît Canet     }
388909158f00SBenoît Canet 
38905a7e7a0bSStefan Hajnoczi out:
38915a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
389209158f00SBenoît Canet     return to_replace_bs;
389309158f00SBenoît Canet }
3894448ad91dSMing Lei 
389591af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
389691af7014SMax Reitz {
389791af7014SMax Reitz     const QDictEntry *entry;
389891af7014SMax Reitz     bool found_any = false;
389991af7014SMax Reitz 
390091af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
390191af7014SMax Reitz          entry = qdict_next(bs->options, entry))
390291af7014SMax Reitz     {
390391af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
390491af7014SMax Reitz          * options */
390591af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
390691af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
390791af7014SMax Reitz         {
390891af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
390991af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
391091af7014SMax Reitz             found_any = true;
391191af7014SMax Reitz         }
391291af7014SMax Reitz     }
391391af7014SMax Reitz 
391491af7014SMax Reitz     return found_any;
391591af7014SMax Reitz }
391691af7014SMax Reitz 
391791af7014SMax Reitz /* Updates the following BDS fields:
391891af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
391991af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
392091af7014SMax Reitz  *                    other options; so reading and writing must return the same
392191af7014SMax Reitz  *                    results, but caching etc. may be different)
392291af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
392391af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
392491af7014SMax Reitz  *                       equalling the given one
392591af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
392691af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
392791af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
392891af7014SMax Reitz  */
392991af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
393091af7014SMax Reitz {
393191af7014SMax Reitz     BlockDriver *drv = bs->drv;
393291af7014SMax Reitz     QDict *opts;
393391af7014SMax Reitz 
393491af7014SMax Reitz     if (!drv) {
393591af7014SMax Reitz         return;
393691af7014SMax Reitz     }
393791af7014SMax Reitz 
393891af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
393991af7014SMax Reitz      * refresh that first */
394091af7014SMax Reitz     if (bs->file) {
394191af7014SMax Reitz         bdrv_refresh_filename(bs->file);
394291af7014SMax Reitz     }
394391af7014SMax Reitz 
394491af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
394591af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
394691af7014SMax Reitz          * information before refreshing it */
394791af7014SMax Reitz         bs->exact_filename[0] = '\0';
394891af7014SMax Reitz         if (bs->full_open_options) {
394991af7014SMax Reitz             QDECREF(bs->full_open_options);
395091af7014SMax Reitz             bs->full_open_options = NULL;
395191af7014SMax Reitz         }
395291af7014SMax Reitz 
395391af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
395491af7014SMax Reitz     } else if (bs->file) {
395591af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
395691af7014SMax Reitz         bool has_open_options;
395791af7014SMax Reitz 
395891af7014SMax Reitz         bs->exact_filename[0] = '\0';
395991af7014SMax Reitz         if (bs->full_open_options) {
396091af7014SMax Reitz             QDECREF(bs->full_open_options);
396191af7014SMax Reitz             bs->full_open_options = NULL;
396291af7014SMax Reitz         }
396391af7014SMax Reitz 
396491af7014SMax Reitz         opts = qdict_new();
396591af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
396691af7014SMax Reitz 
396791af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
396891af7014SMax Reitz          * the underlying file should suffice for this one as well */
396991af7014SMax Reitz         if (bs->file->exact_filename[0] && !has_open_options) {
397091af7014SMax Reitz             strcpy(bs->exact_filename, bs->file->exact_filename);
397191af7014SMax Reitz         }
397291af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
397391af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
397491af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
397591af7014SMax Reitz          * contain a representation of the filename, therefore the following
397691af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
397791af7014SMax Reitz         if (bs->file->full_open_options) {
397891af7014SMax Reitz             qdict_put_obj(opts, "driver",
397991af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
398091af7014SMax Reitz             QINCREF(bs->file->full_open_options);
398191af7014SMax Reitz             qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options));
398291af7014SMax Reitz 
398391af7014SMax Reitz             bs->full_open_options = opts;
398491af7014SMax Reitz         } else {
398591af7014SMax Reitz             QDECREF(opts);
398691af7014SMax Reitz         }
398791af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
398891af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
398991af7014SMax Reitz          * so the full options QDict should be equal to the options given
399091af7014SMax Reitz          * specifically for this block device when it was opened (plus the
399191af7014SMax Reitz          * driver specification).
399291af7014SMax Reitz          * Because those options don't change, there is no need to update
399391af7014SMax Reitz          * full_open_options when it's already set. */
399491af7014SMax Reitz 
399591af7014SMax Reitz         opts = qdict_new();
399691af7014SMax Reitz         append_open_options(opts, bs);
399791af7014SMax Reitz         qdict_put_obj(opts, "driver",
399891af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
399991af7014SMax Reitz 
400091af7014SMax Reitz         if (bs->exact_filename[0]) {
400191af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
400291af7014SMax Reitz              * require this filename to be parsed), but we have to find some
400391af7014SMax Reitz              * default solution here, so just include it. If some block driver
400491af7014SMax Reitz              * does not support pure options without any filename at all or
400591af7014SMax Reitz              * needs some special format of the options QDict, it needs to
400691af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
400791af7014SMax Reitz              */
400891af7014SMax Reitz             qdict_put_obj(opts, "filename",
400991af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
401091af7014SMax Reitz         }
401191af7014SMax Reitz 
401291af7014SMax Reitz         bs->full_open_options = opts;
401391af7014SMax Reitz     }
401491af7014SMax Reitz 
401591af7014SMax Reitz     if (bs->exact_filename[0]) {
401691af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
401791af7014SMax Reitz     } else if (bs->full_open_options) {
401891af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
401991af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
402091af7014SMax Reitz                  qstring_get_str(json));
402191af7014SMax Reitz         QDECREF(json);
402291af7014SMax Reitz     }
402391af7014SMax Reitz }
40245366d0c8SBenoît Canet 
40255366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the
40265366d0c8SBenoît Canet  * BlockAcctStats structure embedded inside a BlockDriverState without being
40275366d0c8SBenoît Canet  * aware of the BlockDriverState structure layout.
40285366d0c8SBenoît Canet  * It will go away when the BlockAcctStats structure will be moved inside
40295366d0c8SBenoît Canet  * the device models.
40305366d0c8SBenoît Canet  */
40315366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
40325366d0c8SBenoît Canet {
40335366d0c8SBenoît Canet     return &bs->stats;
40345366d0c8SBenoît Canet }
4035