xref: /openbmc/qemu/block.c (revision 63eaaae08cb7738311f73d1a7e6e6a68ddf60688)
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 
74191a097e7SKevin Wolf     /* The cache mode is inherited unmodified for backing files */
74291a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_WB);
74391a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_DIRECT);
74491a097e7SKevin Wolf     qdict_copy_default(child_options, parent_options, BDRV_OPT_CACHE_NO_FLUSH);
74591a097e7SKevin Wolf 
746317fc44eSKevin Wolf     /* backing files always opened read-only */
747317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
748317fc44eSKevin Wolf 
749317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
7508bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
751317fc44eSKevin Wolf 
7528e2160e2SKevin Wolf     *child_flags = flags;
753317fc44eSKevin Wolf }
754317fc44eSKevin Wolf 
755f3930ed0SKevin Wolf static const BdrvChildRole child_backing = {
7568e2160e2SKevin Wolf     .inherit_options = bdrv_backing_options,
757f3930ed0SKevin Wolf };
758f3930ed0SKevin Wolf 
7597b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
7607b272452SKevin Wolf {
7617b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
7627b272452SKevin Wolf 
7637b272452SKevin Wolf     /*
7647b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
7657b272452SKevin Wolf      * image.
7667b272452SKevin Wolf      */
76720cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
7687b272452SKevin Wolf 
7697b272452SKevin Wolf     /*
7707b272452SKevin Wolf      * Snapshots should be writable.
7717b272452SKevin Wolf      */
7728bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
7737b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
7747b272452SKevin Wolf     }
7757b272452SKevin Wolf 
7767b272452SKevin Wolf     return open_flags;
7777b272452SKevin Wolf }
7787b272452SKevin Wolf 
77991a097e7SKevin Wolf static void update_flags_from_options(int *flags, QemuOpts *opts)
78091a097e7SKevin Wolf {
78191a097e7SKevin Wolf     *flags &= ~BDRV_O_CACHE_MASK;
78291a097e7SKevin Wolf 
78391a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_WB));
78491a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_WB, false)) {
78591a097e7SKevin Wolf         *flags |= BDRV_O_CACHE_WB;
78691a097e7SKevin Wolf     }
78791a097e7SKevin Wolf 
78891a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_NO_FLUSH));
78991a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_NO_FLUSH, false)) {
79091a097e7SKevin Wolf         *flags |= BDRV_O_NO_FLUSH;
79191a097e7SKevin Wolf     }
79291a097e7SKevin Wolf 
79391a097e7SKevin Wolf     assert(qemu_opt_find(opts, BDRV_OPT_CACHE_DIRECT));
79491a097e7SKevin Wolf     if (qemu_opt_get_bool(opts, BDRV_OPT_CACHE_DIRECT, false)) {
79591a097e7SKevin Wolf         *flags |= BDRV_O_NOCACHE;
79691a097e7SKevin Wolf     }
79791a097e7SKevin Wolf }
79891a097e7SKevin Wolf 
79991a097e7SKevin Wolf static void update_options_from_flags(QDict *options, int flags)
80091a097e7SKevin Wolf {
80191a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_WB)) {
80291a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_WB,
80391a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_CACHE_WB));
80491a097e7SKevin Wolf     }
80591a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_DIRECT)) {
80691a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_DIRECT,
80791a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NOCACHE));
80891a097e7SKevin Wolf     }
80991a097e7SKevin Wolf     if (!qdict_haskey(options, BDRV_OPT_CACHE_NO_FLUSH)) {
81091a097e7SKevin Wolf         qdict_put(options, BDRV_OPT_CACHE_NO_FLUSH,
81191a097e7SKevin Wolf                   qbool_from_bool(flags & BDRV_O_NO_FLUSH));
81291a097e7SKevin Wolf     }
81391a097e7SKevin Wolf }
81491a097e7SKevin Wolf 
815636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8166913c0c2SBenoît Canet                                   const char *node_name,
8176913c0c2SBenoît Canet                                   Error **errp)
8186913c0c2SBenoît Canet {
81915489c76SJeff Cody     char *gen_node_name = NULL;
8206913c0c2SBenoît Canet 
82115489c76SJeff Cody     if (!node_name) {
82215489c76SJeff Cody         node_name = gen_node_name = id_generate(ID_BLOCK);
82315489c76SJeff Cody     } else if (!id_wellformed(node_name)) {
82415489c76SJeff Cody         /*
82515489c76SJeff Cody          * Check for empty string or invalid characters, but not if it is
82615489c76SJeff Cody          * generated (generated names use characters not available to the user)
82715489c76SJeff Cody          */
8289aebf3b8SKevin Wolf         error_setg(errp, "Invalid node name");
829636ea370SKevin Wolf         return;
8306913c0c2SBenoît Canet     }
8316913c0c2SBenoît Canet 
8320c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8337f06d47eSMarkus Armbruster     if (blk_by_name(node_name)) {
8340c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8350c5e94eeSBenoît Canet                    node_name);
83615489c76SJeff Cody         goto out;
8370c5e94eeSBenoît Canet     }
8380c5e94eeSBenoît Canet 
8396913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8406913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8416913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
84215489c76SJeff Cody         goto out;
8436913c0c2SBenoît Canet     }
8446913c0c2SBenoît Canet 
8456913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8466913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8476913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
84815489c76SJeff Cody out:
84915489c76SJeff Cody     g_free(gen_node_name);
8506913c0c2SBenoît Canet }
8516913c0c2SBenoît Canet 
85218edf289SKevin Wolf static QemuOptsList bdrv_runtime_opts = {
85318edf289SKevin Wolf     .name = "bdrv_common",
85418edf289SKevin Wolf     .head = QTAILQ_HEAD_INITIALIZER(bdrv_runtime_opts.head),
85518edf289SKevin Wolf     .desc = {
85618edf289SKevin Wolf         {
85718edf289SKevin Wolf             .name = "node-name",
85818edf289SKevin Wolf             .type = QEMU_OPT_STRING,
85918edf289SKevin Wolf             .help = "Node name of the block device node",
86018edf289SKevin Wolf         },
86162392ebbSKevin Wolf         {
86262392ebbSKevin Wolf             .name = "driver",
86362392ebbSKevin Wolf             .type = QEMU_OPT_STRING,
86462392ebbSKevin Wolf             .help = "Block driver to use for the node",
86562392ebbSKevin Wolf         },
86691a097e7SKevin Wolf         {
86791a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_WB,
86891a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
86991a097e7SKevin Wolf             .help = "Enable writeback mode",
87091a097e7SKevin Wolf         },
87191a097e7SKevin Wolf         {
87291a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_DIRECT,
87391a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87491a097e7SKevin Wolf             .help = "Bypass software writeback cache on the host",
87591a097e7SKevin Wolf         },
87691a097e7SKevin Wolf         {
87791a097e7SKevin Wolf             .name = BDRV_OPT_CACHE_NO_FLUSH,
87891a097e7SKevin Wolf             .type = QEMU_OPT_BOOL,
87991a097e7SKevin Wolf             .help = "Ignore flush requests",
88091a097e7SKevin Wolf         },
88118edf289SKevin Wolf         { /* end of list */ }
88218edf289SKevin Wolf     },
88318edf289SKevin Wolf };
88418edf289SKevin Wolf 
885b6ce07aaSKevin Wolf /*
88657915332SKevin Wolf  * Common part for opening disk images and files
887b6ad491aSKevin Wolf  *
888b6ad491aSKevin Wolf  * Removes all processed options from *options.
88957915332SKevin Wolf  */
8909a4f4c31SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BdrvChild *file,
89182dc8b41SKevin Wolf                             QDict *options, Error **errp)
89257915332SKevin Wolf {
89357915332SKevin Wolf     int ret, open_flags;
894035fccdfSKevin Wolf     const char *filename;
89562392ebbSKevin Wolf     const char *driver_name = NULL;
8966913c0c2SBenoît Canet     const char *node_name = NULL;
89718edf289SKevin Wolf     QemuOpts *opts;
89862392ebbSKevin Wolf     BlockDriver *drv;
89934b5d2c6SMax Reitz     Error *local_err = NULL;
90057915332SKevin Wolf 
9016405875cSPaolo Bonzini     assert(bs->file == NULL);
902707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
90357915332SKevin Wolf 
90462392ebbSKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
90562392ebbSKevin Wolf     qemu_opts_absorb_qdict(opts, options, &local_err);
90662392ebbSKevin Wolf     if (local_err) {
90762392ebbSKevin Wolf         error_propagate(errp, local_err);
90862392ebbSKevin Wolf         ret = -EINVAL;
90962392ebbSKevin Wolf         goto fail_opts;
91062392ebbSKevin Wolf     }
91162392ebbSKevin Wolf 
91262392ebbSKevin Wolf     driver_name = qemu_opt_get(opts, "driver");
91362392ebbSKevin Wolf     drv = bdrv_find_format(driver_name);
91462392ebbSKevin Wolf     assert(drv != NULL);
91562392ebbSKevin Wolf 
91645673671SKevin Wolf     if (file != NULL) {
9179a4f4c31SKevin Wolf         filename = file->bs->filename;
91845673671SKevin Wolf     } else {
91945673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
92045673671SKevin Wolf     }
92145673671SKevin Wolf 
922765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
923765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
924765003dbSKevin Wolf                    drv->format_name);
92518edf289SKevin Wolf         ret = -EINVAL;
92618edf289SKevin Wolf         goto fail_opts;
92718edf289SKevin Wolf     }
92818edf289SKevin Wolf 
92982dc8b41SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", bs->open_flags,
93082dc8b41SKevin Wolf                            drv->format_name);
93162392ebbSKevin Wolf 
93218edf289SKevin Wolf     node_name = qemu_opt_get(opts, "node-name");
933636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9340fb6395cSMarkus Armbruster     if (local_err) {
935636ea370SKevin Wolf         error_propagate(errp, local_err);
93618edf289SKevin Wolf         ret = -EINVAL;
93718edf289SKevin Wolf         goto fail_opts;
9385d186eb0SKevin Wolf     }
9395d186eb0SKevin Wolf 
940c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9410d51b4deSAsias He     bs->zero_beyond_eof = true;
94282dc8b41SKevin Wolf     bs->read_only = !(bs->open_flags & BDRV_O_RDWR);
943b64ec4e4SFam Zheng 
944b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9458f94a6e4SKevin Wolf         error_setg(errp,
9468f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9478f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9488f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9498f94a6e4SKevin Wolf                    drv->format_name);
95018edf289SKevin Wolf         ret = -ENOTSUP;
95118edf289SKevin Wolf         goto fail_opts;
952b64ec4e4SFam Zheng     }
95357915332SKevin Wolf 
95453fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
95582dc8b41SKevin Wolf     if (bs->open_flags & BDRV_O_COPY_ON_READ) {
9560ebd24e0SKevin Wolf         if (!bs->read_only) {
95753fec9d3SStefan Hajnoczi             bdrv_enable_copy_on_read(bs);
9580ebd24e0SKevin Wolf         } else {
9590ebd24e0SKevin Wolf             error_setg(errp, "Can't use copy-on-read on read-only device");
96018edf289SKevin Wolf             ret = -EINVAL;
96118edf289SKevin Wolf             goto fail_opts;
9620ebd24e0SKevin Wolf         }
96353fec9d3SStefan Hajnoczi     }
96453fec9d3SStefan Hajnoczi 
965c2ad1b0cSKevin Wolf     if (filename != NULL) {
96657915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
967c2ad1b0cSKevin Wolf     } else {
968c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
969c2ad1b0cSKevin Wolf     }
97091af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97157915332SKevin Wolf 
97257915332SKevin Wolf     bs->drv = drv;
9737267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
97457915332SKevin Wolf 
97591a097e7SKevin Wolf     /* Apply cache mode options */
97691a097e7SKevin Wolf     update_flags_from_options(&bs->open_flags, opts);
97791a097e7SKevin Wolf     bdrv_set_enable_write_cache(bs, bs->open_flags & BDRV_O_CACHE_WB);
978e7c63796SStefan Hajnoczi 
97966f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
98082dc8b41SKevin Wolf     open_flags = bdrv_open_flags(bs, bs->open_flags);
98166f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9825d186eb0SKevin Wolf         assert(file == NULL);
983030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
98434b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
985f500a6d3SKevin Wolf     } else {
9862af5ef70SKevin Wolf         if (file == NULL) {
98734b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
98834b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9892af5ef70SKevin Wolf             ret = -EINVAL;
9902af5ef70SKevin Wolf             goto free_and_fail;
9912af5ef70SKevin Wolf         }
992f500a6d3SKevin Wolf         bs->file = file;
99334b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
99466f82ceeSKevin Wolf     }
99566f82ceeSKevin Wolf 
99657915332SKevin Wolf     if (ret < 0) {
99784d18f06SMarkus Armbruster         if (local_err) {
99834b5d2c6SMax Reitz             error_propagate(errp, local_err);
9992fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
10002fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
100134b5d2c6SMax Reitz         } else {
100234b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
100334b5d2c6SMax Reitz         }
100457915332SKevin Wolf         goto free_and_fail;
100557915332SKevin Wolf     }
100657915332SKevin Wolf 
1007a1f688f4SMarkus Armbruster     if (bs->encrypted) {
1008a1f688f4SMarkus Armbruster         error_report("Encrypted images are deprecated");
1009a1f688f4SMarkus Armbruster         error_printf("Support for them will be removed in a future release.\n"
1010a1f688f4SMarkus Armbruster                      "You can use 'qemu-img convert' to convert your image"
1011a1f688f4SMarkus Armbruster                      " to an unencrypted one.\n");
1012a1f688f4SMarkus Armbruster     }
1013a1f688f4SMarkus Armbruster 
101451762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
101551762288SStefan Hajnoczi     if (ret < 0) {
101634b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
101751762288SStefan Hajnoczi         goto free_and_fail;
101857915332SKevin Wolf     }
101951762288SStefan Hajnoczi 
10203baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10213baca891SKevin Wolf     if (local_err) {
10223baca891SKevin Wolf         error_propagate(errp, local_err);
10233baca891SKevin Wolf         ret = -EINVAL;
10243baca891SKevin Wolf         goto free_and_fail;
10253baca891SKevin Wolf     }
10263baca891SKevin Wolf 
1027c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
10284196d2f0SDenis V. Lunev     assert(bdrv_min_mem_align(bs) != 0);
1029b192af8aSDimitris Aragiorgis     assert((bs->request_alignment != 0) || bdrv_is_sg(bs));
103018edf289SKevin Wolf 
103118edf289SKevin Wolf     qemu_opts_del(opts);
103257915332SKevin Wolf     return 0;
103357915332SKevin Wolf 
103457915332SKevin Wolf free_and_fail:
103566f82ceeSKevin Wolf     bs->file = NULL;
10367267c094SAnthony Liguori     g_free(bs->opaque);
103757915332SKevin Wolf     bs->opaque = NULL;
103857915332SKevin Wolf     bs->drv = NULL;
103918edf289SKevin Wolf fail_opts:
104018edf289SKevin Wolf     qemu_opts_del(opts);
104157915332SKevin Wolf     return ret;
104257915332SKevin Wolf }
104357915332SKevin Wolf 
10445e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10455e5c4f63SKevin Wolf {
10465e5c4f63SKevin Wolf     QObject *options_obj;
10475e5c4f63SKevin Wolf     QDict *options;
10485e5c4f63SKevin Wolf     int ret;
10495e5c4f63SKevin Wolf 
10505e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10515e5c4f63SKevin Wolf     assert(ret);
10525e5c4f63SKevin Wolf 
10535e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10545e5c4f63SKevin Wolf     if (!options_obj) {
10555e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10565e5c4f63SKevin Wolf         return NULL;
10575e5c4f63SKevin Wolf     }
10585e5c4f63SKevin Wolf 
10595e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10605e5c4f63SKevin Wolf         qobject_decref(options_obj);
10615e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10625e5c4f63SKevin Wolf         return NULL;
10635e5c4f63SKevin Wolf     }
10645e5c4f63SKevin Wolf 
10655e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10665e5c4f63SKevin Wolf     qdict_flatten(options);
10675e5c4f63SKevin Wolf 
10685e5c4f63SKevin Wolf     return options;
10695e5c4f63SKevin Wolf }
10705e5c4f63SKevin Wolf 
1071de3b53f0SKevin Wolf static void parse_json_protocol(QDict *options, const char **pfilename,
1072de3b53f0SKevin Wolf                                 Error **errp)
1073de3b53f0SKevin Wolf {
1074de3b53f0SKevin Wolf     QDict *json_options;
1075de3b53f0SKevin Wolf     Error *local_err = NULL;
1076de3b53f0SKevin Wolf 
1077de3b53f0SKevin Wolf     /* Parse json: pseudo-protocol */
1078de3b53f0SKevin Wolf     if (!*pfilename || !g_str_has_prefix(*pfilename, "json:")) {
1079de3b53f0SKevin Wolf         return;
1080de3b53f0SKevin Wolf     }
1081de3b53f0SKevin Wolf 
1082de3b53f0SKevin Wolf     json_options = parse_json_filename(*pfilename, &local_err);
1083de3b53f0SKevin Wolf     if (local_err) {
1084de3b53f0SKevin Wolf         error_propagate(errp, local_err);
1085de3b53f0SKevin Wolf         return;
1086de3b53f0SKevin Wolf     }
1087de3b53f0SKevin Wolf 
1088de3b53f0SKevin Wolf     /* Options given in the filename have lower priority than options
1089de3b53f0SKevin Wolf      * specified directly */
1090de3b53f0SKevin Wolf     qdict_join(options, json_options, false);
1091de3b53f0SKevin Wolf     QDECREF(json_options);
1092de3b53f0SKevin Wolf     *pfilename = NULL;
1093de3b53f0SKevin Wolf }
1094de3b53f0SKevin Wolf 
109557915332SKevin Wolf /*
1096f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1097f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
109853a29513SMax Reitz  * The BDRV_O_PROTOCOL flag in *flags will be set or cleared accordingly if a
109953a29513SMax Reitz  * block driver has been specified explicitly.
1100f54120ffSKevin Wolf  */
1101de3b53f0SKevin Wolf static int bdrv_fill_options(QDict **options, const char *filename,
1102053e1578SMax Reitz                              int *flags, Error **errp)
1103f54120ffSKevin Wolf {
1104f54120ffSKevin Wolf     const char *drvname;
110553a29513SMax Reitz     bool protocol = *flags & BDRV_O_PROTOCOL;
1106f54120ffSKevin Wolf     bool parse_filename = false;
1107053e1578SMax Reitz     BlockDriver *drv = NULL;
1108f54120ffSKevin Wolf     Error *local_err = NULL;
1109f54120ffSKevin Wolf 
111053a29513SMax Reitz     drvname = qdict_get_try_str(*options, "driver");
1111053e1578SMax Reitz     if (drvname) {
1112053e1578SMax Reitz         drv = bdrv_find_format(drvname);
1113053e1578SMax Reitz         if (!drv) {
1114053e1578SMax Reitz             error_setg(errp, "Unknown driver '%s'", drvname);
1115053e1578SMax Reitz             return -ENOENT;
1116053e1578SMax Reitz         }
111753a29513SMax Reitz         /* If the user has explicitly specified the driver, this choice should
111853a29513SMax Reitz          * override the BDRV_O_PROTOCOL flag */
1119053e1578SMax Reitz         protocol = drv->bdrv_file_open;
112053a29513SMax Reitz     }
112153a29513SMax Reitz 
112253a29513SMax Reitz     if (protocol) {
112353a29513SMax Reitz         *flags |= BDRV_O_PROTOCOL;
112453a29513SMax Reitz     } else {
112553a29513SMax Reitz         *flags &= ~BDRV_O_PROTOCOL;
112653a29513SMax Reitz     }
112753a29513SMax Reitz 
112891a097e7SKevin Wolf     /* Translate cache options from flags into options */
112991a097e7SKevin Wolf     update_options_from_flags(*options, *flags);
113091a097e7SKevin Wolf 
1131f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
113217b005f1SKevin Wolf     if (protocol && filename) {
1133f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1134f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1135f54120ffSKevin Wolf             parse_filename = true;
1136f54120ffSKevin Wolf         } else {
1137f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1138f54120ffSKevin Wolf                              "the same time");
1139f54120ffSKevin Wolf             return -EINVAL;
1140f54120ffSKevin Wolf         }
1141f54120ffSKevin Wolf     }
1142f54120ffSKevin Wolf 
1143f54120ffSKevin Wolf     /* Find the right block driver */
1144f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1145f54120ffSKevin Wolf 
114617b005f1SKevin Wolf     if (!drvname && protocol) {
1147f54120ffSKevin Wolf         if (filename) {
1148b65a5e12SMax Reitz             drv = bdrv_find_protocol(filename, parse_filename, errp);
1149f54120ffSKevin Wolf             if (!drv) {
1150f54120ffSKevin Wolf                 return -EINVAL;
1151f54120ffSKevin Wolf             }
1152f54120ffSKevin Wolf 
1153f54120ffSKevin Wolf             drvname = drv->format_name;
1154f54120ffSKevin Wolf             qdict_put(*options, "driver", qstring_from_str(drvname));
1155f54120ffSKevin Wolf         } else {
1156f54120ffSKevin Wolf             error_setg(errp, "Must specify either driver or file");
1157f54120ffSKevin Wolf             return -EINVAL;
1158f54120ffSKevin Wolf         }
115917b005f1SKevin Wolf     }
116017b005f1SKevin Wolf 
116117b005f1SKevin Wolf     assert(drv || !protocol);
1162f54120ffSKevin Wolf 
1163f54120ffSKevin Wolf     /* Driver-specific filename parsing */
116417b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1165f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1166f54120ffSKevin Wolf         if (local_err) {
1167f54120ffSKevin Wolf             error_propagate(errp, local_err);
1168f54120ffSKevin Wolf             return -EINVAL;
1169f54120ffSKevin Wolf         }
1170f54120ffSKevin Wolf 
1171f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1172f54120ffSKevin Wolf             qdict_del(*options, "filename");
1173f54120ffSKevin Wolf         }
1174f54120ffSKevin Wolf     }
1175f54120ffSKevin Wolf 
1176f54120ffSKevin Wolf     return 0;
1177f54120ffSKevin Wolf }
1178f54120ffSKevin Wolf 
1179f21d96d0SKevin Wolf BdrvChild *bdrv_root_attach_child(BlockDriverState *child_bs,
1180260fecf1SKevin Wolf                                   const char *child_name,
1181df581792SKevin Wolf                                   const BdrvChildRole *child_role)
1182df581792SKevin Wolf {
1183df581792SKevin Wolf     BdrvChild *child = g_new(BdrvChild, 1);
1184df581792SKevin Wolf     *child = (BdrvChild) {
1185df581792SKevin Wolf         .bs     = child_bs,
1186260fecf1SKevin Wolf         .name   = g_strdup(child_name),
1187df581792SKevin Wolf         .role   = child_role,
1188df581792SKevin Wolf     };
1189df581792SKevin Wolf 
1190d42a8a93SKevin Wolf     QLIST_INSERT_HEAD(&child_bs->parents, child, next_parent);
1191b4b059f6SKevin Wolf 
1192b4b059f6SKevin Wolf     return child;
1193df581792SKevin Wolf }
1194df581792SKevin Wolf 
1195f21d96d0SKevin Wolf static BdrvChild *bdrv_attach_child(BlockDriverState *parent_bs,
1196f21d96d0SKevin Wolf                                     BlockDriverState *child_bs,
1197f21d96d0SKevin Wolf                                     const char *child_name,
1198f21d96d0SKevin Wolf                                     const BdrvChildRole *child_role)
1199f21d96d0SKevin Wolf {
1200f21d96d0SKevin Wolf     BdrvChild *child = bdrv_root_attach_child(child_bs, child_name, child_role);
1201f21d96d0SKevin Wolf     QLIST_INSERT_HEAD(&parent_bs->children, child, next);
1202f21d96d0SKevin Wolf     return child;
1203f21d96d0SKevin Wolf }
1204f21d96d0SKevin Wolf 
12053f09bfbcSKevin Wolf static void bdrv_detach_child(BdrvChild *child)
120633a60407SKevin Wolf {
1207f21d96d0SKevin Wolf     if (child->next.le_prev) {
120833a60407SKevin Wolf         QLIST_REMOVE(child, next);
1209f21d96d0SKevin Wolf         child->next.le_prev = NULL;
1210f21d96d0SKevin Wolf     }
1211d42a8a93SKevin Wolf     QLIST_REMOVE(child, next_parent);
1212260fecf1SKevin Wolf     g_free(child->name);
121333a60407SKevin Wolf     g_free(child);
121433a60407SKevin Wolf }
121533a60407SKevin Wolf 
1216f21d96d0SKevin Wolf void bdrv_root_unref_child(BdrvChild *child)
121733a60407SKevin Wolf {
1218779020cbSKevin Wolf     BlockDriverState *child_bs;
1219779020cbSKevin Wolf 
1220f21d96d0SKevin Wolf     child_bs = child->bs;
1221f21d96d0SKevin Wolf     bdrv_detach_child(child);
1222f21d96d0SKevin Wolf     bdrv_unref(child_bs);
1223f21d96d0SKevin Wolf }
1224f21d96d0SKevin Wolf 
1225f21d96d0SKevin Wolf void bdrv_unref_child(BlockDriverState *parent, BdrvChild *child)
1226f21d96d0SKevin Wolf {
1227779020cbSKevin Wolf     if (child == NULL) {
1228779020cbSKevin Wolf         return;
1229779020cbSKevin Wolf     }
123033a60407SKevin Wolf 
123133a60407SKevin Wolf     if (child->bs->inherits_from == parent) {
123233a60407SKevin Wolf         child->bs->inherits_from = NULL;
123333a60407SKevin Wolf     }
123433a60407SKevin Wolf 
1235f21d96d0SKevin Wolf     bdrv_root_unref_child(child);
123633a60407SKevin Wolf }
123733a60407SKevin Wolf 
12385db15a57SKevin Wolf /*
12395db15a57SKevin Wolf  * Sets the backing file link of a BDS. A new reference is created; callers
12405db15a57SKevin Wolf  * which don't need their own reference any more must call bdrv_unref().
12415db15a57SKevin Wolf  */
12428d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
12438d24cce1SFam Zheng {
12445db15a57SKevin Wolf     if (backing_hd) {
12455db15a57SKevin Wolf         bdrv_ref(backing_hd);
12465db15a57SKevin Wolf     }
12478d24cce1SFam Zheng 
1248760e0063SKevin Wolf     if (bs->backing) {
1249826b6ca0SFam Zheng         assert(bs->backing_blocker);
1250760e0063SKevin Wolf         bdrv_op_unblock_all(bs->backing->bs, bs->backing_blocker);
12515db15a57SKevin Wolf         bdrv_unref_child(bs, bs->backing);
1252826b6ca0SFam Zheng     } else if (backing_hd) {
1253826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
125481e5f78aSAlberto Garcia                    "node is used as backing hd of '%s'",
125581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(bs));
1256826b6ca0SFam Zheng     }
1257826b6ca0SFam Zheng 
12588d24cce1SFam Zheng     if (!backing_hd) {
1259826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1260826b6ca0SFam Zheng         bs->backing_blocker = NULL;
1261760e0063SKevin Wolf         bs->backing = NULL;
12628d24cce1SFam Zheng         goto out;
12638d24cce1SFam Zheng     }
1264260fecf1SKevin Wolf     bs->backing = bdrv_attach_child(bs, backing_hd, "backing", &child_backing);
12658d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
12668d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
12678d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
12688d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1269826b6ca0SFam Zheng 
1270760e0063SKevin Wolf     bdrv_op_block_all(backing_hd, bs->backing_blocker);
1271826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1272760e0063SKevin Wolf     bdrv_op_unblock(backing_hd, BLOCK_OP_TYPE_COMMIT_TARGET,
1273826b6ca0SFam Zheng                     bs->backing_blocker);
12748d24cce1SFam Zheng out:
12753baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
12768d24cce1SFam Zheng }
12778d24cce1SFam Zheng 
127831ca6d07SKevin Wolf /*
127931ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
128031ca6d07SKevin Wolf  *
1281d9b7b057SKevin Wolf  * bdref_key specifies the key for the image's BlockdevRef in the options QDict.
1282d9b7b057SKevin Wolf  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1283d9b7b057SKevin Wolf  * itself, all options starting with "${bdref_key}." are considered part of the
1284d9b7b057SKevin Wolf  * BlockdevRef.
1285d9b7b057SKevin Wolf  *
1286d9b7b057SKevin Wolf  * TODO Can this be unified with bdrv_open_image()?
128731ca6d07SKevin Wolf  */
1288d9b7b057SKevin Wolf int bdrv_open_backing_file(BlockDriverState *bs, QDict *parent_options,
1289d9b7b057SKevin Wolf                            const char *bdref_key, Error **errp)
12909156df12SPaolo Bonzini {
12911ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1292d9b7b057SKevin Wolf     char *bdref_key_dot;
1293d9b7b057SKevin Wolf     const char *reference = NULL;
1294317fc44eSKevin Wolf     int ret = 0;
12958d24cce1SFam Zheng     BlockDriverState *backing_hd;
1296d9b7b057SKevin Wolf     QDict *options;
1297d9b7b057SKevin Wolf     QDict *tmp_parent_options = NULL;
129834b5d2c6SMax Reitz     Error *local_err = NULL;
12999156df12SPaolo Bonzini 
1300760e0063SKevin Wolf     if (bs->backing != NULL) {
13011ba4b6a5SBenoît Canet         goto free_exit;
13029156df12SPaolo Bonzini     }
13039156df12SPaolo Bonzini 
130431ca6d07SKevin Wolf     /* NULL means an empty set of options */
1305d9b7b057SKevin Wolf     if (parent_options == NULL) {
1306d9b7b057SKevin Wolf         tmp_parent_options = qdict_new();
1307d9b7b057SKevin Wolf         parent_options = tmp_parent_options;
130831ca6d07SKevin Wolf     }
130931ca6d07SKevin Wolf 
13109156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
1311d9b7b057SKevin Wolf 
1312d9b7b057SKevin Wolf     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1313d9b7b057SKevin Wolf     qdict_extract_subqdict(parent_options, &options, bdref_key_dot);
1314d9b7b057SKevin Wolf     g_free(bdref_key_dot);
1315d9b7b057SKevin Wolf 
1316d9b7b057SKevin Wolf     reference = qdict_get_try_str(parent_options, bdref_key);
1317d9b7b057SKevin Wolf     if (reference || qdict_haskey(options, "file.filename")) {
13181cb6f506SKevin Wolf         backing_filename[0] = '\0';
13191cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
132031ca6d07SKevin Wolf         QDECREF(options);
13211ba4b6a5SBenoît Canet         goto free_exit;
1322dbecebddSFam Zheng     } else {
13239f07429eSMax Reitz         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX,
13249f07429eSMax Reitz                                        &local_err);
13259f07429eSMax Reitz         if (local_err) {
13269f07429eSMax Reitz             ret = -EINVAL;
13279f07429eSMax Reitz             error_propagate(errp, local_err);
13289f07429eSMax Reitz             QDECREF(options);
13299f07429eSMax Reitz             goto free_exit;
13309f07429eSMax Reitz         }
13319156df12SPaolo Bonzini     }
13329156df12SPaolo Bonzini 
13338ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
13348ee79e70SKevin Wolf         ret = -EINVAL;
13358ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
13368ee79e70SKevin Wolf         QDECREF(options);
13378ee79e70SKevin Wolf         goto free_exit;
13388ee79e70SKevin Wolf     }
13398ee79e70SKevin Wolf 
1340c5f6e493SKevin Wolf     if (bs->backing_format[0] != '\0' && !qdict_haskey(options, "driver")) {
1341c5f6e493SKevin Wolf         qdict_put(options, "driver", qstring_from_str(bs->backing_format));
13429156df12SPaolo Bonzini     }
13439156df12SPaolo Bonzini 
1344d9b7b057SKevin Wolf     backing_hd = NULL;
1345f3930ed0SKevin Wolf     ret = bdrv_open_inherit(&backing_hd,
1346f3930ed0SKevin Wolf                             *backing_filename ? backing_filename : NULL,
1347d9b7b057SKevin Wolf                             reference, options, 0, bs, &child_backing,
1348e43bfd9cSMarkus Armbruster                             errp);
13499156df12SPaolo Bonzini     if (ret < 0) {
13509156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1351e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not open backing file: ");
13521ba4b6a5SBenoît Canet         goto free_exit;
13539156df12SPaolo Bonzini     }
1354df581792SKevin Wolf 
13555db15a57SKevin Wolf     /* Hook up the backing file link; drop our reference, bs owns the
13565db15a57SKevin Wolf      * backing_hd reference now */
13578d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
13585db15a57SKevin Wolf     bdrv_unref(backing_hd);
1359d80ac658SPeter Feiner 
1360d9b7b057SKevin Wolf     qdict_del(parent_options, bdref_key);
1361d9b7b057SKevin Wolf 
13621ba4b6a5SBenoît Canet free_exit:
13631ba4b6a5SBenoît Canet     g_free(backing_filename);
1364d9b7b057SKevin Wolf     QDECREF(tmp_parent_options);
13651ba4b6a5SBenoît Canet     return ret;
13669156df12SPaolo Bonzini }
13679156df12SPaolo Bonzini 
1368b6ce07aaSKevin Wolf /*
1369da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1370da557aacSMax Reitz  * device's options.
1371da557aacSMax Reitz  *
1372da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1373b4b059f6SKevin Wolf  * BlockdevRef is given. NULL will be returned, but errp remains unset.
1374da557aacSMax Reitz  *
1375da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1376da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1377da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1378da557aacSMax Reitz  * BlockdevRef.
1379da557aacSMax Reitz  *
1380da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1381da557aacSMax Reitz  */
1382b4b059f6SKevin Wolf BdrvChild *bdrv_open_child(const char *filename,
1383f3930ed0SKevin Wolf                            QDict *options, const char *bdref_key,
1384b4b059f6SKevin Wolf                            BlockDriverState* parent,
1385b4b059f6SKevin Wolf                            const BdrvChildRole *child_role,
1386f7d9fd8cSMax Reitz                            bool allow_none, Error **errp)
1387da557aacSMax Reitz {
1388b4b059f6SKevin Wolf     BdrvChild *c = NULL;
1389b4b059f6SKevin Wolf     BlockDriverState *bs;
1390da557aacSMax Reitz     QDict *image_options;
1391da557aacSMax Reitz     int ret;
1392da557aacSMax Reitz     char *bdref_key_dot;
1393da557aacSMax Reitz     const char *reference;
1394da557aacSMax Reitz 
1395df581792SKevin Wolf     assert(child_role != NULL);
1396f67503e5SMax Reitz 
1397da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1398da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1399da557aacSMax Reitz     g_free(bdref_key_dot);
1400da557aacSMax Reitz 
1401da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1402da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1403b4b059f6SKevin Wolf         if (!allow_none) {
1404da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1405da557aacSMax Reitz                        bdref_key);
1406da557aacSMax Reitz         }
1407b20e61e0SMarkus Armbruster         QDECREF(image_options);
1408da557aacSMax Reitz         goto done;
1409da557aacSMax Reitz     }
1410da557aacSMax Reitz 
1411b4b059f6SKevin Wolf     bs = NULL;
1412b4b059f6SKevin Wolf     ret = bdrv_open_inherit(&bs, filename, reference, image_options, 0,
1413ce343771SMax Reitz                             parent, child_role, errp);
1414df581792SKevin Wolf     if (ret < 0) {
1415df581792SKevin Wolf         goto done;
1416df581792SKevin Wolf     }
1417df581792SKevin Wolf 
1418260fecf1SKevin Wolf     c = bdrv_attach_child(parent, bs, bdref_key, child_role);
1419da557aacSMax Reitz 
1420da557aacSMax Reitz done:
1421da557aacSMax Reitz     qdict_del(options, bdref_key);
1422b4b059f6SKevin Wolf     return c;
1423b4b059f6SKevin Wolf }
1424b4b059f6SKevin Wolf 
142573176beeSKevin Wolf static int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags,
142673176beeSKevin Wolf                                      QDict *snapshot_options, Error **errp)
1427b998875dSKevin Wolf {
1428b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
14291ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1430b998875dSKevin Wolf     int64_t total_size;
143183d0521aSChunyan Liu     QemuOpts *opts = NULL;
1432b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1433c2e0dbbfSFam Zheng     Error *local_err = NULL;
1434b998875dSKevin Wolf     int ret;
1435b998875dSKevin Wolf 
1436b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1437b998875dSKevin Wolf        instead of opening 'filename' directly */
1438b998875dSKevin Wolf 
1439b998875dSKevin Wolf     /* Get the required size from the image */
1440f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1441f187743aSKevin Wolf     if (total_size < 0) {
14426b8aeca5SChen Gang         ret = total_size;
1443f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
14441ba4b6a5SBenoît Canet         goto out;
1445f187743aSKevin Wolf     }
1446b998875dSKevin Wolf 
1447b998875dSKevin Wolf     /* Create the temporary image */
14481ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1449b998875dSKevin Wolf     if (ret < 0) {
1450b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
14511ba4b6a5SBenoît Canet         goto out;
1452b998875dSKevin Wolf     }
1453b998875dSKevin Wolf 
1454ef810437SMax Reitz     opts = qemu_opts_create(bdrv_qcow2.create_opts, NULL, 0,
1455c282e1fdSChunyan Liu                             &error_abort);
145639101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size, &error_abort);
1457e43bfd9cSMarkus Armbruster     ret = bdrv_create(&bdrv_qcow2, tmp_filename, opts, errp);
145883d0521aSChunyan Liu     qemu_opts_del(opts);
1459b998875dSKevin Wolf     if (ret < 0) {
1460e43bfd9cSMarkus Armbruster         error_prepend(errp, "Could not create temporary overlay '%s': ",
1461e43bfd9cSMarkus Armbruster                       tmp_filename);
14621ba4b6a5SBenoît Canet         goto out;
1463b998875dSKevin Wolf     }
1464b998875dSKevin Wolf 
146573176beeSKevin Wolf     /* Prepare options QDict for the temporary file */
1466b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1467b998875dSKevin Wolf               qstring_from_str("file"));
1468b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1469b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1470e6641719SMax Reitz     qdict_put(snapshot_options, "driver",
1471e6641719SMax Reitz               qstring_from_str("qcow2"));
1472b998875dSKevin Wolf 
1473e4e9986bSMarkus Armbruster     bs_snapshot = bdrv_new();
1474b998875dSKevin Wolf 
1475b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
14766ebf9aa2SMax Reitz                     flags, &local_err);
147773176beeSKevin Wolf     snapshot_options = NULL;
1478b998875dSKevin Wolf     if (ret < 0) {
1479b998875dSKevin Wolf         error_propagate(errp, local_err);
14801ba4b6a5SBenoît Canet         goto out;
1481b998875dSKevin Wolf     }
1482b998875dSKevin Wolf 
1483b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
14841ba4b6a5SBenoît Canet 
14851ba4b6a5SBenoît Canet out:
148673176beeSKevin Wolf     QDECREF(snapshot_options);
14871ba4b6a5SBenoît Canet     g_free(tmp_filename);
14886b8aeca5SChen Gang     return ret;
1489b998875dSKevin Wolf }
1490b998875dSKevin Wolf 
1491da557aacSMax Reitz /*
1492b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1493de9c0cecSKevin Wolf  *
1494de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1495de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1496de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1497de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1498f67503e5SMax Reitz  *
1499f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1500f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1501ddf5636dSMax Reitz  *
1502ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1503ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1504ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1505b6ce07aaSKevin Wolf  */
1506f3930ed0SKevin Wolf static int bdrv_open_inherit(BlockDriverState **pbs, const char *filename,
1507ddf5636dSMax Reitz                              const char *reference, QDict *options, int flags,
1508f3930ed0SKevin Wolf                              BlockDriverState *parent,
1509ce343771SMax Reitz                              const BdrvChildRole *child_role, Error **errp)
1510ea2384d3Sbellard {
1511b6ce07aaSKevin Wolf     int ret;
15129a4f4c31SKevin Wolf     BdrvChild *file = NULL;
15139a4f4c31SKevin Wolf     BlockDriverState *bs;
1514ce343771SMax Reitz     BlockDriver *drv = NULL;
151574fe54f2SKevin Wolf     const char *drvname;
15163e8c2e57SAlberto Garcia     const char *backing;
151734b5d2c6SMax Reitz     Error *local_err = NULL;
151873176beeSKevin Wolf     QDict *snapshot_options = NULL;
1519b1e6fc08SKevin Wolf     int snapshot_flags = 0;
152033e3963eSbellard 
1521f67503e5SMax Reitz     assert(pbs);
1522f3930ed0SKevin Wolf     assert(!child_role || !flags);
1523f3930ed0SKevin Wolf     assert(!child_role == !parent);
1524f67503e5SMax Reitz 
1525ddf5636dSMax Reitz     if (reference) {
1526ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1527ddf5636dSMax Reitz         QDECREF(options);
1528ddf5636dSMax Reitz 
1529ddf5636dSMax Reitz         if (*pbs) {
1530ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1531ddf5636dSMax Reitz                        "another block device");
1532ddf5636dSMax Reitz             return -EINVAL;
1533ddf5636dSMax Reitz         }
1534ddf5636dSMax Reitz 
1535ddf5636dSMax Reitz         if (filename || options_non_empty) {
1536ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1537ddf5636dSMax Reitz                        "additional options or a new filename");
1538ddf5636dSMax Reitz             return -EINVAL;
1539ddf5636dSMax Reitz         }
1540ddf5636dSMax Reitz 
1541ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1542ddf5636dSMax Reitz         if (!bs) {
1543ddf5636dSMax Reitz             return -ENODEV;
1544ddf5636dSMax Reitz         }
1545ddf5636dSMax Reitz         bdrv_ref(bs);
1546ddf5636dSMax Reitz         *pbs = bs;
1547ddf5636dSMax Reitz         return 0;
1548ddf5636dSMax Reitz     }
1549ddf5636dSMax Reitz 
1550f67503e5SMax Reitz     if (*pbs) {
1551f67503e5SMax Reitz         bs = *pbs;
1552f67503e5SMax Reitz     } else {
1553e4e9986bSMarkus Armbruster         bs = bdrv_new();
1554f67503e5SMax Reitz     }
1555f67503e5SMax Reitz 
1556de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1557de9c0cecSKevin Wolf     if (options == NULL) {
1558de9c0cecSKevin Wolf         options = qdict_new();
1559de9c0cecSKevin Wolf     }
1560de9c0cecSKevin Wolf 
1561145f598eSKevin Wolf     /* json: syntax counts as explicit options, as if in the QDict */
1562de3b53f0SKevin Wolf     parse_json_protocol(options, &filename, &local_err);
1563de3b53f0SKevin Wolf     if (local_err) {
1564de3b53f0SKevin Wolf         ret = -EINVAL;
1565de3b53f0SKevin Wolf         goto fail;
1566de3b53f0SKevin Wolf     }
1567de3b53f0SKevin Wolf 
1568145f598eSKevin Wolf     bs->explicit_options = qdict_clone_shallow(options);
1569145f598eSKevin Wolf 
1570f3930ed0SKevin Wolf     if (child_role) {
1571bddcec37SKevin Wolf         bs->inherits_from = parent;
15728e2160e2SKevin Wolf         child_role->inherit_options(&flags, options,
15738e2160e2SKevin Wolf                                     parent->open_flags, parent->options);
1574f3930ed0SKevin Wolf     }
1575f3930ed0SKevin Wolf 
1576de3b53f0SKevin Wolf     ret = bdrv_fill_options(&options, filename, &flags, &local_err);
1577462f5bcfSKevin Wolf     if (local_err) {
1578462f5bcfSKevin Wolf         goto fail;
1579462f5bcfSKevin Wolf     }
1580462f5bcfSKevin Wolf 
158162392ebbSKevin Wolf     bs->open_flags = flags;
158262392ebbSKevin Wolf     bs->options = options;
158362392ebbSKevin Wolf     options = qdict_clone_shallow(options);
158462392ebbSKevin Wolf 
158576c591b0SKevin Wolf     /* Find the right image format driver */
158676c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
158776c591b0SKevin Wolf     if (drvname) {
158876c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
158976c591b0SKevin Wolf         if (!drv) {
159076c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
159176c591b0SKevin Wolf             ret = -EINVAL;
159276c591b0SKevin Wolf             goto fail;
159376c591b0SKevin Wolf         }
159476c591b0SKevin Wolf     }
159576c591b0SKevin Wolf 
159676c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
159776c591b0SKevin Wolf 
15983e8c2e57SAlberto Garcia     backing = qdict_get_try_str(options, "backing");
15993e8c2e57SAlberto Garcia     if (backing && *backing == '\0') {
16003e8c2e57SAlberto Garcia         flags |= BDRV_O_NO_BACKING;
16013e8c2e57SAlberto Garcia         qdict_del(options, "backing");
16023e8c2e57SAlberto Garcia     }
16033e8c2e57SAlberto Garcia 
1604f500a6d3SKevin Wolf     /* Open image file without format layer */
1605f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1606be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1607be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1608be028adcSJeff Cody         }
1609b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
161073176beeSKevin Wolf             snapshot_options = qdict_new();
161173176beeSKevin Wolf             bdrv_temp_snapshot_options(&snapshot_flags, snapshot_options,
161273176beeSKevin Wolf                                        flags, options);
16138e2160e2SKevin Wolf             bdrv_backing_options(&flags, options, flags, options);
1614b1e6fc08SKevin Wolf         }
1615be028adcSJeff Cody 
1616f3930ed0SKevin Wolf         bs->open_flags = flags;
16171fdd6933SKevin Wolf 
16189a4f4c31SKevin Wolf         file = bdrv_open_child(filename, options, "file", bs,
16191fdd6933SKevin Wolf                                &child_file, true, &local_err);
16201fdd6933SKevin Wolf         if (local_err) {
16211fdd6933SKevin Wolf             ret = -EINVAL;
16228bfea15dSKevin Wolf             goto fail;
1623f500a6d3SKevin Wolf         }
1624f4788adcSKevin Wolf     }
1625f500a6d3SKevin Wolf 
162676c591b0SKevin Wolf     /* Image format probing */
162738f3ef57SKevin Wolf     bs->probed = !drv;
162876c591b0SKevin Wolf     if (!drv && file) {
16299a4f4c31SKevin Wolf         ret = find_image_format(file->bs, filename, &drv, &local_err);
163017b005f1SKevin Wolf         if (ret < 0) {
163117b005f1SKevin Wolf             goto fail;
163217b005f1SKevin Wolf         }
163362392ebbSKevin Wolf         /*
163462392ebbSKevin Wolf          * This option update would logically belong in bdrv_fill_options(),
163562392ebbSKevin Wolf          * but we first need to open bs->file for the probing to work, while
163662392ebbSKevin Wolf          * opening bs->file already requires the (mostly) final set of options
163762392ebbSKevin Wolf          * so that cache mode etc. can be inherited.
163862392ebbSKevin Wolf          *
163962392ebbSKevin Wolf          * Adding the driver later is somewhat ugly, but it's not an option
164062392ebbSKevin Wolf          * that would ever be inherited, so it's correct. We just need to make
164162392ebbSKevin Wolf          * sure to update both bs->options (which has the full effective
164262392ebbSKevin Wolf          * options for bs) and options (which has file.* already removed).
164362392ebbSKevin Wolf          */
164462392ebbSKevin Wolf         qdict_put(bs->options, "driver", qstring_from_str(drv->format_name));
164562392ebbSKevin Wolf         qdict_put(options, "driver", qstring_from_str(drv->format_name));
164676c591b0SKevin Wolf     } else if (!drv) {
16472a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
16482a05cbe4SMax Reitz         ret = -EINVAL;
16498bfea15dSKevin Wolf         goto fail;
16502a05cbe4SMax Reitz     }
1651f500a6d3SKevin Wolf 
165253a29513SMax Reitz     /* BDRV_O_PROTOCOL must be set iff a protocol BDS is about to be created */
165353a29513SMax Reitz     assert(!!(flags & BDRV_O_PROTOCOL) == !!drv->bdrv_file_open);
165453a29513SMax Reitz     /* file must be NULL if a protocol BDS is about to be created
165553a29513SMax Reitz      * (the inverse results in an error message from bdrv_open_common()) */
165653a29513SMax Reitz     assert(!(flags & BDRV_O_PROTOCOL) || !file);
165753a29513SMax Reitz 
1658b6ce07aaSKevin Wolf     /* Open the image */
165982dc8b41SKevin Wolf     ret = bdrv_open_common(bs, file, options, &local_err);
1660b6ce07aaSKevin Wolf     if (ret < 0) {
16618bfea15dSKevin Wolf         goto fail;
16626987307cSChristoph Hellwig     }
16636987307cSChristoph Hellwig 
16642a05cbe4SMax Reitz     if (file && (bs->file != file)) {
16659a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1666f500a6d3SKevin Wolf         file = NULL;
1667f500a6d3SKevin Wolf     }
1668f500a6d3SKevin Wolf 
1669b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
16709156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
1671d9b7b057SKevin Wolf         ret = bdrv_open_backing_file(bs, options, "backing", &local_err);
1672b6ce07aaSKevin Wolf         if (ret < 0) {
1673b6ad491aSKevin Wolf             goto close_and_fail;
1674b6ce07aaSKevin Wolf         }
1675b6ce07aaSKevin Wolf     }
1676b6ce07aaSKevin Wolf 
167791af7014SMax Reitz     bdrv_refresh_filename(bs);
167891af7014SMax Reitz 
1679b6ad491aSKevin Wolf     /* Check if any unknown options were used */
16805acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1681b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
16825acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
16835acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
16845acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
16855acd9d81SMax Reitz         } else {
1686d0e46a55SMax Reitz             error_setg(errp,
1687d0e46a55SMax Reitz                        "Block format '%s' does not support the option '%s'",
1688d0e46a55SMax Reitz                        drv->format_name, entry->key);
16895acd9d81SMax Reitz         }
1690b6ad491aSKevin Wolf 
1691b6ad491aSKevin Wolf         ret = -EINVAL;
1692b6ad491aSKevin Wolf         goto close_and_fail;
1693b6ad491aSKevin Wolf     }
1694b6ad491aSKevin Wolf 
1695b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
1696a7f53e26SMarkus Armbruster         if (bs->blk) {
1697a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
1698a7f53e26SMarkus Armbruster         }
1699c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1700c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1701c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1702c3adb58fSMarkus Armbruster         error_setg(errp,
1703c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1704c3adb58fSMarkus Armbruster         ret = -EBUSY;
1705c3adb58fSMarkus Armbruster         goto close_and_fail;
1706b6ce07aaSKevin Wolf     }
1707b6ce07aaSKevin Wolf 
1708c3adb58fSMarkus Armbruster     QDECREF(options);
1709f67503e5SMax Reitz     *pbs = bs;
1710dd62f1caSKevin Wolf 
1711dd62f1caSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1712dd62f1caSKevin Wolf      * temporary snapshot afterwards. */
1713dd62f1caSKevin Wolf     if (snapshot_flags) {
171473176beeSKevin Wolf         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, snapshot_options,
171573176beeSKevin Wolf                                         &local_err);
171673176beeSKevin Wolf         snapshot_options = NULL;
1717dd62f1caSKevin Wolf         if (local_err) {
1718dd62f1caSKevin Wolf             goto close_and_fail;
1719dd62f1caSKevin Wolf         }
1720dd62f1caSKevin Wolf     }
1721dd62f1caSKevin Wolf 
1722b6ce07aaSKevin Wolf     return 0;
1723b6ce07aaSKevin Wolf 
17248bfea15dSKevin Wolf fail:
1725f500a6d3SKevin Wolf     if (file != NULL) {
17269a4f4c31SKevin Wolf         bdrv_unref_child(bs, file);
1727f500a6d3SKevin Wolf     }
172873176beeSKevin Wolf     QDECREF(snapshot_options);
1729145f598eSKevin Wolf     QDECREF(bs->explicit_options);
1730de9c0cecSKevin Wolf     QDECREF(bs->options);
1731b6ad491aSKevin Wolf     QDECREF(options);
1732de9c0cecSKevin Wolf     bs->options = NULL;
1733f67503e5SMax Reitz     if (!*pbs) {
1734f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1735f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1736f67503e5SMax Reitz            since it has not really been opened yet. */
1737f67503e5SMax Reitz         bdrv_unref(bs);
1738f67503e5SMax Reitz     }
173984d18f06SMarkus Armbruster     if (local_err) {
174034b5d2c6SMax Reitz         error_propagate(errp, local_err);
174134b5d2c6SMax Reitz     }
1742b6ad491aSKevin Wolf     return ret;
1743de9c0cecSKevin Wolf 
1744b6ad491aSKevin Wolf close_and_fail:
1745f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1746f67503e5SMax Reitz     if (*pbs) {
1747b6ad491aSKevin Wolf         bdrv_close(bs);
1748f67503e5SMax Reitz     } else {
1749f67503e5SMax Reitz         bdrv_unref(bs);
1750f67503e5SMax Reitz     }
175173176beeSKevin Wolf     QDECREF(snapshot_options);
1752b6ad491aSKevin Wolf     QDECREF(options);
175384d18f06SMarkus Armbruster     if (local_err) {
175434b5d2c6SMax Reitz         error_propagate(errp, local_err);
175534b5d2c6SMax Reitz     }
1756b6ce07aaSKevin Wolf     return ret;
1757b6ce07aaSKevin Wolf }
1758b6ce07aaSKevin Wolf 
1759f3930ed0SKevin Wolf int bdrv_open(BlockDriverState **pbs, const char *filename,
17606ebf9aa2SMax Reitz               const char *reference, QDict *options, int flags, Error **errp)
1761f3930ed0SKevin Wolf {
1762f3930ed0SKevin Wolf     return bdrv_open_inherit(pbs, filename, reference, options, flags, NULL,
1763ce343771SMax Reitz                              NULL, errp);
1764f3930ed0SKevin Wolf }
1765f3930ed0SKevin Wolf 
1766e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1767e971aa12SJeff Cody      bool prepared;
1768e971aa12SJeff Cody      BDRVReopenState state;
1769e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1770e971aa12SJeff Cody } BlockReopenQueueEntry;
1771e971aa12SJeff Cody 
1772e971aa12SJeff Cody /*
1773e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1774e971aa12SJeff Cody  * reopen of multiple devices.
1775e971aa12SJeff Cody  *
1776e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1777e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1778e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1779e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1780e971aa12SJeff Cody  * atomic 'set'.
1781e971aa12SJeff Cody  *
1782e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1783e971aa12SJeff Cody  *
17844d2cb092SKevin Wolf  * options contains the changed options for the associated bs
17854d2cb092SKevin Wolf  * (the BlockReopenQueue takes ownership)
17864d2cb092SKevin Wolf  *
1787e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1788e971aa12SJeff Cody  *
1789e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1790e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1791e971aa12SJeff Cody  *
1792e971aa12SJeff Cody  */
179328518102SKevin Wolf static BlockReopenQueue *bdrv_reopen_queue_child(BlockReopenQueue *bs_queue,
17944d2cb092SKevin Wolf                                                  BlockDriverState *bs,
179528518102SKevin Wolf                                                  QDict *options,
179628518102SKevin Wolf                                                  int flags,
179728518102SKevin Wolf                                                  const BdrvChildRole *role,
179828518102SKevin Wolf                                                  QDict *parent_options,
179928518102SKevin Wolf                                                  int parent_flags)
1800e971aa12SJeff Cody {
1801e971aa12SJeff Cody     assert(bs != NULL);
1802e971aa12SJeff Cody 
1803e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
180467251a31SKevin Wolf     BdrvChild *child;
1805145f598eSKevin Wolf     QDict *old_options, *explicit_options;
180667251a31SKevin Wolf 
1807e971aa12SJeff Cody     if (bs_queue == NULL) {
1808e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1809e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1810e971aa12SJeff Cody     }
1811e971aa12SJeff Cody 
18124d2cb092SKevin Wolf     if (!options) {
18134d2cb092SKevin Wolf         options = qdict_new();
18144d2cb092SKevin Wolf     }
18154d2cb092SKevin Wolf 
181628518102SKevin Wolf     /*
181728518102SKevin Wolf      * Precedence of options:
181828518102SKevin Wolf      * 1. Explicitly passed in options (highest)
181991a097e7SKevin Wolf      * 2. Set in flags (only for top level)
1820145f598eSKevin Wolf      * 3. Retained from explicitly set options of bs
18218e2160e2SKevin Wolf      * 4. Inherited from parent node
182228518102SKevin Wolf      * 5. Retained from effective options of bs
182328518102SKevin Wolf      */
182428518102SKevin Wolf 
182591a097e7SKevin Wolf     if (!parent_options) {
182691a097e7SKevin Wolf         /*
182791a097e7SKevin Wolf          * Any setting represented by flags is always updated. If the
182891a097e7SKevin Wolf          * corresponding QDict option is set, it takes precedence. Otherwise
182991a097e7SKevin Wolf          * the flag is translated into a QDict option. The old setting of bs is
183091a097e7SKevin Wolf          * not considered.
183191a097e7SKevin Wolf          */
183291a097e7SKevin Wolf         update_options_from_flags(options, flags);
183391a097e7SKevin Wolf     }
183491a097e7SKevin Wolf 
1835145f598eSKevin Wolf     /* Old explicitly set values (don't overwrite by inherited value) */
1836145f598eSKevin Wolf     old_options = qdict_clone_shallow(bs->explicit_options);
1837145f598eSKevin Wolf     bdrv_join_options(bs, options, old_options);
1838145f598eSKevin Wolf     QDECREF(old_options);
1839145f598eSKevin Wolf 
1840145f598eSKevin Wolf     explicit_options = qdict_clone_shallow(options);
1841145f598eSKevin Wolf 
184228518102SKevin Wolf     /* Inherit from parent node */
184328518102SKevin Wolf     if (parent_options) {
184428518102SKevin Wolf         assert(!flags);
18458e2160e2SKevin Wolf         role->inherit_options(&flags, options, parent_flags, parent_options);
184628518102SKevin Wolf     }
184728518102SKevin Wolf 
184828518102SKevin Wolf     /* Old values are used for options that aren't set yet */
18494d2cb092SKevin Wolf     old_options = qdict_clone_shallow(bs->options);
1850cddff5baSKevin Wolf     bdrv_join_options(bs, options, old_options);
18514d2cb092SKevin Wolf     QDECREF(old_options);
18524d2cb092SKevin Wolf 
1853f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1854f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1855f1f25a2eSKevin Wolf 
185667251a31SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
18574c9dfe5dSKevin Wolf         QDict *new_child_options;
18584c9dfe5dSKevin Wolf         char *child_key_dot;
185967251a31SKevin Wolf 
18604c9dfe5dSKevin Wolf         /* reopen can only change the options of block devices that were
18614c9dfe5dSKevin Wolf          * implicitly created and inherited options. For other (referenced)
18624c9dfe5dSKevin Wolf          * block devices, a syntax like "backing.foo" results in an error. */
186367251a31SKevin Wolf         if (child->bs->inherits_from != bs) {
186467251a31SKevin Wolf             continue;
186567251a31SKevin Wolf         }
186667251a31SKevin Wolf 
18674c9dfe5dSKevin Wolf         child_key_dot = g_strdup_printf("%s.", child->name);
18684c9dfe5dSKevin Wolf         qdict_extract_subqdict(options, &new_child_options, child_key_dot);
18694c9dfe5dSKevin Wolf         g_free(child_key_dot);
18704c9dfe5dSKevin Wolf 
187128518102SKevin Wolf         bdrv_reopen_queue_child(bs_queue, child->bs, new_child_options, 0,
187228518102SKevin Wolf                                 child->role, options, flags);
1873e971aa12SJeff Cody     }
1874e971aa12SJeff Cody 
1875e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1876e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1877e971aa12SJeff Cody 
1878e971aa12SJeff Cody     bs_entry->state.bs = bs;
18794d2cb092SKevin Wolf     bs_entry->state.options = options;
1880145f598eSKevin Wolf     bs_entry->state.explicit_options = explicit_options;
1881e971aa12SJeff Cody     bs_entry->state.flags = flags;
1882e971aa12SJeff Cody 
1883e971aa12SJeff Cody     return bs_queue;
1884e971aa12SJeff Cody }
1885e971aa12SJeff Cody 
188628518102SKevin Wolf BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
188728518102SKevin Wolf                                     BlockDriverState *bs,
188828518102SKevin Wolf                                     QDict *options, int flags)
188928518102SKevin Wolf {
189028518102SKevin Wolf     return bdrv_reopen_queue_child(bs_queue, bs, options, flags,
189128518102SKevin Wolf                                    NULL, NULL, 0);
189228518102SKevin Wolf }
189328518102SKevin Wolf 
1894e971aa12SJeff Cody /*
1895e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1896e971aa12SJeff Cody  *
1897e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1898e971aa12SJeff Cody  * via bdrv_reopen_queue().
1899e971aa12SJeff Cody  *
1900e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1901e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1902e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1903e971aa12SJeff Cody  * data cleaned up.
1904e971aa12SJeff Cody  *
1905e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1906e971aa12SJeff Cody  * to all devices.
1907e971aa12SJeff Cody  *
1908e971aa12SJeff Cody  */
1909e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1910e971aa12SJeff Cody {
1911e971aa12SJeff Cody     int ret = -1;
1912e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1913e971aa12SJeff Cody     Error *local_err = NULL;
1914e971aa12SJeff Cody 
1915e971aa12SJeff Cody     assert(bs_queue != NULL);
1916e971aa12SJeff Cody 
1917e971aa12SJeff Cody     bdrv_drain_all();
1918e971aa12SJeff Cody 
1919e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1920e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1921e971aa12SJeff Cody             error_propagate(errp, local_err);
1922e971aa12SJeff Cody             goto cleanup;
1923e971aa12SJeff Cody         }
1924e971aa12SJeff Cody         bs_entry->prepared = true;
1925e971aa12SJeff Cody     }
1926e971aa12SJeff Cody 
1927e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1928e971aa12SJeff Cody      * changes
1929e971aa12SJeff Cody      */
1930e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1931e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1932e971aa12SJeff Cody     }
1933e971aa12SJeff Cody 
1934e971aa12SJeff Cody     ret = 0;
1935e971aa12SJeff Cody 
1936e971aa12SJeff Cody cleanup:
1937e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1938e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1939e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1940145f598eSKevin Wolf         } else if (ret) {
1941145f598eSKevin Wolf             QDECREF(bs_entry->state.explicit_options);
1942e971aa12SJeff Cody         }
19434d2cb092SKevin Wolf         QDECREF(bs_entry->state.options);
1944e971aa12SJeff Cody         g_free(bs_entry);
1945e971aa12SJeff Cody     }
1946e971aa12SJeff Cody     g_free(bs_queue);
1947e971aa12SJeff Cody     return ret;
1948e971aa12SJeff Cody }
1949e971aa12SJeff Cody 
1950e971aa12SJeff Cody 
1951e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1952e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1953e971aa12SJeff Cody {
1954e971aa12SJeff Cody     int ret = -1;
1955e971aa12SJeff Cody     Error *local_err = NULL;
19564d2cb092SKevin Wolf     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, NULL, bdrv_flags);
1957e971aa12SJeff Cody 
1958e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1959e971aa12SJeff Cody     if (local_err != NULL) {
1960e971aa12SJeff Cody         error_propagate(errp, local_err);
1961e971aa12SJeff Cody     }
1962e971aa12SJeff Cody     return ret;
1963e971aa12SJeff Cody }
1964e971aa12SJeff Cody 
1965e971aa12SJeff Cody 
1966e971aa12SJeff Cody /*
1967e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1968e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1969e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1970e971aa12SJeff Cody  *
1971e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1972e971aa12SJeff Cody  * flags are the new open flags
1973e971aa12SJeff Cody  * queue is the reopen queue
1974e971aa12SJeff Cody  *
1975e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1976e971aa12SJeff Cody  * as well.
1977e971aa12SJeff Cody  *
1978e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1979e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1980e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1981e971aa12SJeff Cody  *
1982e971aa12SJeff Cody  */
1983e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1984e971aa12SJeff Cody                         Error **errp)
1985e971aa12SJeff Cody {
1986e971aa12SJeff Cody     int ret = -1;
1987e971aa12SJeff Cody     Error *local_err = NULL;
1988e971aa12SJeff Cody     BlockDriver *drv;
1989ccf9dc07SKevin Wolf     QemuOpts *opts;
1990ccf9dc07SKevin Wolf     const char *value;
1991e971aa12SJeff Cody 
1992e971aa12SJeff Cody     assert(reopen_state != NULL);
1993e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1994e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1995e971aa12SJeff Cody 
1996ccf9dc07SKevin Wolf     /* Process generic block layer options */
1997ccf9dc07SKevin Wolf     opts = qemu_opts_create(&bdrv_runtime_opts, NULL, 0, &error_abort);
1998ccf9dc07SKevin Wolf     qemu_opts_absorb_qdict(opts, reopen_state->options, &local_err);
1999ccf9dc07SKevin Wolf     if (local_err) {
2000ccf9dc07SKevin Wolf         error_propagate(errp, local_err);
2001ccf9dc07SKevin Wolf         ret = -EINVAL;
2002ccf9dc07SKevin Wolf         goto error;
2003ccf9dc07SKevin Wolf     }
2004ccf9dc07SKevin Wolf 
200591a097e7SKevin Wolf     update_flags_from_options(&reopen_state->flags, opts);
200691a097e7SKevin Wolf 
200791a097e7SKevin Wolf     /* If a guest device is attached, it owns WCE */
200891a097e7SKevin Wolf     if (reopen_state->bs->blk && blk_get_attached_dev(reopen_state->bs->blk)) {
200991a097e7SKevin Wolf         bool old_wce = bdrv_enable_write_cache(reopen_state->bs);
201091a097e7SKevin Wolf         bool new_wce = (reopen_state->flags & BDRV_O_CACHE_WB);
201191a097e7SKevin Wolf         if (old_wce != new_wce) {
201291a097e7SKevin Wolf             error_setg(errp, "Cannot change cache.writeback: Device attached");
201391a097e7SKevin Wolf             ret = -EINVAL;
201491a097e7SKevin Wolf             goto error;
201591a097e7SKevin Wolf         }
201691a097e7SKevin Wolf     }
201791a097e7SKevin Wolf 
2018ccf9dc07SKevin Wolf     /* node-name and driver must be unchanged. Put them back into the QDict, so
2019ccf9dc07SKevin Wolf      * that they are checked at the end of this function. */
2020ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "node-name");
2021ccf9dc07SKevin Wolf     if (value) {
2022ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "node-name", qstring_from_str(value));
2023ccf9dc07SKevin Wolf     }
2024ccf9dc07SKevin Wolf 
2025ccf9dc07SKevin Wolf     value = qemu_opt_get(opts, "driver");
2026ccf9dc07SKevin Wolf     if (value) {
2027ccf9dc07SKevin Wolf         qdict_put(reopen_state->options, "driver", qstring_from_str(value));
2028ccf9dc07SKevin Wolf     }
2029ccf9dc07SKevin Wolf 
2030e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
2031e971aa12SJeff Cody      * to r/w */
2032e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
2033e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
203481e5f78aSAlberto Garcia         error_setg(errp, "Node '%s' is read only",
203581e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2036e971aa12SJeff Cody         goto error;
2037e971aa12SJeff Cody     }
2038e971aa12SJeff Cody 
2039e971aa12SJeff Cody 
2040e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
2041e971aa12SJeff Cody     if (ret) {
2042455b0fdeSEric Blake         error_setg_errno(errp, -ret, "Error flushing drive");
2043e971aa12SJeff Cody         goto error;
2044e971aa12SJeff Cody     }
2045e971aa12SJeff Cody 
2046e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
2047e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
2048e971aa12SJeff Cody         if (ret) {
2049e971aa12SJeff Cody             if (local_err != NULL) {
2050e971aa12SJeff Cody                 error_propagate(errp, local_err);
2051e971aa12SJeff Cody             } else {
2052d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
2053e971aa12SJeff Cody                            reopen_state->bs->filename);
2054e971aa12SJeff Cody             }
2055e971aa12SJeff Cody             goto error;
2056e971aa12SJeff Cody         }
2057e971aa12SJeff Cody     } else {
2058e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
2059e971aa12SJeff Cody          * handler for each supported drv. */
206081e5f78aSAlberto Garcia         error_setg(errp, "Block format '%s' used by node '%s' "
206181e5f78aSAlberto Garcia                    "does not support reopening files", drv->format_name,
206281e5f78aSAlberto Garcia                    bdrv_get_device_or_node_name(reopen_state->bs));
2063e971aa12SJeff Cody         ret = -1;
2064e971aa12SJeff Cody         goto error;
2065e971aa12SJeff Cody     }
2066e971aa12SJeff Cody 
20674d2cb092SKevin Wolf     /* Options that are not handled are only okay if they are unchanged
20684d2cb092SKevin Wolf      * compared to the old state. It is expected that some options are only
20694d2cb092SKevin Wolf      * used for the initial open, but not reopen (e.g. filename) */
20704d2cb092SKevin Wolf     if (qdict_size(reopen_state->options)) {
20714d2cb092SKevin Wolf         const QDictEntry *entry = qdict_first(reopen_state->options);
20724d2cb092SKevin Wolf 
20734d2cb092SKevin Wolf         do {
20744d2cb092SKevin Wolf             QString *new_obj = qobject_to_qstring(entry->value);
20754d2cb092SKevin Wolf             const char *new = qstring_get_str(new_obj);
20764d2cb092SKevin Wolf             const char *old = qdict_get_try_str(reopen_state->bs->options,
20774d2cb092SKevin Wolf                                                 entry->key);
20784d2cb092SKevin Wolf 
20794d2cb092SKevin Wolf             if (!old || strcmp(new, old)) {
20804d2cb092SKevin Wolf                 error_setg(errp, "Cannot change the option '%s'", entry->key);
20814d2cb092SKevin Wolf                 ret = -EINVAL;
20824d2cb092SKevin Wolf                 goto error;
20834d2cb092SKevin Wolf             }
20844d2cb092SKevin Wolf         } while ((entry = qdict_next(reopen_state->options, entry)));
20854d2cb092SKevin Wolf     }
20864d2cb092SKevin Wolf 
2087e971aa12SJeff Cody     ret = 0;
2088e971aa12SJeff Cody 
2089e971aa12SJeff Cody error:
2090ccf9dc07SKevin Wolf     qemu_opts_del(opts);
2091e971aa12SJeff Cody     return ret;
2092e971aa12SJeff Cody }
2093e971aa12SJeff Cody 
2094e971aa12SJeff Cody /*
2095e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
2096e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
2097e971aa12SJeff Cody  * the active BlockDriverState contents.
2098e971aa12SJeff Cody  */
2099e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
2100e971aa12SJeff Cody {
2101e971aa12SJeff Cody     BlockDriver *drv;
2102e971aa12SJeff Cody 
2103e971aa12SJeff Cody     assert(reopen_state != NULL);
2104e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2105e971aa12SJeff Cody     assert(drv != NULL);
2106e971aa12SJeff Cody 
2107e971aa12SJeff Cody     /* If there are any driver level actions to take */
2108e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
2109e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
2110e971aa12SJeff Cody     }
2111e971aa12SJeff Cody 
2112e971aa12SJeff Cody     /* set BDS specific flags now */
2113145f598eSKevin Wolf     QDECREF(reopen_state->bs->explicit_options);
2114145f598eSKevin Wolf 
2115145f598eSKevin Wolf     reopen_state->bs->explicit_options   = reopen_state->explicit_options;
2116e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
2117e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
2118e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
2119e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
2120355ef4acSKevin Wolf 
21213baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
2122e971aa12SJeff Cody }
2123e971aa12SJeff Cody 
2124e971aa12SJeff Cody /*
2125e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
2126e971aa12SJeff Cody  * reopen_state
2127e971aa12SJeff Cody  */
2128e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
2129e971aa12SJeff Cody {
2130e971aa12SJeff Cody     BlockDriver *drv;
2131e971aa12SJeff Cody 
2132e971aa12SJeff Cody     assert(reopen_state != NULL);
2133e971aa12SJeff Cody     drv = reopen_state->bs->drv;
2134e971aa12SJeff Cody     assert(drv != NULL);
2135e971aa12SJeff Cody 
2136e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
2137e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
2138e971aa12SJeff Cody     }
2139145f598eSKevin Wolf 
2140145f598eSKevin Wolf     QDECREF(reopen_state->explicit_options);
2141e971aa12SJeff Cody }
2142e971aa12SJeff Cody 
2143e971aa12SJeff Cody 
214464dff520SMax Reitz static void bdrv_close(BlockDriverState *bs)
2145fc01f7e7Sbellard {
214633384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
214733384421SMax Reitz 
2148ca9bd24cSMax Reitz     assert(!bs->job);
214999b7e775SAlberto Garcia 
215099b7e775SAlberto Garcia     /* Disable I/O limits and drain all pending throttled requests */
2151a0d64a61SAlberto Garcia     if (bs->throttle_state) {
215299b7e775SAlberto Garcia         bdrv_io_limits_disable(bs);
215399b7e775SAlberto Garcia     }
215499b7e775SAlberto Garcia 
2155fc27291dSPaolo Bonzini     bdrv_drained_begin(bs); /* complete I/O */
215658fda173SStefan Hajnoczi     bdrv_flush(bs);
215753ec73e2SFam Zheng     bdrv_drain(bs); /* in case flush left pending I/O */
2158fc27291dSPaolo Bonzini 
2159c5acdc9aSMax Reitz     bdrv_release_named_dirty_bitmaps(bs);
2160c5acdc9aSMax Reitz     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
2161c5acdc9aSMax Reitz 
2162b4d02820SMax Reitz     if (bs->blk) {
2163b4d02820SMax Reitz         blk_dev_change_media_cb(bs->blk, false);
2164b4d02820SMax Reitz     }
2165b4d02820SMax Reitz 
21663cbc002cSPaolo Bonzini     if (bs->drv) {
21676e93e7c4SKevin Wolf         BdrvChild *child, *next;
21686e93e7c4SKevin Wolf 
21699a7dedbcSKevin Wolf         bs->drv->bdrv_close(bs);
21709a4f4c31SKevin Wolf         bs->drv = NULL;
21719a7dedbcSKevin Wolf 
21729a7dedbcSKevin Wolf         bdrv_set_backing_hd(bs, NULL);
21739a7dedbcSKevin Wolf 
21749a4f4c31SKevin Wolf         if (bs->file != NULL) {
21759a4f4c31SKevin Wolf             bdrv_unref_child(bs, bs->file);
21769a4f4c31SKevin Wolf             bs->file = NULL;
21779a4f4c31SKevin Wolf         }
21789a4f4c31SKevin Wolf 
21796e93e7c4SKevin Wolf         QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
218033a60407SKevin Wolf             /* TODO Remove bdrv_unref() from drivers' close function and use
218133a60407SKevin Wolf              * bdrv_unref_child() here */
2182bddcec37SKevin Wolf             if (child->bs->inherits_from == bs) {
2183bddcec37SKevin Wolf                 child->bs->inherits_from = NULL;
2184bddcec37SKevin Wolf             }
218533a60407SKevin Wolf             bdrv_detach_child(child);
21866e93e7c4SKevin Wolf         }
21876e93e7c4SKevin Wolf 
21887267c094SAnthony Liguori         g_free(bs->opaque);
2189ea2384d3Sbellard         bs->opaque = NULL;
219053fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
2191a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
2192a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
21936405875cSPaolo Bonzini         bs->total_sectors = 0;
21946405875cSPaolo Bonzini         bs->encrypted = 0;
21956405875cSPaolo Bonzini         bs->valid_key = 0;
21966405875cSPaolo Bonzini         bs->sg = 0;
21970d51b4deSAsias He         bs->zero_beyond_eof = false;
2198de9c0cecSKevin Wolf         QDECREF(bs->options);
2199145f598eSKevin Wolf         QDECREF(bs->explicit_options);
2200de9c0cecSKevin Wolf         bs->options = NULL;
220191af7014SMax Reitz         QDECREF(bs->full_open_options);
220291af7014SMax Reitz         bs->full_open_options = NULL;
22039ca11154SPavel Hrdina     }
220466f82ceeSKevin Wolf 
220533384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
220633384421SMax Reitz         g_free(ban);
220733384421SMax Reitz     }
220833384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
2209fc27291dSPaolo Bonzini     bdrv_drained_end(bs);
2210b338082bSbellard }
2211b338082bSbellard 
22122bc93fedSMORITA Kazutaka void bdrv_close_all(void)
22132bc93fedSMORITA Kazutaka {
22142bc93fedSMORITA Kazutaka     BlockDriverState *bs;
2215ca9bd24cSMax Reitz     AioContext *aio_context;
22162bc93fedSMORITA Kazutaka 
2217ca9bd24cSMax Reitz     /* Drop references from requests still in flight, such as canceled block
2218ca9bd24cSMax Reitz      * jobs whose AIO context has not been polled yet */
2219ca9bd24cSMax Reitz     bdrv_drain_all();
2220ca9bd24cSMax Reitz 
2221ca9bd24cSMax Reitz     blk_remove_all_bs();
2222ca9bd24cSMax Reitz     blockdev_close_all_bdrv_states();
2223ca9bd24cSMax Reitz 
2224ca9bd24cSMax Reitz     /* Cancel all block jobs */
2225ca9bd24cSMax Reitz     while (!QTAILQ_EMPTY(&all_bdrv_states)) {
2226ca9bd24cSMax Reitz         QTAILQ_FOREACH(bs, &all_bdrv_states, bs_list) {
2227ca9bd24cSMax Reitz             aio_context = bdrv_get_aio_context(bs);
2228ed78cda3SStefan Hajnoczi 
2229ed78cda3SStefan Hajnoczi             aio_context_acquire(aio_context);
2230ca9bd24cSMax Reitz             if (bs->job) {
2231ca9bd24cSMax Reitz                 block_job_cancel_sync(bs->job);
2232ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2233ca9bd24cSMax Reitz                 break;
2234ca9bd24cSMax Reitz             }
2235ca9bd24cSMax Reitz             aio_context_release(aio_context);
2236ca9bd24cSMax Reitz         }
2237ca9bd24cSMax Reitz 
2238ca9bd24cSMax Reitz         /* All the remaining BlockDriverStates are referenced directly or
2239ca9bd24cSMax Reitz          * indirectly from block jobs, so there needs to be at least one BDS
2240ca9bd24cSMax Reitz          * directly used by a block job */
2241ca9bd24cSMax Reitz         assert(bs);
22422bc93fedSMORITA Kazutaka     }
22432bc93fedSMORITA Kazutaka }
22442bc93fedSMORITA Kazutaka 
22458e419aefSKevin Wolf /* Fields that need to stay with the top-level BDS */
22464ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
22474ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
22484ddc07caSPaolo Bonzini {
22494ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
22504ddc07caSPaolo Bonzini 
22514ddc07caSPaolo Bonzini     /* dev info */
22524ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
22534ddc07caSPaolo Bonzini 
22544ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
22554ddc07caSPaolo Bonzini 
2256dd62f1caSKevin Wolf     /* dirty bitmap */
2257dd62f1caSKevin Wolf     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
2258dd62f1caSKevin Wolf }
2259dd62f1caSKevin Wolf 
2260dd62f1caSKevin Wolf static void change_parent_backing_link(BlockDriverState *from,
2261dd62f1caSKevin Wolf                                        BlockDriverState *to)
2262dd62f1caSKevin Wolf {
2263dd62f1caSKevin Wolf     BdrvChild *c, *next;
2264dd62f1caSKevin Wolf 
2265f21d96d0SKevin Wolf     if (from->blk) {
2266f21d96d0SKevin Wolf         /* FIXME We bypass blk_set_bs(), so we need to make these updates
2267f21d96d0SKevin Wolf          * manually. The root problem is not in this change function, but the
2268f21d96d0SKevin Wolf          * existence of BlockDriverState.blk. */
2269f21d96d0SKevin Wolf         to->blk = from->blk;
2270f21d96d0SKevin Wolf         from->blk = NULL;
2271f21d96d0SKevin Wolf     }
2272f21d96d0SKevin Wolf 
2273dd62f1caSKevin Wolf     QLIST_FOREACH_SAFE(c, &from->parents, next_parent, next) {
2274dd62f1caSKevin Wolf         assert(c->role != &child_backing);
2275dd62f1caSKevin Wolf         c->bs = to;
2276dd62f1caSKevin Wolf         QLIST_REMOVE(c, next_parent);
2277dd62f1caSKevin Wolf         QLIST_INSERT_HEAD(&to->parents, c, next_parent);
2278dd62f1caSKevin Wolf         bdrv_ref(to);
2279dd62f1caSKevin Wolf         bdrv_unref(from);
2280dd62f1caSKevin Wolf     }
2281dd62f1caSKevin Wolf }
2282dd62f1caSKevin Wolf 
2283dd62f1caSKevin Wolf static void swap_feature_fields(BlockDriverState *bs_top,
2284dd62f1caSKevin Wolf                                 BlockDriverState *bs_new)
2285dd62f1caSKevin Wolf {
2286dd62f1caSKevin Wolf     BlockDriverState tmp;
2287dd62f1caSKevin Wolf 
2288dd62f1caSKevin Wolf     bdrv_move_feature_fields(&tmp, bs_top);
2289dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_top, bs_new);
2290dd62f1caSKevin Wolf     bdrv_move_feature_fields(bs_new, &tmp);
2291dd62f1caSKevin Wolf 
2292dd62f1caSKevin Wolf     assert(!bs_new->throttle_state);
2293dd62f1caSKevin Wolf     if (bs_top->throttle_state) {
2294dd62f1caSKevin Wolf         assert(bs_top->io_limits_enabled);
2295dd62f1caSKevin Wolf         bdrv_io_limits_enable(bs_new, throttle_group_get_name(bs_top));
2296dd62f1caSKevin Wolf         bdrv_io_limits_disable(bs_top);
2297dd62f1caSKevin Wolf     }
2298dd62f1caSKevin Wolf }
2299dd62f1caSKevin Wolf 
23008802d1fdSJeff Cody /*
23018802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
23028802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
23038802d1fdSJeff Cody  *
23048802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
23058802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
23068802d1fdSJeff Cody  *
2307bfb197e0SMarkus Armbruster  * bs_new must not be attached to a BlockBackend.
2308f6801b83SJeff Cody  *
23098802d1fdSJeff Cody  * This function does not create any image files.
2310dd62f1caSKevin Wolf  *
2311dd62f1caSKevin Wolf  * bdrv_append() takes ownership of a bs_new reference and unrefs it because
2312dd62f1caSKevin Wolf  * that's what the callers commonly need. bs_new will be referenced by the old
2313dd62f1caSKevin Wolf  * parents of bs_top after bdrv_append() returns. If the caller needs to keep a
2314dd62f1caSKevin Wolf  * reference of its own, it must call bdrv_ref().
23158802d1fdSJeff Cody  */
23168802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
23178802d1fdSJeff Cody {
2318dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_top));
2319dd62f1caSKevin Wolf     assert(!bdrv_requests_pending(bs_new));
23208802d1fdSJeff Cody 
2321dd62f1caSKevin Wolf     bdrv_ref(bs_top);
2322dd62f1caSKevin Wolf     change_parent_backing_link(bs_top, bs_new);
2323dd62f1caSKevin Wolf 
2324dd62f1caSKevin Wolf     /* Some fields always stay on top of the backing file chain */
2325dd62f1caSKevin Wolf     swap_feature_fields(bs_top, bs_new);
2326dd62f1caSKevin Wolf 
2327dd62f1caSKevin Wolf     bdrv_set_backing_hd(bs_new, bs_top);
2328dd62f1caSKevin Wolf     bdrv_unref(bs_top);
2329dd62f1caSKevin Wolf 
2330dd62f1caSKevin Wolf     /* bs_new is now referenced by its new parents, we don't need the
2331dd62f1caSKevin Wolf      * additional reference any more. */
2332dd62f1caSKevin Wolf     bdrv_unref(bs_new);
23338802d1fdSJeff Cody }
23348802d1fdSJeff Cody 
23353f09bfbcSKevin Wolf void bdrv_replace_in_backing_chain(BlockDriverState *old, BlockDriverState *new)
23363f09bfbcSKevin Wolf {
23373f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(old));
23383f09bfbcSKevin Wolf     assert(!bdrv_requests_pending(new));
23393f09bfbcSKevin Wolf 
23403f09bfbcSKevin Wolf     bdrv_ref(old);
23413f09bfbcSKevin Wolf 
23423f09bfbcSKevin Wolf     if (old->blk) {
23433f09bfbcSKevin Wolf         /* As long as these fields aren't in BlockBackend, but in the top-level
23443f09bfbcSKevin Wolf          * BlockDriverState, it's not possible for a BDS to have two BBs.
23453f09bfbcSKevin Wolf          *
23463f09bfbcSKevin Wolf          * We really want to copy the fields from old to new, but we go for a
23473f09bfbcSKevin Wolf          * swap instead so that pointers aren't duplicated and cause trouble.
23483f09bfbcSKevin Wolf          * (Also, bdrv_swap() used to do the same.) */
23493f09bfbcSKevin Wolf         assert(!new->blk);
23503f09bfbcSKevin Wolf         swap_feature_fields(old, new);
23513f09bfbcSKevin Wolf     }
23523f09bfbcSKevin Wolf     change_parent_backing_link(old, new);
23533f09bfbcSKevin Wolf 
23543f09bfbcSKevin Wolf     /* Change backing files if a previously independent node is added to the
23553f09bfbcSKevin Wolf      * chain. For active commit, we replace top by its own (indirect) backing
23563f09bfbcSKevin Wolf      * file and don't do anything here so we don't build a loop. */
23573f09bfbcSKevin Wolf     if (new->backing == NULL && !bdrv_chain_contains(backing_bs(old), new)) {
23583f09bfbcSKevin Wolf         bdrv_set_backing_hd(new, backing_bs(old));
23593f09bfbcSKevin Wolf         bdrv_set_backing_hd(old, NULL);
23603f09bfbcSKevin Wolf     }
23613f09bfbcSKevin Wolf 
23623f09bfbcSKevin Wolf     bdrv_unref(old);
23633f09bfbcSKevin Wolf }
23643f09bfbcSKevin Wolf 
23654f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2366b338082bSbellard {
23673e914655SPaolo Bonzini     assert(!bs->job);
23683718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
23694f6fd349SFam Zheng     assert(!bs->refcnt);
237018846deeSMarkus Armbruster 
2371e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2372e1b5c52eSStefan Hajnoczi 
23731b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2374*63eaaae0SKevin Wolf     if (bs->node_name[0] != '\0') {
2375*63eaaae0SKevin Wolf         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
2376*63eaaae0SKevin Wolf     }
23772c1d04e0SMax Reitz     QTAILQ_REMOVE(&all_bdrv_states, bs, bs_list);
23782c1d04e0SMax Reitz 
23797267c094SAnthony Liguori     g_free(bs);
2380fc01f7e7Sbellard }
2381fc01f7e7Sbellard 
2382e97fc193Saliguori /*
2383e97fc193Saliguori  * Run consistency checks on an image
2384e97fc193Saliguori  *
2385e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2386a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2387e076f338SKevin Wolf  * check are stored in res.
2388e97fc193Saliguori  */
23894534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2390e97fc193Saliguori {
2391908bcd54SMax Reitz     if (bs->drv == NULL) {
2392908bcd54SMax Reitz         return -ENOMEDIUM;
2393908bcd54SMax Reitz     }
2394e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2395e97fc193Saliguori         return -ENOTSUP;
2396e97fc193Saliguori     }
2397e97fc193Saliguori 
2398e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
23994534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2400e97fc193Saliguori }
2401e97fc193Saliguori 
24028a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
24038a426614SKevin Wolf 
240433e3963eSbellard /* commit COW file into the raw image */
240533e3963eSbellard int bdrv_commit(BlockDriverState *bs)
240633e3963eSbellard {
240719cb3738Sbellard     BlockDriver *drv = bs->drv;
240872706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
24098a426614SKevin Wolf     int n, ro, open_flags;
24100bce597dSJeff Cody     int ret = 0;
241172706ea4SJeff Cody     uint8_t *buf = NULL;
241233e3963eSbellard 
241319cb3738Sbellard     if (!drv)
241419cb3738Sbellard         return -ENOMEDIUM;
241533e3963eSbellard 
2416760e0063SKevin Wolf     if (!bs->backing) {
24174dca4b63SNaphtali Sprei         return -ENOTSUP;
24184dca4b63SNaphtali Sprei     }
24194dca4b63SNaphtali Sprei 
2420bb00021dSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT_SOURCE, NULL) ||
2421760e0063SKevin Wolf         bdrv_op_is_blocked(bs->backing->bs, BLOCK_OP_TYPE_COMMIT_TARGET, NULL)) {
24222d3735d3SStefan Hajnoczi         return -EBUSY;
24232d3735d3SStefan Hajnoczi     }
24242d3735d3SStefan Hajnoczi 
2425760e0063SKevin Wolf     ro = bs->backing->bs->read_only;
2426760e0063SKevin Wolf     open_flags =  bs->backing->bs->open_flags;
24274dca4b63SNaphtali Sprei 
24284dca4b63SNaphtali Sprei     if (ro) {
2429760e0063SKevin Wolf         if (bdrv_reopen(bs->backing->bs, open_flags | BDRV_O_RDWR, NULL)) {
24300bce597dSJeff Cody             return -EACCES;
24314dca4b63SNaphtali Sprei         }
2432ea2384d3Sbellard     }
2433ea2384d3Sbellard 
243472706ea4SJeff Cody     length = bdrv_getlength(bs);
243572706ea4SJeff Cody     if (length < 0) {
243672706ea4SJeff Cody         ret = length;
243772706ea4SJeff Cody         goto ro_cleanup;
243872706ea4SJeff Cody     }
243972706ea4SJeff Cody 
2440760e0063SKevin Wolf     backing_length = bdrv_getlength(bs->backing->bs);
244172706ea4SJeff Cody     if (backing_length < 0) {
244272706ea4SJeff Cody         ret = backing_length;
244372706ea4SJeff Cody         goto ro_cleanup;
244472706ea4SJeff Cody     }
244572706ea4SJeff Cody 
244672706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
244772706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
244872706ea4SJeff Cody      * we must return an error */
244972706ea4SJeff Cody     if (length > backing_length) {
2450760e0063SKevin Wolf         ret = bdrv_truncate(bs->backing->bs, length);
245172706ea4SJeff Cody         if (ret < 0) {
245272706ea4SJeff Cody             goto ro_cleanup;
245372706ea4SJeff Cody         }
245472706ea4SJeff Cody     }
245572706ea4SJeff Cody 
245672706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2457857d4f46SKevin Wolf 
2458857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2459760e0063SKevin Wolf      * bs->backing->bs as well, so no need to compare the alignment manually. */
2460857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2461857d4f46SKevin Wolf     if (buf == NULL) {
2462857d4f46SKevin Wolf         ret = -ENOMEM;
2463857d4f46SKevin Wolf         goto ro_cleanup;
2464857d4f46SKevin Wolf     }
24658a426614SKevin Wolf 
24668a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2467d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2468d663640cSPaolo Bonzini         if (ret < 0) {
2469d663640cSPaolo Bonzini             goto ro_cleanup;
2470d663640cSPaolo Bonzini         }
2471d663640cSPaolo Bonzini         if (ret) {
2472dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2473dabfa6ccSKevin Wolf             if (ret < 0) {
24744dca4b63SNaphtali Sprei                 goto ro_cleanup;
247533e3963eSbellard             }
247633e3963eSbellard 
2477760e0063SKevin Wolf             ret = bdrv_write(bs->backing->bs, sector, buf, n);
2478dabfa6ccSKevin Wolf             if (ret < 0) {
24794dca4b63SNaphtali Sprei                 goto ro_cleanup;
248033e3963eSbellard             }
248133e3963eSbellard         }
248233e3963eSbellard     }
248395389c86Sbellard 
24841d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
24851d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2486dabfa6ccSKevin Wolf         if (ret < 0) {
2487dabfa6ccSKevin Wolf             goto ro_cleanup;
2488dabfa6ccSKevin Wolf         }
24891d44952fSChristoph Hellwig         bdrv_flush(bs);
24901d44952fSChristoph Hellwig     }
249195389c86Sbellard 
24923f5075aeSChristoph Hellwig     /*
24933f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
24943f5075aeSChristoph Hellwig      * stable on disk.
24953f5075aeSChristoph Hellwig      */
2496760e0063SKevin Wolf     if (bs->backing) {
2497760e0063SKevin Wolf         bdrv_flush(bs->backing->bs);
2498dabfa6ccSKevin Wolf     }
24994dca4b63SNaphtali Sprei 
2500dabfa6ccSKevin Wolf     ret = 0;
25014dca4b63SNaphtali Sprei ro_cleanup:
2502857d4f46SKevin Wolf     qemu_vfree(buf);
25034dca4b63SNaphtali Sprei 
25044dca4b63SNaphtali Sprei     if (ro) {
25050bce597dSJeff Cody         /* ignoring error return here */
2506760e0063SKevin Wolf         bdrv_reopen(bs->backing->bs, open_flags & ~BDRV_O_RDWR, NULL);
25074dca4b63SNaphtali Sprei     }
25084dca4b63SNaphtali Sprei 
25091d44952fSChristoph Hellwig     return ret;
251033e3963eSbellard }
251133e3963eSbellard 
2512756e6736SKevin Wolf /*
2513756e6736SKevin Wolf  * Return values:
2514756e6736SKevin Wolf  * 0        - success
2515756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2516756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2517756e6736SKevin Wolf  *            image file header
2518756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2519756e6736SKevin Wolf  */
2520756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2521756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2522756e6736SKevin Wolf {
2523756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2524469ef350SPaolo Bonzini     int ret;
2525756e6736SKevin Wolf 
25265f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25275f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25285f377794SPaolo Bonzini         return -EINVAL;
25295f377794SPaolo Bonzini     }
25305f377794SPaolo Bonzini 
2531756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2532469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2533756e6736SKevin Wolf     } else {
2534469ef350SPaolo Bonzini         ret = -ENOTSUP;
2535756e6736SKevin Wolf     }
2536469ef350SPaolo Bonzini 
2537469ef350SPaolo Bonzini     if (ret == 0) {
2538469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2539469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2540469ef350SPaolo Bonzini     }
2541469ef350SPaolo Bonzini     return ret;
2542756e6736SKevin Wolf }
2543756e6736SKevin Wolf 
25446ebdcee2SJeff Cody /*
25456ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25466ebdcee2SJeff Cody  *
25476ebdcee2SJeff Cody  * active is the current topmost image.
25486ebdcee2SJeff Cody  *
25496ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25506ebdcee2SJeff Cody  * or if active == bs.
25514caf0fcdSJeff Cody  *
25524caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25536ebdcee2SJeff Cody  */
25546ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25556ebdcee2SJeff Cody                                     BlockDriverState *bs)
25566ebdcee2SJeff Cody {
2557760e0063SKevin Wolf     while (active && bs != backing_bs(active)) {
2558760e0063SKevin Wolf         active = backing_bs(active);
25596ebdcee2SJeff Cody     }
25606ebdcee2SJeff Cody 
25614caf0fcdSJeff Cody     return active;
25626ebdcee2SJeff Cody }
25636ebdcee2SJeff Cody 
25644caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25654caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25664caf0fcdSJeff Cody {
25674caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25686ebdcee2SJeff Cody }
25696ebdcee2SJeff Cody 
25706ebdcee2SJeff Cody /*
25716ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25726ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25736ebdcee2SJeff Cody  *
25746ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25756ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25766ebdcee2SJeff Cody  *
25776ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25786ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25796ebdcee2SJeff Cody  *
25806ebdcee2SJeff Cody  * to
25816ebdcee2SJeff Cody  *
25826ebdcee2SJeff Cody  * bottom <- base <- active
25836ebdcee2SJeff Cody  *
25846ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25856ebdcee2SJeff Cody  *
25866ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25876ebdcee2SJeff Cody  *
25886ebdcee2SJeff Cody  * to
25896ebdcee2SJeff Cody  *
25906ebdcee2SJeff Cody  * base <- active
25916ebdcee2SJeff Cody  *
259254e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
259354e26900SJeff Cody  * overlay image metadata.
259454e26900SJeff Cody  *
25956ebdcee2SJeff Cody  * Error conditions:
25966ebdcee2SJeff Cody  *  if active == top, that is considered an error
25976ebdcee2SJeff Cody  *
25986ebdcee2SJeff Cody  */
25996ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
260054e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
26016ebdcee2SJeff Cody {
26026ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26036ebdcee2SJeff Cody     int ret = -EIO;
26046ebdcee2SJeff Cody 
26056ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26066ebdcee2SJeff Cody         goto exit;
26076ebdcee2SJeff Cody     }
26086ebdcee2SJeff Cody 
26096ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26106ebdcee2SJeff Cody 
26116ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26126ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26136ebdcee2SJeff Cody         goto exit;
26146ebdcee2SJeff Cody     }
26156ebdcee2SJeff Cody 
2616760e0063SKevin Wolf     /* special case of new_top_bs->backing->bs already pointing to base - nothing
26176ebdcee2SJeff Cody      * to do, no intermediate images */
2618760e0063SKevin Wolf     if (backing_bs(new_top_bs) == base) {
26196ebdcee2SJeff Cody         ret = 0;
26206ebdcee2SJeff Cody         goto exit;
26216ebdcee2SJeff Cody     }
26226ebdcee2SJeff Cody 
26235db15a57SKevin Wolf     /* Make sure that base is in the backing chain of top */
26245db15a57SKevin Wolf     if (!bdrv_chain_contains(top, base)) {
26256ebdcee2SJeff Cody         goto exit;
26266ebdcee2SJeff Cody     }
26276ebdcee2SJeff Cody 
26286ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
26295db15a57SKevin Wolf     backing_file_str = backing_file_str ? backing_file_str : base->filename;
263054e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26315db15a57SKevin Wolf                                    base->drv ? base->drv->format_name : "");
26326ebdcee2SJeff Cody     if (ret) {
26336ebdcee2SJeff Cody         goto exit;
26346ebdcee2SJeff Cody     }
26355db15a57SKevin Wolf     bdrv_set_backing_hd(new_top_bs, base);
26366ebdcee2SJeff Cody 
26376ebdcee2SJeff Cody     ret = 0;
26386ebdcee2SJeff Cody exit:
26396ebdcee2SJeff Cody     return ret;
26406ebdcee2SJeff Cody }
26416ebdcee2SJeff Cody 
264283f64091Sbellard /**
264383f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
264483f64091Sbellard  */
264583f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
264683f64091Sbellard {
264783f64091Sbellard     BlockDriver *drv = bs->drv;
264851762288SStefan Hajnoczi     int ret;
264983f64091Sbellard     if (!drv)
265019cb3738Sbellard         return -ENOMEDIUM;
265183f64091Sbellard     if (!drv->bdrv_truncate)
265283f64091Sbellard         return -ENOTSUP;
265359f2689dSNaphtali Sprei     if (bs->read_only)
265459f2689dSNaphtali Sprei         return -EACCES;
26559c75e168SJeff Cody 
265651762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
265751762288SStefan Hajnoczi     if (ret == 0) {
265851762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
2659ce1ffea8SJohn Snow         bdrv_dirty_bitmap_truncate(bs);
2660a7f53e26SMarkus Armbruster         if (bs->blk) {
2661a7f53e26SMarkus Armbruster             blk_dev_resize_cb(bs->blk);
2662a7f53e26SMarkus Armbruster         }
266351762288SStefan Hajnoczi     }
266451762288SStefan Hajnoczi     return ret;
266583f64091Sbellard }
266683f64091Sbellard 
266783f64091Sbellard /**
26684a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
26694a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
26704a1d5e1fSFam Zheng  */
26714a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
26724a1d5e1fSFam Zheng {
26734a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
26744a1d5e1fSFam Zheng     if (!drv) {
26754a1d5e1fSFam Zheng         return -ENOMEDIUM;
26764a1d5e1fSFam Zheng     }
26774a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
26784a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
26794a1d5e1fSFam Zheng     }
26804a1d5e1fSFam Zheng     if (bs->file) {
26819a4f4c31SKevin Wolf         return bdrv_get_allocated_file_size(bs->file->bs);
26824a1d5e1fSFam Zheng     }
26834a1d5e1fSFam Zheng     return -ENOTSUP;
26844a1d5e1fSFam Zheng }
26854a1d5e1fSFam Zheng 
26864a1d5e1fSFam Zheng /**
268765a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
268883f64091Sbellard  */
268965a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
269083f64091Sbellard {
269183f64091Sbellard     BlockDriver *drv = bs->drv;
269265a9bb25SMarkus Armbruster 
269383f64091Sbellard     if (!drv)
269419cb3738Sbellard         return -ENOMEDIUM;
269551762288SStefan Hajnoczi 
2696b94a2610SKevin Wolf     if (drv->has_variable_length) {
2697b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
2698b94a2610SKevin Wolf         if (ret < 0) {
2699b94a2610SKevin Wolf             return ret;
2700fc01f7e7Sbellard         }
270146a4e4e6SStefan Hajnoczi     }
270265a9bb25SMarkus Armbruster     return bs->total_sectors;
270365a9bb25SMarkus Armbruster }
270465a9bb25SMarkus Armbruster 
270565a9bb25SMarkus Armbruster /**
270665a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
270765a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
270865a9bb25SMarkus Armbruster  */
270965a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
271065a9bb25SMarkus Armbruster {
271165a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
271265a9bb25SMarkus Armbruster 
27134a9c9ea0SFam Zheng     ret = ret > INT64_MAX / BDRV_SECTOR_SIZE ? -EFBIG : ret;
271465a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
271546a4e4e6SStefan Hajnoczi }
2716fc01f7e7Sbellard 
271719cb3738Sbellard /* return 0 as number of sectors if no device present or error */
271896b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
2719fc01f7e7Sbellard {
272065a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
272165a9bb25SMarkus Armbruster 
272265a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
2723fc01f7e7Sbellard }
2724cf98951bSbellard 
2725b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
2726b338082bSbellard {
2727b338082bSbellard     return bs->read_only;
2728b338082bSbellard }
2729b338082bSbellard 
2730985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
2731985a03b0Sths {
2732985a03b0Sths     return bs->sg;
2733985a03b0Sths }
2734985a03b0Sths 
2735e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
2736e900a7b7SChristoph Hellwig {
2737e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
2738e900a7b7SChristoph Hellwig }
2739e900a7b7SChristoph Hellwig 
2740425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
2741425b0148SPaolo Bonzini {
2742425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
274355b110f2SJeff Cody 
274455b110f2SJeff Cody     /* so a reopen() will preserve wce */
274555b110f2SJeff Cody     if (wce) {
274655b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
274755b110f2SJeff Cody     } else {
274855b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
274955b110f2SJeff Cody     }
2750425b0148SPaolo Bonzini }
2751425b0148SPaolo Bonzini 
2752ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
2753ea2384d3Sbellard {
2754760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2755ea2384d3Sbellard         return 1;
2756760e0063SKevin Wolf     }
2757ea2384d3Sbellard     return bs->encrypted;
2758ea2384d3Sbellard }
2759ea2384d3Sbellard 
2760c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
2761c0f4ce77Saliguori {
2762760e0063SKevin Wolf     BdrvChild *backing = bs->backing;
2763c0f4ce77Saliguori 
2764760e0063SKevin Wolf     if (backing && backing->bs->encrypted && !backing->bs->valid_key) {
2765c0f4ce77Saliguori         return 1;
2766760e0063SKevin Wolf     }
2767c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
2768c0f4ce77Saliguori }
2769c0f4ce77Saliguori 
2770ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
2771ea2384d3Sbellard {
2772ea2384d3Sbellard     int ret;
2773760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted) {
2774760e0063SKevin Wolf         ret = bdrv_set_key(bs->backing->bs, key);
2775ea2384d3Sbellard         if (ret < 0)
2776ea2384d3Sbellard             return ret;
2777ea2384d3Sbellard         if (!bs->encrypted)
2778ea2384d3Sbellard             return 0;
2779ea2384d3Sbellard     }
2780fd04a2aeSShahar Havivi     if (!bs->encrypted) {
2781fd04a2aeSShahar Havivi         return -EINVAL;
2782fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
2783fd04a2aeSShahar Havivi         return -ENOMEDIUM;
2784fd04a2aeSShahar Havivi     }
2785c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
2786bb5fc20fSaliguori     if (ret < 0) {
2787bb5fc20fSaliguori         bs->valid_key = 0;
2788bb5fc20fSaliguori     } else if (!bs->valid_key) {
2789bb5fc20fSaliguori         bs->valid_key = 1;
2790a7f53e26SMarkus Armbruster         if (bs->blk) {
2791bb5fc20fSaliguori             /* call the change callback now, we skipped it on open */
2792a7f53e26SMarkus Armbruster             blk_dev_change_media_cb(bs->blk, true);
2793a7f53e26SMarkus Armbruster         }
2794bb5fc20fSaliguori     }
2795c0f4ce77Saliguori     return ret;
2796ea2384d3Sbellard }
2797ea2384d3Sbellard 
27984d2855a3SMarkus Armbruster /*
27994d2855a3SMarkus Armbruster  * Provide an encryption key for @bs.
28004d2855a3SMarkus Armbruster  * If @key is non-null:
28014d2855a3SMarkus Armbruster  *     If @bs is not encrypted, fail.
28024d2855a3SMarkus Armbruster  *     Else if the key is invalid, fail.
28034d2855a3SMarkus Armbruster  *     Else set @bs's key to @key, replacing the existing key, if any.
28044d2855a3SMarkus Armbruster  * If @key is null:
28054d2855a3SMarkus Armbruster  *     If @bs is encrypted and still lacks a key, fail.
28064d2855a3SMarkus Armbruster  *     Else do nothing.
28074d2855a3SMarkus Armbruster  * On failure, store an error object through @errp if non-null.
28084d2855a3SMarkus Armbruster  */
28094d2855a3SMarkus Armbruster void bdrv_add_key(BlockDriverState *bs, const char *key, Error **errp)
28104d2855a3SMarkus Armbruster {
28114d2855a3SMarkus Armbruster     if (key) {
28124d2855a3SMarkus Armbruster         if (!bdrv_is_encrypted(bs)) {
281381e5f78aSAlberto Garcia             error_setg(errp, "Node '%s' is not encrypted",
281481e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs));
28154d2855a3SMarkus Armbruster         } else if (bdrv_set_key(bs, key) < 0) {
2816c6bd8c70SMarkus Armbruster             error_setg(errp, QERR_INVALID_PASSWORD);
28174d2855a3SMarkus Armbruster         }
28184d2855a3SMarkus Armbruster     } else {
28194d2855a3SMarkus Armbruster         if (bdrv_key_required(bs)) {
2820b1ca6391SMarkus Armbruster             error_set(errp, ERROR_CLASS_DEVICE_ENCRYPTED,
2821b1ca6391SMarkus Armbruster                       "'%s' (%s) is encrypted",
282281e5f78aSAlberto Garcia                       bdrv_get_device_or_node_name(bs),
28234d2855a3SMarkus Armbruster                       bdrv_get_encrypted_filename(bs));
28244d2855a3SMarkus Armbruster         }
28254d2855a3SMarkus Armbruster     }
28264d2855a3SMarkus Armbruster }
28274d2855a3SMarkus Armbruster 
2828f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
2829ea2384d3Sbellard {
2830f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
2831ea2384d3Sbellard }
2832ea2384d3Sbellard 
2833ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
2834ada42401SStefan Hajnoczi {
2835ada42401SStefan Hajnoczi     return strcmp(a, b);
2836ada42401SStefan Hajnoczi }
2837ada42401SStefan Hajnoczi 
2838ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
2839ea2384d3Sbellard                          void *opaque)
2840ea2384d3Sbellard {
2841ea2384d3Sbellard     BlockDriver *drv;
2842e855e4fbSJeff Cody     int count = 0;
2843ada42401SStefan Hajnoczi     int i;
2844e855e4fbSJeff Cody     const char **formats = NULL;
2845ea2384d3Sbellard 
28468a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
2847e855e4fbSJeff Cody         if (drv->format_name) {
2848e855e4fbSJeff Cody             bool found = false;
2849e855e4fbSJeff Cody             int i = count;
2850e855e4fbSJeff Cody             while (formats && i && !found) {
2851e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
2852e855e4fbSJeff Cody             }
2853e855e4fbSJeff Cody 
2854e855e4fbSJeff Cody             if (!found) {
28555839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
2856e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
2857ea2384d3Sbellard             }
2858ea2384d3Sbellard         }
2859e855e4fbSJeff Cody     }
2860ada42401SStefan Hajnoczi 
2861ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
2862ada42401SStefan Hajnoczi 
2863ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
2864ada42401SStefan Hajnoczi         it(opaque, formats[i]);
2865ada42401SStefan Hajnoczi     }
2866ada42401SStefan Hajnoczi 
2867e855e4fbSJeff Cody     g_free(formats);
2868e855e4fbSJeff Cody }
2869ea2384d3Sbellard 
2870dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
2871dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
2872dc364f4cSBenoît Canet {
2873dc364f4cSBenoît Canet     BlockDriverState *bs;
2874dc364f4cSBenoît Canet 
2875dc364f4cSBenoît Canet     assert(node_name);
2876dc364f4cSBenoît Canet 
2877dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2878dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
2879dc364f4cSBenoît Canet             return bs;
2880dc364f4cSBenoît Canet         }
2881dc364f4cSBenoît Canet     }
2882dc364f4cSBenoît Canet     return NULL;
2883dc364f4cSBenoît Canet }
2884dc364f4cSBenoît Canet 
2885c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
2886d5a8ee60SAlberto Garcia BlockDeviceInfoList *bdrv_named_nodes_list(Error **errp)
2887c13163fbSBenoît Canet {
2888c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
2889c13163fbSBenoît Canet     BlockDriverState *bs;
2890c13163fbSBenoît Canet 
2891c13163fbSBenoît Canet     list = NULL;
2892c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
2893d5a8ee60SAlberto Garcia         BlockDeviceInfo *info = bdrv_block_device_info(bs, errp);
2894d5a8ee60SAlberto Garcia         if (!info) {
2895d5a8ee60SAlberto Garcia             qapi_free_BlockDeviceInfoList(list);
2896d5a8ee60SAlberto Garcia             return NULL;
2897d5a8ee60SAlberto Garcia         }
2898c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
2899d5a8ee60SAlberto Garcia         entry->value = info;
2900c13163fbSBenoît Canet         entry->next = list;
2901c13163fbSBenoît Canet         list = entry;
2902c13163fbSBenoît Canet     }
2903c13163fbSBenoît Canet 
2904c13163fbSBenoît Canet     return list;
2905c13163fbSBenoît Canet }
2906c13163fbSBenoît Canet 
290712d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
290812d3ba82SBenoît Canet                                  const char *node_name,
290912d3ba82SBenoît Canet                                  Error **errp)
291012d3ba82SBenoît Canet {
29117f06d47eSMarkus Armbruster     BlockBackend *blk;
29127f06d47eSMarkus Armbruster     BlockDriverState *bs;
291312d3ba82SBenoît Canet 
291412d3ba82SBenoît Canet     if (device) {
29157f06d47eSMarkus Armbruster         blk = blk_by_name(device);
291612d3ba82SBenoît Canet 
29177f06d47eSMarkus Armbruster         if (blk) {
29189f4ed6fbSAlberto Garcia             bs = blk_bs(blk);
29199f4ed6fbSAlberto Garcia             if (!bs) {
29205433c24fSMax Reitz                 error_setg(errp, "Device '%s' has no medium", device);
29215433c24fSMax Reitz             }
29225433c24fSMax Reitz 
29239f4ed6fbSAlberto Garcia             return bs;
292412d3ba82SBenoît Canet         }
2925dd67fa50SBenoît Canet     }
292612d3ba82SBenoît Canet 
2927dd67fa50SBenoît Canet     if (node_name) {
292812d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
292912d3ba82SBenoît Canet 
2930dd67fa50SBenoît Canet         if (bs) {
2931dd67fa50SBenoît Canet             return bs;
2932dd67fa50SBenoît Canet         }
293312d3ba82SBenoît Canet     }
293412d3ba82SBenoît Canet 
2935dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
2936dd67fa50SBenoît Canet                      device ? device : "",
2937dd67fa50SBenoît Canet                      node_name ? node_name : "");
2938dd67fa50SBenoît Canet     return NULL;
293912d3ba82SBenoît Canet }
294012d3ba82SBenoît Canet 
29415a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
29425a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
29435a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
29445a6684d2SJeff Cody {
29455a6684d2SJeff Cody     while (top && top != base) {
2946760e0063SKevin Wolf         top = backing_bs(top);
29475a6684d2SJeff Cody     }
29485a6684d2SJeff Cody 
29495a6684d2SJeff Cody     return top != NULL;
29505a6684d2SJeff Cody }
29515a6684d2SJeff Cody 
295204df765aSFam Zheng BlockDriverState *bdrv_next_node(BlockDriverState *bs)
295304df765aSFam Zheng {
295404df765aSFam Zheng     if (!bs) {
295504df765aSFam Zheng         return QTAILQ_FIRST(&graph_bdrv_states);
295604df765aSFam Zheng     }
295704df765aSFam Zheng     return QTAILQ_NEXT(bs, node_list);
295804df765aSFam Zheng }
295904df765aSFam Zheng 
296026260580SMax Reitz /* Iterates over all top-level BlockDriverStates, i.e. BDSs that are owned by
296126260580SMax Reitz  * the monitor or attached to a BlockBackend */
29622f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
29632f399b0aSMarkus Armbruster {
296426260580SMax Reitz     if (!bs || bs->blk) {
296526260580SMax Reitz         bs = blk_next_root_bs(bs);
296626260580SMax Reitz         if (bs) {
296726260580SMax Reitz             return bs;
29682f399b0aSMarkus Armbruster         }
296926260580SMax Reitz     }
297026260580SMax Reitz 
297126260580SMax Reitz     /* Ignore all BDSs that are attached to a BlockBackend here; they have been
297226260580SMax Reitz      * handled by the above block already */
297326260580SMax Reitz     do {
297426260580SMax Reitz         bs = bdrv_next_monitor_owned(bs);
297526260580SMax Reitz     } while (bs && bs->blk);
297626260580SMax Reitz     return bs;
29772f399b0aSMarkus Armbruster }
29782f399b0aSMarkus Armbruster 
297920a9e77dSFam Zheng const char *bdrv_get_node_name(const BlockDriverState *bs)
298020a9e77dSFam Zheng {
298120a9e77dSFam Zheng     return bs->node_name;
298220a9e77dSFam Zheng }
298320a9e77dSFam Zheng 
29847f06d47eSMarkus Armbruster /* TODO check what callers really want: bs->node_name or blk_name() */
2985bfb197e0SMarkus Armbruster const char *bdrv_get_device_name(const BlockDriverState *bs)
2986ea2384d3Sbellard {
2987bfb197e0SMarkus Armbruster     return bs->blk ? blk_name(bs->blk) : "";
2988ea2384d3Sbellard }
2989ea2384d3Sbellard 
29909b2aa84fSAlberto Garcia /* This can be used to identify nodes that might not have a device
29919b2aa84fSAlberto Garcia  * name associated. Since node and device names live in the same
29929b2aa84fSAlberto Garcia  * namespace, the result is unambiguous. The exception is if both are
29939b2aa84fSAlberto Garcia  * absent, then this returns an empty (non-null) string. */
29949b2aa84fSAlberto Garcia const char *bdrv_get_device_or_node_name(const BlockDriverState *bs)
29959b2aa84fSAlberto Garcia {
29969b2aa84fSAlberto Garcia     return bs->blk ? blk_name(bs->blk) : bs->node_name;
29979b2aa84fSAlberto Garcia }
29989b2aa84fSAlberto Garcia 
2999c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3000c8433287SMarkus Armbruster {
3001c8433287SMarkus Armbruster     return bs->open_flags;
3002c8433287SMarkus Armbruster }
3003c8433287SMarkus Armbruster 
30043ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
30053ac21627SPeter Lieven {
30063ac21627SPeter Lieven     return 1;
30073ac21627SPeter Lieven }
30083ac21627SPeter Lieven 
3009f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3010f2feebbdSKevin Wolf {
3011f2feebbdSKevin Wolf     assert(bs->drv);
3012f2feebbdSKevin Wolf 
301311212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
301411212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
3015760e0063SKevin Wolf     if (bs->backing) {
301611212d8fSPaolo Bonzini         return 0;
301711212d8fSPaolo Bonzini     }
3018336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3019336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3020f2feebbdSKevin Wolf     }
3021f2feebbdSKevin Wolf 
30223ac21627SPeter Lieven     /* safe default */
30233ac21627SPeter Lieven     return 0;
3024f2feebbdSKevin Wolf }
3025f2feebbdSKevin Wolf 
30264ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
30274ce78691SPeter Lieven {
30284ce78691SPeter Lieven     BlockDriverInfo bdi;
30294ce78691SPeter Lieven 
3030760e0063SKevin Wolf     if (bs->backing) {
30314ce78691SPeter Lieven         return false;
30324ce78691SPeter Lieven     }
30334ce78691SPeter Lieven 
30344ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30354ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
30364ce78691SPeter Lieven     }
30374ce78691SPeter Lieven 
30384ce78691SPeter Lieven     return false;
30394ce78691SPeter Lieven }
30404ce78691SPeter Lieven 
30414ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
30424ce78691SPeter Lieven {
30434ce78691SPeter Lieven     BlockDriverInfo bdi;
30444ce78691SPeter Lieven 
3045760e0063SKevin Wolf     if (bs->backing || !(bs->open_flags & BDRV_O_UNMAP)) {
30464ce78691SPeter Lieven         return false;
30474ce78691SPeter Lieven     }
30484ce78691SPeter Lieven 
30494ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
30504ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
30514ce78691SPeter Lieven     }
30524ce78691SPeter Lieven 
30534ce78691SPeter Lieven     return false;
30544ce78691SPeter Lieven }
30554ce78691SPeter Lieven 
3056045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
3057045df330Saliguori {
3058760e0063SKevin Wolf     if (bs->backing && bs->backing->bs->encrypted)
3059045df330Saliguori         return bs->backing_file;
3060045df330Saliguori     else if (bs->encrypted)
3061045df330Saliguori         return bs->filename;
3062045df330Saliguori     else
3063045df330Saliguori         return NULL;
3064045df330Saliguori }
3065045df330Saliguori 
306683f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
306783f64091Sbellard                                char *filename, int filename_size)
306883f64091Sbellard {
306983f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
307083f64091Sbellard }
307183f64091Sbellard 
3072faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
3073faea38e7Sbellard {
3074faea38e7Sbellard     BlockDriver *drv = bs->drv;
3075faea38e7Sbellard     if (!drv)
307619cb3738Sbellard         return -ENOMEDIUM;
3077faea38e7Sbellard     if (!drv->bdrv_get_info)
3078faea38e7Sbellard         return -ENOTSUP;
3079faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
3080faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
3081faea38e7Sbellard }
3082faea38e7Sbellard 
3083eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
3084eae041feSMax Reitz {
3085eae041feSMax Reitz     BlockDriver *drv = bs->drv;
3086eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
3087eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
3088eae041feSMax Reitz     }
3089eae041feSMax Reitz     return NULL;
3090eae041feSMax Reitz }
3091eae041feSMax Reitz 
3092a31939e6SEric Blake void bdrv_debug_event(BlockDriverState *bs, BlkdebugEvent event)
30938b9b0cc2SKevin Wolf {
3094bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
30958b9b0cc2SKevin Wolf         return;
30968b9b0cc2SKevin Wolf     }
30978b9b0cc2SKevin Wolf 
3098bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
309941c695c7SKevin Wolf }
31008b9b0cc2SKevin Wolf 
310141c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
310241c695c7SKevin Wolf                           const char *tag)
310341c695c7SKevin Wolf {
310441c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
31059a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
310641c695c7SKevin Wolf     }
310741c695c7SKevin Wolf 
310841c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
310941c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
311041c695c7SKevin Wolf     }
311141c695c7SKevin Wolf 
311241c695c7SKevin Wolf     return -ENOTSUP;
311341c695c7SKevin Wolf }
311441c695c7SKevin Wolf 
31154cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
31164cc70e93SFam Zheng {
31174cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
31189a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
31194cc70e93SFam Zheng     }
31204cc70e93SFam Zheng 
31214cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
31224cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
31234cc70e93SFam Zheng     }
31244cc70e93SFam Zheng 
31254cc70e93SFam Zheng     return -ENOTSUP;
31264cc70e93SFam Zheng }
31274cc70e93SFam Zheng 
312841c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
312941c695c7SKevin Wolf {
3130938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
31319a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
313241c695c7SKevin Wolf     }
313341c695c7SKevin Wolf 
313441c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
313541c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
313641c695c7SKevin Wolf     }
313741c695c7SKevin Wolf 
313841c695c7SKevin Wolf     return -ENOTSUP;
313941c695c7SKevin Wolf }
314041c695c7SKevin Wolf 
314141c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
314241c695c7SKevin Wolf {
314341c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
31449a4f4c31SKevin Wolf         bs = bs->file ? bs->file->bs : NULL;
314541c695c7SKevin Wolf     }
314641c695c7SKevin Wolf 
314741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
314841c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
314941c695c7SKevin Wolf     }
315041c695c7SKevin Wolf 
315141c695c7SKevin Wolf     return false;
31528b9b0cc2SKevin Wolf }
31538b9b0cc2SKevin Wolf 
3154199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
3155199630b6SBlue Swirl {
3156199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
3157199630b6SBlue Swirl }
3158199630b6SBlue Swirl 
3159b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
3160b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
3161b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
3162b1b1d783SJeff Cody  * the CWD rather than the chain. */
3163e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
3164e8a6bb9cSMarcelo Tosatti         const char *backing_file)
3165e8a6bb9cSMarcelo Tosatti {
3166b1b1d783SJeff Cody     char *filename_full = NULL;
3167b1b1d783SJeff Cody     char *backing_file_full = NULL;
3168b1b1d783SJeff Cody     char *filename_tmp = NULL;
3169b1b1d783SJeff Cody     int is_protocol = 0;
3170b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
3171b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
3172b1b1d783SJeff Cody 
3173b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
3174e8a6bb9cSMarcelo Tosatti         return NULL;
3175e8a6bb9cSMarcelo Tosatti     }
3176e8a6bb9cSMarcelo Tosatti 
3177b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
3178b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
3179b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
3180b1b1d783SJeff Cody 
3181b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
3182b1b1d783SJeff Cody 
3183760e0063SKevin Wolf     for (curr_bs = bs; curr_bs->backing; curr_bs = curr_bs->backing->bs) {
3184b1b1d783SJeff Cody 
3185b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
3186b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
3187b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
3188b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
3189760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3190b1b1d783SJeff Cody                 break;
3191b1b1d783SJeff Cody             }
3192e8a6bb9cSMarcelo Tosatti         } else {
3193b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
3194b1b1d783SJeff Cody              * image's filename path */
3195b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3196b1b1d783SJeff Cody                          backing_file);
3197b1b1d783SJeff Cody 
3198b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
3199b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
3200b1b1d783SJeff Cody                 continue;
3201b1b1d783SJeff Cody             }
3202b1b1d783SJeff Cody 
3203b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
3204b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
3205b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
3206b1b1d783SJeff Cody                          curr_bs->backing_file);
3207b1b1d783SJeff Cody 
3208b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
3209b1b1d783SJeff Cody                 continue;
3210b1b1d783SJeff Cody             }
3211b1b1d783SJeff Cody 
3212b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
3213760e0063SKevin Wolf                 retval = curr_bs->backing->bs;
3214b1b1d783SJeff Cody                 break;
3215b1b1d783SJeff Cody             }
3216e8a6bb9cSMarcelo Tosatti         }
3217e8a6bb9cSMarcelo Tosatti     }
3218e8a6bb9cSMarcelo Tosatti 
3219b1b1d783SJeff Cody     g_free(filename_full);
3220b1b1d783SJeff Cody     g_free(backing_file_full);
3221b1b1d783SJeff Cody     g_free(filename_tmp);
3222b1b1d783SJeff Cody     return retval;
3223e8a6bb9cSMarcelo Tosatti }
3224e8a6bb9cSMarcelo Tosatti 
3225f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
3226f198fd1cSBenoît Canet {
3227f198fd1cSBenoît Canet     if (!bs->drv) {
3228f198fd1cSBenoît Canet         return 0;
3229f198fd1cSBenoît Canet     }
3230f198fd1cSBenoît Canet 
3231760e0063SKevin Wolf     if (!bs->backing) {
3232f198fd1cSBenoît Canet         return 0;
3233f198fd1cSBenoît Canet     }
3234f198fd1cSBenoît Canet 
3235760e0063SKevin Wolf     return 1 + bdrv_get_backing_file_depth(bs->backing->bs);
3236f198fd1cSBenoît Canet }
3237f198fd1cSBenoît Canet 
3238ea2384d3Sbellard void bdrv_init(void)
3239ea2384d3Sbellard {
32405efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
3241ea2384d3Sbellard }
3242ce1a14dcSpbrook 
3243eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
3244eb852011SMarkus Armbruster {
3245eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
3246eb852011SMarkus Armbruster     bdrv_init();
3247eb852011SMarkus Armbruster }
3248eb852011SMarkus Armbruster 
32495a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
32500f15423cSAnthony Liguori {
32515a8a30dbSKevin Wolf     Error *local_err = NULL;
32525a8a30dbSKevin Wolf     int ret;
32535a8a30dbSKevin Wolf 
32543456a8d1SKevin Wolf     if (!bs->drv)  {
32553456a8d1SKevin Wolf         return;
32560f15423cSAnthony Liguori     }
32573456a8d1SKevin Wolf 
325804c01a5cSKevin Wolf     if (!(bs->open_flags & BDRV_O_INACTIVE)) {
32597ea2d269SAlexey Kardashevskiy         return;
32607ea2d269SAlexey Kardashevskiy     }
326104c01a5cSKevin Wolf     bs->open_flags &= ~BDRV_O_INACTIVE;
32627ea2d269SAlexey Kardashevskiy 
32633456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
32645a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
32653456a8d1SKevin Wolf     } else if (bs->file) {
32669a4f4c31SKevin Wolf         bdrv_invalidate_cache(bs->file->bs, &local_err);
32675a8a30dbSKevin Wolf     }
32685a8a30dbSKevin Wolf     if (local_err) {
326904c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32705a8a30dbSKevin Wolf         error_propagate(errp, local_err);
32715a8a30dbSKevin Wolf         return;
32723456a8d1SKevin Wolf     }
32733456a8d1SKevin Wolf 
32745a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
32755a8a30dbSKevin Wolf     if (ret < 0) {
327604c01a5cSKevin Wolf         bs->open_flags |= BDRV_O_INACTIVE;
32775a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
32785a8a30dbSKevin Wolf         return;
32795a8a30dbSKevin Wolf     }
32800f15423cSAnthony Liguori }
32810f15423cSAnthony Liguori 
32825a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
32830f15423cSAnthony Liguori {
328479720af6SMax Reitz     BlockDriverState *bs = NULL;
32855a8a30dbSKevin Wolf     Error *local_err = NULL;
32860f15423cSAnthony Liguori 
328779720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3288ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3289ed78cda3SStefan Hajnoczi 
3290ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
32915a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
3292ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
32935a8a30dbSKevin Wolf         if (local_err) {
32945a8a30dbSKevin Wolf             error_propagate(errp, local_err);
32955a8a30dbSKevin Wolf             return;
32965a8a30dbSKevin Wolf         }
32970f15423cSAnthony Liguori     }
32980f15423cSAnthony Liguori }
32990f15423cSAnthony Liguori 
330076b1c7feSKevin Wolf static int bdrv_inactivate(BlockDriverState *bs)
330176b1c7feSKevin Wolf {
330276b1c7feSKevin Wolf     int ret;
330376b1c7feSKevin Wolf 
330476b1c7feSKevin Wolf     if (bs->drv->bdrv_inactivate) {
330576b1c7feSKevin Wolf         ret = bs->drv->bdrv_inactivate(bs);
330676b1c7feSKevin Wolf         if (ret < 0) {
330776b1c7feSKevin Wolf             return ret;
330876b1c7feSKevin Wolf         }
330976b1c7feSKevin Wolf     }
331076b1c7feSKevin Wolf 
331176b1c7feSKevin Wolf     bs->open_flags |= BDRV_O_INACTIVE;
331276b1c7feSKevin Wolf     return 0;
331376b1c7feSKevin Wolf }
331476b1c7feSKevin Wolf 
331576b1c7feSKevin Wolf int bdrv_inactivate_all(void)
331676b1c7feSKevin Wolf {
331779720af6SMax Reitz     BlockDriverState *bs = NULL;
331876b1c7feSKevin Wolf     int ret;
331976b1c7feSKevin Wolf 
332079720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
332176b1c7feSKevin Wolf         AioContext *aio_context = bdrv_get_aio_context(bs);
332276b1c7feSKevin Wolf 
332376b1c7feSKevin Wolf         aio_context_acquire(aio_context);
332476b1c7feSKevin Wolf         ret = bdrv_inactivate(bs);
332576b1c7feSKevin Wolf         aio_context_release(aio_context);
332676b1c7feSKevin Wolf         if (ret < 0) {
332776b1c7feSKevin Wolf             return ret;
332876b1c7feSKevin Wolf         }
332976b1c7feSKevin Wolf     }
333076b1c7feSKevin Wolf 
333176b1c7feSKevin Wolf     return 0;
333276b1c7feSKevin Wolf }
333376b1c7feSKevin Wolf 
3334f9f05dc5SKevin Wolf /**************************************************************/
333519cb3738Sbellard /* removable device support */
333619cb3738Sbellard 
333719cb3738Sbellard /**
333819cb3738Sbellard  * Return TRUE if the media is present
333919cb3738Sbellard  */
3340e031f750SMax Reitz bool bdrv_is_inserted(BlockDriverState *bs)
334119cb3738Sbellard {
334219cb3738Sbellard     BlockDriver *drv = bs->drv;
334328d7a789SMax Reitz     BdrvChild *child;
3344a1aff5bfSMarkus Armbruster 
3345e031f750SMax Reitz     if (!drv) {
3346e031f750SMax Reitz         return false;
3347e031f750SMax Reitz     }
334828d7a789SMax Reitz     if (drv->bdrv_is_inserted) {
3349a1aff5bfSMarkus Armbruster         return drv->bdrv_is_inserted(bs);
335019cb3738Sbellard     }
335128d7a789SMax Reitz     QLIST_FOREACH(child, &bs->children, next) {
335228d7a789SMax Reitz         if (!bdrv_is_inserted(child->bs)) {
335328d7a789SMax Reitz             return false;
335428d7a789SMax Reitz         }
335528d7a789SMax Reitz     }
335628d7a789SMax Reitz     return true;
335728d7a789SMax Reitz }
335819cb3738Sbellard 
335919cb3738Sbellard /**
33608e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
33618e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
336219cb3738Sbellard  */
336319cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
336419cb3738Sbellard {
336519cb3738Sbellard     BlockDriver *drv = bs->drv;
336619cb3738Sbellard 
33678e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
33688e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
33698e49ca46SMarkus Armbruster     }
33708e49ca46SMarkus Armbruster     return -ENOTSUP;
337119cb3738Sbellard }
337219cb3738Sbellard 
337319cb3738Sbellard /**
337419cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
337519cb3738Sbellard  */
3376f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
337719cb3738Sbellard {
337819cb3738Sbellard     BlockDriver *drv = bs->drv;
3379bfb197e0SMarkus Armbruster     const char *device_name;
338019cb3738Sbellard 
3381822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
3382822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
338319cb3738Sbellard     }
33846f382ed2SLuiz Capitulino 
3385bfb197e0SMarkus Armbruster     device_name = bdrv_get_device_name(bs);
3386bfb197e0SMarkus Armbruster     if (device_name[0] != '\0') {
3387bfb197e0SMarkus Armbruster         qapi_event_send_device_tray_moved(device_name,
3388a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
33896f382ed2SLuiz Capitulino     }
339019cb3738Sbellard }
339119cb3738Sbellard 
339219cb3738Sbellard /**
339319cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
339419cb3738Sbellard  * to eject it manually).
339519cb3738Sbellard  */
3396025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
339719cb3738Sbellard {
339819cb3738Sbellard     BlockDriver *drv = bs->drv;
339919cb3738Sbellard 
3400025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
3401b8c6d095SStefan Hajnoczi 
3402025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
3403025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
340419cb3738Sbellard     }
340519cb3738Sbellard }
3406985a03b0Sths 
34079fcb0251SFam Zheng /* Get a reference to bs */
34089fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
34099fcb0251SFam Zheng {
34109fcb0251SFam Zheng     bs->refcnt++;
34119fcb0251SFam Zheng }
34129fcb0251SFam Zheng 
34139fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
34149fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
34159fcb0251SFam Zheng  * deleted. */
34169fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
34179fcb0251SFam Zheng {
34189a4d5ca6SJeff Cody     if (!bs) {
34199a4d5ca6SJeff Cody         return;
34209a4d5ca6SJeff Cody     }
34219fcb0251SFam Zheng     assert(bs->refcnt > 0);
34229fcb0251SFam Zheng     if (--bs->refcnt == 0) {
34239fcb0251SFam Zheng         bdrv_delete(bs);
34249fcb0251SFam Zheng     }
34259fcb0251SFam Zheng }
34269fcb0251SFam Zheng 
3427fbe40ff7SFam Zheng struct BdrvOpBlocker {
3428fbe40ff7SFam Zheng     Error *reason;
3429fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
3430fbe40ff7SFam Zheng };
3431fbe40ff7SFam Zheng 
3432fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
3433fbe40ff7SFam Zheng {
3434fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3435fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3436fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
3437fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
3438fbe40ff7SFam Zheng         if (errp) {
3439e43bfd9cSMarkus Armbruster             *errp = error_copy(blocker->reason);
3440e43bfd9cSMarkus Armbruster             error_prepend(errp, "Node '%s' is busy: ",
3441e43bfd9cSMarkus Armbruster                           bdrv_get_device_or_node_name(bs));
3442fbe40ff7SFam Zheng         }
3443fbe40ff7SFam Zheng         return true;
3444fbe40ff7SFam Zheng     }
3445fbe40ff7SFam Zheng     return false;
3446fbe40ff7SFam Zheng }
3447fbe40ff7SFam Zheng 
3448fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
3449fbe40ff7SFam Zheng {
3450fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
3451fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3452fbe40ff7SFam Zheng 
34535839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
3454fbe40ff7SFam Zheng     blocker->reason = reason;
3455fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
3456fbe40ff7SFam Zheng }
3457fbe40ff7SFam Zheng 
3458fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
3459fbe40ff7SFam Zheng {
3460fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
3461fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
3462fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
3463fbe40ff7SFam Zheng         if (blocker->reason == reason) {
3464fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
3465fbe40ff7SFam Zheng             g_free(blocker);
3466fbe40ff7SFam Zheng         }
3467fbe40ff7SFam Zheng     }
3468fbe40ff7SFam Zheng }
3469fbe40ff7SFam Zheng 
3470fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
3471fbe40ff7SFam Zheng {
3472fbe40ff7SFam Zheng     int i;
3473fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3474fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
3475fbe40ff7SFam Zheng     }
3476fbe40ff7SFam Zheng }
3477fbe40ff7SFam Zheng 
3478fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
3479fbe40ff7SFam Zheng {
3480fbe40ff7SFam Zheng     int i;
3481fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3482fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
3483fbe40ff7SFam Zheng     }
3484fbe40ff7SFam Zheng }
3485fbe40ff7SFam Zheng 
3486fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
3487fbe40ff7SFam Zheng {
3488fbe40ff7SFam Zheng     int i;
3489fbe40ff7SFam Zheng 
3490fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
3491fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
3492fbe40ff7SFam Zheng             return false;
3493fbe40ff7SFam Zheng         }
3494fbe40ff7SFam Zheng     }
3495fbe40ff7SFam Zheng     return true;
3496fbe40ff7SFam Zheng }
3497fbe40ff7SFam Zheng 
3498d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
3499f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
3500f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
3501f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
3502f88e1a42SJes Sorensen {
350383d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
350483d0521aSChunyan Liu     QemuOpts *opts = NULL;
350583d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
350683d0521aSChunyan Liu     int64_t size;
3507f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
3508cc84d90fSMax Reitz     Error *local_err = NULL;
3509f88e1a42SJes Sorensen     int ret = 0;
3510f88e1a42SJes Sorensen 
3511f88e1a42SJes Sorensen     /* Find driver and parse its options */
3512f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
3513f88e1a42SJes Sorensen     if (!drv) {
351471c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
3515d92ada22SLuiz Capitulino         return;
3516f88e1a42SJes Sorensen     }
3517f88e1a42SJes Sorensen 
3518b65a5e12SMax Reitz     proto_drv = bdrv_find_protocol(filename, true, errp);
3519f88e1a42SJes Sorensen     if (!proto_drv) {
3520d92ada22SLuiz Capitulino         return;
3521f88e1a42SJes Sorensen     }
3522f88e1a42SJes Sorensen 
3523c6149724SMax Reitz     if (!drv->create_opts) {
3524c6149724SMax Reitz         error_setg(errp, "Format driver '%s' does not support image creation",
3525c6149724SMax Reitz                    drv->format_name);
3526c6149724SMax Reitz         return;
3527c6149724SMax Reitz     }
3528c6149724SMax Reitz 
3529c6149724SMax Reitz     if (!proto_drv->create_opts) {
3530c6149724SMax Reitz         error_setg(errp, "Protocol driver '%s' does not support image creation",
3531c6149724SMax Reitz                    proto_drv->format_name);
3532c6149724SMax Reitz         return;
3533c6149724SMax Reitz     }
3534c6149724SMax Reitz 
3535c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
3536c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
3537f88e1a42SJes Sorensen 
3538f88e1a42SJes Sorensen     /* Create parameter list with default values */
353983d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
354039101f25SMarkus Armbruster     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size, &error_abort);
3541f88e1a42SJes Sorensen 
3542f88e1a42SJes Sorensen     /* Parse -o options */
3543f88e1a42SJes Sorensen     if (options) {
3544dc523cd3SMarkus Armbruster         qemu_opts_do_parse(opts, options, NULL, &local_err);
3545dc523cd3SMarkus Armbruster         if (local_err) {
3546dc523cd3SMarkus Armbruster             error_report_err(local_err);
3547dc523cd3SMarkus Armbruster             local_err = NULL;
354883d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
3549f88e1a42SJes Sorensen             goto out;
3550f88e1a42SJes Sorensen         }
3551f88e1a42SJes Sorensen     }
3552f88e1a42SJes Sorensen 
3553f88e1a42SJes Sorensen     if (base_filename) {
3554f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename, &local_err);
35556be4194bSMarkus Armbruster         if (local_err) {
355671c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
355771c79813SLuiz Capitulino                        fmt);
3558f88e1a42SJes Sorensen             goto out;
3559f88e1a42SJes Sorensen         }
3560f88e1a42SJes Sorensen     }
3561f88e1a42SJes Sorensen 
3562f88e1a42SJes Sorensen     if (base_fmt) {
3563f43e47dbSMarkus Armbruster         qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt, &local_err);
35646be4194bSMarkus Armbruster         if (local_err) {
356571c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
356671c79813SLuiz Capitulino                              "format '%s'", fmt);
3567f88e1a42SJes Sorensen             goto out;
3568f88e1a42SJes Sorensen         }
3569f88e1a42SJes Sorensen     }
3570f88e1a42SJes Sorensen 
357183d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
357283d0521aSChunyan Liu     if (backing_file) {
357383d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
357471c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
357571c79813SLuiz Capitulino                              "same filename as the backing file");
3576792da93aSJes Sorensen             goto out;
3577792da93aSJes Sorensen         }
3578792da93aSJes Sorensen     }
3579792da93aSJes Sorensen 
358083d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
3581f88e1a42SJes Sorensen 
3582f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
3583f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
358483d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
358583d0521aSChunyan Liu     if (size == -1) {
358683d0521aSChunyan Liu         if (backing_file) {
358766f6b814SMax Reitz             BlockDriverState *bs;
358829168018SMax Reitz             char *full_backing = g_new0(char, PATH_MAX);
358952bf1e72SMarkus Armbruster             int64_t size;
359063090dacSPaolo Bonzini             int back_flags;
3591e6641719SMax Reitz             QDict *backing_options = NULL;
359263090dacSPaolo Bonzini 
359329168018SMax Reitz             bdrv_get_full_backing_filename_from_filename(filename, backing_file,
359429168018SMax Reitz                                                          full_backing, PATH_MAX,
359529168018SMax Reitz                                                          &local_err);
359629168018SMax Reitz             if (local_err) {
359729168018SMax Reitz                 g_free(full_backing);
359829168018SMax Reitz                 goto out;
359929168018SMax Reitz             }
360029168018SMax Reitz 
360163090dacSPaolo Bonzini             /* backing files always opened read-only */
360263090dacSPaolo Bonzini             back_flags =
360363090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
3604f88e1a42SJes Sorensen 
3605e6641719SMax Reitz             if (backing_fmt) {
3606e6641719SMax Reitz                 backing_options = qdict_new();
3607e6641719SMax Reitz                 qdict_put(backing_options, "driver",
3608e6641719SMax Reitz                           qstring_from_str(backing_fmt));
3609e6641719SMax Reitz             }
3610e6641719SMax Reitz 
3611f67503e5SMax Reitz             bs = NULL;
3612e6641719SMax Reitz             ret = bdrv_open(&bs, full_backing, NULL, backing_options,
36136ebf9aa2SMax Reitz                             back_flags, &local_err);
361429168018SMax Reitz             g_free(full_backing);
3615f88e1a42SJes Sorensen             if (ret < 0) {
3616f88e1a42SJes Sorensen                 goto out;
3617f88e1a42SJes Sorensen             }
361852bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
361952bf1e72SMarkus Armbruster             if (size < 0) {
362052bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
362152bf1e72SMarkus Armbruster                                  backing_file);
362252bf1e72SMarkus Armbruster                 bdrv_unref(bs);
362352bf1e72SMarkus Armbruster                 goto out;
362452bf1e72SMarkus Armbruster             }
3625f88e1a42SJes Sorensen 
362639101f25SMarkus Armbruster             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size, &error_abort);
362766f6b814SMax Reitz 
362866f6b814SMax Reitz             bdrv_unref(bs);
3629f88e1a42SJes Sorensen         } else {
363071c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
3631f88e1a42SJes Sorensen             goto out;
3632f88e1a42SJes Sorensen         }
3633f88e1a42SJes Sorensen     }
3634f88e1a42SJes Sorensen 
3635f382d43aSMiroslav Rezanina     if (!quiet) {
3636f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
363743c5d8f8SFam Zheng         qemu_opts_print(opts, " ");
3638f88e1a42SJes Sorensen         puts("");
3639f382d43aSMiroslav Rezanina     }
364083d0521aSChunyan Liu 
3641c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
364283d0521aSChunyan Liu 
3643cc84d90fSMax Reitz     if (ret == -EFBIG) {
3644cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
3645cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
3646cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
3647f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
364883d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
3649f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
3650f3f4d2c0SKevin Wolf         }
3651cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
3652cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
3653cc84d90fSMax Reitz         error_free(local_err);
3654cc84d90fSMax Reitz         local_err = NULL;
3655f88e1a42SJes Sorensen     }
3656f88e1a42SJes Sorensen 
3657f88e1a42SJes Sorensen out:
365883d0521aSChunyan Liu     qemu_opts_del(opts);
365983d0521aSChunyan Liu     qemu_opts_free(create_opts);
366084d18f06SMarkus Armbruster     if (local_err) {
3661cc84d90fSMax Reitz         error_propagate(errp, local_err);
3662cc84d90fSMax Reitz     }
3663f88e1a42SJes Sorensen }
366485d126f3SStefan Hajnoczi 
366585d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
366685d126f3SStefan Hajnoczi {
3667dcd04228SStefan Hajnoczi     return bs->aio_context;
3668dcd04228SStefan Hajnoczi }
3669dcd04228SStefan Hajnoczi 
3670dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
3671dcd04228SStefan Hajnoczi {
367233384421SMax Reitz     BdrvAioNotifier *baf;
367333384421SMax Reitz 
3674dcd04228SStefan Hajnoczi     if (!bs->drv) {
3675dcd04228SStefan Hajnoczi         return;
3676dcd04228SStefan Hajnoczi     }
3677dcd04228SStefan Hajnoczi 
367833384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
367933384421SMax Reitz         baf->detach_aio_context(baf->opaque);
368033384421SMax Reitz     }
368133384421SMax Reitz 
3682a0d64a61SAlberto Garcia     if (bs->throttle_state) {
36830e5b0a2dSBenoît Canet         throttle_timers_detach_aio_context(&bs->throttle_timers);
368413af91ebSStefan Hajnoczi     }
3685dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
3686dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
3687dcd04228SStefan Hajnoczi     }
3688dcd04228SStefan Hajnoczi     if (bs->file) {
36899a4f4c31SKevin Wolf         bdrv_detach_aio_context(bs->file->bs);
3690dcd04228SStefan Hajnoczi     }
3691760e0063SKevin Wolf     if (bs->backing) {
3692760e0063SKevin Wolf         bdrv_detach_aio_context(bs->backing->bs);
3693dcd04228SStefan Hajnoczi     }
3694dcd04228SStefan Hajnoczi 
3695dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
3696dcd04228SStefan Hajnoczi }
3697dcd04228SStefan Hajnoczi 
3698dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
3699dcd04228SStefan Hajnoczi                              AioContext *new_context)
3700dcd04228SStefan Hajnoczi {
370133384421SMax Reitz     BdrvAioNotifier *ban;
370233384421SMax Reitz 
3703dcd04228SStefan Hajnoczi     if (!bs->drv) {
3704dcd04228SStefan Hajnoczi         return;
3705dcd04228SStefan Hajnoczi     }
3706dcd04228SStefan Hajnoczi 
3707dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
3708dcd04228SStefan Hajnoczi 
3709760e0063SKevin Wolf     if (bs->backing) {
3710760e0063SKevin Wolf         bdrv_attach_aio_context(bs->backing->bs, new_context);
3711dcd04228SStefan Hajnoczi     }
3712dcd04228SStefan Hajnoczi     if (bs->file) {
37139a4f4c31SKevin Wolf         bdrv_attach_aio_context(bs->file->bs, new_context);
3714dcd04228SStefan Hajnoczi     }
3715dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
3716dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
3717dcd04228SStefan Hajnoczi     }
3718a0d64a61SAlberto Garcia     if (bs->throttle_state) {
37190e5b0a2dSBenoît Canet         throttle_timers_attach_aio_context(&bs->throttle_timers, new_context);
372013af91ebSStefan Hajnoczi     }
372133384421SMax Reitz 
372233384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
372333384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
372433384421SMax Reitz     }
3725dcd04228SStefan Hajnoczi }
3726dcd04228SStefan Hajnoczi 
3727dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
3728dcd04228SStefan Hajnoczi {
372953ec73e2SFam Zheng     bdrv_drain(bs); /* ensure there are no in-flight requests */
3730dcd04228SStefan Hajnoczi 
3731dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
3732dcd04228SStefan Hajnoczi 
3733dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
3734dcd04228SStefan Hajnoczi      * case it runs in a different thread.
3735dcd04228SStefan Hajnoczi      */
3736dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
3737dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
3738dcd04228SStefan Hajnoczi     aio_context_release(new_context);
373985d126f3SStefan Hajnoczi }
3740d616b224SStefan Hajnoczi 
374133384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
374233384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
374333384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
374433384421SMax Reitz {
374533384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
374633384421SMax Reitz     *ban = (BdrvAioNotifier){
374733384421SMax Reitz         .attached_aio_context = attached_aio_context,
374833384421SMax Reitz         .detach_aio_context   = detach_aio_context,
374933384421SMax Reitz         .opaque               = opaque
375033384421SMax Reitz     };
375133384421SMax Reitz 
375233384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
375333384421SMax Reitz }
375433384421SMax Reitz 
375533384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
375633384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
375733384421SMax Reitz                                                                    void *),
375833384421SMax Reitz                                       void (*detach_aio_context)(void *),
375933384421SMax Reitz                                       void *opaque)
376033384421SMax Reitz {
376133384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
376233384421SMax Reitz 
376333384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
376433384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
376533384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
376633384421SMax Reitz             ban->opaque               == opaque)
376733384421SMax Reitz         {
376833384421SMax Reitz             QLIST_REMOVE(ban, list);
376933384421SMax Reitz             g_free(ban);
377033384421SMax Reitz 
377133384421SMax Reitz             return;
377233384421SMax Reitz         }
377333384421SMax Reitz     }
377433384421SMax Reitz 
377533384421SMax Reitz     abort();
377633384421SMax Reitz }
377733384421SMax Reitz 
377877485434SMax Reitz int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts,
37798b13976dSMax Reitz                        BlockDriverAmendStatusCB *status_cb, void *cb_opaque)
37806f176b48SMax Reitz {
3781c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
37826f176b48SMax Reitz         return -ENOTSUP;
37836f176b48SMax Reitz     }
37848b13976dSMax Reitz     return bs->drv->bdrv_amend_options(bs, opts, status_cb, cb_opaque);
37856f176b48SMax Reitz }
3786f6186f49SBenoît Canet 
3787b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
3788b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
3789b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
3790b5042a36SBenoît Canet  * node graph.
3791212a5a8fSBenoît Canet  */
3792212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
3793212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
3794f6186f49SBenoît Canet {
3795b5042a36SBenoît Canet     /* return false if basic checks fails */
3796b5042a36SBenoît Canet     if (!bs || !bs->drv) {
3797b5042a36SBenoît Canet         return false;
3798b5042a36SBenoît Canet     }
3799b5042a36SBenoît Canet 
3800b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
3801b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
3802b5042a36SBenoît Canet      */
3803b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
3804b5042a36SBenoît Canet         return bs == candidate;
3805b5042a36SBenoît Canet     }
3806b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
3807b5042a36SBenoît Canet 
3808b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
3809b5042a36SBenoît Canet      * the node graph.
3810b5042a36SBenoît Canet      */
3811b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
3812212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
3813212a5a8fSBenoît Canet     }
3814212a5a8fSBenoît Canet 
3815b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
3816b5042a36SBenoît Canet      */
3817b5042a36SBenoît Canet     return false;
3818212a5a8fSBenoît Canet }
3819212a5a8fSBenoît Canet 
3820212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
3821212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
3822212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
3823212a5a8fSBenoît Canet  */
3824212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
3825212a5a8fSBenoît Canet {
382679720af6SMax Reitz     BlockDriverState *bs = NULL;
3827212a5a8fSBenoît Canet 
3828212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
382979720af6SMax Reitz     while ((bs = bdrv_next(bs)) != NULL) {
3830212a5a8fSBenoît Canet         bool perm;
3831212a5a8fSBenoît Canet 
3832b5042a36SBenoît Canet         /* try to recurse in this top level bs */
3833e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
3834212a5a8fSBenoît Canet 
3835212a5a8fSBenoît Canet         /* candidate is the first non filter */
3836212a5a8fSBenoît Canet         if (perm) {
3837212a5a8fSBenoît Canet             return true;
3838212a5a8fSBenoît Canet         }
3839212a5a8fSBenoît Canet     }
3840212a5a8fSBenoît Canet 
3841212a5a8fSBenoît Canet     return false;
3842f6186f49SBenoît Canet }
384309158f00SBenoît Canet 
3844e12f3784SWen Congyang BlockDriverState *check_to_replace_node(BlockDriverState *parent_bs,
3845e12f3784SWen Congyang                                         const char *node_name, Error **errp)
384609158f00SBenoît Canet {
384709158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
38485a7e7a0bSStefan Hajnoczi     AioContext *aio_context;
38495a7e7a0bSStefan Hajnoczi 
385009158f00SBenoît Canet     if (!to_replace_bs) {
385109158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
385209158f00SBenoît Canet         return NULL;
385309158f00SBenoît Canet     }
385409158f00SBenoît Canet 
38555a7e7a0bSStefan Hajnoczi     aio_context = bdrv_get_aio_context(to_replace_bs);
38565a7e7a0bSStefan Hajnoczi     aio_context_acquire(aio_context);
38575a7e7a0bSStefan Hajnoczi 
385809158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
38595a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38605a7e7a0bSStefan Hajnoczi         goto out;
386109158f00SBenoît Canet     }
386209158f00SBenoît Canet 
386309158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
386409158f00SBenoît Canet      * most non filter in order to prevent data corruption.
386509158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
386609158f00SBenoît Canet      * blocked by the backing blockers.
386709158f00SBenoît Canet      */
3868e12f3784SWen Congyang     if (!bdrv_recurse_is_first_non_filter(parent_bs, to_replace_bs)) {
386909158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
38705a7e7a0bSStefan Hajnoczi         to_replace_bs = NULL;
38715a7e7a0bSStefan Hajnoczi         goto out;
387209158f00SBenoît Canet     }
387309158f00SBenoît Canet 
38745a7e7a0bSStefan Hajnoczi out:
38755a7e7a0bSStefan Hajnoczi     aio_context_release(aio_context);
387609158f00SBenoît Canet     return to_replace_bs;
387709158f00SBenoît Canet }
3878448ad91dSMing Lei 
387991af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
388091af7014SMax Reitz {
388191af7014SMax Reitz     const QDictEntry *entry;
38829e700c1aSKevin Wolf     QemuOptDesc *desc;
3883260fecf1SKevin Wolf     BdrvChild *child;
388491af7014SMax Reitz     bool found_any = false;
3885260fecf1SKevin Wolf     const char *p;
388691af7014SMax Reitz 
388791af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
388891af7014SMax Reitz          entry = qdict_next(bs->options, entry))
388991af7014SMax Reitz     {
3890260fecf1SKevin Wolf         /* Exclude options for children */
3891260fecf1SKevin Wolf         QLIST_FOREACH(child, &bs->children, next) {
3892260fecf1SKevin Wolf             if (strstart(qdict_entry_key(entry), child->name, &p)
3893260fecf1SKevin Wolf                 && (!*p || *p == '.'))
3894260fecf1SKevin Wolf             {
3895260fecf1SKevin Wolf                 break;
3896260fecf1SKevin Wolf             }
3897260fecf1SKevin Wolf         }
3898260fecf1SKevin Wolf         if (child) {
38999e700c1aSKevin Wolf             continue;
39009e700c1aSKevin Wolf         }
39019e700c1aSKevin Wolf 
39029e700c1aSKevin Wolf         /* And exclude all non-driver-specific options */
39039e700c1aSKevin Wolf         for (desc = bdrv_runtime_opts.desc; desc->name; desc++) {
39049e700c1aSKevin Wolf             if (!strcmp(qdict_entry_key(entry), desc->name)) {
39059e700c1aSKevin Wolf                 break;
39069e700c1aSKevin Wolf             }
39079e700c1aSKevin Wolf         }
39089e700c1aSKevin Wolf         if (desc->name) {
39099e700c1aSKevin Wolf             continue;
39109e700c1aSKevin Wolf         }
39119e700c1aSKevin Wolf 
391291af7014SMax Reitz         qobject_incref(qdict_entry_value(entry));
391391af7014SMax Reitz         qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
391491af7014SMax Reitz         found_any = true;
391591af7014SMax Reitz     }
391691af7014SMax Reitz 
391791af7014SMax Reitz     return found_any;
391891af7014SMax Reitz }
391991af7014SMax Reitz 
392091af7014SMax Reitz /* Updates the following BDS fields:
392191af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
392291af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
392391af7014SMax Reitz  *                    other options; so reading and writing must return the same
392491af7014SMax Reitz  *                    results, but caching etc. may be different)
392591af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
392691af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
392791af7014SMax Reitz  *                       equalling the given one
392891af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
392991af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
393091af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
393191af7014SMax Reitz  */
393291af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
393391af7014SMax Reitz {
393491af7014SMax Reitz     BlockDriver *drv = bs->drv;
393591af7014SMax Reitz     QDict *opts;
393691af7014SMax Reitz 
393791af7014SMax Reitz     if (!drv) {
393891af7014SMax Reitz         return;
393991af7014SMax Reitz     }
394091af7014SMax Reitz 
394191af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
394291af7014SMax Reitz      * refresh that first */
394391af7014SMax Reitz     if (bs->file) {
39449a4f4c31SKevin Wolf         bdrv_refresh_filename(bs->file->bs);
394591af7014SMax Reitz     }
394691af7014SMax Reitz 
394791af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
394891af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
394991af7014SMax Reitz          * information before refreshing it */
395091af7014SMax Reitz         bs->exact_filename[0] = '\0';
395191af7014SMax Reitz         if (bs->full_open_options) {
395291af7014SMax Reitz             QDECREF(bs->full_open_options);
395391af7014SMax Reitz             bs->full_open_options = NULL;
395491af7014SMax Reitz         }
395591af7014SMax Reitz 
39564cdd01d3SKevin Wolf         opts = qdict_new();
39574cdd01d3SKevin Wolf         append_open_options(opts, bs);
39584cdd01d3SKevin Wolf         drv->bdrv_refresh_filename(bs, opts);
39594cdd01d3SKevin Wolf         QDECREF(opts);
396091af7014SMax Reitz     } else if (bs->file) {
396191af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
396291af7014SMax Reitz         bool has_open_options;
396391af7014SMax Reitz 
396491af7014SMax Reitz         bs->exact_filename[0] = '\0';
396591af7014SMax Reitz         if (bs->full_open_options) {
396691af7014SMax Reitz             QDECREF(bs->full_open_options);
396791af7014SMax Reitz             bs->full_open_options = NULL;
396891af7014SMax Reitz         }
396991af7014SMax Reitz 
397091af7014SMax Reitz         opts = qdict_new();
397191af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
397291af7014SMax Reitz 
397391af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
397491af7014SMax Reitz          * the underlying file should suffice for this one as well */
39759a4f4c31SKevin Wolf         if (bs->file->bs->exact_filename[0] && !has_open_options) {
39769a4f4c31SKevin Wolf             strcpy(bs->exact_filename, bs->file->bs->exact_filename);
397791af7014SMax Reitz         }
397891af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
397991af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
398091af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
398191af7014SMax Reitz          * contain a representation of the filename, therefore the following
398291af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
39839a4f4c31SKevin Wolf         if (bs->file->bs->full_open_options) {
398491af7014SMax Reitz             qdict_put_obj(opts, "driver",
398591af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
39869a4f4c31SKevin Wolf             QINCREF(bs->file->bs->full_open_options);
39879a4f4c31SKevin Wolf             qdict_put_obj(opts, "file",
39889a4f4c31SKevin Wolf                           QOBJECT(bs->file->bs->full_open_options));
398991af7014SMax Reitz 
399091af7014SMax Reitz             bs->full_open_options = opts;
399191af7014SMax Reitz         } else {
399291af7014SMax Reitz             QDECREF(opts);
399391af7014SMax Reitz         }
399491af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
399591af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
399691af7014SMax Reitz          * so the full options QDict should be equal to the options given
399791af7014SMax Reitz          * specifically for this block device when it was opened (plus the
399891af7014SMax Reitz          * driver specification).
399991af7014SMax Reitz          * Because those options don't change, there is no need to update
400091af7014SMax Reitz          * full_open_options when it's already set. */
400191af7014SMax Reitz 
400291af7014SMax Reitz         opts = qdict_new();
400391af7014SMax Reitz         append_open_options(opts, bs);
400491af7014SMax Reitz         qdict_put_obj(opts, "driver",
400591af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
400691af7014SMax Reitz 
400791af7014SMax Reitz         if (bs->exact_filename[0]) {
400891af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
400991af7014SMax Reitz              * require this filename to be parsed), but we have to find some
401091af7014SMax Reitz              * default solution here, so just include it. If some block driver
401191af7014SMax Reitz              * does not support pure options without any filename at all or
401291af7014SMax Reitz              * needs some special format of the options QDict, it needs to
401391af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
401491af7014SMax Reitz              */
401591af7014SMax Reitz             qdict_put_obj(opts, "filename",
401691af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
401791af7014SMax Reitz         }
401891af7014SMax Reitz 
401991af7014SMax Reitz         bs->full_open_options = opts;
402091af7014SMax Reitz     }
402191af7014SMax Reitz 
402291af7014SMax Reitz     if (bs->exact_filename[0]) {
402391af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
402491af7014SMax Reitz     } else if (bs->full_open_options) {
402591af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
402691af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
402791af7014SMax Reitz                  qstring_get_str(json));
402891af7014SMax Reitz         QDECREF(json);
402991af7014SMax Reitz     }
403091af7014SMax Reitz }
4031