xref: /openbmc/qemu/block.c (revision 73ac451f3435910433900d7d01a1cac6ccb401e6)
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  */
24d38ea87aSPeter Maydell #include "qemu/osdep.h"
256d519a5fSStefan Hajnoczi #include "trace.h"
26737e150eSPaolo Bonzini #include "block/block_int.h"
27737e150eSPaolo Bonzini #include "block/blockjob.h"
28d49b6836SMarkus Armbruster #include "qemu/error-report.h"
291de7afc9SPaolo Bonzini #include "qemu/module.h"
30cc7a8ea7SMarkus Armbruster #include "qapi/qmp/qerror.h"
3191a097e7SKevin Wolf #include "qapi/qmp/qbool.h"
327b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
33bfb197e0SMarkus Armbruster #include "sysemu/block-backend.h"
349c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
351de7afc9SPaolo Bonzini #include "qemu/notify.h"
3610817bf0SDaniel P. Berrange #include "qemu/coroutine.h"
37c13163fbSBenoît Canet #include "block/qapi.h"
38b2023818SLuiz Capitulino #include "qmp-commands.h"
391de7afc9SPaolo Bonzini #include "qemu/timer.h"
40a5ee7bd4SWenchao Xia #include "qapi-event.h"
41db628338SAlberto Garcia #include "block/throttle-groups.h"
42f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
43f348b6d1SVeronia Bahaa #include "qemu/id.h"
44fc01f7e7Sbellard 
4571e72a19SJuan Quintela #ifdef CONFIG_BSD
467674e7bfSbellard #include <sys/ioctl.h>
4772cf2d4fSBlue Swirl #include <sys/queue.h>
48c5e97233Sblueswir1 #ifndef __DragonFly__
497674e7bfSbellard #include <sys/disk.h>
507674e7bfSbellard #endif
51c5e97233Sblueswir1 #endif
527674e7bfSbellard 
5349dc768dSaliguori #ifdef _WIN32
5449dc768dSaliguori #include <windows.h>
5549dc768dSaliguori #endif
5649dc768dSaliguori 
571c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
581c9805a3SStefan Hajnoczi 
59dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
60dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
61dc364f4cSBenoît Canet 
622c1d04e0SMax Reitz static QTAILQ_HEAD(, BlockDriverState) all_bdrv_states =
632c1d04e0SMax Reitz     QTAILQ_HEAD_INITIALIZER(all_bdrv_states);
642c1d04e0SMax Reitz 
658a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
668a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
67ea2384d3Sbellard 
68f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
69f3930ed0SKevin Wolf                              const char *reference, QDict *options, int flags,
70f3930ed0SKevin Wolf                              BlockDriverState *parent,
71ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp);
72f3930ed0SKevin Wolf 
73eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
74eb852011SMarkus Armbruster static int use_bdrv_whitelist;
75eb852011SMarkus Armbruster 
7664dff520SMax Reitz static void bdrv_close(BlockDriverState *bs);
7764dff520SMax Reitz 
789e0b22f4SStefan Hajnoczi #ifdef _WIN32
799e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
809e0b22f4SStefan Hajnoczi {
819e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
829e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
839e0b22f4SStefan Hajnoczi             filename[1] == ':');
849e0b22f4SStefan Hajnoczi }
859e0b22f4SStefan Hajnoczi 
869e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
879e0b22f4SStefan Hajnoczi {
889e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
899e0b22f4SStefan Hajnoczi         filename[2] == '\0')
909e0b22f4SStefan Hajnoczi         return 1;
919e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
929e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
939e0b22f4SStefan Hajnoczi         return 1;
949e0b22f4SStefan Hajnoczi     return 0;
959e0b22f4SStefan Hajnoczi }
969e0b22f4SStefan Hajnoczi #endif
979e0b22f4SStefan Hajnoczi 
98339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
99339064d5SKevin Wolf {
100339064d5SKevin Wolf     if (!bs || !bs->drv) {
101459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
102459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
103339064d5SKevin Wolf     }
104339064d5SKevin Wolf 
105339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
106339064d5SKevin Wolf }
107339064d5SKevin Wolf 
1084196d2f0SDenis V. Lunev size_t bdrv_min_mem_align(BlockDriverState *bs)
1094196d2f0SDenis V. Lunev {
1104196d2f0SDenis V. Lunev     if (!bs || !bs->drv) {
111459b4e66SDenis V. Lunev         /* page size or 4k (hdd sector size) should be on the safe side */
112459b4e66SDenis V. Lunev         return MAX(4096, getpagesize());
1134196d2f0SDenis V. Lunev     }
1144196d2f0SDenis V. Lunev 
1154196d2f0SDenis V. Lunev     return bs->bl.min_mem_alignment;
1164196d2f0SDenis V. Lunev }
1174196d2f0SDenis V. Lunev 
1189e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
1195c98415bSMax Reitz int path_has_protocol(const char *path)
1209e0b22f4SStefan Hajnoczi {
121947995c0SPaolo Bonzini     const char *p;
122947995c0SPaolo Bonzini 
1239e0b22f4SStefan Hajnoczi #ifdef _WIN32
1249e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
1259e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
1269e0b22f4SStefan Hajnoczi         return 0;
1279e0b22f4SStefan Hajnoczi     }
128947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
129947995c0SPaolo Bonzini #else
130947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
1319e0b22f4SStefan Hajnoczi #endif
1329e0b22f4SStefan Hajnoczi 
133947995c0SPaolo Bonzini     return *p == ':';
1349e0b22f4SStefan Hajnoczi }
1359e0b22f4SStefan Hajnoczi 
13683f64091Sbellard int path_is_absolute(const char *path)
13783f64091Sbellard {
13821664424Sbellard #ifdef _WIN32
13921664424Sbellard     /* specific case for names like: "\\.\d:" */
140f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
14121664424Sbellard         return 1;
142f53f4da9SPaolo Bonzini     }
143f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
1443b9f94e1Sbellard #else
145f53f4da9SPaolo Bonzini     return (*path == '/');
1463b9f94e1Sbellard #endif
14783f64091Sbellard }
14883f64091Sbellard 
14983f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
15083f64091Sbellard    path to it by considering it is relative to base_path. URL are
15183f64091Sbellard    supported. */
15283f64091Sbellard void path_combine(char *dest, int dest_size,
15383f64091Sbellard                   const char *base_path,
15483f64091Sbellard                   const char *filename)
15583f64091Sbellard {
15683f64091Sbellard     const char *p, *p1;
15783f64091Sbellard     int len;
15883f64091Sbellard 
15983f64091Sbellard     if (dest_size <= 0)
16083f64091Sbellard         return;
16183f64091Sbellard     if (path_is_absolute(filename)) {
16283f64091Sbellard         pstrcpy(dest, dest_size, filename);
16383f64091Sbellard     } else {
16483f64091Sbellard         p = strchr(base_path, ':');
16583f64091Sbellard         if (p)
16683f64091Sbellard             p++;
16783f64091Sbellard         else
16883f64091Sbellard             p = base_path;
1693b9f94e1Sbellard         p1 = strrchr(base_path, '/');
1703b9f94e1Sbellard #ifdef _WIN32
1713b9f94e1Sbellard         {
1723b9f94e1Sbellard             const char *p2;
1733b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
1743b9f94e1Sbellard             if (!p1 || p2 > p1)
1753b9f94e1Sbellard                 p1 = p2;
1763b9f94e1Sbellard         }
1773b9f94e1Sbellard #endif
17883f64091Sbellard         if (p1)
17983f64091Sbellard             p1++;
18083f64091Sbellard         else
18183f64091Sbellard             p1 = base_path;
18283f64091Sbellard         if (p1 > p)
18383f64091Sbellard             p = p1;
18483f64091Sbellard         len = p - base_path;
18583f64091Sbellard         if (len > dest_size - 1)
18683f64091Sbellard             len = dest_size - 1;
18783f64091Sbellard         memcpy(dest, base_path, len);
18883f64091Sbellard         dest[len] = '\0';
18983f64091Sbellard         pstrcat(dest, dest_size, filename);
19083f64091Sbellard     }
19183f64091Sbellard }
19283f64091Sbellard 
1930a82855aSMax Reitz void bdrv_get_full_backing_filename_from_filename(const char *backed,
1940a82855aSMax Reitz                                                   const char *backing,
1959f07429eSMax Reitz                                                   char *dest, size_t sz,
1969f07429eSMax Reitz                                                   Error **errp)
1970a82855aSMax Reitz {
1989f07429eSMax Reitz     if (backing[0] == '\0' || path_has_protocol(backing) ||
1999f07429eSMax Reitz         path_is_absolute(backing))
2009f07429eSMax Reitz     {
2010a82855aSMax Reitz         pstrcpy(dest, sz, backing);
2029f07429eSMax Reitz     } else if (backed[0] == '\0' || strstart(backed, "json:", NULL)) {
2039f07429eSMax Reitz         error_setg(errp, "Cannot use relative backing file names for '%s'",
2049f07429eSMax Reitz                    backed);
2050a82855aSMax Reitz     } else {
2060a82855aSMax Reitz         path_combine(dest, sz, backed, backing);
2070a82855aSMax Reitz     }
2080a82855aSMax Reitz }
2090a82855aSMax Reitz 
2109f07429eSMax Reitz void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz,
2119f07429eSMax Reitz                                     Error **errp)
212dc5a1371SPaolo Bonzini {
2139f07429eSMax Reitz     char *backed = bs->exact_filename[0] ? bs->exact_filename : bs->filename;
2149f07429eSMax Reitz 
2159f07429eSMax Reitz     bdrv_get_full_backing_filename_from_filename(backed, bs->backing_file,
2169f07429eSMax Reitz                                                  dest, sz, errp);
217dc5a1371SPaolo Bonzini }
218dc5a1371SPaolo Bonzini 
2190eb7217eSStefan Hajnoczi void bdrv_register(BlockDriver *bdrv)
2200eb7217eSStefan Hajnoczi {
2210eb7217eSStefan Hajnoczi     bdrv_setup_io_funcs(bdrv);
222b2e12bc6SChristoph Hellwig 
2238a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
224ea2384d3Sbellard }
225b338082bSbellard 
2267f06d47eSMarkus Armbruster BlockDriverState *bdrv_new_root(void)
227fc01f7e7Sbellard {
2289aaf28c6SMax Reitz     return bdrv_new();
229e4e9986bSMarkus Armbruster }
230e4e9986bSMarkus Armbruster 
231e4e9986bSMarkus Armbruster BlockDriverState *bdrv_new(void)
232e4e9986bSMarkus Armbruster {
233e4e9986bSMarkus Armbruster     BlockDriverState *bs;
234e4e9986bSMarkus Armbruster     int i;
235e4e9986bSMarkus Armbruster 
2365839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
237e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
238fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
239fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
240fbe40ff7SFam Zheng     }
241d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
242cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
243cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
2449fcb0251SFam Zheng     bs->refcnt = 1;
245dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
246d7d512f6SPaolo Bonzini 
2472c1d04e0SMax Reitz     QTAILQ_INSERT_TAIL(&all_bdrv_states, bs, bs_list);
2482c1d04e0SMax Reitz 
249b338082bSbellard     return bs;
250b338082bSbellard }
251b338082bSbellard 
252ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
253ea2384d3Sbellard {
254ea2384d3Sbellard     BlockDriver *drv1;
2558a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
2568a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
257ea2384d3Sbellard             return drv1;
258ea2384d3Sbellard         }
2598a22f02aSStefan Hajnoczi     }
260ea2384d3Sbellard     return NULL;
261ea2384d3Sbellard }
262ea2384d3Sbellard 
263b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
264eb852011SMarkus Armbruster {
265b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
266b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
267b64ec4e4SFam Zheng     };
268b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
269b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
270eb852011SMarkus Armbruster     };
271eb852011SMarkus Armbruster     const char **p;
272eb852011SMarkus Armbruster 
273b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
274eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
275b64ec4e4SFam Zheng     }
276eb852011SMarkus Armbruster 
277b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
278eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
279eb852011SMarkus Armbruster             return 1;
280eb852011SMarkus Armbruster         }
281eb852011SMarkus Armbruster     }
282b64ec4e4SFam Zheng     if (read_only) {
283b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
284b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
285b64ec4e4SFam Zheng                 return 1;
286b64ec4e4SFam Zheng             }
287b64ec4e4SFam Zheng         }
288b64ec4e4SFam Zheng     }
289eb852011SMarkus Armbruster     return 0;
290eb852011SMarkus Armbruster }
291eb852011SMarkus Armbruster 
2925b7e1542SZhi Yong Wu typedef struct CreateCo {
2935b7e1542SZhi Yong Wu     BlockDriver *drv;
2945b7e1542SZhi Yong Wu     char *filename;
29583d0521aSChunyan Liu     QemuOpts *opts;
2965b7e1542SZhi Yong Wu     int ret;
297cc84d90fSMax Reitz     Error *err;
2985b7e1542SZhi Yong Wu } CreateCo;
2995b7e1542SZhi Yong Wu 
3005b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
3015b7e1542SZhi Yong Wu {
302cc84d90fSMax Reitz     Error *local_err = NULL;
303cc84d90fSMax Reitz     int ret;
304cc84d90fSMax Reitz 
3055b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
3065b7e1542SZhi Yong Wu     assert(cco->drv);
3075b7e1542SZhi Yong Wu 
308c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
30984d18f06SMarkus Armbruster     if (local_err) {
310cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
311cc84d90fSMax Reitz     }
312cc84d90fSMax Reitz     cco->ret = ret;
3135b7e1542SZhi Yong Wu }
3145b7e1542SZhi Yong Wu 
3150e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
31683d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
317ea2384d3Sbellard {
3185b7e1542SZhi Yong Wu     int ret;
3190e7e1989SKevin Wolf 
3205b7e1542SZhi Yong Wu     Coroutine *co;
3215b7e1542SZhi Yong Wu     CreateCo cco = {
3225b7e1542SZhi Yong Wu         .drv = drv,
3235b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
32483d0521aSChunyan Liu         .opts = opts,
3255b7e1542SZhi Yong Wu         .ret = NOT_DONE,
326cc84d90fSMax Reitz         .err = NULL,
3275b7e1542SZhi Yong Wu     };
3285b7e1542SZhi Yong Wu 
329c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
330cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
33180168bffSLuiz Capitulino         ret = -ENOTSUP;
33280168bffSLuiz Capitulino         goto out;
3335b7e1542SZhi Yong Wu     }
3345b7e1542SZhi Yong Wu 
3355b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
3365b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
3375b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
3385b7e1542SZhi Yong Wu     } else {
3395b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
3405b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
3415b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
342b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
3435b7e1542SZhi Yong Wu         }
3445b7e1542SZhi Yong Wu     }
3455b7e1542SZhi Yong Wu 
3465b7e1542SZhi Yong Wu     ret = cco.ret;
347cc84d90fSMax Reitz     if (ret < 0) {
34884d18f06SMarkus Armbruster         if (cco.err) {
349cc84d90fSMax Reitz             error_propagate(errp, cco.err);
350cc84d90fSMax Reitz         } else {
351cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
352cc84d90fSMax Reitz         }
353cc84d90fSMax Reitz     }
3545b7e1542SZhi Yong Wu 
35580168bffSLuiz Capitulino out:
35680168bffSLuiz Capitulino     g_free(cco.filename);
3575b7e1542SZhi Yong Wu     return ret;
358ea2384d3Sbellard }
359ea2384d3Sbellard 
360c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
36184a12e66SChristoph Hellwig {
36284a12e66SChristoph Hellwig     BlockDriver *drv;
363cc84d90fSMax Reitz     Error *local_err = NULL;
364cc84d90fSMax Reitz     int ret;
36584a12e66SChristoph Hellwig 
366b65a5e12SMax Reitz     drv = bdrv_find_protocol(filename, true, errp);
36784a12e66SChristoph Hellwig     if (drv == NULL) {
36816905d71SStefan Hajnoczi         return -ENOENT;
36984a12e66SChristoph Hellwig     }
37084a12e66SChristoph Hellwig 
371c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
37284d18f06SMarkus Armbruster     if (local_err) {
373cc84d90fSMax Reitz         error_propagate(errp, local_err);
374cc84d90fSMax Reitz     }
375cc84d90fSMax Reitz     return ret;
37684a12e66SChristoph Hellwig }
37784a12e66SChristoph Hellwig 
378892b7de8SEkaterina Tumanova /**
379892b7de8SEkaterina Tumanova  * Try to get @bs's logical and physical block size.
380892b7de8SEkaterina Tumanova  * On success, store them in @bsz struct and return 0.
381892b7de8SEkaterina Tumanova  * On failure return -errno.
382892b7de8SEkaterina Tumanova  * @bs must not be empty.
383892b7de8SEkaterina Tumanova  */
384892b7de8SEkaterina Tumanova int bdrv_probe_blocksizes(BlockDriverState *bs, BlockSizes *bsz)
385892b7de8SEkaterina Tumanova {
386892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
387892b7de8SEkaterina Tumanova 
388892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_blocksizes) {
389892b7de8SEkaterina Tumanova         return drv->bdrv_probe_blocksizes(bs, bsz);
390892b7de8SEkaterina Tumanova     }
391892b7de8SEkaterina Tumanova 
392892b7de8SEkaterina Tumanova     return -ENOTSUP;
393892b7de8SEkaterina Tumanova }
394892b7de8SEkaterina Tumanova 
395892b7de8SEkaterina Tumanova /**
396892b7de8SEkaterina Tumanova  * Try to get @bs's geometry (cyls, heads, sectors).
397892b7de8SEkaterina Tumanova  * On success, store them in @geo struct and return 0.
398892b7de8SEkaterina Tumanova  * On failure return -errno.
399892b7de8SEkaterina Tumanova  * @bs must not be empty.
400892b7de8SEkaterina Tumanova  */
401892b7de8SEkaterina Tumanova int bdrv_probe_geometry(BlockDriverState *bs, HDGeometry *geo)
402892b7de8SEkaterina Tumanova {
403892b7de8SEkaterina Tumanova     BlockDriver *drv = bs->drv;
404892b7de8SEkaterina Tumanova 
405892b7de8SEkaterina Tumanova     if (drv && drv->bdrv_probe_geometry) {
406892b7de8SEkaterina Tumanova         return drv->bdrv_probe_geometry(bs, geo);
407892b7de8SEkaterina Tumanova     }
408892b7de8SEkaterina Tumanova 
409892b7de8SEkaterina Tumanova     return -ENOTSUP;
410892b7de8SEkaterina Tumanova }
411892b7de8SEkaterina Tumanova 
412eba25057SJim Meyering /*
413eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
414eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
415eba25057SJim Meyering  */
416eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
417eba25057SJim Meyering {
418d5249393Sbellard #ifdef _WIN32
4193b9f94e1Sbellard     char temp_dir[MAX_PATH];
420eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
421eba25057SJim Meyering        have length MAX_PATH or greater.  */
422eba25057SJim Meyering     assert(size >= MAX_PATH);
423eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
424eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
425eba25057SJim Meyering             ? 0 : -GetLastError());
426d5249393Sbellard #else
427ea2384d3Sbellard     int fd;
4287ccfb2ebSblueswir1     const char *tmpdir;
4290badc1eeSaurel32     tmpdir = getenv("TMPDIR");
43069bef793SAmit Shah     if (!tmpdir) {
43169bef793SAmit Shah         tmpdir = "/var/tmp";
43269bef793SAmit Shah     }
433eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
434eba25057SJim Meyering         return -EOVERFLOW;
435ea2384d3Sbellard     }
436eba25057SJim Meyering     fd = mkstemp(filename);
437fe235a06SDunrong Huang     if (fd < 0) {
438fe235a06SDunrong Huang         return -errno;
439fe235a06SDunrong Huang     }
440fe235a06SDunrong Huang     if (close(fd) != 0) {
441fe235a06SDunrong Huang         unlink(filename);
442eba25057SJim Meyering         return -errno;
443eba25057SJim Meyering     }
444eba25057SJim Meyering     return 0;
445d5249393Sbellard #endif
446eba25057SJim Meyering }
447ea2384d3Sbellard 
448f3a5d3f8SChristoph Hellwig /*
449f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
450f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
451f3a5d3f8SChristoph Hellwig  */
452f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
453f3a5d3f8SChristoph Hellwig {
454508c7cb3SChristoph Hellwig     int score_max = 0, score;
455508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
456f3a5d3f8SChristoph Hellwig 
4578a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
458508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
459508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
460508c7cb3SChristoph Hellwig             if (score > score_max) {
461508c7cb3SChristoph Hellwig                 score_max = score;
462508c7cb3SChristoph Hellwig                 drv = d;
463f3a5d3f8SChristoph Hellwig             }
464508c7cb3SChristoph Hellwig         }
465f3a5d3f8SChristoph Hellwig     }
466f3a5d3f8SChristoph Hellwig 
467508c7cb3SChristoph Hellwig     return drv;
468f3a5d3f8SChristoph Hellwig }
469f3a5d3f8SChristoph Hellwig 
47098289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
471b65a5e12SMax Reitz                                 bool allow_protocol_prefix,
472b65a5e12SMax Reitz                                 Error **errp)
47384a12e66SChristoph Hellwig {
47484a12e66SChristoph Hellwig     BlockDriver *drv1;
47584a12e66SChristoph Hellwig     char protocol[128];
47684a12e66SChristoph Hellwig     int len;
47784a12e66SChristoph Hellwig     const char *p;
47884a12e66SChristoph Hellwig 
47966f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
48066f82ceeSKevin Wolf 
48139508e7aSChristoph Hellwig     /*
48239508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
48339508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
48439508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
48539508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
48639508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
48739508e7aSChristoph Hellwig      */
48884a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
48939508e7aSChristoph Hellwig     if (drv1) {
49084a12e66SChristoph Hellwig         return drv1;
49184a12e66SChristoph Hellwig     }
49239508e7aSChristoph Hellwig 
49398289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
494ef810437SMax Reitz         return &bdrv_file;
49539508e7aSChristoph Hellwig     }
49698289620SKevin Wolf 
4979e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
4989e0b22f4SStefan Hajnoczi     assert(p != NULL);
49984a12e66SChristoph Hellwig     len = p - filename;
50084a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
50184a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
50284a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
50384a12e66SChristoph Hellwig     protocol[len] = '\0';
50484a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
50584a12e66SChristoph Hellwig         if (drv1->protocol_name &&
50684a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
50784a12e66SChristoph Hellwig             return drv1;
50884a12e66SChristoph Hellwig         }
50984a12e66SChristoph Hellwig     }
510b65a5e12SMax Reitz 
511b65a5e12SMax Reitz     error_setg(errp, "Unknown protocol '%s'", protocol);
51284a12e66SChristoph Hellwig     return NULL;
51384a12e66SChristoph Hellwig }
51484a12e66SChristoph Hellwig 
515c6684249SMarkus Armbruster /*
516c6684249SMarkus Armbruster  * Guess image format by probing its contents.
517c6684249SMarkus Armbruster  * This is not a good idea when your image is raw (CVE-2008-2004), but
518c6684249SMarkus Armbruster  * we do it anyway for backward compatibility.
519c6684249SMarkus Armbruster  *
520c6684249SMarkus Armbruster  * @buf         contains the image's first @buf_size bytes.
5217cddd372SKevin Wolf  * @buf_size    is the buffer size in bytes (generally BLOCK_PROBE_BUF_SIZE,
5227cddd372SKevin Wolf  *              but can be smaller if the image file is smaller)
523c6684249SMarkus Armbruster  * @filename    is its filename.
524c6684249SMarkus Armbruster  *
525c6684249SMarkus Armbruster  * For all block drivers, call the bdrv_probe() method to get its
526c6684249SMarkus Armbruster  * probing score.
527c6684249SMarkus Armbruster  * Return the first block driver with the highest probing score.
528c6684249SMarkus Armbruster  */
52938f3ef57SKevin Wolf BlockDriver *bdrv_probe_all(const uint8_t *buf, int buf_size,
530c6684249SMarkus Armbruster                             const char *filename)
531c6684249SMarkus Armbruster {
532c6684249SMarkus Armbruster     int score_max = 0, score;
533c6684249SMarkus Armbruster     BlockDriver *drv = NULL, *d;
534c6684249SMarkus Armbruster 
535c6684249SMarkus Armbruster     QLIST_FOREACH(d, &bdrv_drivers, list) {
536c6684249SMarkus Armbruster         if (d->bdrv_probe) {
537c6684249SMarkus Armbruster             score = d->bdrv_probe(buf, buf_size, filename);
538c6684249SMarkus Armbruster             if (score > score_max) {
539c6684249SMarkus Armbruster                 score_max = score;
540c6684249SMarkus Armbruster                 drv = d;
541c6684249SMarkus Armbruster             }
542c6684249SMarkus Armbruster         }
543c6684249SMarkus Armbruster     }
544c6684249SMarkus Armbruster 
545c6684249SMarkus Armbruster     return drv;
546c6684249SMarkus Armbruster }
547c6684249SMarkus Armbruster 
548f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
54934b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
550ea2384d3Sbellard {
551c6684249SMarkus Armbruster     BlockDriver *drv;
5527cddd372SKevin Wolf     uint8_t buf[BLOCK_PROBE_BUF_SIZE];
553f500a6d3SKevin Wolf     int ret = 0;
554f8ea0b00SNicholas Bellinger 
55508a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
556b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs) || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
557ef810437SMax Reitz         *pdrv = &bdrv_raw;
558c98ac35dSStefan Weil         return ret;
5591a396859SNicholas A. Bellinger     }
560f8ea0b00SNicholas Bellinger 
56183f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
562ea2384d3Sbellard     if (ret < 0) {
56334b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
56434b5d2c6SMax Reitz                          "format");
565c98ac35dSStefan Weil         *pdrv = NULL;
566c98ac35dSStefan Weil         return ret;
567ea2384d3Sbellard     }
568ea2384d3Sbellard 
569c6684249SMarkus Armbruster     drv = bdrv_probe_all(buf, ret, filename);
570c98ac35dSStefan Weil     if (!drv) {
57134b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
57234b5d2c6SMax Reitz                    "driver found");
573c98ac35dSStefan Weil         ret = -ENOENT;
574c98ac35dSStefan Weil     }
575c98ac35dSStefan Weil     *pdrv = drv;
576c98ac35dSStefan Weil     return ret;
577ea2384d3Sbellard }
578ea2384d3Sbellard 
57951762288SStefan Hajnoczi /**
58051762288SStefan Hajnoczi  * Set the current 'total_sectors' value
58165a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
58251762288SStefan Hajnoczi  */
58351762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
58451762288SStefan Hajnoczi {
58551762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
58651762288SStefan Hajnoczi 
587396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
588b192af8aSDimitris Aragiorgis     if (bdrv_is_sg(bs))
589396759adSNicholas Bellinger         return 0;
590396759adSNicholas Bellinger 
59151762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
59251762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
59351762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
59451762288SStefan Hajnoczi         if (length < 0) {
59551762288SStefan Hajnoczi             return length;
59651762288SStefan Hajnoczi         }
5977e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
59851762288SStefan Hajnoczi     }
59951762288SStefan Hajnoczi 
60051762288SStefan Hajnoczi     bs->total_sectors = hint;
60151762288SStefan Hajnoczi     return 0;
60251762288SStefan Hajnoczi }
60351762288SStefan Hajnoczi 
604c3993cdcSStefan Hajnoczi /**
605cddff5baSKevin Wolf  * Combines a QDict of new block driver @options with any missing options taken
606cddff5baSKevin Wolf  * from @old_options, so that leaving out an option defaults to its old value.
607cddff5baSKevin Wolf  */
608cddff5baSKevin Wolf static void bdrv_join_options(BlockDriverState *bs, QDict *options,
609cddff5baSKevin Wolf                               QDict *old_options)
610cddff5baSKevin Wolf {
611cddff5baSKevin Wolf     if (bs->drv && bs->drv->bdrv_join_options) {
612cddff5baSKevin Wolf         bs->drv->bdrv_join_options(options, old_options);
613cddff5baSKevin Wolf     } else {
614cddff5baSKevin Wolf         qdict_join(options, old_options, false);
615cddff5baSKevin Wolf     }
616cddff5baSKevin Wolf }
617cddff5baSKevin Wolf 
618cddff5baSKevin Wolf /**
6199e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
6209e8f1835SPaolo Bonzini  *
6219e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
6229e8f1835SPaolo Bonzini  */
6239e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
6249e8f1835SPaolo Bonzini {
6259e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
6269e8f1835SPaolo Bonzini 
6279e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
6289e8f1835SPaolo Bonzini         /* do nothing */
6299e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
6309e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
6319e8f1835SPaolo Bonzini     } else {
6329e8f1835SPaolo Bonzini         return -1;
6339e8f1835SPaolo Bonzini     }
6349e8f1835SPaolo Bonzini 
6359e8f1835SPaolo Bonzini     return 0;
6369e8f1835SPaolo Bonzini }
6379e8f1835SPaolo Bonzini 
6389e8f1835SPaolo Bonzini /**
639c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
640c3993cdcSStefan Hajnoczi  *
641c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
642c3993cdcSStefan Hajnoczi  */
643c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
644c3993cdcSStefan Hajnoczi {
645c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
646c3993cdcSStefan Hajnoczi 
647c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
648c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
64992196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
65092196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
651c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
652c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
653c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
654c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
655c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
656c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
657c3993cdcSStefan Hajnoczi         /* this is the default */
658c3993cdcSStefan Hajnoczi     } else {
659c3993cdcSStefan Hajnoczi         return -1;
660c3993cdcSStefan Hajnoczi     }
661c3993cdcSStefan Hajnoczi 
662c3993cdcSStefan Hajnoczi     return 0;
663c3993cdcSStefan Hajnoczi }
664c3993cdcSStefan Hajnoczi 
6650b50cc88SKevin Wolf /*
66673176beeSKevin Wolf  * Returns the options and flags that a temporary snapshot should get, based on
66773176beeSKevin Wolf  * the originally requested flags (the originally requested image will have
66873176beeSKevin Wolf  * flags like a backing file)
669b1e6fc08SKevin Wolf  */
67073176beeSKevin Wolf static void bdrv_temp_snapshot_options(int *child_flags, QDict *child_options,
67173176beeSKevin Wolf                                        int parent_flags, QDict *parent_options)
672b1e6fc08SKevin Wolf {
67373176beeSKevin Wolf     *child_flags = (parent_flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
67473176beeSKevin Wolf 
67573176beeSKevin Wolf     /* For temporary files, unconditional cache=unsafe is fine */
67673176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
67773176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_DIRECT, "off");
67873176beeSKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_NO_FLUSH, "on");
679b1e6fc08SKevin Wolf }
680b1e6fc08SKevin Wolf 
681b1e6fc08SKevin Wolf /*
6828e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if a protocol driver
6838e2160e2SKevin Wolf  * is expected, based on the given options and flags for the parent BDS
6840b50cc88SKevin Wolf  */
6858e2160e2SKevin Wolf static void bdrv_inherited_options(int *child_flags, QDict *child_options,
6868e2160e2SKevin Wolf                                    int parent_flags, QDict *parent_options)
6870b50cc88SKevin Wolf {
6888e2160e2SKevin Wolf     int flags = parent_flags;
6898e2160e2SKevin Wolf 
6900b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
6910b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
6920b50cc88SKevin Wolf 
69391a097e7SKevin Wolf     /* If the cache mode isn't explicitly set, inherit direct and no-flush from
69491a097e7SKevin Wolf      * the parent. */
69591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
69691a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
69791a097e7SKevin Wolf 
6980b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
69991a097e7SKevin Wolf      * so we can default to enable both on lower layers regardless of the
70091a097e7SKevin Wolf      * corresponding parent options. */
70191a097e7SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
70291a097e7SKevin Wolf     flags |= BDRV_O_UNMAP;
7030b50cc88SKevin Wolf 
7040b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
7055669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
7060b50cc88SKevin Wolf 
7078e2160e2SKevin Wolf     *child_flags = flags;
7080b50cc88SKevin Wolf }
7090b50cc88SKevin Wolf 
710f3930ed0SKevin Wolf const BdrvChildRole child_file = {
7118e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_options,
712f3930ed0SKevin Wolf };
713f3930ed0SKevin Wolf 
714f3930ed0SKevin Wolf /*
7158e2160e2SKevin Wolf  * Returns the options and flags that bs->file should get if the use of formats
7168e2160e2SKevin Wolf  * (and not only protocols) is permitted for it, based on the given options and
7178e2160e2SKevin Wolf  * flags for the parent BDS
718f3930ed0SKevin Wolf  */
7198e2160e2SKevin Wolf static void bdrv_inherited_fmt_options(int *child_flags, QDict *child_options,
7208e2160e2SKevin Wolf                                        int parent_flags, QDict *parent_options)
721f3930ed0SKevin Wolf {
7228e2160e2SKevin Wolf     child_file.inherit_options(child_flags, child_options,
7238e2160e2SKevin Wolf                                parent_flags, parent_options);
7248e2160e2SKevin Wolf 
7258e2160e2SKevin Wolf     *child_flags &= ~BDRV_O_PROTOCOL;
726f3930ed0SKevin Wolf }
727f3930ed0SKevin Wolf 
728f3930ed0SKevin Wolf const BdrvChildRole child_format = {
7298e2160e2SKevin Wolf     .inherit_options = bdrv_inherited_fmt_options,
730f3930ed0SKevin Wolf };
731f3930ed0SKevin Wolf 
732317fc44eSKevin Wolf /*
7338e2160e2SKevin Wolf  * Returns the options and flags that bs->backing should get, based on the
7348e2160e2SKevin Wolf  * given options and flags for the parent BDS
735317fc44eSKevin Wolf  */
7368e2160e2SKevin Wolf static void bdrv_backing_options(int *child_flags, QDict *child_options,
7378e2160e2SKevin Wolf                                  int parent_flags, QDict *parent_options)
738317fc44eSKevin Wolf {
7398e2160e2SKevin Wolf     int flags = parent_flags;
7408e2160e2SKevin Wolf 
741b8816a43SKevin Wolf     /* The cache mode is inherited unmodified for backing files; except WCE,
742b8816a43SKevin Wolf      * which is only applied on the top level (BlockBackend) */
743b8816a43SKevin Wolf     qdict_set_default_str(child_options, BDRV_OPT_CACHE_WB, "on");
74491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
74591a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
74691a097e7SKevin Wolf 
747317fc44eSKevin Wolf     /* backing files always opened read-only */
748317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
749317fc44eSKevin Wolf 
750317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7518bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
752317fc44eSKevin Wolf 
7538e2160e2SKevin Wolf     *child_flags = flags;
754317fc44eSKevin Wolf }
755317fc44eSKevin Wolf 
756f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7578e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
758f3930ed0SKevin Wolf };
759f3930ed0SKevin Wolf 
7607b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7617b272452SKevin Wolf {
7627b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7637b272452SKevin Wolf 
7647b272452SKevin Wolf     /*
7657b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7667b272452SKevin Wolf      * image.
7677b272452SKevin Wolf      */
76820cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7697b272452SKevin Wolf 
7707b272452SKevin Wolf     /*
7717b272452SKevin Wolf      * Snapshots should be writable.
7727b272452SKevin Wolf      */
7738bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7747b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7757b272452SKevin Wolf     }
7767b272452SKevin Wolf 
7777b272452SKevin Wolf     return open_flags;
7787b272452SKevin Wolf }
7797b272452SKevin Wolf 
78091a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
78191a097e7SKevin Wolf {
78291a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
78391a097e7SKevin Wolf 
78491a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_WB));
78591a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, false)) {
78691a097e7SKevin Wolf         *flags |= BDRV_O_CACHE_WB;
78791a097e7SKevin Wolf     }
78891a097e7SKevin Wolf 
78991a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
79091a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
79191a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
79291a097e7SKevin Wolf     }
79391a097e7SKevin Wolf 
79491a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
79591a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
79691a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
79791a097e7SKevin Wolf     }
79891a097e7SKevin Wolf }
79991a097e7SKevin Wolf 
80091a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
80191a097e7SKevin Wolf {
80291a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_WB)) {
80391a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_WB,
80491a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_CACHE_WB));
80591a097e7SKevin Wolf     }
80691a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
80791a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
80891a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
80991a097e7SKevin Wolf     }
81091a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
81191a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
81291a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
81391a097e7SKevin Wolf     }
81491a097e7SKevin Wolf }
81591a097e7SKevin Wolf 
816636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8176913c0c2SBenoît Canet                                   const char *node_name,
8186913c0c2SBenoît Canet                                   Error **errp)
8196913c0c2SBenoît Canet {
82015489c76SJeff Cody     char *gen_node_name = NULL;
8216913c0c2SBenoît Canet 
82215489c76SJeff Cody     if (!node_name) {
82315489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
82415489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
82515489c76SJeff Cody         /*
82615489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
82715489c76SJeff Cody          * generated (generated names use characters not available to the user)
82815489c76SJeff Cody          */
8299aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
830636ea370SKevin Wolf         return;
8316913c0c2SBenoît Canet     }
8326913c0c2SBenoît Canet 
8330c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8347f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8350c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8360c5e94eeSBenoît Canet                    node_name);
83715489c76SJeff Cody         goto out;
8380c5e94eeSBenoît Canet     }
8390c5e94eeSBenoît Canet 
8406913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8416913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8426913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
84315489c76SJeff Cody         goto out;
8446913c0c2SBenoît Canet     }
8456913c0c2SBenoît Canet 
8466913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8476913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8486913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
84915489c76SJeff Cody out:
85015489c76SJeff Cody     g_free(gen_node_name);
8516913c0c2SBenoît Canet }
8526913c0c2SBenoît Canet 
85318edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
85418edf289SKevin Wolf     .name = "bdrv_common",
85518edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
85618edf289SKevin Wolf     .desc = {
85718edf289SKevin Wolf         {
85818edf289SKevin Wolf             .name = "node-name",
85918edf289SKevin Wolf             .type = QEMU_OPT_STRING,
86018edf289SKevin Wolf             .help = "Node name of the block device node",
86118edf289SKevin Wolf         },
86262392ebbSKevin Wolf         {
86362392ebbSKevin Wolf             .name = "driver",
86462392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
86562392ebbSKevin Wolf             .help = "Block driver to use for the node",
86662392ebbSKevin Wolf         },
86791a097e7SKevin Wolf         {
86891a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
86991a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87091a097e7SKevin Wolf             .help = "Enable writeback mode",
87191a097e7SKevin Wolf         },
87291a097e7SKevin Wolf         {
87391a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
87491a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87591a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
87691a097e7SKevin Wolf         },
87791a097e7SKevin Wolf         {
87891a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
87991a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
88091a097e7SKevin Wolf             .help = "Ignore flush requests",
88191a097e7SKevin Wolf         },
88218edf289SKevin Wolf         { /* end of list */ }
88318edf289SKevin Wolf     },
88418edf289SKevin Wolf };
88518edf289SKevin Wolf 
886b6ce07aaSKevin Wolf /*
88757915332SKevin Wolf  * Common part for opening disk images and files
888b6ad491aSKevin Wolf  *
889b6ad491aSKevin Wolf  * Removes all processed options from *options.
89057915332SKevin Wolf  */
8919a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
89282dc8b41SKevin Wolf                             QDict *options, Error **errp)
89357915332SKevin Wolf {
89457915332SKevin Wolf     int ret, open_flags;
895035fccdfSKevin Wolf     const char *filename;
89662392ebbSKevin Wolf     const char *driver_name = NULL;
8976913c0c2SBenoît Canet     const char *node_name = NULL;
89818edf289SKevin Wolf     QemuOpts *opts;
89962392ebbSKevin Wolf     BlockDriver *drv;
90034b5d2c6SMax Reitz     Error *local_err = NULL;
90157915332SKevin Wolf 
9026405875cSPaolo Bonzini     assert(bs->file == NULL);
903707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
90457915332SKevin Wolf 
90562392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
90662392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
90762392ebbSKevin Wolf     if (local_err) {
90862392ebbSKevin Wolf         error_propagate(errp, local_err);
90962392ebbSKevin Wolf         ret = -EINVAL;
91062392ebbSKevin Wolf         goto fail_opts;
91162392ebbSKevin Wolf     }
91262392ebbSKevin Wolf 
91362392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
91462392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
91562392ebbSKevin Wolf     assert(drv != NULL);
91662392ebbSKevin Wolf 
91745673671SKevin Wolf     if (file != NULL) {
9189a4f4c31SKevin Wolf         filename = file->bs->filename;
91945673671SKevin Wolf     } else {
92045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
92145673671SKevin Wolf     }
92245673671SKevin Wolf 
923765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
924765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
925765003dbSKevin Wolf                    drv->format_name);
92618edf289SKevin Wolf         ret = -EINVAL;
92718edf289SKevin Wolf         goto fail_opts;
92818edf289SKevin Wolf     }
92918edf289SKevin Wolf 
93082dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
93182dc8b41SKevin Wolf                            drv->format_name);
93262392ebbSKevin Wolf 
93318edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
934636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9350fb6395cSMarkus Armbruster     if (local_err) {
936636ea370SKevin Wolf         error_propagate(errp, local_err);
93718edf289SKevin Wolf         ret = -EINVAL;
93818edf289SKevin Wolf         goto fail_opts;
9395d186eb0SKevin Wolf     }
9405d186eb0SKevin Wolf 
941c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9420d51b4deSAsias He     bs->zero_beyond_eof = true;
94382dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
944b64ec4e4SFam Zheng 
945b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9468f94a6e4SKevin Wolf         error_setg(errp,
9478f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9488f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9498f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9508f94a6e4SKevin Wolf                    drv->format_name);
95118edf289SKevin Wolf         ret = -ENOTSUP;
95218edf289SKevin Wolf         goto fail_opts;
953b64ec4e4SFam Zheng     }
95457915332SKevin Wolf 
95553fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
95682dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9570ebd24e0SKevin Wolf         if (!bs->read_only) {
95853fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9590ebd24e0SKevin Wolf         } else {
9600ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
96118edf289SKevin Wolf             ret = -EINVAL;
96218edf289SKevin Wolf             goto fail_opts;
9630ebd24e0SKevin Wolf         }
96453fec9d3SStefan Hajnoczi     }
96553fec9d3SStefan Hajnoczi 
966c2ad1b0cSKevin Wolf     if (filename != NULL) {
96757915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
968c2ad1b0cSKevin Wolf     } else {
969c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
970c2ad1b0cSKevin Wolf     }
97191af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97257915332SKevin Wolf 
97357915332SKevin Wolf     bs->drv = drv;
9747267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
97557915332SKevin Wolf 
97691a097e7SKevin Wolf     /* Apply cache mode options */
97791a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
978*73ac451fSKevin Wolf 
979*73ac451fSKevin Wolf     if (!bs->blk && (bs->open_flags & BDRV_O_CACHE_WB) == 0) {
980*73ac451fSKevin Wolf         error_setg(errp, "Can't set writethrough mode except for the root");
981*73ac451fSKevin Wolf         ret = -EINVAL;
982*73ac451fSKevin Wolf         goto free_and_fail;
983*73ac451fSKevin Wolf     }
984*73ac451fSKevin Wolf 
98591a097e7SKevin Wolf     bdrv_set_enable_write_cache(bs, bs->open_flags & BDRV_O_CACHE_WB);
986e7c63796SStefan Hajnoczi 
98766f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
98882dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
98966f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9905d186eb0SKevin Wolf         assert(file == NULL);
991030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
99234b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
993f500a6d3SKevin Wolf     } else {
9942af5ef70SKevin Wolf         if (file == NULL) {
99534b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
99634b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9972af5ef70SKevin Wolf             ret = -EINVAL;
9982af5ef70SKevin Wolf             goto free_and_fail;
9992af5ef70SKevin Wolf         }
1000f500a6d3SKevin Wolf         bs->file = file;
100134b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
100266f82ceeSKevin Wolf     }
100366f82ceeSKevin Wolf 
100457915332SKevin Wolf     if (ret < 0) {
100584d18f06SMarkus Armbruster         if (local_err) {
100634b5d2c6SMax Reitz             error_propagate(errp, local_err);
10072fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
10082fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
100934b5d2c6SMax Reitz         } else {
101034b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
101134b5d2c6SMax Reitz         }
101257915332SKevin Wolf         goto free_and_fail;
101357915332SKevin Wolf     }
101457915332SKevin Wolf 
1015a1f688f4SMarkus Armbruster     if (bs->encrypted) {
1016a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
1017a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
1018a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
1019a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
1020a1f688f4SMarkus Armbruster     }
1021a1f688f4SMarkus Armbruster 
102251762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
102351762288SStefan Hajnoczi     if (ret < 0) {
102434b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
102551762288SStefan Hajnoczi         goto free_and_fail;
102657915332SKevin Wolf     }
102751762288SStefan Hajnoczi 
10283baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10293baca891SKevin Wolf     if (local_err) {
10303baca891SKevin Wolf         error_propagate(errp, local_err);
10313baca891SKevin Wolf         ret = -EINVAL;
10323baca891SKevin Wolf         goto free_and_fail;
10333baca891SKevin Wolf     }
10343baca891SKevin Wolf 
1035c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10364196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1037b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
103818edf289SKevin Wolf 
103918edf289SKevin Wolf     qemu_opts_del(opts);
104057915332SKevin Wolf     return 0;
104157915332SKevin Wolf 
104257915332SKevin Wolf free_and_fail:
104366f82ceeSKevin Wolf     bs->file = NULL;
10447267c094SAnthony Liguori     g_free(bs->opaque);
104557915332SKevin Wolf     bs->opaque = NULL;
104657915332SKevin Wolf     bs->drv = NULL;
104718edf289SKevin Wolf fail_opts:
104818edf289SKevin Wolf     qemu_opts_del(opts);
104957915332SKevin Wolf     return ret;
105057915332SKevin Wolf }
105157915332SKevin Wolf 
10525e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10535e5c4f63SKevin Wolf {
10545e5c4f63SKevin Wolf     QObject *options_obj;
10555e5c4f63SKevin Wolf     QDict *options;
10565e5c4f63SKevin Wolf     int ret;
10575e5c4f63SKevin Wolf 
10585e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10595e5c4f63SKevin Wolf     assert(ret);
10605e5c4f63SKevin Wolf 
10615e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10625e5c4f63SKevin Wolf     if (!options_obj) {
10635e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10645e5c4f63SKevin Wolf         return NULL;
10655e5c4f63SKevin Wolf     }
10665e5c4f63SKevin Wolf 
10675e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10685e5c4f63SKevin Wolf         qobject_decref(options_obj);
10695e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10705e5c4f63SKevin Wolf         return NULL;
10715e5c4f63SKevin Wolf     }
10725e5c4f63SKevin Wolf 
10735e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10745e5c4f63SKevin Wolf     qdict_flatten(options);
10755e5c4f63SKevin Wolf 
10765e5c4f63SKevin Wolf     return options;
10775e5c4f63SKevin Wolf }
10785e5c4f63SKevin Wolf 
1079de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1080de3b53f0SKevin Wolf                                 Error **errp)
1081de3b53f0SKevin Wolf {
1082de3b53f0SKevin Wolf     QDict *json_options;
1083de3b53f0SKevin Wolf     Error *local_err = NULL;
1084de3b53f0SKevin Wolf 
1085de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1086de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1087de3b53f0SKevin Wolf         return;
1088de3b53f0SKevin Wolf     }
1089de3b53f0SKevin Wolf 
1090de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1091de3b53f0SKevin Wolf     if (local_err) {
1092de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1093de3b53f0SKevin Wolf         return;
1094de3b53f0SKevin Wolf     }
1095de3b53f0SKevin Wolf 
1096de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1097de3b53f0SKevin Wolf      * specified directly */
1098de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1099de3b53f0SKevin Wolf     QDECREF(json_options);
1100de3b53f0SKevin Wolf     *pfilename = NULL;
1101de3b53f0SKevin Wolf }
1102de3b53f0SKevin Wolf 
110357915332SKevin Wolf /*
1104f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1105f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
110653a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
110753a29513SMax Reitz  * block driver has been specified explicitly.
1108f54120ffSKevin Wolf  */
1109de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1110053e1578SMax Reitz                              int *flags, Error **errp)
1111f54120ffSKevin Wolf {
1112f54120ffSKevin Wolf     const char *drvname;
111353a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1114f54120ffSKevin Wolf     bool parse_filename = false;
1115053e1578SMax Reitz     BlockDriver *drv = NULL;
1116f54120ffSKevin Wolf     Error *local_err = NULL;
1117f54120ffSKevin Wolf 
111853a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1119053e1578SMax Reitz     if (drvname) {
1120053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1121053e1578SMax Reitz         if (!drv) {
1122053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1123053e1578SMax Reitz             return -ENOENT;
1124053e1578SMax Reitz         }
112553a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
112653a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1127053e1578SMax Reitz         protocol = drv->bdrv_file_open;
112853a29513SMax Reitz     }
112953a29513SMax Reitz 
113053a29513SMax Reitz     if (protocol) {
113153a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
113253a29513SMax Reitz     } else {
113353a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
113453a29513SMax Reitz     }
113553a29513SMax Reitz 
113691a097e7SKevin Wolf     /* Translate cache options from flags into options */
113791a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
113891a097e7SKevin Wolf 
1139f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
114017b005f1SKevin Wolf     if (protocol && filename) {
1141f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1142f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1143f54120ffSKevin Wolf             parse_filename = true;
1144f54120ffSKevin Wolf         } else {
1145f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1146f54120ffSKevin Wolf                              "the same time");
1147f54120ffSKevin Wolf             return -EINVAL;
1148f54120ffSKevin Wolf         }
1149f54120ffSKevin Wolf     }
1150f54120ffSKevin Wolf 
1151f54120ffSKevin Wolf     /* Find the right block driver */
1152f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1153f54120ffSKevin Wolf 
115417b005f1SKevin Wolf     if (!drvname && protocol) {
1155f54120ffSKevin Wolf         if (filename) {
1156b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1157f54120ffSKevin Wolf             if (!drv) {
1158f54120ffSKevin Wolf                 return -EINVAL;
1159f54120ffSKevin Wolf             }
1160f54120ffSKevin Wolf 
1161f54120ffSKevin Wolf             drvname = drv->format_name;
1162f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1163f54120ffSKevin Wolf         } else {
1164f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1165f54120ffSKevin Wolf             return -EINVAL;
1166f54120ffSKevin Wolf         }
116717b005f1SKevin Wolf     }
116817b005f1SKevin Wolf 
116917b005f1SKevin Wolf     assert(drv || !protocol);
1170f54120ffSKevin Wolf 
1171f54120ffSKevin Wolf     /* Driver-specific filename parsing */
117217b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1173f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1174f54120ffSKevin Wolf         if (local_err) {
1175f54120ffSKevin Wolf             error_propagate(errp, local_err);
1176f54120ffSKevin Wolf             return -EINVAL;
1177f54120ffSKevin Wolf         }
1178f54120ffSKevin Wolf 
1179f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1180f54120ffSKevin Wolf             qdict_del(*options, "filename");
1181f54120ffSKevin Wolf         }
1182f54120ffSKevin Wolf     }
1183f54120ffSKevin Wolf 
1184f54120ffSKevin Wolf     return 0;
1185f54120ffSKevin Wolf }
1186f54120ffSKevin Wolf 
1187f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1188260fecf1SKevin Wolf                                   const char *child_name,
1189df581792SKevin Wolf                                   const BdrvChildRole *child_role)
1190df581792SKevin Wolf {
1191df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1192df581792SKevin Wolf     *child = (BdrvChild) {
1193df581792SKevin Wolf         .bs     = child_bs,
1194260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1195df581792SKevin Wolf         .role   = child_role,
1196df581792SKevin Wolf     };
1197df581792SKevin Wolf 
1198d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1199b4b059f6SKevin Wolf 
1200b4b059f6SKevin Wolf     return child;
1201df581792SKevin Wolf }
1202df581792SKevin Wolf 
1203f21d96d0SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1204f21d96d0SKevin Wolf                                     BlockDriverState *child_bs,
1205f21d96d0SKevin Wolf                                     const char *child_name,
1206f21d96d0SKevin Wolf                                     const BdrvChildRole *child_role)
1207f21d96d0SKevin Wolf {
1208f21d96d0SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role);
1209f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1210f21d96d0SKevin Wolf     return child;
1211f21d96d0SKevin Wolf }
1212f21d96d0SKevin Wolf 
12133f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
121433a60407SKevin Wolf {
1215f21d96d0SKevin Wolf     if (child->next.le_prev) {
121633a60407SKevin Wolf         QLIST_REMOVE(child, next);
1217f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1218f21d96d0SKevin Wolf     }
1219d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1220260fecf1SKevin Wolf     g_free(child->name);
122133a60407SKevin Wolf     g_free(child);
122233a60407SKevin Wolf }
122333a60407SKevin Wolf 
1224f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
122533a60407SKevin Wolf {
1226779020cbSKevin Wolf     BlockDriverState *child_bs;
1227779020cbSKevin Wolf 
1228f21d96d0SKevin Wolf     child_bs = child->bs;
1229f21d96d0SKevin Wolf     bdrv_detach_child(child);
1230f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1231f21d96d0SKevin Wolf }
1232f21d96d0SKevin Wolf 
1233f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1234f21d96d0SKevin Wolf {
1235779020cbSKevin Wolf     if (child == NULL) {
1236779020cbSKevin Wolf         return;
1237779020cbSKevin Wolf     }
123833a60407SKevin Wolf 
123933a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
124033a60407SKevin Wolf         child->bs->inherits_from = NULL;
124133a60407SKevin Wolf     }
124233a60407SKevin Wolf 
1243f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
124433a60407SKevin Wolf }
124533a60407SKevin Wolf 
12465db15a57SKevin Wolf /*
12475db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12485db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12495db15a57SKevin Wolf  */
12508d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12518d24cce1SFam Zheng {
12525db15a57SKevin Wolf     if (backing_hd) {
12535db15a57SKevin Wolf         bdrv_ref(backing_hd);
12545db15a57SKevin Wolf     }
12558d24cce1SFam Zheng 
1256760e0063SKevin Wolf     if (bs->backing) {
1257826b6ca0SFam Zheng         assert(bs->backing_blocker);
1258760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12595db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1260826b6ca0SFam Zheng     } else if (backing_hd) {
1261826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
126281e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
126381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1264826b6ca0SFam Zheng     }
1265826b6ca0SFam Zheng 
12668d24cce1SFam Zheng     if (!backing_hd) {
1267826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1268826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1269760e0063SKevin Wolf         bs->backing = NULL;
12708d24cce1SFam Zheng         goto out;
12718d24cce1SFam Zheng     }
1272260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
12738d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
12748d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
12758d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
12768d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1277826b6ca0SFam Zheng 
1278760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1279826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1280760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1281826b6ca0SFam Zheng                     bs->backing_blocker);
12828d24cce1SFam Zheng out:
12833baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
12848d24cce1SFam Zheng }
12858d24cce1SFam Zheng 
128631ca6d07SKevin Wolf /*
128731ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
128831ca6d07SKevin Wolf  *
1289d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1290d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1291d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1292d9b7b057SKevin Wolf  * BlockdevRef.
1293d9b7b057SKevin Wolf  *
1294d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
129531ca6d07SKevin Wolf  */
1296d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1297d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12989156df12SPaolo Bonzini {
12991ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1300d9b7b057SKevin Wolf     char *bdref_key_dot;
1301d9b7b057SKevin Wolf     const char *reference = NULL;
1302317fc44eSKevin Wolf     int ret = 0;
13038d24cce1SFam Zheng     BlockDriverState *backing_hd;
1304d9b7b057SKevin Wolf     QDict *options;
1305d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
130634b5d2c6SMax Reitz     Error *local_err = NULL;
13079156df12SPaolo Bonzini 
1308760e0063SKevin Wolf     if (bs->backing != NULL) {
13091ba4b6a5SBenoît Canet         goto free_exit;
13109156df12SPaolo Bonzini     }
13119156df12SPaolo Bonzini 
131231ca6d07SKevin Wolf     /* NULL means an empty set of options */
1313d9b7b057SKevin Wolf     if (parent_options == NULL) {
1314d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1315d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
131631ca6d07SKevin Wolf     }
131731ca6d07SKevin Wolf 
13189156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1319d9b7b057SKevin Wolf 
1320d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1321d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1322d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1323d9b7b057SKevin Wolf 
1324d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1325d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13261cb6f506SKevin Wolf         backing_filename[0] = '\0';
13271cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
132831ca6d07SKevin Wolf         QDECREF(options);
13291ba4b6a5SBenoît Canet         goto free_exit;
1330dbecebddSFam Zheng     } else {
13319f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13329f07429eSMax Reitz                                        &local_err);
13339f07429eSMax Reitz         if (local_err) {
13349f07429eSMax Reitz             ret = -EINVAL;
13359f07429eSMax Reitz             error_propagate(errp, local_err);
13369f07429eSMax Reitz             QDECREF(options);
13379f07429eSMax Reitz             goto free_exit;
13389f07429eSMax Reitz         }
13399156df12SPaolo Bonzini     }
13409156df12SPaolo Bonzini 
13418ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13428ee79e70SKevin Wolf         ret = -EINVAL;
13438ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13448ee79e70SKevin Wolf         QDECREF(options);
13458ee79e70SKevin Wolf         goto free_exit;
13468ee79e70SKevin Wolf     }
13478ee79e70SKevin Wolf 
1348c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1349c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13509156df12SPaolo Bonzini     }
13519156df12SPaolo Bonzini 
1352d9b7b057SKevin Wolf     backing_hd = NULL;
1353f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1354f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1355d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1356e43bfd9cSMarkus Armbruster                             errp);
13579156df12SPaolo Bonzini     if (ret < 0) {
13589156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1359e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13601ba4b6a5SBenoît Canet         goto free_exit;
13619156df12SPaolo Bonzini     }
1362df581792SKevin Wolf 
13635db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13645db15a57SKevin Wolf      * backing_hd reference now */
13658d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13665db15a57SKevin Wolf     bdrv_unref(backing_hd);
1367d80ac658SPeter Feiner 
1368d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1369d9b7b057SKevin Wolf 
13701ba4b6a5SBenoît Canet free_exit:
13711ba4b6a5SBenoît Canet     g_free(backing_filename);
1372d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
13731ba4b6a5SBenoît Canet     return ret;
13749156df12SPaolo Bonzini }
13759156df12SPaolo Bonzini 
1376b6ce07aaSKevin Wolf /*
1377da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1378da557aacSMax Reitz  * device's options.
1379da557aacSMax Reitz  *
1380da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1381b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1382da557aacSMax Reitz  *
1383da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1384da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1385da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1386da557aacSMax Reitz  * BlockdevRef.
1387da557aacSMax Reitz  *
1388da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1389da557aacSMax Reitz  */
1390b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1391f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1392b4b059f6SKevin Wolf                            BlockDriverState* parent,
1393b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1394f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1395da557aacSMax Reitz {
1396b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1397b4b059f6SKevin Wolf     BlockDriverState *bs;
1398da557aacSMax Reitz     QDict *image_options;
1399da557aacSMax Reitz     int ret;
1400da557aacSMax Reitz     char *bdref_key_dot;
1401da557aacSMax Reitz     const char *reference;
1402da557aacSMax Reitz 
1403df581792SKevin Wolf     assert(child_role != NULL);
1404f67503e5SMax Reitz 
1405da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1406da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1407da557aacSMax Reitz     g_free(bdref_key_dot);
1408da557aacSMax Reitz 
1409da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1410da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1411b4b059f6SKevin Wolf         if (!allow_none) {
1412da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1413da557aacSMax Reitz                        bdref_key);
1414da557aacSMax Reitz         }
1415b20e61e0SMarkus Armbruster         QDECREF(image_options);
1416da557aacSMax Reitz         goto done;
1417da557aacSMax Reitz     }
1418da557aacSMax Reitz 
1419b4b059f6SKevin Wolf     bs = NULL;
1420b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1421ce343771SMax Reitz                             parent, child_role, errp);
1422df581792SKevin Wolf     if (ret < 0) {
1423df581792SKevin Wolf         goto done;
1424df581792SKevin Wolf     }
1425df581792SKevin Wolf 
1426260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1427da557aacSMax Reitz 
1428da557aacSMax Reitz done:
1429da557aacSMax Reitz     qdict_del(options, bdref_key);
1430b4b059f6SKevin Wolf     return c;
1431b4b059f6SKevin Wolf }
1432b4b059f6SKevin Wolf 
143373176beeSKevin Wolf static int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags,
143473176beeSKevin Wolf                                      QDict *snapshot_options, Error **errp)
1435b998875dSKevin Wolf {
1436b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14371ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1438b998875dSKevin Wolf     int64_t total_size;
143983d0521aSChunyan Liu     QemuOpts *opts = NULL;
1440b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1441c2e0dbbfSFam Zheng     Error *local_err = NULL;
1442b998875dSKevin Wolf     int ret;
1443b998875dSKevin Wolf 
1444b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1445b998875dSKevin Wolf        instead of opening 'filename' directly */
1446b998875dSKevin Wolf 
1447b998875dSKevin Wolf     /* Get the required size from the image */
1448f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1449f187743aSKevin Wolf     if (total_size < 0) {
14506b8aeca5SChen Gang         ret = total_size;
1451f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14521ba4b6a5SBenoît Canet         goto out;
1453f187743aSKevin Wolf     }
1454b998875dSKevin Wolf 
1455b998875dSKevin Wolf     /* Create the temporary image */
14561ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1457b998875dSKevin Wolf     if (ret < 0) {
1458b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14591ba4b6a5SBenoît Canet         goto out;
1460b998875dSKevin Wolf     }
1461b998875dSKevin Wolf 
1462ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1463c282e1fdSChunyan Liu                             &error_abort);
146439101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1465e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
146683d0521aSChunyan Liu     qemu_opts_del(opts);
1467b998875dSKevin Wolf     if (ret < 0) {
1468e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1469e43bfd9cSMarkus Armbruster                       tmp_filename);
14701ba4b6a5SBenoît Canet         goto out;
1471b998875dSKevin Wolf     }
1472b998875dSKevin Wolf 
147373176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1474b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1475b998875dSKevin Wolf               qstring_from_str("file"));
1476b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1477b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1478e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1479e6641719SMax Reitz               qstring_from_str("qcow2"));
1480b998875dSKevin Wolf 
1481e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1482b998875dSKevin Wolf 
1483b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
14846ebf9aa2SMax Reitz                     flags, &local_err);
148573176beeSKevin Wolf     snapshot_options = NULL;
1486b998875dSKevin Wolf     if (ret < 0) {
1487b998875dSKevin Wolf         error_propagate(errp, local_err);
14881ba4b6a5SBenoît Canet         goto out;
1489b998875dSKevin Wolf     }
1490b998875dSKevin Wolf 
1491b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14921ba4b6a5SBenoît Canet 
14931ba4b6a5SBenoît Canet out:
149473176beeSKevin Wolf     QDECREF(snapshot_options);
14951ba4b6a5SBenoît Canet     g_free(tmp_filename);
14966b8aeca5SChen Gang     return ret;
1497b998875dSKevin Wolf }
1498b998875dSKevin Wolf 
1499da557aacSMax Reitz /*
1500b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1501de9c0cecSKevin Wolf  *
1502de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1503de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1504de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1505de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1506f67503e5SMax Reitz  *
1507f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1508f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1509ddf5636dSMax Reitz  *
1510ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1511ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1512ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1513b6ce07aaSKevin Wolf  */
1514f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1515ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1516f3930ed0SKevin Wolf                              BlockDriverState *parent,
1517ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1518ea2384d3Sbellard {
1519b6ce07aaSKevin Wolf     int ret;
15209a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15219a4f4c31SKevin Wolf     BlockDriverState *bs;
1522ce343771SMax Reitz     BlockDriver *drv = NULL;
152374fe54f2SKevin Wolf     const char *drvname;
15243e8c2e57SAlberto Garcia     const char *backing;
152534b5d2c6SMax Reitz     Error *local_err = NULL;
152673176beeSKevin Wolf     QDict *snapshot_options = NULL;
1527b1e6fc08SKevin Wolf     int snapshot_flags = 0;
152833e3963eSbellard 
1529f67503e5SMax Reitz     assert(pbs);
1530f3930ed0SKevin Wolf     assert(!child_role || !flags);
1531f3930ed0SKevin Wolf     assert(!child_role == !parent);
1532f67503e5SMax Reitz 
1533ddf5636dSMax Reitz     if (reference) {
1534ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1535ddf5636dSMax Reitz         QDECREF(options);
1536ddf5636dSMax Reitz 
1537ddf5636dSMax Reitz         if (*pbs) {
1538ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1539ddf5636dSMax Reitz                        "another block device");
1540ddf5636dSMax Reitz             return -EINVAL;
1541ddf5636dSMax Reitz         }
1542ddf5636dSMax Reitz 
1543ddf5636dSMax Reitz         if (filename || options_non_empty) {
1544ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1545ddf5636dSMax Reitz                        "additional options or a new filename");
1546ddf5636dSMax Reitz             return -EINVAL;
1547ddf5636dSMax Reitz         }
1548ddf5636dSMax Reitz 
1549ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1550ddf5636dSMax Reitz         if (!bs) {
1551ddf5636dSMax Reitz             return -ENODEV;
1552ddf5636dSMax Reitz         }
1553ddf5636dSMax Reitz         bdrv_ref(bs);
1554ddf5636dSMax Reitz         *pbs = bs;
1555ddf5636dSMax Reitz         return 0;
1556ddf5636dSMax Reitz     }
1557ddf5636dSMax Reitz 
1558f67503e5SMax Reitz     if (*pbs) {
1559f67503e5SMax Reitz         bs = *pbs;
1560f67503e5SMax Reitz     } else {
1561e4e9986bSMarkus Armbruster         bs = bdrv_new();
1562f67503e5SMax Reitz     }
1563f67503e5SMax Reitz 
1564de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1565de9c0cecSKevin Wolf     if (options == NULL) {
1566de9c0cecSKevin Wolf         options = qdict_new();
1567de9c0cecSKevin Wolf     }
1568de9c0cecSKevin Wolf 
1569145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1570de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1571de3b53f0SKevin Wolf     if (local_err) {
1572de3b53f0SKevin Wolf         ret = -EINVAL;
1573de3b53f0SKevin Wolf         goto fail;
1574de3b53f0SKevin Wolf     }
1575de3b53f0SKevin Wolf 
1576145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1577145f598eSKevin Wolf 
1578f3930ed0SKevin Wolf     if (child_role) {
1579bddcec37SKevin Wolf         bs->inherits_from = parent;
15808e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
15818e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1582f3930ed0SKevin Wolf     }
1583f3930ed0SKevin Wolf 
1584de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1585462f5bcfSKevin Wolf     if (local_err) {
1586462f5bcfSKevin Wolf         goto fail;
1587462f5bcfSKevin Wolf     }
1588462f5bcfSKevin Wolf 
158962392ebbSKevin Wolf     bs->open_flags = flags;
159062392ebbSKevin Wolf     bs->options = options;
159162392ebbSKevin Wolf     options = qdict_clone_shallow(options);
159262392ebbSKevin Wolf 
159376c591b0SKevin Wolf     /* Find the right image format driver */
159476c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
159576c591b0SKevin Wolf     if (drvname) {
159676c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
159776c591b0SKevin Wolf         if (!drv) {
159876c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
159976c591b0SKevin Wolf             ret = -EINVAL;
160076c591b0SKevin Wolf             goto fail;
160176c591b0SKevin Wolf         }
160276c591b0SKevin Wolf     }
160376c591b0SKevin Wolf 
160476c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
160576c591b0SKevin Wolf 
16063e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
16073e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16083e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16093e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16103e8c2e57SAlberto Garcia     }
16113e8c2e57SAlberto Garcia 
1612f500a6d3SKevin Wolf     /* Open image file without format layer */
1613f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1614be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1615be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1616be028adcSJeff Cody         }
1617b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
161873176beeSKevin Wolf             snapshot_options = qdict_new();
161973176beeSKevin Wolf             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
162073176beeSKevin Wolf                                        flags, options);
16218e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1622b1e6fc08SKevin Wolf         }
1623be028adcSJeff Cody 
1624f3930ed0SKevin Wolf         bs->open_flags = flags;
16251fdd6933SKevin Wolf 
16269a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16271fdd6933SKevin Wolf                                &child_file, true, &local_err);
16281fdd6933SKevin Wolf         if (local_err) {
16291fdd6933SKevin Wolf             ret = -EINVAL;
16308bfea15dSKevin Wolf             goto fail;
1631f500a6d3SKevin Wolf         }
1632f4788adcSKevin Wolf     }
1633f500a6d3SKevin Wolf 
163476c591b0SKevin Wolf     /* Image format probing */
163538f3ef57SKevin Wolf     bs->probed = !drv;
163676c591b0SKevin Wolf     if (!drv && file) {
16379a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
163817b005f1SKevin Wolf         if (ret < 0) {
163917b005f1SKevin Wolf             goto fail;
164017b005f1SKevin Wolf         }
164162392ebbSKevin Wolf         /*
164262392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
164362392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
164462392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
164562392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
164662392ebbSKevin Wolf          *
164762392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
164862392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
164962392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
165062392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
165162392ebbSKevin Wolf          */
165262392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
165362392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
165476c591b0SKevin Wolf     } else if (!drv) {
16552a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16562a05cbe4SMax Reitz         ret = -EINVAL;
16578bfea15dSKevin Wolf         goto fail;
16582a05cbe4SMax Reitz     }
1659f500a6d3SKevin Wolf 
166053a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
166153a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
166253a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
166353a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
166453a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
166553a29513SMax Reitz 
1666b6ce07aaSKevin Wolf     /* Open the image */
166782dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1668b6ce07aaSKevin Wolf     if (ret < 0) {
16698bfea15dSKevin Wolf         goto fail;
16706987307cSChristoph Hellwig     }
16716987307cSChristoph Hellwig 
16722a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16739a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1674f500a6d3SKevin Wolf         file = NULL;
1675f500a6d3SKevin Wolf     }
1676f500a6d3SKevin Wolf 
1677b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16789156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1679d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1680b6ce07aaSKevin Wolf         if (ret < 0) {
1681b6ad491aSKevin Wolf             goto close_and_fail;
1682b6ce07aaSKevin Wolf         }
1683b6ce07aaSKevin Wolf     }
1684b6ce07aaSKevin Wolf 
168591af7014SMax Reitz     bdrv_refresh_filename(bs);
168691af7014SMax Reitz 
1687b6ad491aSKevin Wolf     /* Check if any unknown options were used */
16885acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1689b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
16905acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
16915acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
16925acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
16935acd9d81SMax Reitz         } else {
1694d0e46a55SMax Reitz             error_setg(errp,
1695d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1696d0e46a55SMax Reitz                        drv->format_name, entry->key);
16975acd9d81SMax Reitz         }
1698b6ad491aSKevin Wolf 
1699b6ad491aSKevin Wolf         ret = -EINVAL;
1700b6ad491aSKevin Wolf         goto close_and_fail;
1701b6ad491aSKevin Wolf     }
1702b6ad491aSKevin Wolf 
1703b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1704a7f53e26SMarkus Armbruster         if (bs->blk) {
1705a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1706a7f53e26SMarkus Armbruster         }
1707c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1708c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1709c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1710c3adb58fSMarkus Armbruster         error_setg(errp,
1711c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1712c3adb58fSMarkus Armbruster         ret = -EBUSY;
1713c3adb58fSMarkus Armbruster         goto close_and_fail;
1714b6ce07aaSKevin Wolf     }
1715b6ce07aaSKevin Wolf 
1716c3adb58fSMarkus Armbruster     QDECREF(options);
1717f67503e5SMax Reitz     *pbs = bs;
1718dd62f1caSKevin Wolf 
1719dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1720dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1721dd62f1caSKevin Wolf     if (snapshot_flags) {
172273176beeSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, snapshot_options,
172373176beeSKevin Wolf                                         &local_err);
172473176beeSKevin Wolf         snapshot_options = NULL;
1725dd62f1caSKevin Wolf         if (local_err) {
1726dd62f1caSKevin Wolf             goto close_and_fail;
1727dd62f1caSKevin Wolf         }
1728dd62f1caSKevin Wolf     }
1729dd62f1caSKevin Wolf 
1730b6ce07aaSKevin Wolf     return 0;
1731b6ce07aaSKevin Wolf 
17328bfea15dSKevin Wolf fail:
1733f500a6d3SKevin Wolf     if (file != NULL) {
17349a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1735f500a6d3SKevin Wolf     }
173673176beeSKevin Wolf     QDECREF(snapshot_options);
1737145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1738de9c0cecSKevin Wolf     QDECREF(bs->options);
1739b6ad491aSKevin Wolf     QDECREF(options);
1740de9c0cecSKevin Wolf     bs->options = NULL;
1741f67503e5SMax Reitz     if (!*pbs) {
1742f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1743f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1744f67503e5SMax Reitz            since it has not really been opened yet. */
1745f67503e5SMax Reitz         bdrv_unref(bs);
1746f67503e5SMax Reitz     }
174784d18f06SMarkus Armbruster     if (local_err) {
174834b5d2c6SMax Reitz         error_propagate(errp, local_err);
174934b5d2c6SMax Reitz     }
1750b6ad491aSKevin Wolf     return ret;
1751de9c0cecSKevin Wolf 
1752b6ad491aSKevin Wolf close_and_fail:
1753f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1754f67503e5SMax Reitz     if (*pbs) {
1755b6ad491aSKevin Wolf         bdrv_close(bs);
1756f67503e5SMax Reitz     } else {
1757f67503e5SMax Reitz         bdrv_unref(bs);
1758f67503e5SMax Reitz     }
175973176beeSKevin Wolf     QDECREF(snapshot_options);
1760b6ad491aSKevin Wolf     QDECREF(options);
176184d18f06SMarkus Armbruster     if (local_err) {
176234b5d2c6SMax Reitz         error_propagate(errp, local_err);
176334b5d2c6SMax Reitz     }
1764b6ce07aaSKevin Wolf     return ret;
1765b6ce07aaSKevin Wolf }
1766b6ce07aaSKevin Wolf 
1767f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
17686ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1769f3930ed0SKevin Wolf {
1770f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1771ce343771SMax Reitz                              NULL, errp);
1772f3930ed0SKevin Wolf }
1773f3930ed0SKevin Wolf 
1774e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1775e971aa12SJeff Cody      bool prepared;
1776e971aa12SJeff Cody      BDRVReopenState state;
1777e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1778e971aa12SJeff Cody } BlockReopenQueueEntry;
1779e971aa12SJeff Cody 
1780e971aa12SJeff Cody /*
1781e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1782e971aa12SJeff Cody  * reopen of multiple devices.
1783e971aa12SJeff Cody  *
1784e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1785e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1786e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1787e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1788e971aa12SJeff Cody  * atomic 'set'.
1789e971aa12SJeff Cody  *
1790e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1791e971aa12SJeff Cody  *
17924d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17934d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
17944d2cb092SKevin Wolf  *
1795e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1796e971aa12SJeff Cody  *
1797e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1798e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1799e971aa12SJeff Cody  *
1800e971aa12SJeff Cody  */
180128518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
18024d2cb092SKevin Wolf                                                  BlockDriverState *bs,
180328518102SKevin Wolf                                                  QDict *options,
180428518102SKevin Wolf                                                  int flags,
180528518102SKevin Wolf                                                  const BdrvChildRole *role,
180628518102SKevin Wolf                                                  QDict *parent_options,
180728518102SKevin Wolf                                                  int parent_flags)
1808e971aa12SJeff Cody {
1809e971aa12SJeff Cody     assert(bs != NULL);
1810e971aa12SJeff Cody 
1811e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
181267251a31SKevin Wolf     BdrvChild *child;
1813145f598eSKevin Wolf     QDict *old_options, *explicit_options;
181467251a31SKevin Wolf 
1815e971aa12SJeff Cody     if (bs_queue == NULL) {
1816e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1817e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1818e971aa12SJeff Cody     }
1819e971aa12SJeff Cody 
18204d2cb092SKevin Wolf     if (!options) {
18214d2cb092SKevin Wolf         options = qdict_new();
18224d2cb092SKevin Wolf     }
18234d2cb092SKevin Wolf 
182428518102SKevin Wolf     /*
182528518102SKevin Wolf      * Precedence of options:
182628518102SKevin Wolf      * 1. Explicitly passed in options (highest)
182791a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1828145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18298e2160e2SKevin Wolf      * 4. Inherited from parent node
183028518102SKevin Wolf      * 5. Retained from effective options of bs
183128518102SKevin Wolf      */
183228518102SKevin Wolf 
183391a097e7SKevin Wolf     if (!parent_options) {
183491a097e7SKevin Wolf         /*
183591a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
183691a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
183791a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
183891a097e7SKevin Wolf          * not considered.
183991a097e7SKevin Wolf          */
184091a097e7SKevin Wolf         update_options_from_flags(options, flags);
184191a097e7SKevin Wolf     }
184291a097e7SKevin Wolf 
1843145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1844145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1845145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1846145f598eSKevin Wolf     QDECREF(old_options);
1847145f598eSKevin Wolf 
1848145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1849145f598eSKevin Wolf 
185028518102SKevin Wolf     /* Inherit from parent node */
185128518102SKevin Wolf     if (parent_options) {
185228518102SKevin Wolf         assert(!flags);
18538e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
185428518102SKevin Wolf     }
185528518102SKevin Wolf 
185628518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18574d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1858cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18594d2cb092SKevin Wolf     QDECREF(old_options);
18604d2cb092SKevin Wolf 
1861f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1862f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1863f1f25a2eSKevin Wolf 
186467251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18654c9dfe5dSKevin Wolf         QDict *new_child_options;
18664c9dfe5dSKevin Wolf         char *child_key_dot;
186767251a31SKevin Wolf 
18684c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18694c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18704c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
187167251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
187267251a31SKevin Wolf             continue;
187367251a31SKevin Wolf         }
187467251a31SKevin Wolf 
18754c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18764c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18774c9dfe5dSKevin Wolf         g_free(child_key_dot);
18784c9dfe5dSKevin Wolf 
187928518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
188028518102SKevin Wolf                                 child->role, options, flags);
1881e971aa12SJeff Cody     }
1882e971aa12SJeff Cody 
1883e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1884e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1885e971aa12SJeff Cody 
1886e971aa12SJeff Cody     bs_entry->state.bs = bs;
18874d2cb092SKevin Wolf     bs_entry->state.options = options;
1888145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1889e971aa12SJeff Cody     bs_entry->state.flags = flags;
1890e971aa12SJeff Cody 
1891e971aa12SJeff Cody     return bs_queue;
1892e971aa12SJeff Cody }
1893e971aa12SJeff Cody 
189428518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
189528518102SKevin Wolf                                     BlockDriverState *bs,
189628518102SKevin Wolf                                     QDict *options, int flags)
189728518102SKevin Wolf {
189828518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
189928518102SKevin Wolf                                    NULL, NULL, 0);
190028518102SKevin Wolf }
190128518102SKevin Wolf 
1902e971aa12SJeff Cody /*
1903e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1904e971aa12SJeff Cody  *
1905e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1906e971aa12SJeff Cody  * via bdrv_reopen_queue().
1907e971aa12SJeff Cody  *
1908e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1909e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1910e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1911e971aa12SJeff Cody  * data cleaned up.
1912e971aa12SJeff Cody  *
1913e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1914e971aa12SJeff Cody  * to all devices.
1915e971aa12SJeff Cody  *
1916e971aa12SJeff Cody  */
1917e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1918e971aa12SJeff Cody {
1919e971aa12SJeff Cody     int ret = -1;
1920e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1921e971aa12SJeff Cody     Error *local_err = NULL;
1922e971aa12SJeff Cody 
1923e971aa12SJeff Cody     assert(bs_queue != NULL);
1924e971aa12SJeff Cody 
1925e971aa12SJeff Cody     bdrv_drain_all();
1926e971aa12SJeff Cody 
1927e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1928e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1929e971aa12SJeff Cody             error_propagate(errp, local_err);
1930e971aa12SJeff Cody             goto cleanup;
1931e971aa12SJeff Cody         }
1932e971aa12SJeff Cody         bs_entry->prepared = true;
1933e971aa12SJeff Cody     }
1934e971aa12SJeff Cody 
1935e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1936e971aa12SJeff Cody      * changes
1937e971aa12SJeff Cody      */
1938e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1939e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1940e971aa12SJeff Cody     }
1941e971aa12SJeff Cody 
1942e971aa12SJeff Cody     ret = 0;
1943e971aa12SJeff Cody 
1944e971aa12SJeff Cody cleanup:
1945e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1946e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1947e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1948145f598eSKevin Wolf         } else if (ret) {
1949145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1950e971aa12SJeff Cody         }
19514d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1952e971aa12SJeff Cody         g_free(bs_entry);
1953e971aa12SJeff Cody     }
1954e971aa12SJeff Cody     g_free(bs_queue);
1955e971aa12SJeff Cody     return ret;
1956e971aa12SJeff Cody }
1957e971aa12SJeff Cody 
1958e971aa12SJeff Cody 
1959e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1960e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1961e971aa12SJeff Cody {
1962e971aa12SJeff Cody     int ret = -1;
1963e971aa12SJeff Cody     Error *local_err = NULL;
19644d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1965e971aa12SJeff Cody 
1966e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1967e971aa12SJeff Cody     if (local_err != NULL) {
1968e971aa12SJeff Cody         error_propagate(errp, local_err);
1969e971aa12SJeff Cody     }
1970e971aa12SJeff Cody     return ret;
1971e971aa12SJeff Cody }
1972e971aa12SJeff Cody 
1973e971aa12SJeff Cody 
1974e971aa12SJeff Cody /*
1975e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1976e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1977e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1978e971aa12SJeff Cody  *
1979e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1980e971aa12SJeff Cody  * flags are the new open flags
1981e971aa12SJeff Cody  * queue is the reopen queue
1982e971aa12SJeff Cody  *
1983e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1984e971aa12SJeff Cody  * as well.
1985e971aa12SJeff Cody  *
1986e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1987e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1988e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1989e971aa12SJeff Cody  *
1990e971aa12SJeff Cody  */
1991e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1992e971aa12SJeff Cody                         Error **errp)
1993e971aa12SJeff Cody {
1994e971aa12SJeff Cody     int ret = -1;
1995e971aa12SJeff Cody     Error *local_err = NULL;
1996e971aa12SJeff Cody     BlockDriver *drv;
1997ccf9dc07SKevin Wolf     QemuOpts *opts;
1998ccf9dc07SKevin Wolf     const char *value;
1999e971aa12SJeff Cody 
2000e971aa12SJeff Cody     assert(reopen_state != NULL);
2001e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
2002e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2003e971aa12SJeff Cody 
2004ccf9dc07SKevin Wolf     /* Process generic block layer options */
2005ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
2006ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
2007ccf9dc07SKevin Wolf     if (local_err) {
2008ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2009ccf9dc07SKevin Wolf         ret = -EINVAL;
2010ccf9dc07SKevin Wolf         goto error;
2011ccf9dc07SKevin Wolf     }
2012ccf9dc07SKevin Wolf 
201391a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
201491a097e7SKevin Wolf 
201591a097e7SKevin Wolf     /* If a guest device is attached, it owns WCE */
201691a097e7SKevin Wolf     if (reopen_state->bs->blk && blk_get_attached_dev(reopen_state->bs->blk)) {
201791a097e7SKevin Wolf         bool old_wce = bdrv_enable_write_cache(reopen_state->bs);
201891a097e7SKevin Wolf         bool new_wce = (reopen_state->flags & BDRV_O_CACHE_WB);
201991a097e7SKevin Wolf         if (old_wce != new_wce) {
202091a097e7SKevin Wolf             error_setg(errp, "Cannot change cache.writeback: Device attached");
202191a097e7SKevin Wolf             ret = -EINVAL;
202291a097e7SKevin Wolf             goto error;
202391a097e7SKevin Wolf         }
202491a097e7SKevin Wolf     }
202591a097e7SKevin Wolf 
2026ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2027ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2028ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2029ccf9dc07SKevin Wolf     if (value) {
2030ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2031ccf9dc07SKevin Wolf     }
2032ccf9dc07SKevin Wolf 
2033ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2034ccf9dc07SKevin Wolf     if (value) {
2035ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2036ccf9dc07SKevin Wolf     }
2037ccf9dc07SKevin Wolf 
2038e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2039e971aa12SJeff Cody      * to r/w */
2040e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2041e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
204281e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
204381e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2044e971aa12SJeff Cody         goto error;
2045e971aa12SJeff Cody     }
2046e971aa12SJeff Cody 
2047e971aa12SJeff Cody 
2048e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2049e971aa12SJeff Cody     if (ret) {
2050455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2051e971aa12SJeff Cody         goto error;
2052e971aa12SJeff Cody     }
2053e971aa12SJeff Cody 
2054e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2055e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2056e971aa12SJeff Cody         if (ret) {
2057e971aa12SJeff Cody             if (local_err != NULL) {
2058e971aa12SJeff Cody                 error_propagate(errp, local_err);
2059e971aa12SJeff Cody             } else {
2060d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2061e971aa12SJeff Cody                            reopen_state->bs->filename);
2062e971aa12SJeff Cody             }
2063e971aa12SJeff Cody             goto error;
2064e971aa12SJeff Cody         }
2065e971aa12SJeff Cody     } else {
2066e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2067e971aa12SJeff Cody          * handler for each supported drv. */
206881e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206981e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
207081e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2071e971aa12SJeff Cody         ret = -1;
2072e971aa12SJeff Cody         goto error;
2073e971aa12SJeff Cody     }
2074e971aa12SJeff Cody 
20754d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20764d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20774d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20784d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20794d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20804d2cb092SKevin Wolf 
20814d2cb092SKevin Wolf         do {
20824d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20834d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20844d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20854d2cb092SKevin Wolf                                                 entry->key);
20864d2cb092SKevin Wolf 
20874d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20884d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20894d2cb092SKevin Wolf                 ret = -EINVAL;
20904d2cb092SKevin Wolf                 goto error;
20914d2cb092SKevin Wolf             }
20924d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20934d2cb092SKevin Wolf     }
20944d2cb092SKevin Wolf 
2095e971aa12SJeff Cody     ret = 0;
2096e971aa12SJeff Cody 
2097e971aa12SJeff Cody error:
2098ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2099e971aa12SJeff Cody     return ret;
2100e971aa12SJeff Cody }
2101e971aa12SJeff Cody 
2102e971aa12SJeff Cody /*
2103e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2104e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2105e971aa12SJeff Cody  * the active BlockDriverState contents.
2106e971aa12SJeff Cody  */
2107e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2108e971aa12SJeff Cody {
2109e971aa12SJeff Cody     BlockDriver *drv;
2110e971aa12SJeff Cody 
2111e971aa12SJeff Cody     assert(reopen_state != NULL);
2112e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2113e971aa12SJeff Cody     assert(drv != NULL);
2114e971aa12SJeff Cody 
2115e971aa12SJeff Cody     /* If there are any driver level actions to take */
2116e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2117e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2118e971aa12SJeff Cody     }
2119e971aa12SJeff Cody 
2120e971aa12SJeff Cody     /* set BDS specific flags now */
2121145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2122145f598eSKevin Wolf 
2123145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2124e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2125e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
2126e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
2127e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2128355ef4acSKevin Wolf 
21293baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2130e971aa12SJeff Cody }
2131e971aa12SJeff Cody 
2132e971aa12SJeff Cody /*
2133e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2134e971aa12SJeff Cody  * reopen_state
2135e971aa12SJeff Cody  */
2136e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2137e971aa12SJeff Cody {
2138e971aa12SJeff Cody     BlockDriver *drv;
2139e971aa12SJeff Cody 
2140e971aa12SJeff Cody     assert(reopen_state != NULL);
2141e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2142e971aa12SJeff Cody     assert(drv != NULL);
2143e971aa12SJeff Cody 
2144e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2145e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2146e971aa12SJeff Cody     }
2147145f598eSKevin Wolf 
2148145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2149e971aa12SJeff Cody }
2150e971aa12SJeff Cody 
2151e971aa12SJeff Cody 
215264dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2153fc01f7e7Sbellard {
215433384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
215533384421SMax Reitz 
2156ca9bd24cSMax Reitz     assert(!bs->job);
215799b7e775SAlberto Garcia 
215899b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
2159a0d64a61SAlberto Garcia     if (bs->throttle_state) {
216099b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
216199b7e775SAlberto Garcia     }
216299b7e775SAlberto Garcia 
2163fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
216458fda173SStefan Hajnoczi     bdrv_flush(bs);
216553ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2166fc27291dSPaolo Bonzini 
2167c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2168c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2169c5acdc9aSMax Reitz 
2170b4d02820SMax Reitz     if (bs->blk) {
2171b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
2172b4d02820SMax Reitz     }
2173b4d02820SMax Reitz 
21743cbc002cSPaolo Bonzini     if (bs->drv) {
21756e93e7c4SKevin Wolf         BdrvChild *child, *next;
21766e93e7c4SKevin Wolf 
21779a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21789a4f4c31SKevin Wolf         bs->drv = NULL;
21799a7dedbcSKevin Wolf 
21809a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21819a7dedbcSKevin Wolf 
21829a4f4c31SKevin Wolf         if (bs->file != NULL) {
21839a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21849a4f4c31SKevin Wolf             bs->file = NULL;
21859a4f4c31SKevin Wolf         }
21869a4f4c31SKevin Wolf 
21876e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
218833a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
218933a60407SKevin Wolf              * bdrv_unref_child() here */
2190bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2191bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2192bddcec37SKevin Wolf             }
219333a60407SKevin Wolf             bdrv_detach_child(child);
21946e93e7c4SKevin Wolf         }
21956e93e7c4SKevin Wolf 
21967267c094SAnthony Liguori         g_free(bs->opaque);
2197ea2384d3Sbellard         bs->opaque = NULL;
219853fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2199a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2200a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
22016405875cSPaolo Bonzini         bs->total_sectors = 0;
22026405875cSPaolo Bonzini         bs->encrypted = 0;
22036405875cSPaolo Bonzini         bs->valid_key = 0;
22046405875cSPaolo Bonzini         bs->sg = 0;
22050d51b4deSAsias He         bs->zero_beyond_eof = false;
2206de9c0cecSKevin Wolf         QDECREF(bs->options);
2207145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2208de9c0cecSKevin Wolf         bs->options = NULL;
220991af7014SMax Reitz         QDECREF(bs->full_open_options);
221091af7014SMax Reitz         bs->full_open_options = NULL;
22119ca11154SPavel Hrdina     }
221266f82ceeSKevin Wolf 
221333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
221433384421SMax Reitz         g_free(ban);
221533384421SMax Reitz     }
221633384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2217fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2218b338082bSbellard }
2219b338082bSbellard 
22202bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22212bc93fedSMORITA Kazutaka {
22222bc93fedSMORITA Kazutaka     BlockDriverState *bs;
2223ca9bd24cSMax Reitz     AioContext *aio_context;
22242bc93fedSMORITA Kazutaka 
2225ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2226ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2227ca9bd24cSMax Reitz     bdrv_drain_all();
2228ca9bd24cSMax Reitz 
2229ca9bd24cSMax Reitz     blk_remove_all_bs();
2230ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2231ca9bd24cSMax Reitz 
2232ca9bd24cSMax Reitz     /* Cancel all block jobs */
2233ca9bd24cSMax Reitz     while (!QTAILQ_EMPTY(&all_bdrv_states)) {
2234ca9bd24cSMax Reitz         QTAILQ_FOREACH(bs, &all_bdrv_states, bs_list) {
2235ca9bd24cSMax Reitz             aio_context = bdrv_get_aio_context(bs);
2236ed78cda3SStefan Hajnoczi 
2237ed78cda3SStefan Hajnoczi             aio_context_acquire(aio_context);
2238ca9bd24cSMax Reitz             if (bs->job) {
2239ca9bd24cSMax Reitz                 block_job_cancel_sync(bs->job);
2240ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2241ca9bd24cSMax Reitz                 break;
2242ca9bd24cSMax Reitz             }
2243ca9bd24cSMax Reitz             aio_context_release(aio_context);
2244ca9bd24cSMax Reitz         }
2245ca9bd24cSMax Reitz 
2246ca9bd24cSMax Reitz         /* All the remaining BlockDriverStates are referenced directly or
2247ca9bd24cSMax Reitz          * indirectly from block jobs, so there needs to be at least one BDS
2248ca9bd24cSMax Reitz          * directly used by a block job */
2249ca9bd24cSMax Reitz         assert(bs);
22502bc93fedSMORITA Kazutaka     }
22512bc93fedSMORITA Kazutaka }
22522bc93fedSMORITA Kazutaka 
22538e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
22544ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
22554ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
22564ddc07caSPaolo Bonzini {
22574ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
22584ddc07caSPaolo Bonzini 
22594ddc07caSPaolo Bonzini     /* dev info */
22604ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
2261dd62f1caSKevin Wolf }
2262dd62f1caSKevin Wolf 
2263dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2264dd62f1caSKevin Wolf                                        BlockDriverState *to)
2265dd62f1caSKevin Wolf {
2266dd62f1caSKevin Wolf     BdrvChild *c, *next;
2267dd62f1caSKevin Wolf 
2268f21d96d0SKevin Wolf     if (from->blk) {
2269f21d96d0SKevin Wolf         /* FIXME We bypass blk_set_bs(), so we need to make these updates
2270f21d96d0SKevin Wolf          * manually. The root problem is not in this change function, but the
2271f21d96d0SKevin Wolf          * existence of BlockDriverState.blk. */
2272f21d96d0SKevin Wolf         to->blk = from->blk;
2273f21d96d0SKevin Wolf         from->blk = NULL;
2274f21d96d0SKevin Wolf     }
2275f21d96d0SKevin Wolf 
2276dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2277dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2278dd62f1caSKevin Wolf         c->bs = to;
2279dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2280dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2281dd62f1caSKevin Wolf         bdrv_ref(to);
2282dd62f1caSKevin Wolf         bdrv_unref(from);
2283dd62f1caSKevin Wolf     }
2284dd62f1caSKevin Wolf }
2285dd62f1caSKevin Wolf 
2286dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2287dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2288dd62f1caSKevin Wolf {
2289dd62f1caSKevin Wolf     BlockDriverState tmp;
2290dd62f1caSKevin Wolf 
2291dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2292dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2293dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2294dd62f1caSKevin Wolf 
2295dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2296dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2297dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2298dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2299dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2300dd62f1caSKevin Wolf     }
2301dd62f1caSKevin Wolf }
2302dd62f1caSKevin Wolf 
23038802d1fdSJeff Cody /*
23048802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
23058802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
23068802d1fdSJeff Cody  *
23078802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
23088802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
23098802d1fdSJeff Cody  *
2310bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2311f6801b83SJeff Cody  *
23128802d1fdSJeff Cody  * This function does not create any image files.
2313dd62f1caSKevin Wolf  *
2314dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2315dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2316dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2317dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
23188802d1fdSJeff Cody  */
23198802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
23208802d1fdSJeff Cody {
2321dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2322dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
23238802d1fdSJeff Cody 
2324dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2325dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2326dd62f1caSKevin Wolf 
2327dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2328dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2329dd62f1caSKevin Wolf 
2330dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2331dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2332dd62f1caSKevin Wolf 
2333dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2334dd62f1caSKevin Wolf      * additional reference any more. */
2335dd62f1caSKevin Wolf     bdrv_unref(bs_new);
23368802d1fdSJeff Cody }
23378802d1fdSJeff Cody 
23383f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
23393f09bfbcSKevin Wolf {
23403f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
23413f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
23423f09bfbcSKevin Wolf 
23433f09bfbcSKevin Wolf     bdrv_ref(old);
23443f09bfbcSKevin Wolf 
23453f09bfbcSKevin Wolf     if (old->blk) {
23463f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
23473f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
23483f09bfbcSKevin Wolf          *
23493f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
23503f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
23513f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
23523f09bfbcSKevin Wolf         assert(!new->blk);
23533f09bfbcSKevin Wolf         swap_feature_fields(old, new);
23543f09bfbcSKevin Wolf     }
23553f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
23563f09bfbcSKevin Wolf 
23573f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
23583f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
23593f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
23603f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
23613f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
23623f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
23633f09bfbcSKevin Wolf     }
23643f09bfbcSKevin Wolf 
23653f09bfbcSKevin Wolf     bdrv_unref(old);
23663f09bfbcSKevin Wolf }
23673f09bfbcSKevin Wolf 
23684f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2369b338082bSbellard {
23703e914655SPaolo Bonzini     assert(!bs->job);
23713718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
23724f6fd349SFam Zheng     assert(!bs->refcnt);
237318846deeSMarkus Armbruster 
2374e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2375e1b5c52eSStefan Hajnoczi 
23761b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
237763eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
237863eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
237963eaaae0SKevin Wolf     }
23802c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
23812c1d04e0SMax Reitz 
23827267c094SAnthony Liguori     g_free(bs);
2383fc01f7e7Sbellard }
2384fc01f7e7Sbellard 
2385e97fc193Saliguori /*
2386e97fc193Saliguori  * Run consistency checks on an image
2387e97fc193Saliguori  *
2388e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2389a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2390e076f338SKevin Wolf  * check are stored in res.
2391e97fc193Saliguori  */
23924534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2393e97fc193Saliguori {
2394908bcd54SMax Reitz     if (bs->drv == NULL) {
2395908bcd54SMax Reitz         return -ENOMEDIUM;
2396908bcd54SMax Reitz     }
2397e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2398e97fc193Saliguori         return -ENOTSUP;
2399e97fc193Saliguori     }
2400e97fc193Saliguori 
2401e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
24024534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2403e97fc193Saliguori }
2404e97fc193Saliguori 
24058a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
24068a426614SKevin Wolf 
240733e3963eSbellard /* commit COW file into the raw image */
240833e3963eSbellard int bdrv_commit(BlockDriverState *bs)
240933e3963eSbellard {
241019cb3738Sbellard     BlockDriver *drv = bs->drv;
241172706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
24128a426614SKevin Wolf     int n, ro, open_flags;
24130bce597dSJeff Cody     int ret = 0;
241472706ea4SJeff Cody     uint8_t *buf = NULL;
241533e3963eSbellard 
241619cb3738Sbellard     if (!drv)
241719cb3738Sbellard         return -ENOMEDIUM;
241833e3963eSbellard 
2419760e0063SKevin Wolf     if (!bs->backing) {
24204dca4b63SNaphtali Sprei         return -ENOTSUP;
24214dca4b63SNaphtali Sprei     }
24224dca4b63SNaphtali Sprei 
2423bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2424760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
24252d3735d3SStefan Hajnoczi         return -EBUSY;
24262d3735d3SStefan Hajnoczi     }
24272d3735d3SStefan Hajnoczi 
2428760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2429760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
24304dca4b63SNaphtali Sprei 
24314dca4b63SNaphtali Sprei     if (ro) {
2432760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
24330bce597dSJeff Cody             return -EACCES;
24344dca4b63SNaphtali Sprei         }
2435ea2384d3Sbellard     }
2436ea2384d3Sbellard 
243772706ea4SJeff Cody     length = bdrv_getlength(bs);
243872706ea4SJeff Cody     if (length < 0) {
243972706ea4SJeff Cody         ret = length;
244072706ea4SJeff Cody         goto ro_cleanup;
244172706ea4SJeff Cody     }
244272706ea4SJeff Cody 
2443760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
244472706ea4SJeff Cody     if (backing_length < 0) {
244572706ea4SJeff Cody         ret = backing_length;
244672706ea4SJeff Cody         goto ro_cleanup;
244772706ea4SJeff Cody     }
244872706ea4SJeff Cody 
244972706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
245072706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
245172706ea4SJeff Cody      * we must return an error */
245272706ea4SJeff Cody     if (length > backing_length) {
2453760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
245472706ea4SJeff Cody         if (ret < 0) {
245572706ea4SJeff Cody             goto ro_cleanup;
245672706ea4SJeff Cody         }
245772706ea4SJeff Cody     }
245872706ea4SJeff Cody 
245972706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2460857d4f46SKevin Wolf 
2461857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2462760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2463857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2464857d4f46SKevin Wolf     if (buf == NULL) {
2465857d4f46SKevin Wolf         ret = -ENOMEM;
2466857d4f46SKevin Wolf         goto ro_cleanup;
2467857d4f46SKevin Wolf     }
24688a426614SKevin Wolf 
24698a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2470d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2471d663640cSPaolo Bonzini         if (ret < 0) {
2472d663640cSPaolo Bonzini             goto ro_cleanup;
2473d663640cSPaolo Bonzini         }
2474d663640cSPaolo Bonzini         if (ret) {
2475dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2476dabfa6ccSKevin Wolf             if (ret < 0) {
24774dca4b63SNaphtali Sprei                 goto ro_cleanup;
247833e3963eSbellard             }
247933e3963eSbellard 
2480760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2481dabfa6ccSKevin Wolf             if (ret < 0) {
24824dca4b63SNaphtali Sprei                 goto ro_cleanup;
248333e3963eSbellard             }
248433e3963eSbellard         }
248533e3963eSbellard     }
248695389c86Sbellard 
24871d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
24881d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2489dabfa6ccSKevin Wolf         if (ret < 0) {
2490dabfa6ccSKevin Wolf             goto ro_cleanup;
2491dabfa6ccSKevin Wolf         }
24921d44952fSChristoph Hellwig         bdrv_flush(bs);
24931d44952fSChristoph Hellwig     }
249495389c86Sbellard 
24953f5075aeSChristoph Hellwig     /*
24963f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24973f5075aeSChristoph Hellwig      * stable on disk.
24983f5075aeSChristoph Hellwig      */
2499760e0063SKevin Wolf     if (bs->backing) {
2500760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2501dabfa6ccSKevin Wolf     }
25024dca4b63SNaphtali Sprei 
2503dabfa6ccSKevin Wolf     ret = 0;
25044dca4b63SNaphtali Sprei ro_cleanup:
2505857d4f46SKevin Wolf     qemu_vfree(buf);
25064dca4b63SNaphtali Sprei 
25074dca4b63SNaphtali Sprei     if (ro) {
25080bce597dSJeff Cody         /* ignoring error return here */
2509760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
25104dca4b63SNaphtali Sprei     }
25114dca4b63SNaphtali Sprei 
25121d44952fSChristoph Hellwig     return ret;
251333e3963eSbellard }
251433e3963eSbellard 
2515756e6736SKevin Wolf /*
2516756e6736SKevin Wolf  * Return values:
2517756e6736SKevin Wolf  * 0        - success
2518756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2519756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2520756e6736SKevin Wolf  *            image file header
2521756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2522756e6736SKevin Wolf  */
2523756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2524756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2525756e6736SKevin Wolf {
2526756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2527469ef350SPaolo Bonzini     int ret;
2528756e6736SKevin Wolf 
25295f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25305f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25315f377794SPaolo Bonzini         return -EINVAL;
25325f377794SPaolo Bonzini     }
25335f377794SPaolo Bonzini 
2534756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2535469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2536756e6736SKevin Wolf     } else {
2537469ef350SPaolo Bonzini         ret = -ENOTSUP;
2538756e6736SKevin Wolf     }
2539469ef350SPaolo Bonzini 
2540469ef350SPaolo Bonzini     if (ret == 0) {
2541469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2542469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2543469ef350SPaolo Bonzini     }
2544469ef350SPaolo Bonzini     return ret;
2545756e6736SKevin Wolf }
2546756e6736SKevin Wolf 
25476ebdcee2SJeff Cody /*
25486ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25496ebdcee2SJeff Cody  *
25506ebdcee2SJeff Cody  * active is the current topmost image.
25516ebdcee2SJeff Cody  *
25526ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25536ebdcee2SJeff Cody  * or if active == bs.
25544caf0fcdSJeff Cody  *
25554caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25566ebdcee2SJeff Cody  */
25576ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25586ebdcee2SJeff Cody                                     BlockDriverState *bs)
25596ebdcee2SJeff Cody {
2560760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2561760e0063SKevin Wolf         active = backing_bs(active);
25626ebdcee2SJeff Cody     }
25636ebdcee2SJeff Cody 
25644caf0fcdSJeff Cody     return active;
25656ebdcee2SJeff Cody }
25666ebdcee2SJeff Cody 
25674caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25684caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25694caf0fcdSJeff Cody {
25704caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25716ebdcee2SJeff Cody }
25726ebdcee2SJeff Cody 
25736ebdcee2SJeff Cody /*
25746ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25756ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25766ebdcee2SJeff Cody  *
25776ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25786ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25796ebdcee2SJeff Cody  *
25806ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25816ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25826ebdcee2SJeff Cody  *
25836ebdcee2SJeff Cody  * to
25846ebdcee2SJeff Cody  *
25856ebdcee2SJeff Cody  * bottom <- base <- active
25866ebdcee2SJeff Cody  *
25876ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25886ebdcee2SJeff Cody  *
25896ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25906ebdcee2SJeff Cody  *
25916ebdcee2SJeff Cody  * to
25926ebdcee2SJeff Cody  *
25936ebdcee2SJeff Cody  * base <- active
25946ebdcee2SJeff Cody  *
259554e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
259654e26900SJeff Cody  * overlay image metadata.
259754e26900SJeff Cody  *
25986ebdcee2SJeff Cody  * Error conditions:
25996ebdcee2SJeff Cody  *  if active == top, that is considered an error
26006ebdcee2SJeff Cody  *
26016ebdcee2SJeff Cody  */
26026ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
260354e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
26046ebdcee2SJeff Cody {
26056ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26066ebdcee2SJeff Cody     int ret = -EIO;
26076ebdcee2SJeff Cody 
26086ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26096ebdcee2SJeff Cody         goto exit;
26106ebdcee2SJeff Cody     }
26116ebdcee2SJeff Cody 
26126ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26136ebdcee2SJeff Cody 
26146ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26156ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26166ebdcee2SJeff Cody         goto exit;
26176ebdcee2SJeff Cody     }
26186ebdcee2SJeff Cody 
2619760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
26206ebdcee2SJeff Cody      * to do, no intermediate images */
2621760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
26226ebdcee2SJeff Cody         ret = 0;
26236ebdcee2SJeff Cody         goto exit;
26246ebdcee2SJeff Cody     }
26256ebdcee2SJeff Cody 
26265db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
26275db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
26286ebdcee2SJeff Cody         goto exit;
26296ebdcee2SJeff Cody     }
26306ebdcee2SJeff Cody 
26316ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26325db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
263354e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26345db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
26356ebdcee2SJeff Cody     if (ret) {
26366ebdcee2SJeff Cody         goto exit;
26376ebdcee2SJeff Cody     }
26385db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
26396ebdcee2SJeff Cody 
26406ebdcee2SJeff Cody     ret = 0;
26416ebdcee2SJeff Cody exit:
26426ebdcee2SJeff Cody     return ret;
26436ebdcee2SJeff Cody }
26446ebdcee2SJeff Cody 
264583f64091Sbellard /**
264683f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
264783f64091Sbellard  */
264883f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
264983f64091Sbellard {
265083f64091Sbellard     BlockDriver *drv = bs->drv;
265151762288SStefan Hajnoczi     int ret;
265283f64091Sbellard     if (!drv)
265319cb3738Sbellard         return -ENOMEDIUM;
265483f64091Sbellard     if (!drv->bdrv_truncate)
265583f64091Sbellard         return -ENOTSUP;
265659f2689dSNaphtali Sprei     if (bs->read_only)
265759f2689dSNaphtali Sprei         return -EACCES;
26589c75e168SJeff Cody 
265951762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
266051762288SStefan Hajnoczi     if (ret == 0) {
266151762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2662ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2663a7f53e26SMarkus Armbruster         if (bs->blk) {
2664a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2665a7f53e26SMarkus Armbruster         }
266651762288SStefan Hajnoczi     }
266751762288SStefan Hajnoczi     return ret;
266883f64091Sbellard }
266983f64091Sbellard 
267083f64091Sbellard /**
26714a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26724a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26734a1d5e1fSFam Zheng  */
26744a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26754a1d5e1fSFam Zheng {
26764a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26774a1d5e1fSFam Zheng     if (!drv) {
26784a1d5e1fSFam Zheng         return -ENOMEDIUM;
26794a1d5e1fSFam Zheng     }
26804a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26814a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26824a1d5e1fSFam Zheng     }
26834a1d5e1fSFam Zheng     if (bs->file) {
26849a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26854a1d5e1fSFam Zheng     }
26864a1d5e1fSFam Zheng     return -ENOTSUP;
26874a1d5e1fSFam Zheng }
26884a1d5e1fSFam Zheng 
26894a1d5e1fSFam Zheng /**
269065a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
269183f64091Sbellard  */
269265a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
269383f64091Sbellard {
269483f64091Sbellard     BlockDriver *drv = bs->drv;
269565a9bb25SMarkus Armbruster 
269683f64091Sbellard     if (!drv)
269719cb3738Sbellard         return -ENOMEDIUM;
269851762288SStefan Hajnoczi 
2699b94a2610SKevin Wolf     if (drv->has_variable_length) {
2700b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2701b94a2610SKevin Wolf         if (ret < 0) {
2702b94a2610SKevin Wolf             return ret;
2703fc01f7e7Sbellard         }
270446a4e4e6SStefan Hajnoczi     }
270565a9bb25SMarkus Armbruster     return bs->total_sectors;
270665a9bb25SMarkus Armbruster }
270765a9bb25SMarkus Armbruster 
270865a9bb25SMarkus Armbruster /**
270965a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
271065a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
271165a9bb25SMarkus Armbruster  */
271265a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
271365a9bb25SMarkus Armbruster {
271465a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
271565a9bb25SMarkus Armbruster 
27164a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
271765a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
271846a4e4e6SStefan Hajnoczi }
2719fc01f7e7Sbellard 
272019cb3738Sbellard /* return 0 as number of sectors if no device present or error */
272196b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2722fc01f7e7Sbellard {
272365a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
272465a9bb25SMarkus Armbruster 
272565a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2726fc01f7e7Sbellard }
2727cf98951bSbellard 
2728b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2729b338082bSbellard {
2730b338082bSbellard     return bs->read_only;
2731b338082bSbellard }
2732b338082bSbellard 
2733985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2734985a03b0Sths {
2735985a03b0Sths     return bs->sg;
2736985a03b0Sths }
2737985a03b0Sths 
2738e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2739e900a7b7SChristoph Hellwig {
2740e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2741e900a7b7SChristoph Hellwig }
2742e900a7b7SChristoph Hellwig 
2743425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2744425b0148SPaolo Bonzini {
2745425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
274655b110f2SJeff Cody 
274755b110f2SJeff Cody     /* so a reopen() will preserve wce */
274855b110f2SJeff Cody     if (wce) {
274955b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
275055b110f2SJeff Cody     } else {
275155b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
275255b110f2SJeff Cody     }
2753425b0148SPaolo Bonzini }
2754425b0148SPaolo Bonzini 
2755ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2756ea2384d3Sbellard {
2757760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2758ea2384d3Sbellard         return 1;
2759760e0063SKevin Wolf     }
2760ea2384d3Sbellard     return bs->encrypted;
2761ea2384d3Sbellard }
2762ea2384d3Sbellard 
2763c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2764c0f4ce77Saliguori {
2765760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2766c0f4ce77Saliguori 
2767760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2768c0f4ce77Saliguori         return 1;
2769760e0063SKevin Wolf     }
2770c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2771c0f4ce77Saliguori }
2772c0f4ce77Saliguori 
2773ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2774ea2384d3Sbellard {
2775ea2384d3Sbellard     int ret;
2776760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2777760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2778ea2384d3Sbellard         if (ret < 0)
2779ea2384d3Sbellard             return ret;
2780ea2384d3Sbellard         if (!bs->encrypted)
2781ea2384d3Sbellard             return 0;
2782ea2384d3Sbellard     }
2783fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2784fd04a2aeSShahar Havivi         return -EINVAL;
2785fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2786fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2787fd04a2aeSShahar Havivi     }
2788c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2789bb5fc20fSaliguori     if (ret < 0) {
2790bb5fc20fSaliguori         bs->valid_key = 0;
2791bb5fc20fSaliguori     } else if (!bs->valid_key) {
2792bb5fc20fSaliguori         bs->valid_key = 1;
2793a7f53e26SMarkus Armbruster         if (bs->blk) {
2794bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2795a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2796a7f53e26SMarkus Armbruster         }
2797bb5fc20fSaliguori     }
2798c0f4ce77Saliguori     return ret;
2799ea2384d3Sbellard }
2800ea2384d3Sbellard 
28014d2855a3SMarkus Armbruster /*
28024d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
28034d2855a3SMarkus Armbruster  * If @key is non-null:
28044d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
28054d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
28064d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
28074d2855a3SMarkus Armbruster  * If @key is null:
28084d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
28094d2855a3SMarkus Armbruster  *     Else do nothing.
28104d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
28114d2855a3SMarkus Armbruster  */
28124d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
28134d2855a3SMarkus Armbruster {
28144d2855a3SMarkus Armbruster     if (key) {
28154d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
281681e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
281781e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
28184d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2819c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
28204d2855a3SMarkus Armbruster         }
28214d2855a3SMarkus Armbruster     } else {
28224d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2823b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2824b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
282581e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
28264d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
28274d2855a3SMarkus Armbruster         }
28284d2855a3SMarkus Armbruster     }
28294d2855a3SMarkus Armbruster }
28304d2855a3SMarkus Armbruster 
2831f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2832ea2384d3Sbellard {
2833f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2834ea2384d3Sbellard }
2835ea2384d3Sbellard 
2836ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2837ada42401SStefan Hajnoczi {
2838ada42401SStefan Hajnoczi     return strcmp(a, b);
2839ada42401SStefan Hajnoczi }
2840ada42401SStefan Hajnoczi 
2841ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2842ea2384d3Sbellard                          void *opaque)
2843ea2384d3Sbellard {
2844ea2384d3Sbellard     BlockDriver *drv;
2845e855e4fbSJeff Cody     int count = 0;
2846ada42401SStefan Hajnoczi     int i;
2847e855e4fbSJeff Cody     const char **formats = NULL;
2848ea2384d3Sbellard 
28498a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2850e855e4fbSJeff Cody         if (drv->format_name) {
2851e855e4fbSJeff Cody             bool found = false;
2852e855e4fbSJeff Cody             int i = count;
2853e855e4fbSJeff Cody             while (formats && i && !found) {
2854e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2855e855e4fbSJeff Cody             }
2856e855e4fbSJeff Cody 
2857e855e4fbSJeff Cody             if (!found) {
28585839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2859e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2860ea2384d3Sbellard             }
2861ea2384d3Sbellard         }
2862e855e4fbSJeff Cody     }
2863ada42401SStefan Hajnoczi 
2864ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2865ada42401SStefan Hajnoczi 
2866ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2867ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2868ada42401SStefan Hajnoczi     }
2869ada42401SStefan Hajnoczi 
2870e855e4fbSJeff Cody     g_free(formats);
2871e855e4fbSJeff Cody }
2872ea2384d3Sbellard 
2873dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2874dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2875dc364f4cSBenoît Canet {
2876dc364f4cSBenoît Canet     BlockDriverState *bs;
2877dc364f4cSBenoît Canet 
2878dc364f4cSBenoît Canet     assert(node_name);
2879dc364f4cSBenoît Canet 
2880dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2881dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2882dc364f4cSBenoît Canet             return bs;
2883dc364f4cSBenoît Canet         }
2884dc364f4cSBenoît Canet     }
2885dc364f4cSBenoît Canet     return NULL;
2886dc364f4cSBenoît Canet }
2887dc364f4cSBenoît Canet 
2888c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2889d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2890c13163fbSBenoît Canet {
2891c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2892c13163fbSBenoît Canet     BlockDriverState *bs;
2893c13163fbSBenoît Canet 
2894c13163fbSBenoît Canet     list = NULL;
2895c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2896d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2897d5a8ee60SAlberto Garcia         if (!info) {
2898d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2899d5a8ee60SAlberto Garcia             return NULL;
2900d5a8ee60SAlberto Garcia         }
2901c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2902d5a8ee60SAlberto Garcia         entry->value = info;
2903c13163fbSBenoît Canet         entry->next = list;
2904c13163fbSBenoît Canet         list = entry;
2905c13163fbSBenoît Canet     }
2906c13163fbSBenoît Canet 
2907c13163fbSBenoît Canet     return list;
2908c13163fbSBenoît Canet }
2909c13163fbSBenoît Canet 
291012d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
291112d3ba82SBenoît Canet                                  const char *node_name,
291212d3ba82SBenoît Canet                                  Error **errp)
291312d3ba82SBenoît Canet {
29147f06d47eSMarkus Armbruster     BlockBackend *blk;
29157f06d47eSMarkus Armbruster     BlockDriverState *bs;
291612d3ba82SBenoît Canet 
291712d3ba82SBenoît Canet     if (device) {
29187f06d47eSMarkus Armbruster         blk = blk_by_name(device);
291912d3ba82SBenoît Canet 
29207f06d47eSMarkus Armbruster         if (blk) {
29219f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
29229f4ed6fbSAlberto Garcia             if (!bs) {
29235433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
29245433c24fSMax Reitz             }
29255433c24fSMax Reitz 
29269f4ed6fbSAlberto Garcia             return bs;
292712d3ba82SBenoît Canet         }
2928dd67fa50SBenoît Canet     }
292912d3ba82SBenoît Canet 
2930dd67fa50SBenoît Canet     if (node_name) {
293112d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
293212d3ba82SBenoît Canet 
2933dd67fa50SBenoît Canet         if (bs) {
2934dd67fa50SBenoît Canet             return bs;
2935dd67fa50SBenoît Canet         }
293612d3ba82SBenoît Canet     }
293712d3ba82SBenoît Canet 
2938dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2939dd67fa50SBenoît Canet                      device ? device : "",
2940dd67fa50SBenoît Canet                      node_name ? node_name : "");
2941dd67fa50SBenoît Canet     return NULL;
294212d3ba82SBenoît Canet }
294312d3ba82SBenoît Canet 
29445a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
29455a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
29465a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
29475a6684d2SJeff Cody {
29485a6684d2SJeff Cody     while (top && top != base) {
2949760e0063SKevin Wolf         top = backing_bs(top);
29505a6684d2SJeff Cody     }
29515a6684d2SJeff Cody 
29525a6684d2SJeff Cody     return top != NULL;
29535a6684d2SJeff Cody }
29545a6684d2SJeff Cody 
295504df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
295604df765aSFam Zheng {
295704df765aSFam Zheng     if (!bs) {
295804df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
295904df765aSFam Zheng     }
296004df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
296104df765aSFam Zheng }
296204df765aSFam Zheng 
296326260580SMax Reitz /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
296426260580SMax Reitz  * the monitor or attached to a BlockBackend */
29652f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29662f399b0aSMarkus Armbruster {
296726260580SMax Reitz     if (!bs || bs->blk) {
296826260580SMax Reitz         bs = blk_next_root_bs(bs);
296926260580SMax Reitz         if (bs) {
297026260580SMax Reitz             return bs;
29712f399b0aSMarkus Armbruster         }
297226260580SMax Reitz     }
297326260580SMax Reitz 
297426260580SMax Reitz     /* Ignore all BDSs that are attached to a BlockBackend here; they have been
297526260580SMax Reitz      * handled by the above block already */
297626260580SMax Reitz     do {
297726260580SMax Reitz         bs = bdrv_next_monitor_owned(bs);
297826260580SMax Reitz     } while (bs && bs->blk);
297926260580SMax Reitz     return bs;
29802f399b0aSMarkus Armbruster }
29812f399b0aSMarkus Armbruster 
298220a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
298320a9e77dSFam Zheng {
298420a9e77dSFam Zheng     return bs->node_name;
298520a9e77dSFam Zheng }
298620a9e77dSFam Zheng 
29877f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2988bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2989ea2384d3Sbellard {
2990bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2991ea2384d3Sbellard }
2992ea2384d3Sbellard 
29939b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29949b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29959b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29969b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29979b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29989b2aa84fSAlberto Garcia {
29999b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
30009b2aa84fSAlberto Garcia }
30019b2aa84fSAlberto Garcia 
3002c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3003c8433287SMarkus Armbruster {
3004c8433287SMarkus Armbruster     return bs->open_flags;
3005c8433287SMarkus Armbruster }
3006c8433287SMarkus Armbruster 
30073ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30083ac21627SPeter Lieven {
30093ac21627SPeter Lieven     return 1;
30103ac21627SPeter Lieven }
30113ac21627SPeter Lieven 
3012f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3013f2feebbdSKevin Wolf {
3014f2feebbdSKevin Wolf     assert(bs->drv);
3015f2feebbdSKevin Wolf 
301611212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
301711212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
3018760e0063SKevin Wolf     if (bs->backing) {
301911212d8fSPaolo Bonzini         return 0;
302011212d8fSPaolo Bonzini     }
3021336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3022336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3023f2feebbdSKevin Wolf     }
3024f2feebbdSKevin Wolf 
30253ac21627SPeter Lieven     /* safe default */
30263ac21627SPeter Lieven     return 0;
3027f2feebbdSKevin Wolf }
3028f2feebbdSKevin Wolf 
30294ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
30304ce78691SPeter Lieven {
30314ce78691SPeter Lieven     BlockDriverInfo bdi;
30324ce78691SPeter Lieven 
3033760e0063SKevin Wolf     if (bs->backing) {
30344ce78691SPeter Lieven         return false;
30354ce78691SPeter Lieven     }
30364ce78691SPeter Lieven 
30374ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30384ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
30394ce78691SPeter Lieven     }
30404ce78691SPeter Lieven 
30414ce78691SPeter Lieven     return false;
30424ce78691SPeter Lieven }
30434ce78691SPeter Lieven 
30444ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
30454ce78691SPeter Lieven {
30464ce78691SPeter Lieven     BlockDriverInfo bdi;
30474ce78691SPeter Lieven 
3048760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
30494ce78691SPeter Lieven         return false;
30504ce78691SPeter Lieven     }
30514ce78691SPeter Lieven 
30524ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30534ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
30544ce78691SPeter Lieven     }
30554ce78691SPeter Lieven 
30564ce78691SPeter Lieven     return false;
30574ce78691SPeter Lieven }
30584ce78691SPeter Lieven 
3059045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3060045df330Saliguori {
3061760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
3062045df330Saliguori         return bs->backing_file;
3063045df330Saliguori     else if (bs->encrypted)
3064045df330Saliguori         return bs->filename;
3065045df330Saliguori     else
3066045df330Saliguori         return NULL;
3067045df330Saliguori }
3068045df330Saliguori 
306983f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
307083f64091Sbellard                                char *filename, int filename_size)
307183f64091Sbellard {
307283f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
307383f64091Sbellard }
307483f64091Sbellard 
3075faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3076faea38e7Sbellard {
3077faea38e7Sbellard     BlockDriver *drv = bs->drv;
3078faea38e7Sbellard     if (!drv)
307919cb3738Sbellard         return -ENOMEDIUM;
3080faea38e7Sbellard     if (!drv->bdrv_get_info)
3081faea38e7Sbellard         return -ENOTSUP;
3082faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3083faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3084faea38e7Sbellard }
3085faea38e7Sbellard 
3086eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3087eae041feSMax Reitz {
3088eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3089eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3090eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3091eae041feSMax Reitz     }
3092eae041feSMax Reitz     return NULL;
3093eae041feSMax Reitz }
3094eae041feSMax Reitz 
3095a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
30968b9b0cc2SKevin Wolf {
3097bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30988b9b0cc2SKevin Wolf         return;
30998b9b0cc2SKevin Wolf     }
31008b9b0cc2SKevin Wolf 
3101bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
310241c695c7SKevin Wolf }
31038b9b0cc2SKevin Wolf 
310441c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
310541c695c7SKevin Wolf                           const char *tag)
310641c695c7SKevin Wolf {
310741c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
31089a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
310941c695c7SKevin Wolf     }
311041c695c7SKevin Wolf 
311141c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
311241c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
311341c695c7SKevin Wolf     }
311441c695c7SKevin Wolf 
311541c695c7SKevin Wolf     return -ENOTSUP;
311641c695c7SKevin Wolf }
311741c695c7SKevin Wolf 
31184cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
31194cc70e93SFam Zheng {
31204cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
31219a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
31224cc70e93SFam Zheng     }
31234cc70e93SFam Zheng 
31244cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
31254cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
31264cc70e93SFam Zheng     }
31274cc70e93SFam Zheng 
31284cc70e93SFam Zheng     return -ENOTSUP;
31294cc70e93SFam Zheng }
31304cc70e93SFam Zheng 
313141c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
313241c695c7SKevin Wolf {
3133938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
31349a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
313541c695c7SKevin Wolf     }
313641c695c7SKevin Wolf 
313741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
313841c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
313941c695c7SKevin Wolf     }
314041c695c7SKevin Wolf 
314141c695c7SKevin Wolf     return -ENOTSUP;
314241c695c7SKevin Wolf }
314341c695c7SKevin Wolf 
314441c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
314541c695c7SKevin Wolf {
314641c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
31479a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
314841c695c7SKevin Wolf     }
314941c695c7SKevin Wolf 
315041c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
315141c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
315241c695c7SKevin Wolf     }
315341c695c7SKevin Wolf 
315441c695c7SKevin Wolf     return false;
31558b9b0cc2SKevin Wolf }
31568b9b0cc2SKevin Wolf 
3157199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3158199630b6SBlue Swirl {
3159199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3160199630b6SBlue Swirl }
3161199630b6SBlue Swirl 
3162b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3163b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3164b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3165b1b1d783SJeff Cody  * the CWD rather than the chain. */
3166e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3167e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3168e8a6bb9cSMarcelo Tosatti {
3169b1b1d783SJeff Cody     char *filename_full = NULL;
3170b1b1d783SJeff Cody     char *backing_file_full = NULL;
3171b1b1d783SJeff Cody     char *filename_tmp = NULL;
3172b1b1d783SJeff Cody     int is_protocol = 0;
3173b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3174b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3175b1b1d783SJeff Cody 
3176b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3177e8a6bb9cSMarcelo Tosatti         return NULL;
3178e8a6bb9cSMarcelo Tosatti     }
3179e8a6bb9cSMarcelo Tosatti 
3180b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3181b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3182b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3183b1b1d783SJeff Cody 
3184b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3185b1b1d783SJeff Cody 
3186760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3187b1b1d783SJeff Cody 
3188b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3189b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3190b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3191b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3192760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3193b1b1d783SJeff Cody                 break;
3194b1b1d783SJeff Cody             }
3195e8a6bb9cSMarcelo Tosatti         } else {
3196b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3197b1b1d783SJeff Cody              * image's filename path */
3198b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3199b1b1d783SJeff Cody                          backing_file);
3200b1b1d783SJeff Cody 
3201b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3202b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3203b1b1d783SJeff Cody                 continue;
3204b1b1d783SJeff Cody             }
3205b1b1d783SJeff Cody 
3206b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3207b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3208b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3209b1b1d783SJeff Cody                          curr_bs->backing_file);
3210b1b1d783SJeff Cody 
3211b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3212b1b1d783SJeff Cody                 continue;
3213b1b1d783SJeff Cody             }
3214b1b1d783SJeff Cody 
3215b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3216760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3217b1b1d783SJeff Cody                 break;
3218b1b1d783SJeff Cody             }
3219e8a6bb9cSMarcelo Tosatti         }
3220e8a6bb9cSMarcelo Tosatti     }
3221e8a6bb9cSMarcelo Tosatti 
3222b1b1d783SJeff Cody     g_free(filename_full);
3223b1b1d783SJeff Cody     g_free(backing_file_full);
3224b1b1d783SJeff Cody     g_free(filename_tmp);
3225b1b1d783SJeff Cody     return retval;
3226e8a6bb9cSMarcelo Tosatti }
3227e8a6bb9cSMarcelo Tosatti 
3228f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3229f198fd1cSBenoît Canet {
3230f198fd1cSBenoît Canet     if (!bs->drv) {
3231f198fd1cSBenoît Canet         return 0;
3232f198fd1cSBenoît Canet     }
3233f198fd1cSBenoît Canet 
3234760e0063SKevin Wolf     if (!bs->backing) {
3235f198fd1cSBenoît Canet         return 0;
3236f198fd1cSBenoît Canet     }
3237f198fd1cSBenoît Canet 
3238760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3239f198fd1cSBenoît Canet }
3240f198fd1cSBenoît Canet 
3241ea2384d3Sbellard void bdrv_init(void)
3242ea2384d3Sbellard {
32435efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3244ea2384d3Sbellard }
3245ce1a14dcSpbrook 
3246eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3247eb852011SMarkus Armbruster {
3248eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3249eb852011SMarkus Armbruster     bdrv_init();
3250eb852011SMarkus Armbruster }
3251eb852011SMarkus Armbruster 
32525a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
32530f15423cSAnthony Liguori {
32545a8a30dbSKevin Wolf     Error *local_err = NULL;
32555a8a30dbSKevin Wolf     int ret;
32565a8a30dbSKevin Wolf 
32573456a8d1SKevin Wolf     if (!bs->drv)  {
32583456a8d1SKevin Wolf         return;
32590f15423cSAnthony Liguori     }
32603456a8d1SKevin Wolf 
326104c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
32627ea2d269SAlexey Kardashevskiy         return;
32637ea2d269SAlexey Kardashevskiy     }
326404c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
32657ea2d269SAlexey Kardashevskiy 
32663456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
32675a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
32683456a8d1SKevin Wolf     } else if (bs->file) {
32699a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
32705a8a30dbSKevin Wolf     }
32715a8a30dbSKevin Wolf     if (local_err) {
327204c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32735a8a30dbSKevin Wolf         error_propagate(errp, local_err);
32745a8a30dbSKevin Wolf         return;
32753456a8d1SKevin Wolf     }
32763456a8d1SKevin Wolf 
32775a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
32785a8a30dbSKevin Wolf     if (ret < 0) {
327904c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32805a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
32815a8a30dbSKevin Wolf         return;
32825a8a30dbSKevin Wolf     }
32830f15423cSAnthony Liguori }
32840f15423cSAnthony Liguori 
32855a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
32860f15423cSAnthony Liguori {
328779720af6SMax Reitz     BlockDriverState *bs = NULL;
32885a8a30dbSKevin Wolf     Error *local_err = NULL;
32890f15423cSAnthony Liguori 
329079720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3291ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3292ed78cda3SStefan Hajnoczi 
3293ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32945a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3295ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32965a8a30dbSKevin Wolf         if (local_err) {
32975a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32985a8a30dbSKevin Wolf             return;
32995a8a30dbSKevin Wolf         }
33000f15423cSAnthony Liguori     }
33010f15423cSAnthony Liguori }
33020f15423cSAnthony Liguori 
330376b1c7feSKevin Wolf static int bdrv_inactivate(BlockDriverState *bs)
330476b1c7feSKevin Wolf {
330576b1c7feSKevin Wolf     int ret;
330676b1c7feSKevin Wolf 
330776b1c7feSKevin Wolf     if (bs->drv->bdrv_inactivate) {
330876b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
330976b1c7feSKevin Wolf         if (ret < 0) {
331076b1c7feSKevin Wolf             return ret;
331176b1c7feSKevin Wolf         }
331276b1c7feSKevin Wolf     }
331376b1c7feSKevin Wolf 
331476b1c7feSKevin Wolf     bs->open_flags |= BDRV_O_INACTIVE;
331576b1c7feSKevin Wolf     return 0;
331676b1c7feSKevin Wolf }
331776b1c7feSKevin Wolf 
331876b1c7feSKevin Wolf int bdrv_inactivate_all(void)
331976b1c7feSKevin Wolf {
332079720af6SMax Reitz     BlockDriverState *bs = NULL;
332176b1c7feSKevin Wolf     int ret;
332276b1c7feSKevin Wolf 
332379720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
332476b1c7feSKevin Wolf         AioContext *aio_context = bdrv_get_aio_context(bs);
332576b1c7feSKevin Wolf 
332676b1c7feSKevin Wolf         aio_context_acquire(aio_context);
332776b1c7feSKevin Wolf         ret = bdrv_inactivate(bs);
332876b1c7feSKevin Wolf         aio_context_release(aio_context);
332976b1c7feSKevin Wolf         if (ret < 0) {
333076b1c7feSKevin Wolf             return ret;
333176b1c7feSKevin Wolf         }
333276b1c7feSKevin Wolf     }
333376b1c7feSKevin Wolf 
333476b1c7feSKevin Wolf     return 0;
333576b1c7feSKevin Wolf }
333676b1c7feSKevin Wolf 
3337f9f05dc5SKevin Wolf /**************************************************************/
333819cb3738Sbellard /* removable device support */
333919cb3738Sbellard 
334019cb3738Sbellard /**
334119cb3738Sbellard  * Return TRUE if the media is present
334219cb3738Sbellard  */
3343e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
334419cb3738Sbellard {
334519cb3738Sbellard     BlockDriver *drv = bs->drv;
334628d7a789SMax Reitz     BdrvChild *child;
3347a1aff5bfSMarkus Armbruster 
3348e031f750SMax Reitz     if (!drv) {
3349e031f750SMax Reitz         return false;
3350e031f750SMax Reitz     }
335128d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3352a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
335319cb3738Sbellard     }
335428d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
335528d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
335628d7a789SMax Reitz             return false;
335728d7a789SMax Reitz         }
335828d7a789SMax Reitz     }
335928d7a789SMax Reitz     return true;
336028d7a789SMax Reitz }
336119cb3738Sbellard 
336219cb3738Sbellard /**
33638e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
33648e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
336519cb3738Sbellard  */
336619cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
336719cb3738Sbellard {
336819cb3738Sbellard     BlockDriver *drv = bs->drv;
336919cb3738Sbellard 
33708e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33718e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33728e49ca46SMarkus Armbruster     }
33738e49ca46SMarkus Armbruster     return -ENOTSUP;
337419cb3738Sbellard }
337519cb3738Sbellard 
337619cb3738Sbellard /**
337719cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
337819cb3738Sbellard  */
3379f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
338019cb3738Sbellard {
338119cb3738Sbellard     BlockDriver *drv = bs->drv;
3382bfb197e0SMarkus Armbruster     const char *device_name;
338319cb3738Sbellard 
3384822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3385822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
338619cb3738Sbellard     }
33876f382ed2SLuiz Capitulino 
3388bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3389bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3390bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3391a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
33926f382ed2SLuiz Capitulino     }
339319cb3738Sbellard }
339419cb3738Sbellard 
339519cb3738Sbellard /**
339619cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
339719cb3738Sbellard  * to eject it manually).
339819cb3738Sbellard  */
3399025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
340019cb3738Sbellard {
340119cb3738Sbellard     BlockDriver *drv = bs->drv;
340219cb3738Sbellard 
3403025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3404b8c6d095SStefan Hajnoczi 
3405025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3406025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
340719cb3738Sbellard     }
340819cb3738Sbellard }
3409985a03b0Sths 
34109fcb0251SFam Zheng /* Get a reference to bs */
34119fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
34129fcb0251SFam Zheng {
34139fcb0251SFam Zheng     bs->refcnt++;
34149fcb0251SFam Zheng }
34159fcb0251SFam Zheng 
34169fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
34179fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
34189fcb0251SFam Zheng  * deleted. */
34199fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
34209fcb0251SFam Zheng {
34219a4d5ca6SJeff Cody     if (!bs) {
34229a4d5ca6SJeff Cody         return;
34239a4d5ca6SJeff Cody     }
34249fcb0251SFam Zheng     assert(bs->refcnt > 0);
34259fcb0251SFam Zheng     if (--bs->refcnt == 0) {
34269fcb0251SFam Zheng         bdrv_delete(bs);
34279fcb0251SFam Zheng     }
34289fcb0251SFam Zheng }
34299fcb0251SFam Zheng 
3430fbe40ff7SFam Zheng struct BdrvOpBlocker {
3431fbe40ff7SFam Zheng     Error *reason;
3432fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3433fbe40ff7SFam Zheng };
3434fbe40ff7SFam Zheng 
3435fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3436fbe40ff7SFam Zheng {
3437fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3438fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3439fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3440fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3441fbe40ff7SFam Zheng         if (errp) {
3442e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3443e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3444e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3445fbe40ff7SFam Zheng         }
3446fbe40ff7SFam Zheng         return true;
3447fbe40ff7SFam Zheng     }
3448fbe40ff7SFam Zheng     return false;
3449fbe40ff7SFam Zheng }
3450fbe40ff7SFam Zheng 
3451fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3452fbe40ff7SFam Zheng {
3453fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3454fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3455fbe40ff7SFam Zheng 
34565839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3457fbe40ff7SFam Zheng     blocker->reason = reason;
3458fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3459fbe40ff7SFam Zheng }
3460fbe40ff7SFam Zheng 
3461fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3462fbe40ff7SFam Zheng {
3463fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3464fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3465fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3466fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3467fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3468fbe40ff7SFam Zheng             g_free(blocker);
3469fbe40ff7SFam Zheng         }
3470fbe40ff7SFam Zheng     }
3471fbe40ff7SFam Zheng }
3472fbe40ff7SFam Zheng 
3473fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3474fbe40ff7SFam Zheng {
3475fbe40ff7SFam Zheng     int i;
3476fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3477fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3478fbe40ff7SFam Zheng     }
3479fbe40ff7SFam Zheng }
3480fbe40ff7SFam Zheng 
3481fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3482fbe40ff7SFam Zheng {
3483fbe40ff7SFam Zheng     int i;
3484fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3485fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3486fbe40ff7SFam Zheng     }
3487fbe40ff7SFam Zheng }
3488fbe40ff7SFam Zheng 
3489fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3490fbe40ff7SFam Zheng {
3491fbe40ff7SFam Zheng     int i;
3492fbe40ff7SFam Zheng 
3493fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3494fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3495fbe40ff7SFam Zheng             return false;
3496fbe40ff7SFam Zheng         }
3497fbe40ff7SFam Zheng     }
3498fbe40ff7SFam Zheng     return true;
3499fbe40ff7SFam Zheng }
3500fbe40ff7SFam Zheng 
3501d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3502f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3503f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3504f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3505f88e1a42SJes Sorensen {
350683d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
350783d0521aSChunyan Liu     QemuOpts *opts = NULL;
350883d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
350983d0521aSChunyan Liu     int64_t size;
3510f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3511cc84d90fSMax Reitz     Error *local_err = NULL;
3512f88e1a42SJes Sorensen     int ret = 0;
3513f88e1a42SJes Sorensen 
3514f88e1a42SJes Sorensen     /* Find driver and parse its options */
3515f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3516f88e1a42SJes Sorensen     if (!drv) {
351771c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3518d92ada22SLuiz Capitulino         return;
3519f88e1a42SJes Sorensen     }
3520f88e1a42SJes Sorensen 
3521b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3522f88e1a42SJes Sorensen     if (!proto_drv) {
3523d92ada22SLuiz Capitulino         return;
3524f88e1a42SJes Sorensen     }
3525f88e1a42SJes Sorensen 
3526c6149724SMax Reitz     if (!drv->create_opts) {
3527c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3528c6149724SMax Reitz                    drv->format_name);
3529c6149724SMax Reitz         return;
3530c6149724SMax Reitz     }
3531c6149724SMax Reitz 
3532c6149724SMax Reitz     if (!proto_drv->create_opts) {
3533c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3534c6149724SMax Reitz                    proto_drv->format_name);
3535c6149724SMax Reitz         return;
3536c6149724SMax Reitz     }
3537c6149724SMax Reitz 
3538c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3539c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3540f88e1a42SJes Sorensen 
3541f88e1a42SJes Sorensen     /* Create parameter list with default values */
354283d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
354339101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3544f88e1a42SJes Sorensen 
3545f88e1a42SJes Sorensen     /* Parse -o options */
3546f88e1a42SJes Sorensen     if (options) {
3547dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3548dc523cd3SMarkus Armbruster         if (local_err) {
3549dc523cd3SMarkus Armbruster             error_report_err(local_err);
3550dc523cd3SMarkus Armbruster             local_err = NULL;
355183d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3552f88e1a42SJes Sorensen             goto out;
3553f88e1a42SJes Sorensen         }
3554f88e1a42SJes Sorensen     }
3555f88e1a42SJes Sorensen 
3556f88e1a42SJes Sorensen     if (base_filename) {
3557f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35586be4194bSMarkus Armbruster         if (local_err) {
355971c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
356071c79813SLuiz Capitulino                        fmt);
3561f88e1a42SJes Sorensen             goto out;
3562f88e1a42SJes Sorensen         }
3563f88e1a42SJes Sorensen     }
3564f88e1a42SJes Sorensen 
3565f88e1a42SJes Sorensen     if (base_fmt) {
3566f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35676be4194bSMarkus Armbruster         if (local_err) {
356871c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
356971c79813SLuiz Capitulino                              "format '%s'", fmt);
3570f88e1a42SJes Sorensen             goto out;
3571f88e1a42SJes Sorensen         }
3572f88e1a42SJes Sorensen     }
3573f88e1a42SJes Sorensen 
357483d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
357583d0521aSChunyan Liu     if (backing_file) {
357683d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
357771c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
357871c79813SLuiz Capitulino                              "same filename as the backing file");
3579792da93aSJes Sorensen             goto out;
3580792da93aSJes Sorensen         }
3581792da93aSJes Sorensen     }
3582792da93aSJes Sorensen 
358383d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3584f88e1a42SJes Sorensen 
3585f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3586f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
358783d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
358883d0521aSChunyan Liu     if (size == -1) {
358983d0521aSChunyan Liu         if (backing_file) {
359066f6b814SMax Reitz             BlockDriverState *bs;
359129168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
359252bf1e72SMarkus Armbruster             int64_t size;
359363090dacSPaolo Bonzini             int back_flags;
3594e6641719SMax Reitz             QDict *backing_options = NULL;
359563090dacSPaolo Bonzini 
359629168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
359729168018SMax Reitz                                                          full_backing, PATH_MAX,
359829168018SMax Reitz                                                          &local_err);
359929168018SMax Reitz             if (local_err) {
360029168018SMax Reitz                 g_free(full_backing);
360129168018SMax Reitz                 goto out;
360229168018SMax Reitz             }
360329168018SMax Reitz 
360463090dacSPaolo Bonzini             /* backing files always opened read-only */
360563090dacSPaolo Bonzini             back_flags =
360663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3607f88e1a42SJes Sorensen 
3608e6641719SMax Reitz             if (backing_fmt) {
3609e6641719SMax Reitz                 backing_options = qdict_new();
3610e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3611e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3612e6641719SMax Reitz             }
3613e6641719SMax Reitz 
3614f67503e5SMax Reitz             bs = NULL;
3615e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
36166ebf9aa2SMax Reitz                             back_flags, &local_err);
361729168018SMax Reitz             g_free(full_backing);
3618f88e1a42SJes Sorensen             if (ret < 0) {
3619f88e1a42SJes Sorensen                 goto out;
3620f88e1a42SJes Sorensen             }
362152bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
362252bf1e72SMarkus Armbruster             if (size < 0) {
362352bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
362452bf1e72SMarkus Armbruster                                  backing_file);
362552bf1e72SMarkus Armbruster                 bdrv_unref(bs);
362652bf1e72SMarkus Armbruster                 goto out;
362752bf1e72SMarkus Armbruster             }
3628f88e1a42SJes Sorensen 
362939101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
363066f6b814SMax Reitz 
363166f6b814SMax Reitz             bdrv_unref(bs);
3632f88e1a42SJes Sorensen         } else {
363371c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3634f88e1a42SJes Sorensen             goto out;
3635f88e1a42SJes Sorensen         }
3636f88e1a42SJes Sorensen     }
3637f88e1a42SJes Sorensen 
3638f382d43aSMiroslav Rezanina     if (!quiet) {
3639f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
364043c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3641f88e1a42SJes Sorensen         puts("");
3642f382d43aSMiroslav Rezanina     }
364383d0521aSChunyan Liu 
3644c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
364583d0521aSChunyan Liu 
3646cc84d90fSMax Reitz     if (ret == -EFBIG) {
3647cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3648cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3649cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3650f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
365183d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3652f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3653f3f4d2c0SKevin Wolf         }
3654cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3655cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3656cc84d90fSMax Reitz         error_free(local_err);
3657cc84d90fSMax Reitz         local_err = NULL;
3658f88e1a42SJes Sorensen     }
3659f88e1a42SJes Sorensen 
3660f88e1a42SJes Sorensen out:
366183d0521aSChunyan Liu     qemu_opts_del(opts);
366283d0521aSChunyan Liu     qemu_opts_free(create_opts);
366384d18f06SMarkus Armbruster     if (local_err) {
3664cc84d90fSMax Reitz         error_propagate(errp, local_err);
3665cc84d90fSMax Reitz     }
3666f88e1a42SJes Sorensen }
366785d126f3SStefan Hajnoczi 
366885d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
366985d126f3SStefan Hajnoczi {
3670dcd04228SStefan Hajnoczi     return bs->aio_context;
3671dcd04228SStefan Hajnoczi }
3672dcd04228SStefan Hajnoczi 
3673dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3674dcd04228SStefan Hajnoczi {
367533384421SMax Reitz     BdrvAioNotifier *baf;
367633384421SMax Reitz 
3677dcd04228SStefan Hajnoczi     if (!bs->drv) {
3678dcd04228SStefan Hajnoczi         return;
3679dcd04228SStefan Hajnoczi     }
3680dcd04228SStefan Hajnoczi 
368133384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
368233384421SMax Reitz         baf->detach_aio_context(baf->opaque);
368333384421SMax Reitz     }
368433384421SMax Reitz 
3685a0d64a61SAlberto Garcia     if (bs->throttle_state) {
36860e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
368713af91ebSStefan Hajnoczi     }
3688dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3689dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3690dcd04228SStefan Hajnoczi     }
3691dcd04228SStefan Hajnoczi     if (bs->file) {
36929a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3693dcd04228SStefan Hajnoczi     }
3694760e0063SKevin Wolf     if (bs->backing) {
3695760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3696dcd04228SStefan Hajnoczi     }
3697dcd04228SStefan Hajnoczi 
3698dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3699dcd04228SStefan Hajnoczi }
3700dcd04228SStefan Hajnoczi 
3701dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3702dcd04228SStefan Hajnoczi                              AioContext *new_context)
3703dcd04228SStefan Hajnoczi {
370433384421SMax Reitz     BdrvAioNotifier *ban;
370533384421SMax Reitz 
3706dcd04228SStefan Hajnoczi     if (!bs->drv) {
3707dcd04228SStefan Hajnoczi         return;
3708dcd04228SStefan Hajnoczi     }
3709dcd04228SStefan Hajnoczi 
3710dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3711dcd04228SStefan Hajnoczi 
3712760e0063SKevin Wolf     if (bs->backing) {
3713760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3714dcd04228SStefan Hajnoczi     }
3715dcd04228SStefan Hajnoczi     if (bs->file) {
37169a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3717dcd04228SStefan Hajnoczi     }
3718dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3719dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3720dcd04228SStefan Hajnoczi     }
3721a0d64a61SAlberto Garcia     if (bs->throttle_state) {
37220e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
372313af91ebSStefan Hajnoczi     }
372433384421SMax Reitz 
372533384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
372633384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
372733384421SMax Reitz     }
3728dcd04228SStefan Hajnoczi }
3729dcd04228SStefan Hajnoczi 
3730dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3731dcd04228SStefan Hajnoczi {
373253ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3733dcd04228SStefan Hajnoczi 
3734dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3735dcd04228SStefan Hajnoczi 
3736dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3737dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3738dcd04228SStefan Hajnoczi      */
3739dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3740dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3741dcd04228SStefan Hajnoczi     aio_context_release(new_context);
374285d126f3SStefan Hajnoczi }
3743d616b224SStefan Hajnoczi 
374433384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
374533384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
374633384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
374733384421SMax Reitz {
374833384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
374933384421SMax Reitz     *ban = (BdrvAioNotifier){
375033384421SMax Reitz         .attached_aio_context = attached_aio_context,
375133384421SMax Reitz         .detach_aio_context   = detach_aio_context,
375233384421SMax Reitz         .opaque               = opaque
375333384421SMax Reitz     };
375433384421SMax Reitz 
375533384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
375633384421SMax Reitz }
375733384421SMax Reitz 
375833384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
375933384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
376033384421SMax Reitz                                                                    void *),
376133384421SMax Reitz                                       void (*detach_aio_context)(void *),
376233384421SMax Reitz                                       void *opaque)
376333384421SMax Reitz {
376433384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
376533384421SMax Reitz 
376633384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
376733384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
376833384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
376933384421SMax Reitz             ban->opaque               == opaque)
377033384421SMax Reitz         {
377133384421SMax Reitz             QLIST_REMOVE(ban, list);
377233384421SMax Reitz             g_free(ban);
377333384421SMax Reitz 
377433384421SMax Reitz             return;
377533384421SMax Reitz         }
377633384421SMax Reitz     }
377733384421SMax Reitz 
377833384421SMax Reitz     abort();
377933384421SMax Reitz }
378033384421SMax Reitz 
378177485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
37828b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
37836f176b48SMax Reitz {
3784c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
37856f176b48SMax Reitz         return -ENOTSUP;
37866f176b48SMax Reitz     }
37878b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
37886f176b48SMax Reitz }
3789f6186f49SBenoît Canet 
3790b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3791b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3792b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3793b5042a36SBenoît Canet  * node graph.
3794212a5a8fSBenoît Canet  */
3795212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3796212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3797f6186f49SBenoît Canet {
3798b5042a36SBenoît Canet     /* return false if basic checks fails */
3799b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3800b5042a36SBenoît Canet         return false;
3801b5042a36SBenoît Canet     }
3802b5042a36SBenoît Canet 
3803b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3804b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3805b5042a36SBenoît Canet      */
3806b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3807b5042a36SBenoît Canet         return bs == candidate;
3808b5042a36SBenoît Canet     }
3809b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3810b5042a36SBenoît Canet 
3811b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3812b5042a36SBenoît Canet      * the node graph.
3813b5042a36SBenoît Canet      */
3814b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3815212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3816212a5a8fSBenoît Canet     }
3817212a5a8fSBenoît Canet 
3818b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3819b5042a36SBenoît Canet      */
3820b5042a36SBenoît Canet     return false;
3821212a5a8fSBenoît Canet }
3822212a5a8fSBenoît Canet 
3823212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3824212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3825212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3826212a5a8fSBenoît Canet  */
3827212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3828212a5a8fSBenoît Canet {
382979720af6SMax Reitz     BlockDriverState *bs = NULL;
3830212a5a8fSBenoît Canet 
3831212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
383279720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3833212a5a8fSBenoît Canet         bool perm;
3834212a5a8fSBenoît Canet 
3835b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3836e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3837212a5a8fSBenoît Canet 
3838212a5a8fSBenoît Canet         /* candidate is the first non filter */
3839212a5a8fSBenoît Canet         if (perm) {
3840212a5a8fSBenoît Canet             return true;
3841212a5a8fSBenoît Canet         }
3842212a5a8fSBenoît Canet     }
3843212a5a8fSBenoît Canet 
3844212a5a8fSBenoît Canet     return false;
3845f6186f49SBenoît Canet }
384609158f00SBenoît Canet 
3847e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3848e12f3784SWen Congyang                                         const char *node_name, Error **errp)
384909158f00SBenoît Canet {
385009158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38515a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38525a7e7a0bSStefan Hajnoczi 
385309158f00SBenoît Canet     if (!to_replace_bs) {
385409158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
385509158f00SBenoît Canet         return NULL;
385609158f00SBenoît Canet     }
385709158f00SBenoît Canet 
38585a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38595a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38605a7e7a0bSStefan Hajnoczi 
386109158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38625a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38635a7e7a0bSStefan Hajnoczi         goto out;
386409158f00SBenoît Canet     }
386509158f00SBenoît Canet 
386609158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
386709158f00SBenoît Canet      * most non filter in order to prevent data corruption.
386809158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
386909158f00SBenoît Canet      * blocked by the backing blockers.
387009158f00SBenoît Canet      */
3871e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
387209158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
38735a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38745a7e7a0bSStefan Hajnoczi         goto out;
387509158f00SBenoît Canet     }
387609158f00SBenoît Canet 
38775a7e7a0bSStefan Hajnoczi out:
38785a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
387909158f00SBenoît Canet     return to_replace_bs;
388009158f00SBenoît Canet }
3881448ad91dSMing Lei 
388291af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
388391af7014SMax Reitz {
388491af7014SMax Reitz     const QDictEntry *entry;
38859e700c1aSKevin Wolf     QemuOptDesc *desc;
3886260fecf1SKevin Wolf     BdrvChild *child;
388791af7014SMax Reitz     bool found_any = false;
3888260fecf1SKevin Wolf     const char *p;
388991af7014SMax Reitz 
389091af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
389191af7014SMax Reitz          entry = qdict_next(bs->options, entry))
389291af7014SMax Reitz     {
3893260fecf1SKevin Wolf         /* Exclude options for children */
3894260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3895260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3896260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3897260fecf1SKevin Wolf             {
3898260fecf1SKevin Wolf                 break;
3899260fecf1SKevin Wolf             }
3900260fecf1SKevin Wolf         }
3901260fecf1SKevin Wolf         if (child) {
39029e700c1aSKevin Wolf             continue;
39039e700c1aSKevin Wolf         }
39049e700c1aSKevin Wolf 
39059e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
39069e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
39079e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
39089e700c1aSKevin Wolf                 break;
39099e700c1aSKevin Wolf             }
39109e700c1aSKevin Wolf         }
39119e700c1aSKevin Wolf         if (desc->name) {
39129e700c1aSKevin Wolf             continue;
39139e700c1aSKevin Wolf         }
39149e700c1aSKevin Wolf 
391591af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
391691af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
391791af7014SMax Reitz         found_any = true;
391891af7014SMax Reitz     }
391991af7014SMax Reitz 
392091af7014SMax Reitz     return found_any;
392191af7014SMax Reitz }
392291af7014SMax Reitz 
392391af7014SMax Reitz /* Updates the following BDS fields:
392491af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
392591af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
392691af7014SMax Reitz  *                    other options; so reading and writing must return the same
392791af7014SMax Reitz  *                    results, but caching etc. may be different)
392891af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
392991af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
393091af7014SMax Reitz  *                       equalling the given one
393191af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
393291af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
393391af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
393491af7014SMax Reitz  */
393591af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
393691af7014SMax Reitz {
393791af7014SMax Reitz     BlockDriver *drv = bs->drv;
393891af7014SMax Reitz     QDict *opts;
393991af7014SMax Reitz 
394091af7014SMax Reitz     if (!drv) {
394191af7014SMax Reitz         return;
394291af7014SMax Reitz     }
394391af7014SMax Reitz 
394491af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
394591af7014SMax Reitz      * refresh that first */
394691af7014SMax Reitz     if (bs->file) {
39479a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
394891af7014SMax Reitz     }
394991af7014SMax Reitz 
395091af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
395191af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
395291af7014SMax Reitz          * information before refreshing it */
395391af7014SMax Reitz         bs->exact_filename[0] = '\0';
395491af7014SMax Reitz         if (bs->full_open_options) {
395591af7014SMax Reitz             QDECREF(bs->full_open_options);
395691af7014SMax Reitz             bs->full_open_options = NULL;
395791af7014SMax Reitz         }
395891af7014SMax Reitz 
39594cdd01d3SKevin Wolf         opts = qdict_new();
39604cdd01d3SKevin Wolf         append_open_options(opts, bs);
39614cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
39624cdd01d3SKevin Wolf         QDECREF(opts);
396391af7014SMax Reitz     } else if (bs->file) {
396491af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
396591af7014SMax Reitz         bool has_open_options;
396691af7014SMax Reitz 
396791af7014SMax Reitz         bs->exact_filename[0] = '\0';
396891af7014SMax Reitz         if (bs->full_open_options) {
396991af7014SMax Reitz             QDECREF(bs->full_open_options);
397091af7014SMax Reitz             bs->full_open_options = NULL;
397191af7014SMax Reitz         }
397291af7014SMax Reitz 
397391af7014SMax Reitz         opts = qdict_new();
397491af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
397591af7014SMax Reitz 
397691af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
397791af7014SMax Reitz          * the underlying file should suffice for this one as well */
39789a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
39799a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
398091af7014SMax Reitz         }
398191af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
398291af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
398391af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
398491af7014SMax Reitz          * contain a representation of the filename, therefore the following
398591af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
39869a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
398791af7014SMax Reitz             qdict_put_obj(opts, "driver",
398891af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
39899a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
39909a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
39919a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
399291af7014SMax Reitz 
399391af7014SMax Reitz             bs->full_open_options = opts;
399491af7014SMax Reitz         } else {
399591af7014SMax Reitz             QDECREF(opts);
399691af7014SMax Reitz         }
399791af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
399891af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
399991af7014SMax Reitz          * so the full options QDict should be equal to the options given
400091af7014SMax Reitz          * specifically for this block device when it was opened (plus the
400191af7014SMax Reitz          * driver specification).
400291af7014SMax Reitz          * Because those options don't change, there is no need to update
400391af7014SMax Reitz          * full_open_options when it's already set. */
400491af7014SMax Reitz 
400591af7014SMax Reitz         opts = qdict_new();
400691af7014SMax Reitz         append_open_options(opts, bs);
400791af7014SMax Reitz         qdict_put_obj(opts, "driver",
400891af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
400991af7014SMax Reitz 
401091af7014SMax Reitz         if (bs->exact_filename[0]) {
401191af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
401291af7014SMax Reitz              * require this filename to be parsed), but we have to find some
401391af7014SMax Reitz              * default solution here, so just include it. If some block driver
401491af7014SMax Reitz              * does not support pure options without any filename at all or
401591af7014SMax Reitz              * needs some special format of the options QDict, it needs to
401691af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
401791af7014SMax Reitz              */
401891af7014SMax Reitz             qdict_put_obj(opts, "filename",
401991af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
402091af7014SMax Reitz         }
402191af7014SMax Reitz 
402291af7014SMax Reitz         bs->full_open_options = opts;
402391af7014SMax Reitz     }
402491af7014SMax Reitz 
402591af7014SMax Reitz     if (bs->exact_filename[0]) {
402691af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
402791af7014SMax Reitz     } else if (bs->full_open_options) {
402891af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
402991af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
403091af7014SMax Reitz                  qstring_get_str(json));
403191af7014SMax Reitz         QDECREF(json);
403291af7014SMax Reitz     }
403391af7014SMax Reitz }
4034