xref: /openbmc/qemu/block.c (revision d224469d87140f0ab9496f752f6042606b80718b)
1fc01f7e7Sbellard /*
2fc01f7e7Sbellard  * QEMU System Emulator block driver
3fc01f7e7Sbellard  *
4fc01f7e7Sbellard  * Copyright (c) 2003 Fabrice Bellard
5fc01f7e7Sbellard  *
6fc01f7e7Sbellard  * Permission is hereby granted, free of charge, to any person obtaining a copy
7fc01f7e7Sbellard  * of this software and associated documentation files (the "Software"), to deal
8fc01f7e7Sbellard  * in the Software without restriction, including without limitation the rights
9fc01f7e7Sbellard  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10fc01f7e7Sbellard  * copies of the Software, and to permit persons to whom the Software is
11fc01f7e7Sbellard  * furnished to do so, subject to the following conditions:
12fc01f7e7Sbellard  *
13fc01f7e7Sbellard  * The above copyright notice and this permission notice shall be included in
14fc01f7e7Sbellard  * all copies or substantial portions of the Software.
15fc01f7e7Sbellard  *
16fc01f7e7Sbellard  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17fc01f7e7Sbellard  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18fc01f7e7Sbellard  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19fc01f7e7Sbellard  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20fc01f7e7Sbellard  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21fc01f7e7Sbellard  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22fc01f7e7Sbellard  * THE SOFTWARE.
23fc01f7e7Sbellard  */
243990d09aSblueswir1 #include "config-host.h"
25faf07963Spbrook #include "qemu-common.h"
266d519a5fSStefan Hajnoczi #include "trace.h"
27737e150eSPaolo Bonzini #include "block/block_int.h"
28737e150eSPaolo Bonzini #include "block/blockjob.h"
291de7afc9SPaolo Bonzini #include "qemu/module.h"
307b1b5d19SPaolo Bonzini #include "qapi/qmp/qjson.h"
319c17d615SPaolo Bonzini #include "sysemu/sysemu.h"
323ae59580SMarkus Armbruster #include "sysemu/blockdev.h"    /* FIXME layering violation */
331de7afc9SPaolo Bonzini #include "qemu/notify.h"
34737e150eSPaolo Bonzini #include "block/coroutine.h"
35c13163fbSBenoît Canet #include "block/qapi.h"
36b2023818SLuiz Capitulino #include "qmp-commands.h"
371de7afc9SPaolo Bonzini #include "qemu/timer.h"
38a5ee7bd4SWenchao Xia #include "qapi-event.h"
39fc01f7e7Sbellard 
4071e72a19SJuan Quintela #ifdef CONFIG_BSD
417674e7bfSbellard #include <sys/types.h>
427674e7bfSbellard #include <sys/stat.h>
437674e7bfSbellard #include <sys/ioctl.h>
4472cf2d4fSBlue Swirl #include <sys/queue.h>
45c5e97233Sblueswir1 #ifndef __DragonFly__
467674e7bfSbellard #include <sys/disk.h>
477674e7bfSbellard #endif
48c5e97233Sblueswir1 #endif
497674e7bfSbellard 
5049dc768dSaliguori #ifdef _WIN32
5149dc768dSaliguori #include <windows.h>
5249dc768dSaliguori #endif
5349dc768dSaliguori 
54e4654d2dSFam Zheng struct BdrvDirtyBitmap {
55e4654d2dSFam Zheng     HBitmap *bitmap;
56e4654d2dSFam Zheng     QLIST_ENTRY(BdrvDirtyBitmap) list;
57e4654d2dSFam Zheng };
58e4654d2dSFam Zheng 
591c9805a3SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
601c9805a3SStefan Hajnoczi 
612a87151fSStefan Hajnoczi #define COROUTINE_POOL_RESERVATION 64 /* number of coroutines to reserve */
622a87151fSStefan Hajnoczi 
637d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load);
64f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
65f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
66c87c0672Saliguori         BlockDriverCompletionFunc *cb, void *opaque);
67f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
68f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
69ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque);
70f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
71f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
72f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
73f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
74f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
75f9f05dc5SKevin Wolf                                          QEMUIOVector *iov);
76775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
77775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
78470c0504SStefan Hajnoczi     BdrvRequestFlags flags);
79775aa8b6SKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
80775aa8b6SKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
81f08f2ddaSStefan Hajnoczi     BdrvRequestFlags flags);
82b2a61371SStefan Hajnoczi static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
83b2a61371SStefan Hajnoczi                                                int64_t sector_num,
84b2a61371SStefan Hajnoczi                                                QEMUIOVector *qiov,
85b2a61371SStefan Hajnoczi                                                int nb_sectors,
86d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
87b2a61371SStefan Hajnoczi                                                BlockDriverCompletionFunc *cb,
88b2a61371SStefan Hajnoczi                                                void *opaque,
898c5873d6SStefan Hajnoczi                                                bool is_write);
90b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
91621f0589SKevin Wolf static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
92aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags);
93ec530c81Sbellard 
941b7bdbc1SStefan Hajnoczi static QTAILQ_HEAD(, BlockDriverState) bdrv_states =
951b7bdbc1SStefan Hajnoczi     QTAILQ_HEAD_INITIALIZER(bdrv_states);
967ee930d0Sblueswir1 
97dc364f4cSBenoît Canet static QTAILQ_HEAD(, BlockDriverState) graph_bdrv_states =
98dc364f4cSBenoît Canet     QTAILQ_HEAD_INITIALIZER(graph_bdrv_states);
99dc364f4cSBenoît Canet 
1008a22f02aSStefan Hajnoczi static QLIST_HEAD(, BlockDriver) bdrv_drivers =
1018a22f02aSStefan Hajnoczi     QLIST_HEAD_INITIALIZER(bdrv_drivers);
102ea2384d3Sbellard 
103eb852011SMarkus Armbruster /* If non-zero, use only whitelisted block drivers */
104eb852011SMarkus Armbruster static int use_bdrv_whitelist;
105eb852011SMarkus Armbruster 
1069e0b22f4SStefan Hajnoczi #ifdef _WIN32
1079e0b22f4SStefan Hajnoczi static int is_windows_drive_prefix(const char *filename)
1089e0b22f4SStefan Hajnoczi {
1099e0b22f4SStefan Hajnoczi     return (((filename[0] >= 'a' && filename[0] <= 'z') ||
1109e0b22f4SStefan Hajnoczi              (filename[0] >= 'A' && filename[0] <= 'Z')) &&
1119e0b22f4SStefan Hajnoczi             filename[1] == ':');
1129e0b22f4SStefan Hajnoczi }
1139e0b22f4SStefan Hajnoczi 
1149e0b22f4SStefan Hajnoczi int is_windows_drive(const char *filename)
1159e0b22f4SStefan Hajnoczi {
1169e0b22f4SStefan Hajnoczi     if (is_windows_drive_prefix(filename) &&
1179e0b22f4SStefan Hajnoczi         filename[2] == '\0')
1189e0b22f4SStefan Hajnoczi         return 1;
1199e0b22f4SStefan Hajnoczi     if (strstart(filename, "\\\\.\\", NULL) ||
1209e0b22f4SStefan Hajnoczi         strstart(filename, "//./", NULL))
1219e0b22f4SStefan Hajnoczi         return 1;
1229e0b22f4SStefan Hajnoczi     return 0;
1239e0b22f4SStefan Hajnoczi }
1249e0b22f4SStefan Hajnoczi #endif
1259e0b22f4SStefan Hajnoczi 
1260563e191SZhi Yong Wu /* throttling disk I/O limits */
127cc0681c4SBenoît Canet void bdrv_set_io_limits(BlockDriverState *bs,
128cc0681c4SBenoît Canet                         ThrottleConfig *cfg)
129cc0681c4SBenoît Canet {
130cc0681c4SBenoît Canet     int i;
131cc0681c4SBenoît Canet 
132cc0681c4SBenoît Canet     throttle_config(&bs->throttle_state, cfg);
133cc0681c4SBenoît Canet 
134cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
135cc0681c4SBenoît Canet         qemu_co_enter_next(&bs->throttled_reqs[i]);
136cc0681c4SBenoît Canet     }
137cc0681c4SBenoît Canet }
138cc0681c4SBenoît Canet 
139cc0681c4SBenoît Canet /* this function drain all the throttled IOs */
140cc0681c4SBenoît Canet static bool bdrv_start_throttled_reqs(BlockDriverState *bs)
141cc0681c4SBenoît Canet {
142cc0681c4SBenoît Canet     bool drained = false;
143cc0681c4SBenoît Canet     bool enabled = bs->io_limits_enabled;
144cc0681c4SBenoît Canet     int i;
145cc0681c4SBenoît Canet 
146cc0681c4SBenoît Canet     bs->io_limits_enabled = false;
147cc0681c4SBenoît Canet 
148cc0681c4SBenoît Canet     for (i = 0; i < 2; i++) {
149cc0681c4SBenoît Canet         while (qemu_co_enter_next(&bs->throttled_reqs[i])) {
150cc0681c4SBenoît Canet             drained = true;
151cc0681c4SBenoît Canet         }
152cc0681c4SBenoît Canet     }
153cc0681c4SBenoît Canet 
154cc0681c4SBenoît Canet     bs->io_limits_enabled = enabled;
155cc0681c4SBenoît Canet 
156cc0681c4SBenoît Canet     return drained;
157cc0681c4SBenoît Canet }
158cc0681c4SBenoît Canet 
15998f90dbaSZhi Yong Wu void bdrv_io_limits_disable(BlockDriverState *bs)
16098f90dbaSZhi Yong Wu {
16198f90dbaSZhi Yong Wu     bs->io_limits_enabled = false;
16298f90dbaSZhi Yong Wu 
163cc0681c4SBenoît Canet     bdrv_start_throttled_reqs(bs);
16498f90dbaSZhi Yong Wu 
165cc0681c4SBenoît Canet     throttle_destroy(&bs->throttle_state);
16698f90dbaSZhi Yong Wu }
16798f90dbaSZhi Yong Wu 
168cc0681c4SBenoît Canet static void bdrv_throttle_read_timer_cb(void *opaque)
1690563e191SZhi Yong Wu {
1700563e191SZhi Yong Wu     BlockDriverState *bs = opaque;
171cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[0]);
1720563e191SZhi Yong Wu }
1730563e191SZhi Yong Wu 
174cc0681c4SBenoît Canet static void bdrv_throttle_write_timer_cb(void *opaque)
175cc0681c4SBenoît Canet {
176cc0681c4SBenoît Canet     BlockDriverState *bs = opaque;
177cc0681c4SBenoît Canet     qemu_co_enter_next(&bs->throttled_reqs[1]);
178cc0681c4SBenoît Canet }
179cc0681c4SBenoît Canet 
180cc0681c4SBenoît Canet /* should be called before bdrv_set_io_limits if a limit is set */
1810563e191SZhi Yong Wu void bdrv_io_limits_enable(BlockDriverState *bs)
1820563e191SZhi Yong Wu {
183cc0681c4SBenoît Canet     assert(!bs->io_limits_enabled);
184cc0681c4SBenoît Canet     throttle_init(&bs->throttle_state,
18513af91ebSStefan Hajnoczi                   bdrv_get_aio_context(bs),
186cc0681c4SBenoît Canet                   QEMU_CLOCK_VIRTUAL,
187cc0681c4SBenoît Canet                   bdrv_throttle_read_timer_cb,
188cc0681c4SBenoît Canet                   bdrv_throttle_write_timer_cb,
189cc0681c4SBenoît Canet                   bs);
1900563e191SZhi Yong Wu     bs->io_limits_enabled = true;
1910563e191SZhi Yong Wu }
1920563e191SZhi Yong Wu 
193cc0681c4SBenoît Canet /* This function makes an IO wait if needed
194cc0681c4SBenoît Canet  *
195cc0681c4SBenoît Canet  * @nb_sectors: the number of sectors of the IO
196cc0681c4SBenoît Canet  * @is_write:   is the IO a write
19798f90dbaSZhi Yong Wu  */
198cc0681c4SBenoît Canet static void bdrv_io_limits_intercept(BlockDriverState *bs,
199d5103588SKevin Wolf                                      unsigned int bytes,
200cc0681c4SBenoît Canet                                      bool is_write)
201cc0681c4SBenoît Canet {
202cc0681c4SBenoît Canet     /* does this io must wait */
203cc0681c4SBenoît Canet     bool must_wait = throttle_schedule_timer(&bs->throttle_state, is_write);
20498f90dbaSZhi Yong Wu 
205cc0681c4SBenoît Canet     /* if must wait or any request of this type throttled queue the IO */
206cc0681c4SBenoît Canet     if (must_wait ||
207cc0681c4SBenoît Canet         !qemu_co_queue_empty(&bs->throttled_reqs[is_write])) {
208cc0681c4SBenoît Canet         qemu_co_queue_wait(&bs->throttled_reqs[is_write]);
20998f90dbaSZhi Yong Wu     }
21098f90dbaSZhi Yong Wu 
211cc0681c4SBenoît Canet     /* the IO will be executed, do the accounting */
212d5103588SKevin Wolf     throttle_account(&bs->throttle_state, is_write, bytes);
213d5103588SKevin Wolf 
214cc0681c4SBenoît Canet 
215cc0681c4SBenoît Canet     /* if the next request must wait -> do nothing */
216cc0681c4SBenoît Canet     if (throttle_schedule_timer(&bs->throttle_state, is_write)) {
217cc0681c4SBenoît Canet         return;
218cc0681c4SBenoît Canet     }
219cc0681c4SBenoît Canet 
220cc0681c4SBenoît Canet     /* else queue next request for execution */
221cc0681c4SBenoît Canet     qemu_co_queue_next(&bs->throttled_reqs[is_write]);
22298f90dbaSZhi Yong Wu }
22398f90dbaSZhi Yong Wu 
224339064d5SKevin Wolf size_t bdrv_opt_mem_align(BlockDriverState *bs)
225339064d5SKevin Wolf {
226339064d5SKevin Wolf     if (!bs || !bs->drv) {
227339064d5SKevin Wolf         /* 4k should be on the safe side */
228339064d5SKevin Wolf         return 4096;
229339064d5SKevin Wolf     }
230339064d5SKevin Wolf 
231339064d5SKevin Wolf     return bs->bl.opt_mem_alignment;
232339064d5SKevin Wolf }
233339064d5SKevin Wolf 
2349e0b22f4SStefan Hajnoczi /* check if the path starts with "<protocol>:" */
2359e0b22f4SStefan Hajnoczi static int path_has_protocol(const char *path)
2369e0b22f4SStefan Hajnoczi {
237947995c0SPaolo Bonzini     const char *p;
238947995c0SPaolo Bonzini 
2399e0b22f4SStefan Hajnoczi #ifdef _WIN32
2409e0b22f4SStefan Hajnoczi     if (is_windows_drive(path) ||
2419e0b22f4SStefan Hajnoczi         is_windows_drive_prefix(path)) {
2429e0b22f4SStefan Hajnoczi         return 0;
2439e0b22f4SStefan Hajnoczi     }
244947995c0SPaolo Bonzini     p = path + strcspn(path, ":/\\");
245947995c0SPaolo Bonzini #else
246947995c0SPaolo Bonzini     p = path + strcspn(path, ":/");
2479e0b22f4SStefan Hajnoczi #endif
2489e0b22f4SStefan Hajnoczi 
249947995c0SPaolo Bonzini     return *p == ':';
2509e0b22f4SStefan Hajnoczi }
2519e0b22f4SStefan Hajnoczi 
25283f64091Sbellard int path_is_absolute(const char *path)
25383f64091Sbellard {
25421664424Sbellard #ifdef _WIN32
25521664424Sbellard     /* specific case for names like: "\\.\d:" */
256f53f4da9SPaolo Bonzini     if (is_windows_drive(path) || is_windows_drive_prefix(path)) {
25721664424Sbellard         return 1;
258f53f4da9SPaolo Bonzini     }
259f53f4da9SPaolo Bonzini     return (*path == '/' || *path == '\\');
2603b9f94e1Sbellard #else
261f53f4da9SPaolo Bonzini     return (*path == '/');
2623b9f94e1Sbellard #endif
26383f64091Sbellard }
26483f64091Sbellard 
26583f64091Sbellard /* if filename is absolute, just copy it to dest. Otherwise, build a
26683f64091Sbellard    path to it by considering it is relative to base_path. URL are
26783f64091Sbellard    supported. */
26883f64091Sbellard void path_combine(char *dest, int dest_size,
26983f64091Sbellard                   const char *base_path,
27083f64091Sbellard                   const char *filename)
27183f64091Sbellard {
27283f64091Sbellard     const char *p, *p1;
27383f64091Sbellard     int len;
27483f64091Sbellard 
27583f64091Sbellard     if (dest_size <= 0)
27683f64091Sbellard         return;
27783f64091Sbellard     if (path_is_absolute(filename)) {
27883f64091Sbellard         pstrcpy(dest, dest_size, filename);
27983f64091Sbellard     } else {
28083f64091Sbellard         p = strchr(base_path, ':');
28183f64091Sbellard         if (p)
28283f64091Sbellard             p++;
28383f64091Sbellard         else
28483f64091Sbellard             p = base_path;
2853b9f94e1Sbellard         p1 = strrchr(base_path, '/');
2863b9f94e1Sbellard #ifdef _WIN32
2873b9f94e1Sbellard         {
2883b9f94e1Sbellard             const char *p2;
2893b9f94e1Sbellard             p2 = strrchr(base_path, '\\');
2903b9f94e1Sbellard             if (!p1 || p2 > p1)
2913b9f94e1Sbellard                 p1 = p2;
2923b9f94e1Sbellard         }
2933b9f94e1Sbellard #endif
29483f64091Sbellard         if (p1)
29583f64091Sbellard             p1++;
29683f64091Sbellard         else
29783f64091Sbellard             p1 = base_path;
29883f64091Sbellard         if (p1 > p)
29983f64091Sbellard             p = p1;
30083f64091Sbellard         len = p - base_path;
30183f64091Sbellard         if (len > dest_size - 1)
30283f64091Sbellard             len = dest_size - 1;
30383f64091Sbellard         memcpy(dest, base_path, len);
30483f64091Sbellard         dest[len] = '\0';
30583f64091Sbellard         pstrcat(dest, dest_size, filename);
30683f64091Sbellard     }
30783f64091Sbellard }
30883f64091Sbellard 
309dc5a1371SPaolo Bonzini void bdrv_get_full_backing_filename(BlockDriverState *bs, char *dest, size_t sz)
310dc5a1371SPaolo Bonzini {
311dc5a1371SPaolo Bonzini     if (bs->backing_file[0] == '\0' || path_has_protocol(bs->backing_file)) {
312dc5a1371SPaolo Bonzini         pstrcpy(dest, sz, bs->backing_file);
313dc5a1371SPaolo Bonzini     } else {
314dc5a1371SPaolo Bonzini         path_combine(dest, sz, bs->filename, bs->backing_file);
315dc5a1371SPaolo Bonzini     }
316dc5a1371SPaolo Bonzini }
317dc5a1371SPaolo Bonzini 
3185efa9d5aSAnthony Liguori void bdrv_register(BlockDriver *bdrv)
319ea2384d3Sbellard {
3208c5873d6SStefan Hajnoczi     /* Block drivers without coroutine functions need emulation */
3218c5873d6SStefan Hajnoczi     if (!bdrv->bdrv_co_readv) {
322f9f05dc5SKevin Wolf         bdrv->bdrv_co_readv = bdrv_co_readv_em;
323f9f05dc5SKevin Wolf         bdrv->bdrv_co_writev = bdrv_co_writev_em;
324f9f05dc5SKevin Wolf 
325f8c35c1dSStefan Hajnoczi         /* bdrv_co_readv_em()/brdv_co_writev_em() work in terms of aio, so if
326f8c35c1dSStefan Hajnoczi          * the block driver lacks aio we need to emulate that too.
327f8c35c1dSStefan Hajnoczi          */
328f9f05dc5SKevin Wolf         if (!bdrv->bdrv_aio_readv) {
32983f64091Sbellard             /* add AIO emulation layer */
330f141eafeSaliguori             bdrv->bdrv_aio_readv = bdrv_aio_readv_em;
331f141eafeSaliguori             bdrv->bdrv_aio_writev = bdrv_aio_writev_em;
33283f64091Sbellard         }
333f9f05dc5SKevin Wolf     }
334b2e12bc6SChristoph Hellwig 
3358a22f02aSStefan Hajnoczi     QLIST_INSERT_HEAD(&bdrv_drivers, bdrv, list);
336ea2384d3Sbellard }
337b338082bSbellard 
338b338082bSbellard /* create a new block device (by default it is empty) */
33998522f63SKevin Wolf BlockDriverState *bdrv_new(const char *device_name, Error **errp)
340fc01f7e7Sbellard {
3411b7bdbc1SStefan Hajnoczi     BlockDriverState *bs;
342fbe40ff7SFam Zheng     int i;
343b338082bSbellard 
344f2d953ecSKevin Wolf     if (bdrv_find(device_name)) {
345f2d953ecSKevin Wolf         error_setg(errp, "Device with id '%s' already exists",
346f2d953ecSKevin Wolf                    device_name);
347f2d953ecSKevin Wolf         return NULL;
348f2d953ecSKevin Wolf     }
349f2d953ecSKevin Wolf     if (bdrv_find_node(device_name)) {
350*d224469dSMarkus Armbruster         error_setg(errp,
351*d224469dSMarkus Armbruster                    "Device name '%s' conflicts with an existing node name",
352f2d953ecSKevin Wolf                    device_name);
353f2d953ecSKevin Wolf         return NULL;
354f2d953ecSKevin Wolf     }
355f2d953ecSKevin Wolf 
3565839e53bSMarkus Armbruster     bs = g_new0(BlockDriverState, 1);
357e4654d2dSFam Zheng     QLIST_INIT(&bs->dirty_bitmaps);
358b338082bSbellard     pstrcpy(bs->device_name, sizeof(bs->device_name), device_name);
359ea2384d3Sbellard     if (device_name[0] != '\0') {
360dc364f4cSBenoît Canet         QTAILQ_INSERT_TAIL(&bdrv_states, bs, device_list);
361ea2384d3Sbellard     }
362fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
363fbe40ff7SFam Zheng         QLIST_INIT(&bs->op_blockers[i]);
364fbe40ff7SFam Zheng     }
36528a7282aSLuiz Capitulino     bdrv_iostatus_disable(bs);
366d7d512f6SPaolo Bonzini     notifier_list_init(&bs->close_notifiers);
367d616b224SStefan Hajnoczi     notifier_with_return_list_init(&bs->before_write_notifiers);
368cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[0]);
369cc0681c4SBenoît Canet     qemu_co_queue_init(&bs->throttled_reqs[1]);
3709fcb0251SFam Zheng     bs->refcnt = 1;
371dcd04228SStefan Hajnoczi     bs->aio_context = qemu_get_aio_context();
372d7d512f6SPaolo Bonzini 
373b338082bSbellard     return bs;
374b338082bSbellard }
375b338082bSbellard 
376d7d512f6SPaolo Bonzini void bdrv_add_close_notifier(BlockDriverState *bs, Notifier *notify)
377d7d512f6SPaolo Bonzini {
378d7d512f6SPaolo Bonzini     notifier_list_add(&bs->close_notifiers, notify);
379d7d512f6SPaolo Bonzini }
380d7d512f6SPaolo Bonzini 
381ea2384d3Sbellard BlockDriver *bdrv_find_format(const char *format_name)
382ea2384d3Sbellard {
383ea2384d3Sbellard     BlockDriver *drv1;
3848a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
3858a22f02aSStefan Hajnoczi         if (!strcmp(drv1->format_name, format_name)) {
386ea2384d3Sbellard             return drv1;
387ea2384d3Sbellard         }
3888a22f02aSStefan Hajnoczi     }
389ea2384d3Sbellard     return NULL;
390ea2384d3Sbellard }
391ea2384d3Sbellard 
392b64ec4e4SFam Zheng static int bdrv_is_whitelisted(BlockDriver *drv, bool read_only)
393eb852011SMarkus Armbruster {
394b64ec4e4SFam Zheng     static const char *whitelist_rw[] = {
395b64ec4e4SFam Zheng         CONFIG_BDRV_RW_WHITELIST
396b64ec4e4SFam Zheng     };
397b64ec4e4SFam Zheng     static const char *whitelist_ro[] = {
398b64ec4e4SFam Zheng         CONFIG_BDRV_RO_WHITELIST
399eb852011SMarkus Armbruster     };
400eb852011SMarkus Armbruster     const char **p;
401eb852011SMarkus Armbruster 
402b64ec4e4SFam Zheng     if (!whitelist_rw[0] && !whitelist_ro[0]) {
403eb852011SMarkus Armbruster         return 1;               /* no whitelist, anything goes */
404b64ec4e4SFam Zheng     }
405eb852011SMarkus Armbruster 
406b64ec4e4SFam Zheng     for (p = whitelist_rw; *p; p++) {
407eb852011SMarkus Armbruster         if (!strcmp(drv->format_name, *p)) {
408eb852011SMarkus Armbruster             return 1;
409eb852011SMarkus Armbruster         }
410eb852011SMarkus Armbruster     }
411b64ec4e4SFam Zheng     if (read_only) {
412b64ec4e4SFam Zheng         for (p = whitelist_ro; *p; p++) {
413b64ec4e4SFam Zheng             if (!strcmp(drv->format_name, *p)) {
414b64ec4e4SFam Zheng                 return 1;
415b64ec4e4SFam Zheng             }
416b64ec4e4SFam Zheng         }
417b64ec4e4SFam Zheng     }
418eb852011SMarkus Armbruster     return 0;
419eb852011SMarkus Armbruster }
420eb852011SMarkus Armbruster 
421b64ec4e4SFam Zheng BlockDriver *bdrv_find_whitelisted_format(const char *format_name,
422b64ec4e4SFam Zheng                                           bool read_only)
423eb852011SMarkus Armbruster {
424eb852011SMarkus Armbruster     BlockDriver *drv = bdrv_find_format(format_name);
425b64ec4e4SFam Zheng     return drv && bdrv_is_whitelisted(drv, read_only) ? drv : NULL;
426eb852011SMarkus Armbruster }
427eb852011SMarkus Armbruster 
4285b7e1542SZhi Yong Wu typedef struct CreateCo {
4295b7e1542SZhi Yong Wu     BlockDriver *drv;
4305b7e1542SZhi Yong Wu     char *filename;
43183d0521aSChunyan Liu     QemuOpts *opts;
4325b7e1542SZhi Yong Wu     int ret;
433cc84d90fSMax Reitz     Error *err;
4345b7e1542SZhi Yong Wu } CreateCo;
4355b7e1542SZhi Yong Wu 
4365b7e1542SZhi Yong Wu static void coroutine_fn bdrv_create_co_entry(void *opaque)
4375b7e1542SZhi Yong Wu {
438cc84d90fSMax Reitz     Error *local_err = NULL;
439cc84d90fSMax Reitz     int ret;
440cc84d90fSMax Reitz 
4415b7e1542SZhi Yong Wu     CreateCo *cco = opaque;
4425b7e1542SZhi Yong Wu     assert(cco->drv);
4435b7e1542SZhi Yong Wu 
444c282e1fdSChunyan Liu     ret = cco->drv->bdrv_create(cco->filename, cco->opts, &local_err);
44584d18f06SMarkus Armbruster     if (local_err) {
446cc84d90fSMax Reitz         error_propagate(&cco->err, local_err);
447cc84d90fSMax Reitz     }
448cc84d90fSMax Reitz     cco->ret = ret;
4495b7e1542SZhi Yong Wu }
4505b7e1542SZhi Yong Wu 
4510e7e1989SKevin Wolf int bdrv_create(BlockDriver *drv, const char* filename,
45283d0521aSChunyan Liu                 QemuOpts *opts, Error **errp)
453ea2384d3Sbellard {
4545b7e1542SZhi Yong Wu     int ret;
4550e7e1989SKevin Wolf 
4565b7e1542SZhi Yong Wu     Coroutine *co;
4575b7e1542SZhi Yong Wu     CreateCo cco = {
4585b7e1542SZhi Yong Wu         .drv = drv,
4595b7e1542SZhi Yong Wu         .filename = g_strdup(filename),
46083d0521aSChunyan Liu         .opts = opts,
4615b7e1542SZhi Yong Wu         .ret = NOT_DONE,
462cc84d90fSMax Reitz         .err = NULL,
4635b7e1542SZhi Yong Wu     };
4645b7e1542SZhi Yong Wu 
465c282e1fdSChunyan Liu     if (!drv->bdrv_create) {
466cc84d90fSMax Reitz         error_setg(errp, "Driver '%s' does not support image creation", drv->format_name);
46780168bffSLuiz Capitulino         ret = -ENOTSUP;
46880168bffSLuiz Capitulino         goto out;
4695b7e1542SZhi Yong Wu     }
4705b7e1542SZhi Yong Wu 
4715b7e1542SZhi Yong Wu     if (qemu_in_coroutine()) {
4725b7e1542SZhi Yong Wu         /* Fast-path if already in coroutine context */
4735b7e1542SZhi Yong Wu         bdrv_create_co_entry(&cco);
4745b7e1542SZhi Yong Wu     } else {
4755b7e1542SZhi Yong Wu         co = qemu_coroutine_create(bdrv_create_co_entry);
4765b7e1542SZhi Yong Wu         qemu_coroutine_enter(co, &cco);
4775b7e1542SZhi Yong Wu         while (cco.ret == NOT_DONE) {
478b47ec2c4SPaolo Bonzini             aio_poll(qemu_get_aio_context(), true);
4795b7e1542SZhi Yong Wu         }
4805b7e1542SZhi Yong Wu     }
4815b7e1542SZhi Yong Wu 
4825b7e1542SZhi Yong Wu     ret = cco.ret;
483cc84d90fSMax Reitz     if (ret < 0) {
48484d18f06SMarkus Armbruster         if (cco.err) {
485cc84d90fSMax Reitz             error_propagate(errp, cco.err);
486cc84d90fSMax Reitz         } else {
487cc84d90fSMax Reitz             error_setg_errno(errp, -ret, "Could not create image");
488cc84d90fSMax Reitz         }
489cc84d90fSMax Reitz     }
4905b7e1542SZhi Yong Wu 
49180168bffSLuiz Capitulino out:
49280168bffSLuiz Capitulino     g_free(cco.filename);
4935b7e1542SZhi Yong Wu     return ret;
494ea2384d3Sbellard }
495ea2384d3Sbellard 
496c282e1fdSChunyan Liu int bdrv_create_file(const char *filename, QemuOpts *opts, Error **errp)
49784a12e66SChristoph Hellwig {
49884a12e66SChristoph Hellwig     BlockDriver *drv;
499cc84d90fSMax Reitz     Error *local_err = NULL;
500cc84d90fSMax Reitz     int ret;
50184a12e66SChristoph Hellwig 
50298289620SKevin Wolf     drv = bdrv_find_protocol(filename, true);
50384a12e66SChristoph Hellwig     if (drv == NULL) {
504cc84d90fSMax Reitz         error_setg(errp, "Could not find protocol for file '%s'", filename);
50516905d71SStefan Hajnoczi         return -ENOENT;
50684a12e66SChristoph Hellwig     }
50784a12e66SChristoph Hellwig 
508c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
50984d18f06SMarkus Armbruster     if (local_err) {
510cc84d90fSMax Reitz         error_propagate(errp, local_err);
511cc84d90fSMax Reitz     }
512cc84d90fSMax Reitz     return ret;
51384a12e66SChristoph Hellwig }
51484a12e66SChristoph Hellwig 
5153baca891SKevin Wolf void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
516d34682cdSKevin Wolf {
517d34682cdSKevin Wolf     BlockDriver *drv = bs->drv;
5183baca891SKevin Wolf     Error *local_err = NULL;
519d34682cdSKevin Wolf 
520d34682cdSKevin Wolf     memset(&bs->bl, 0, sizeof(bs->bl));
521d34682cdSKevin Wolf 
522466ad822SKevin Wolf     if (!drv) {
5233baca891SKevin Wolf         return;
524466ad822SKevin Wolf     }
525466ad822SKevin Wolf 
526466ad822SKevin Wolf     /* Take some limits from the children as a default */
527466ad822SKevin Wolf     if (bs->file) {
5283baca891SKevin Wolf         bdrv_refresh_limits(bs->file, &local_err);
5293baca891SKevin Wolf         if (local_err) {
5303baca891SKevin Wolf             error_propagate(errp, local_err);
5313baca891SKevin Wolf             return;
5323baca891SKevin Wolf         }
533466ad822SKevin Wolf         bs->bl.opt_transfer_length = bs->file->bl.opt_transfer_length;
534339064d5SKevin Wolf         bs->bl.opt_mem_alignment = bs->file->bl.opt_mem_alignment;
535339064d5SKevin Wolf     } else {
536339064d5SKevin Wolf         bs->bl.opt_mem_alignment = 512;
537466ad822SKevin Wolf     }
538466ad822SKevin Wolf 
539466ad822SKevin Wolf     if (bs->backing_hd) {
5403baca891SKevin Wolf         bdrv_refresh_limits(bs->backing_hd, &local_err);
5413baca891SKevin Wolf         if (local_err) {
5423baca891SKevin Wolf             error_propagate(errp, local_err);
5433baca891SKevin Wolf             return;
5443baca891SKevin Wolf         }
545466ad822SKevin Wolf         bs->bl.opt_transfer_length =
546466ad822SKevin Wolf             MAX(bs->bl.opt_transfer_length,
547466ad822SKevin Wolf                 bs->backing_hd->bl.opt_transfer_length);
548339064d5SKevin Wolf         bs->bl.opt_mem_alignment =
549339064d5SKevin Wolf             MAX(bs->bl.opt_mem_alignment,
550339064d5SKevin Wolf                 bs->backing_hd->bl.opt_mem_alignment);
551466ad822SKevin Wolf     }
552466ad822SKevin Wolf 
553466ad822SKevin Wolf     /* Then let the driver override it */
554466ad822SKevin Wolf     if (drv->bdrv_refresh_limits) {
5553baca891SKevin Wolf         drv->bdrv_refresh_limits(bs, errp);
556d34682cdSKevin Wolf     }
557d34682cdSKevin Wolf }
558d34682cdSKevin Wolf 
559eba25057SJim Meyering /*
560eba25057SJim Meyering  * Create a uniquely-named empty temporary file.
561eba25057SJim Meyering  * Return 0 upon success, otherwise a negative errno value.
562eba25057SJim Meyering  */
563eba25057SJim Meyering int get_tmp_filename(char *filename, int size)
564eba25057SJim Meyering {
565d5249393Sbellard #ifdef _WIN32
5663b9f94e1Sbellard     char temp_dir[MAX_PATH];
567eba25057SJim Meyering     /* GetTempFileName requires that its output buffer (4th param)
568eba25057SJim Meyering        have length MAX_PATH or greater.  */
569eba25057SJim Meyering     assert(size >= MAX_PATH);
570eba25057SJim Meyering     return (GetTempPath(MAX_PATH, temp_dir)
571eba25057SJim Meyering             && GetTempFileName(temp_dir, "qem", 0, filename)
572eba25057SJim Meyering             ? 0 : -GetLastError());
573d5249393Sbellard #else
574ea2384d3Sbellard     int fd;
5757ccfb2ebSblueswir1     const char *tmpdir;
5760badc1eeSaurel32     tmpdir = getenv("TMPDIR");
57769bef793SAmit Shah     if (!tmpdir) {
57869bef793SAmit Shah         tmpdir = "/var/tmp";
57969bef793SAmit Shah     }
580eba25057SJim Meyering     if (snprintf(filename, size, "%s/vl.XXXXXX", tmpdir) >= size) {
581eba25057SJim Meyering         return -EOVERFLOW;
582ea2384d3Sbellard     }
583eba25057SJim Meyering     fd = mkstemp(filename);
584fe235a06SDunrong Huang     if (fd < 0) {
585fe235a06SDunrong Huang         return -errno;
586fe235a06SDunrong Huang     }
587fe235a06SDunrong Huang     if (close(fd) != 0) {
588fe235a06SDunrong Huang         unlink(filename);
589eba25057SJim Meyering         return -errno;
590eba25057SJim Meyering     }
591eba25057SJim Meyering     return 0;
592d5249393Sbellard #endif
593eba25057SJim Meyering }
594ea2384d3Sbellard 
595f3a5d3f8SChristoph Hellwig /*
596f3a5d3f8SChristoph Hellwig  * Detect host devices. By convention, /dev/cdrom[N] is always
597f3a5d3f8SChristoph Hellwig  * recognized as a host CDROM.
598f3a5d3f8SChristoph Hellwig  */
599f3a5d3f8SChristoph Hellwig static BlockDriver *find_hdev_driver(const char *filename)
600f3a5d3f8SChristoph Hellwig {
601508c7cb3SChristoph Hellwig     int score_max = 0, score;
602508c7cb3SChristoph Hellwig     BlockDriver *drv = NULL, *d;
603f3a5d3f8SChristoph Hellwig 
6048a22f02aSStefan Hajnoczi     QLIST_FOREACH(d, &bdrv_drivers, list) {
605508c7cb3SChristoph Hellwig         if (d->bdrv_probe_device) {
606508c7cb3SChristoph Hellwig             score = d->bdrv_probe_device(filename);
607508c7cb3SChristoph Hellwig             if (score > score_max) {
608508c7cb3SChristoph Hellwig                 score_max = score;
609508c7cb3SChristoph Hellwig                 drv = d;
610f3a5d3f8SChristoph Hellwig             }
611508c7cb3SChristoph Hellwig         }
612f3a5d3f8SChristoph Hellwig     }
613f3a5d3f8SChristoph Hellwig 
614508c7cb3SChristoph Hellwig     return drv;
615f3a5d3f8SChristoph Hellwig }
616f3a5d3f8SChristoph Hellwig 
61798289620SKevin Wolf BlockDriver *bdrv_find_protocol(const char *filename,
61898289620SKevin Wolf                                 bool allow_protocol_prefix)
61984a12e66SChristoph Hellwig {
62084a12e66SChristoph Hellwig     BlockDriver *drv1;
62184a12e66SChristoph Hellwig     char protocol[128];
62284a12e66SChristoph Hellwig     int len;
62384a12e66SChristoph Hellwig     const char *p;
62484a12e66SChristoph Hellwig 
62566f82ceeSKevin Wolf     /* TODO Drivers without bdrv_file_open must be specified explicitly */
62666f82ceeSKevin Wolf 
62739508e7aSChristoph Hellwig     /*
62839508e7aSChristoph Hellwig      * XXX(hch): we really should not let host device detection
62939508e7aSChristoph Hellwig      * override an explicit protocol specification, but moving this
63039508e7aSChristoph Hellwig      * later breaks access to device names with colons in them.
63139508e7aSChristoph Hellwig      * Thanks to the brain-dead persistent naming schemes on udev-
63239508e7aSChristoph Hellwig      * based Linux systems those actually are quite common.
63339508e7aSChristoph Hellwig      */
63484a12e66SChristoph Hellwig     drv1 = find_hdev_driver(filename);
63539508e7aSChristoph Hellwig     if (drv1) {
63684a12e66SChristoph Hellwig         return drv1;
63784a12e66SChristoph Hellwig     }
63839508e7aSChristoph Hellwig 
63998289620SKevin Wolf     if (!path_has_protocol(filename) || !allow_protocol_prefix) {
64039508e7aSChristoph Hellwig         return bdrv_find_format("file");
64139508e7aSChristoph Hellwig     }
64298289620SKevin Wolf 
6439e0b22f4SStefan Hajnoczi     p = strchr(filename, ':');
6449e0b22f4SStefan Hajnoczi     assert(p != NULL);
64584a12e66SChristoph Hellwig     len = p - filename;
64684a12e66SChristoph Hellwig     if (len > sizeof(protocol) - 1)
64784a12e66SChristoph Hellwig         len = sizeof(protocol) - 1;
64884a12e66SChristoph Hellwig     memcpy(protocol, filename, len);
64984a12e66SChristoph Hellwig     protocol[len] = '\0';
65084a12e66SChristoph Hellwig     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
65184a12e66SChristoph Hellwig         if (drv1->protocol_name &&
65284a12e66SChristoph Hellwig             !strcmp(drv1->protocol_name, protocol)) {
65384a12e66SChristoph Hellwig             return drv1;
65484a12e66SChristoph Hellwig         }
65584a12e66SChristoph Hellwig     }
65684a12e66SChristoph Hellwig     return NULL;
65784a12e66SChristoph Hellwig }
65884a12e66SChristoph Hellwig 
659f500a6d3SKevin Wolf static int find_image_format(BlockDriverState *bs, const char *filename,
66034b5d2c6SMax Reitz                              BlockDriver **pdrv, Error **errp)
661ea2384d3Sbellard {
662f500a6d3SKevin Wolf     int score, score_max;
663ea2384d3Sbellard     BlockDriver *drv1, *drv;
66483f64091Sbellard     uint8_t buf[2048];
665f500a6d3SKevin Wolf     int ret = 0;
666f8ea0b00SNicholas Bellinger 
66708a00559SKevin Wolf     /* Return the raw BlockDriver * to scsi-generic devices or empty drives */
6688e895599SPaolo Bonzini     if (bs->sg || !bdrv_is_inserted(bs) || bdrv_getlength(bs) == 0) {
669c98ac35dSStefan Weil         drv = bdrv_find_format("raw");
670c98ac35dSStefan Weil         if (!drv) {
67134b5d2c6SMax Reitz             error_setg(errp, "Could not find raw image format");
672c98ac35dSStefan Weil             ret = -ENOENT;
673c98ac35dSStefan Weil         }
674c98ac35dSStefan Weil         *pdrv = drv;
675c98ac35dSStefan Weil         return ret;
6761a396859SNicholas A. Bellinger     }
677f8ea0b00SNicholas Bellinger 
67883f64091Sbellard     ret = bdrv_pread(bs, 0, buf, sizeof(buf));
679ea2384d3Sbellard     if (ret < 0) {
68034b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not read image for determining its "
68134b5d2c6SMax Reitz                          "format");
682c98ac35dSStefan Weil         *pdrv = NULL;
683c98ac35dSStefan Weil         return ret;
684ea2384d3Sbellard     }
685ea2384d3Sbellard 
686ea2384d3Sbellard     score_max = 0;
68784a12e66SChristoph Hellwig     drv = NULL;
6888a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv1, &bdrv_drivers, list) {
68983f64091Sbellard         if (drv1->bdrv_probe) {
690ea2384d3Sbellard             score = drv1->bdrv_probe(buf, ret, filename);
691ea2384d3Sbellard             if (score > score_max) {
692ea2384d3Sbellard                 score_max = score;
693ea2384d3Sbellard                 drv = drv1;
694ea2384d3Sbellard             }
695ea2384d3Sbellard         }
69683f64091Sbellard     }
697c98ac35dSStefan Weil     if (!drv) {
69834b5d2c6SMax Reitz         error_setg(errp, "Could not determine image format: No compatible "
69934b5d2c6SMax Reitz                    "driver found");
700c98ac35dSStefan Weil         ret = -ENOENT;
701c98ac35dSStefan Weil     }
702c98ac35dSStefan Weil     *pdrv = drv;
703c98ac35dSStefan Weil     return ret;
704ea2384d3Sbellard }
705ea2384d3Sbellard 
70651762288SStefan Hajnoczi /**
70751762288SStefan Hajnoczi  * Set the current 'total_sectors' value
70865a9bb25SMarkus Armbruster  * Return 0 on success, -errno on error.
70951762288SStefan Hajnoczi  */
71051762288SStefan Hajnoczi static int refresh_total_sectors(BlockDriverState *bs, int64_t hint)
71151762288SStefan Hajnoczi {
71251762288SStefan Hajnoczi     BlockDriver *drv = bs->drv;
71351762288SStefan Hajnoczi 
714396759adSNicholas Bellinger     /* Do not attempt drv->bdrv_getlength() on scsi-generic devices */
715396759adSNicholas Bellinger     if (bs->sg)
716396759adSNicholas Bellinger         return 0;
717396759adSNicholas Bellinger 
71851762288SStefan Hajnoczi     /* query actual device if possible, otherwise just trust the hint */
71951762288SStefan Hajnoczi     if (drv->bdrv_getlength) {
72051762288SStefan Hajnoczi         int64_t length = drv->bdrv_getlength(bs);
72151762288SStefan Hajnoczi         if (length < 0) {
72251762288SStefan Hajnoczi             return length;
72351762288SStefan Hajnoczi         }
7247e382003SFam Zheng         hint = DIV_ROUND_UP(length, BDRV_SECTOR_SIZE);
72551762288SStefan Hajnoczi     }
72651762288SStefan Hajnoczi 
72751762288SStefan Hajnoczi     bs->total_sectors = hint;
72851762288SStefan Hajnoczi     return 0;
72951762288SStefan Hajnoczi }
73051762288SStefan Hajnoczi 
731c3993cdcSStefan Hajnoczi /**
7329e8f1835SPaolo Bonzini  * Set open flags for a given discard mode
7339e8f1835SPaolo Bonzini  *
7349e8f1835SPaolo Bonzini  * Return 0 on success, -1 if the discard mode was invalid.
7359e8f1835SPaolo Bonzini  */
7369e8f1835SPaolo Bonzini int bdrv_parse_discard_flags(const char *mode, int *flags)
7379e8f1835SPaolo Bonzini {
7389e8f1835SPaolo Bonzini     *flags &= ~BDRV_O_UNMAP;
7399e8f1835SPaolo Bonzini 
7409e8f1835SPaolo Bonzini     if (!strcmp(mode, "off") || !strcmp(mode, "ignore")) {
7419e8f1835SPaolo Bonzini         /* do nothing */
7429e8f1835SPaolo Bonzini     } else if (!strcmp(mode, "on") || !strcmp(mode, "unmap")) {
7439e8f1835SPaolo Bonzini         *flags |= BDRV_O_UNMAP;
7449e8f1835SPaolo Bonzini     } else {
7459e8f1835SPaolo Bonzini         return -1;
7469e8f1835SPaolo Bonzini     }
7479e8f1835SPaolo Bonzini 
7489e8f1835SPaolo Bonzini     return 0;
7499e8f1835SPaolo Bonzini }
7509e8f1835SPaolo Bonzini 
7519e8f1835SPaolo Bonzini /**
752c3993cdcSStefan Hajnoczi  * Set open flags for a given cache mode
753c3993cdcSStefan Hajnoczi  *
754c3993cdcSStefan Hajnoczi  * Return 0 on success, -1 if the cache mode was invalid.
755c3993cdcSStefan Hajnoczi  */
756c3993cdcSStefan Hajnoczi int bdrv_parse_cache_flags(const char *mode, int *flags)
757c3993cdcSStefan Hajnoczi {
758c3993cdcSStefan Hajnoczi     *flags &= ~BDRV_O_CACHE_MASK;
759c3993cdcSStefan Hajnoczi 
760c3993cdcSStefan Hajnoczi     if (!strcmp(mode, "off") || !strcmp(mode, "none")) {
761c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE | BDRV_O_CACHE_WB;
76292196b2fSStefan Hajnoczi     } else if (!strcmp(mode, "directsync")) {
76392196b2fSStefan Hajnoczi         *flags |= BDRV_O_NOCACHE;
764c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writeback")) {
765c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
766c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "unsafe")) {
767c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_CACHE_WB;
768c3993cdcSStefan Hajnoczi         *flags |= BDRV_O_NO_FLUSH;
769c3993cdcSStefan Hajnoczi     } else if (!strcmp(mode, "writethrough")) {
770c3993cdcSStefan Hajnoczi         /* this is the default */
771c3993cdcSStefan Hajnoczi     } else {
772c3993cdcSStefan Hajnoczi         return -1;
773c3993cdcSStefan Hajnoczi     }
774c3993cdcSStefan Hajnoczi 
775c3993cdcSStefan Hajnoczi     return 0;
776c3993cdcSStefan Hajnoczi }
777c3993cdcSStefan Hajnoczi 
77853fec9d3SStefan Hajnoczi /**
77953fec9d3SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
78053fec9d3SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
78153fec9d3SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
78253fec9d3SStefan Hajnoczi  */
78353fec9d3SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
78453fec9d3SStefan Hajnoczi {
78553fec9d3SStefan Hajnoczi     bs->copy_on_read++;
78653fec9d3SStefan Hajnoczi }
78753fec9d3SStefan Hajnoczi 
78853fec9d3SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
78953fec9d3SStefan Hajnoczi {
79053fec9d3SStefan Hajnoczi     assert(bs->copy_on_read > 0);
79153fec9d3SStefan Hajnoczi     bs->copy_on_read--;
79253fec9d3SStefan Hajnoczi }
79353fec9d3SStefan Hajnoczi 
7940b50cc88SKevin Wolf /*
795b1e6fc08SKevin Wolf  * Returns the flags that a temporary snapshot should get, based on the
796b1e6fc08SKevin Wolf  * originally requested flags (the originally requested image will have flags
797b1e6fc08SKevin Wolf  * like a backing file)
798b1e6fc08SKevin Wolf  */
799b1e6fc08SKevin Wolf static int bdrv_temp_snapshot_flags(int flags)
800b1e6fc08SKevin Wolf {
801b1e6fc08SKevin Wolf     return (flags & ~BDRV_O_SNAPSHOT) | BDRV_O_TEMPORARY;
802b1e6fc08SKevin Wolf }
803b1e6fc08SKevin Wolf 
804b1e6fc08SKevin Wolf /*
8050b50cc88SKevin Wolf  * Returns the flags that bs->file should get, based on the given flags for
8060b50cc88SKevin Wolf  * the parent BDS
8070b50cc88SKevin Wolf  */
8080b50cc88SKevin Wolf static int bdrv_inherited_flags(int flags)
8090b50cc88SKevin Wolf {
8100b50cc88SKevin Wolf     /* Enable protocol handling, disable format probing for bs->file */
8110b50cc88SKevin Wolf     flags |= BDRV_O_PROTOCOL;
8120b50cc88SKevin Wolf 
8130b50cc88SKevin Wolf     /* Our block drivers take care to send flushes and respect unmap policy,
8140b50cc88SKevin Wolf      * so we can enable both unconditionally on lower layers. */
8150b50cc88SKevin Wolf     flags |= BDRV_O_CACHE_WB | BDRV_O_UNMAP;
8160b50cc88SKevin Wolf 
8170b50cc88SKevin Wolf     /* Clear flags that only apply to the top layer */
8185669b44dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_COPY_ON_READ);
8190b50cc88SKevin Wolf 
8200b50cc88SKevin Wolf     return flags;
8210b50cc88SKevin Wolf }
8220b50cc88SKevin Wolf 
823317fc44eSKevin Wolf /*
824317fc44eSKevin Wolf  * Returns the flags that bs->backing_hd should get, based on the given flags
825317fc44eSKevin Wolf  * for the parent BDS
826317fc44eSKevin Wolf  */
827317fc44eSKevin Wolf static int bdrv_backing_flags(int flags)
828317fc44eSKevin Wolf {
829317fc44eSKevin Wolf     /* backing files always opened read-only */
830317fc44eSKevin Wolf     flags &= ~(BDRV_O_RDWR | BDRV_O_COPY_ON_READ);
831317fc44eSKevin Wolf 
832317fc44eSKevin Wolf     /* snapshot=on is handled on the top layer */
8338bfea15dSKevin Wolf     flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_TEMPORARY);
834317fc44eSKevin Wolf 
835317fc44eSKevin Wolf     return flags;
836317fc44eSKevin Wolf }
837317fc44eSKevin Wolf 
8387b272452SKevin Wolf static int bdrv_open_flags(BlockDriverState *bs, int flags)
8397b272452SKevin Wolf {
8407b272452SKevin Wolf     int open_flags = flags | BDRV_O_CACHE_WB;
8417b272452SKevin Wolf 
8427b272452SKevin Wolf     /*
8437b272452SKevin Wolf      * Clear flags that are internal to the block layer before opening the
8447b272452SKevin Wolf      * image.
8457b272452SKevin Wolf      */
84620cca275SKevin Wolf     open_flags &= ~(BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING | BDRV_O_PROTOCOL);
8477b272452SKevin Wolf 
8487b272452SKevin Wolf     /*
8497b272452SKevin Wolf      * Snapshots should be writable.
8507b272452SKevin Wolf      */
8518bfea15dSKevin Wolf     if (flags & BDRV_O_TEMPORARY) {
8527b272452SKevin Wolf         open_flags |= BDRV_O_RDWR;
8537b272452SKevin Wolf     }
8547b272452SKevin Wolf 
8557b272452SKevin Wolf     return open_flags;
8567b272452SKevin Wolf }
8577b272452SKevin Wolf 
858636ea370SKevin Wolf static void bdrv_assign_node_name(BlockDriverState *bs,
8596913c0c2SBenoît Canet                                   const char *node_name,
8606913c0c2SBenoît Canet                                   Error **errp)
8616913c0c2SBenoît Canet {
8626913c0c2SBenoît Canet     if (!node_name) {
863636ea370SKevin Wolf         return;
8646913c0c2SBenoît Canet     }
8656913c0c2SBenoît Canet 
8666913c0c2SBenoît Canet     /* empty string node name is invalid */
8676913c0c2SBenoît Canet     if (node_name[0] == '\0') {
8686913c0c2SBenoît Canet         error_setg(errp, "Empty node name");
869636ea370SKevin Wolf         return;
8706913c0c2SBenoît Canet     }
8716913c0c2SBenoît Canet 
8720c5e94eeSBenoît Canet     /* takes care of avoiding namespaces collisions */
8730c5e94eeSBenoît Canet     if (bdrv_find(node_name)) {
8740c5e94eeSBenoît Canet         error_setg(errp, "node-name=%s is conflicting with a device id",
8750c5e94eeSBenoît Canet                    node_name);
876636ea370SKevin Wolf         return;
8770c5e94eeSBenoît Canet     }
8780c5e94eeSBenoît Canet 
8796913c0c2SBenoît Canet     /* takes care of avoiding duplicates node names */
8806913c0c2SBenoît Canet     if (bdrv_find_node(node_name)) {
8816913c0c2SBenoît Canet         error_setg(errp, "Duplicate node name");
882636ea370SKevin Wolf         return;
8836913c0c2SBenoît Canet     }
8846913c0c2SBenoît Canet 
8856913c0c2SBenoît Canet     /* copy node name into the bs and insert it into the graph list */
8866913c0c2SBenoît Canet     pstrcpy(bs->node_name, sizeof(bs->node_name), node_name);
8876913c0c2SBenoît Canet     QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs, node_list);
8886913c0c2SBenoît Canet }
8896913c0c2SBenoît Canet 
890b6ce07aaSKevin Wolf /*
89157915332SKevin Wolf  * Common part for opening disk images and files
892b6ad491aSKevin Wolf  *
893b6ad491aSKevin Wolf  * Removes all processed options from *options.
89457915332SKevin Wolf  */
895f500a6d3SKevin Wolf static int bdrv_open_common(BlockDriverState *bs, BlockDriverState *file,
89634b5d2c6SMax Reitz     QDict *options, int flags, BlockDriver *drv, Error **errp)
89757915332SKevin Wolf {
89857915332SKevin Wolf     int ret, open_flags;
899035fccdfSKevin Wolf     const char *filename;
9006913c0c2SBenoît Canet     const char *node_name = NULL;
90134b5d2c6SMax Reitz     Error *local_err = NULL;
90257915332SKevin Wolf 
90357915332SKevin Wolf     assert(drv != NULL);
9046405875cSPaolo Bonzini     assert(bs->file == NULL);
905707ff828SKevin Wolf     assert(options != NULL && bs->options != options);
90657915332SKevin Wolf 
90745673671SKevin Wolf     if (file != NULL) {
90845673671SKevin Wolf         filename = file->filename;
90945673671SKevin Wolf     } else {
91045673671SKevin Wolf         filename = qdict_get_try_str(options, "filename");
91145673671SKevin Wolf     }
91245673671SKevin Wolf 
913765003dbSKevin Wolf     if (drv->bdrv_needs_filename && !filename) {
914765003dbSKevin Wolf         error_setg(errp, "The '%s' block driver requires a file name",
915765003dbSKevin Wolf                    drv->format_name);
916765003dbSKevin Wolf         return -EINVAL;
917765003dbSKevin Wolf     }
918765003dbSKevin Wolf 
91945673671SKevin Wolf     trace_bdrv_open_common(bs, filename ?: "", flags, drv->format_name);
92028dcee10SStefan Hajnoczi 
9216913c0c2SBenoît Canet     node_name = qdict_get_try_str(options, "node-name");
922636ea370SKevin Wolf     bdrv_assign_node_name(bs, node_name, &local_err);
9230fb6395cSMarkus Armbruster     if (local_err) {
924636ea370SKevin Wolf         error_propagate(errp, local_err);
925636ea370SKevin Wolf         return -EINVAL;
9266913c0c2SBenoît Canet     }
9276913c0c2SBenoît Canet     qdict_del(options, "node-name");
9286913c0c2SBenoît Canet 
9295d186eb0SKevin Wolf     /* bdrv_open() with directly using a protocol as drv. This layer is already
9305d186eb0SKevin Wolf      * opened, so assign it to bs (while file becomes a closed BlockDriverState)
9315d186eb0SKevin Wolf      * and return immediately. */
9325d186eb0SKevin Wolf     if (file != NULL && drv->bdrv_file_open) {
9335d186eb0SKevin Wolf         bdrv_swap(file, bs);
9345d186eb0SKevin Wolf         return 0;
9355d186eb0SKevin Wolf     }
9365d186eb0SKevin Wolf 
93757915332SKevin Wolf     bs->open_flags = flags;
9381b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
939c25f53b0SPaolo Bonzini     bs->request_alignment = 512;
9400d51b4deSAsias He     bs->zero_beyond_eof = true;
941b64ec4e4SFam Zheng     open_flags = bdrv_open_flags(bs, flags);
942b64ec4e4SFam Zheng     bs->read_only = !(open_flags & BDRV_O_RDWR);
94320cca275SKevin Wolf     bs->growable = !!(flags & BDRV_O_PROTOCOL);
944b64ec4e4SFam Zheng 
945b64ec4e4SFam Zheng     if (use_bdrv_whitelist && !bdrv_is_whitelisted(drv, bs->read_only)) {
9468f94a6e4SKevin Wolf         error_setg(errp,
9478f94a6e4SKevin Wolf                    !bs->read_only && bdrv_is_whitelisted(drv, true)
9488f94a6e4SKevin Wolf                         ? "Driver '%s' can only be used for read-only devices"
9498f94a6e4SKevin Wolf                         : "Driver '%s' is not whitelisted",
9508f94a6e4SKevin Wolf                    drv->format_name);
951b64ec4e4SFam Zheng         return -ENOTSUP;
952b64ec4e4SFam Zheng     }
95357915332SKevin Wolf 
95453fec9d3SStefan Hajnoczi     assert(bs->copy_on_read == 0); /* bdrv_new() and bdrv_close() make it so */
9550ebd24e0SKevin Wolf     if (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");
9600ebd24e0SKevin Wolf             return -EINVAL;
9610ebd24e0SKevin Wolf         }
96253fec9d3SStefan Hajnoczi     }
96353fec9d3SStefan Hajnoczi 
964c2ad1b0cSKevin Wolf     if (filename != NULL) {
96557915332SKevin Wolf         pstrcpy(bs->filename, sizeof(bs->filename), filename);
966c2ad1b0cSKevin Wolf     } else {
967c2ad1b0cSKevin Wolf         bs->filename[0] = '\0';
968c2ad1b0cSKevin Wolf     }
96991af7014SMax Reitz     pstrcpy(bs->exact_filename, sizeof(bs->exact_filename), bs->filename);
97057915332SKevin Wolf 
97157915332SKevin Wolf     bs->drv = drv;
9727267c094SAnthony Liguori     bs->opaque = g_malloc0(drv->instance_size);
97357915332SKevin Wolf 
97403f541bdSStefan Hajnoczi     bs->enable_write_cache = !!(flags & BDRV_O_CACHE_WB);
975e7c63796SStefan Hajnoczi 
97666f82ceeSKevin Wolf     /* Open the image, either directly or using a protocol */
97766f82ceeSKevin Wolf     if (drv->bdrv_file_open) {
9785d186eb0SKevin Wolf         assert(file == NULL);
979030be321SBenoît Canet         assert(!drv->bdrv_needs_filename || filename != NULL);
98034b5d2c6SMax Reitz         ret = drv->bdrv_file_open(bs, options, open_flags, &local_err);
981f500a6d3SKevin Wolf     } else {
9822af5ef70SKevin Wolf         if (file == NULL) {
98334b5d2c6SMax Reitz             error_setg(errp, "Can't use '%s' as a block driver for the "
98434b5d2c6SMax Reitz                        "protocol level", drv->format_name);
9852af5ef70SKevin Wolf             ret = -EINVAL;
9862af5ef70SKevin Wolf             goto free_and_fail;
9872af5ef70SKevin Wolf         }
988f500a6d3SKevin Wolf         bs->file = file;
98934b5d2c6SMax Reitz         ret = drv->bdrv_open(bs, options, open_flags, &local_err);
99066f82ceeSKevin Wolf     }
99166f82ceeSKevin Wolf 
99257915332SKevin Wolf     if (ret < 0) {
99384d18f06SMarkus Armbruster         if (local_err) {
99434b5d2c6SMax Reitz             error_propagate(errp, local_err);
9952fa9aa59SDunrong Huang         } else if (bs->filename[0]) {
9962fa9aa59SDunrong Huang             error_setg_errno(errp, -ret, "Could not open '%s'", bs->filename);
99734b5d2c6SMax Reitz         } else {
99834b5d2c6SMax Reitz             error_setg_errno(errp, -ret, "Could not open image");
99934b5d2c6SMax Reitz         }
100057915332SKevin Wolf         goto free_and_fail;
100157915332SKevin Wolf     }
100257915332SKevin Wolf 
100351762288SStefan Hajnoczi     ret = refresh_total_sectors(bs, bs->total_sectors);
100451762288SStefan Hajnoczi     if (ret < 0) {
100534b5d2c6SMax Reitz         error_setg_errno(errp, -ret, "Could not refresh total sector count");
100651762288SStefan Hajnoczi         goto free_and_fail;
100757915332SKevin Wolf     }
100851762288SStefan Hajnoczi 
10093baca891SKevin Wolf     bdrv_refresh_limits(bs, &local_err);
10103baca891SKevin Wolf     if (local_err) {
10113baca891SKevin Wolf         error_propagate(errp, local_err);
10123baca891SKevin Wolf         ret = -EINVAL;
10133baca891SKevin Wolf         goto free_and_fail;
10143baca891SKevin Wolf     }
10153baca891SKevin Wolf 
1016c25f53b0SPaolo Bonzini     assert(bdrv_opt_mem_align(bs) != 0);
101747ea2de2SKevin Wolf     assert((bs->request_alignment != 0) || bs->sg);
101857915332SKevin Wolf     return 0;
101957915332SKevin Wolf 
102057915332SKevin Wolf free_and_fail:
102166f82ceeSKevin Wolf     bs->file = NULL;
10227267c094SAnthony Liguori     g_free(bs->opaque);
102357915332SKevin Wolf     bs->opaque = NULL;
102457915332SKevin Wolf     bs->drv = NULL;
102557915332SKevin Wolf     return ret;
102657915332SKevin Wolf }
102757915332SKevin Wolf 
10285e5c4f63SKevin Wolf static QDict *parse_json_filename(const char *filename, Error **errp)
10295e5c4f63SKevin Wolf {
10305e5c4f63SKevin Wolf     QObject *options_obj;
10315e5c4f63SKevin Wolf     QDict *options;
10325e5c4f63SKevin Wolf     int ret;
10335e5c4f63SKevin Wolf 
10345e5c4f63SKevin Wolf     ret = strstart(filename, "json:", &filename);
10355e5c4f63SKevin Wolf     assert(ret);
10365e5c4f63SKevin Wolf 
10375e5c4f63SKevin Wolf     options_obj = qobject_from_json(filename);
10385e5c4f63SKevin Wolf     if (!options_obj) {
10395e5c4f63SKevin Wolf         error_setg(errp, "Could not parse the JSON options");
10405e5c4f63SKevin Wolf         return NULL;
10415e5c4f63SKevin Wolf     }
10425e5c4f63SKevin Wolf 
10435e5c4f63SKevin Wolf     if (qobject_type(options_obj) != QTYPE_QDICT) {
10445e5c4f63SKevin Wolf         qobject_decref(options_obj);
10455e5c4f63SKevin Wolf         error_setg(errp, "Invalid JSON object given");
10465e5c4f63SKevin Wolf         return NULL;
10475e5c4f63SKevin Wolf     }
10485e5c4f63SKevin Wolf 
10495e5c4f63SKevin Wolf     options = qobject_to_qdict(options_obj);
10505e5c4f63SKevin Wolf     qdict_flatten(options);
10515e5c4f63SKevin Wolf 
10525e5c4f63SKevin Wolf     return options;
10535e5c4f63SKevin Wolf }
10545e5c4f63SKevin Wolf 
105557915332SKevin Wolf /*
1056f54120ffSKevin Wolf  * Fills in default options for opening images and converts the legacy
1057f54120ffSKevin Wolf  * filename/flags pair to option QDict entries.
1058f54120ffSKevin Wolf  */
10595e5c4f63SKevin Wolf static int bdrv_fill_options(QDict **options, const char **pfilename, int flags,
106017b005f1SKevin Wolf                              BlockDriver *drv, Error **errp)
1061f54120ffSKevin Wolf {
10625e5c4f63SKevin Wolf     const char *filename = *pfilename;
1063f54120ffSKevin Wolf     const char *drvname;
1064462f5bcfSKevin Wolf     bool protocol = flags & BDRV_O_PROTOCOL;
1065f54120ffSKevin Wolf     bool parse_filename = false;
1066f54120ffSKevin Wolf     Error *local_err = NULL;
1067f54120ffSKevin Wolf 
10685e5c4f63SKevin Wolf     /* Parse json: pseudo-protocol */
10695e5c4f63SKevin Wolf     if (filename && g_str_has_prefix(filename, "json:")) {
10705e5c4f63SKevin Wolf         QDict *json_options = parse_json_filename(filename, &local_err);
10715e5c4f63SKevin Wolf         if (local_err) {
10725e5c4f63SKevin Wolf             error_propagate(errp, local_err);
10735e5c4f63SKevin Wolf             return -EINVAL;
10745e5c4f63SKevin Wolf         }
10755e5c4f63SKevin Wolf 
10765e5c4f63SKevin Wolf         /* Options given in the filename have lower priority than options
10775e5c4f63SKevin Wolf          * specified directly */
10785e5c4f63SKevin Wolf         qdict_join(*options, json_options, false);
10795e5c4f63SKevin Wolf         QDECREF(json_options);
10805e5c4f63SKevin Wolf         *pfilename = filename = NULL;
10815e5c4f63SKevin Wolf     }
10825e5c4f63SKevin Wolf 
1083f54120ffSKevin Wolf     /* Fetch the file name from the options QDict if necessary */
108417b005f1SKevin Wolf     if (protocol && filename) {
1085f54120ffSKevin Wolf         if (!qdict_haskey(*options, "filename")) {
1086f54120ffSKevin Wolf             qdict_put(*options, "filename", qstring_from_str(filename));
1087f54120ffSKevin Wolf             parse_filename = true;
1088f54120ffSKevin Wolf         } else {
1089f54120ffSKevin Wolf             error_setg(errp, "Can't specify 'file' and 'filename' options at "
1090f54120ffSKevin Wolf                              "the same time");
1091f54120ffSKevin Wolf             return -EINVAL;
1092f54120ffSKevin Wolf         }
1093f54120ffSKevin Wolf     }
1094f54120ffSKevin Wolf 
1095f54120ffSKevin Wolf     /* Find the right block driver */
1096f54120ffSKevin Wolf     filename = qdict_get_try_str(*options, "filename");
1097f54120ffSKevin Wolf     drvname = qdict_get_try_str(*options, "driver");
1098f54120ffSKevin Wolf 
109917b005f1SKevin Wolf     if (drv) {
110017b005f1SKevin Wolf         if (drvname) {
110117b005f1SKevin Wolf             error_setg(errp, "Driver specified twice");
110217b005f1SKevin Wolf             return -EINVAL;
110317b005f1SKevin Wolf         }
110417b005f1SKevin Wolf         drvname = drv->format_name;
110517b005f1SKevin Wolf         qdict_put(*options, "driver", qstring_from_str(drvname));
110617b005f1SKevin Wolf     } else {
110717b005f1SKevin Wolf         if (!drvname && protocol) {
1108f54120ffSKevin Wolf             if (filename) {
1109f54120ffSKevin Wolf                 drv = bdrv_find_protocol(filename, parse_filename);
1110f54120ffSKevin Wolf                 if (!drv) {
1111f54120ffSKevin Wolf                     error_setg(errp, "Unknown protocol");
1112f54120ffSKevin Wolf                     return -EINVAL;
1113f54120ffSKevin Wolf                 }
1114f54120ffSKevin Wolf 
1115f54120ffSKevin Wolf                 drvname = drv->format_name;
1116f54120ffSKevin Wolf                 qdict_put(*options, "driver", qstring_from_str(drvname));
1117f54120ffSKevin Wolf             } else {
1118f54120ffSKevin Wolf                 error_setg(errp, "Must specify either driver or file");
1119f54120ffSKevin Wolf                 return -EINVAL;
1120f54120ffSKevin Wolf             }
112117b005f1SKevin Wolf         } else if (drvname) {
1122f54120ffSKevin Wolf             drv = bdrv_find_format(drvname);
1123f54120ffSKevin Wolf             if (!drv) {
1124f54120ffSKevin Wolf                 error_setg(errp, "Unknown driver '%s'", drvname);
1125f54120ffSKevin Wolf                 return -ENOENT;
1126f54120ffSKevin Wolf             }
112717b005f1SKevin Wolf         }
112817b005f1SKevin Wolf     }
112917b005f1SKevin Wolf 
113017b005f1SKevin Wolf     assert(drv || !protocol);
1131f54120ffSKevin Wolf 
1132f54120ffSKevin Wolf     /* Driver-specific filename parsing */
113317b005f1SKevin Wolf     if (drv && drv->bdrv_parse_filename && parse_filename) {
1134f54120ffSKevin Wolf         drv->bdrv_parse_filename(filename, *options, &local_err);
1135f54120ffSKevin Wolf         if (local_err) {
1136f54120ffSKevin Wolf             error_propagate(errp, local_err);
1137f54120ffSKevin Wolf             return -EINVAL;
1138f54120ffSKevin Wolf         }
1139f54120ffSKevin Wolf 
1140f54120ffSKevin Wolf         if (!drv->bdrv_needs_filename) {
1141f54120ffSKevin Wolf             qdict_del(*options, "filename");
1142f54120ffSKevin Wolf         }
1143f54120ffSKevin Wolf     }
1144f54120ffSKevin Wolf 
1145f54120ffSKevin Wolf     return 0;
1146f54120ffSKevin Wolf }
1147f54120ffSKevin Wolf 
11488d24cce1SFam Zheng void bdrv_set_backing_hd(BlockDriverState *bs, BlockDriverState *backing_hd)
11498d24cce1SFam Zheng {
11508d24cce1SFam Zheng 
1151826b6ca0SFam Zheng     if (bs->backing_hd) {
1152826b6ca0SFam Zheng         assert(bs->backing_blocker);
1153826b6ca0SFam Zheng         bdrv_op_unblock_all(bs->backing_hd, bs->backing_blocker);
1154826b6ca0SFam Zheng     } else if (backing_hd) {
1155826b6ca0SFam Zheng         error_setg(&bs->backing_blocker,
1156826b6ca0SFam Zheng                    "device is used as backing hd of '%s'",
1157826b6ca0SFam Zheng                    bs->device_name);
1158826b6ca0SFam Zheng     }
1159826b6ca0SFam Zheng 
11608d24cce1SFam Zheng     bs->backing_hd = backing_hd;
11618d24cce1SFam Zheng     if (!backing_hd) {
1162826b6ca0SFam Zheng         error_free(bs->backing_blocker);
1163826b6ca0SFam Zheng         bs->backing_blocker = NULL;
11648d24cce1SFam Zheng         goto out;
11658d24cce1SFam Zheng     }
11668d24cce1SFam Zheng     bs->open_flags &= ~BDRV_O_NO_BACKING;
11678d24cce1SFam Zheng     pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_hd->filename);
11688d24cce1SFam Zheng     pstrcpy(bs->backing_format, sizeof(bs->backing_format),
11698d24cce1SFam Zheng             backing_hd->drv ? backing_hd->drv->format_name : "");
1170826b6ca0SFam Zheng 
1171826b6ca0SFam Zheng     bdrv_op_block_all(bs->backing_hd, bs->backing_blocker);
1172826b6ca0SFam Zheng     /* Otherwise we won't be able to commit due to check in bdrv_commit */
1173826b6ca0SFam Zheng     bdrv_op_unblock(bs->backing_hd, BLOCK_OP_TYPE_COMMIT,
1174826b6ca0SFam Zheng                     bs->backing_blocker);
11758d24cce1SFam Zheng out:
11763baca891SKevin Wolf     bdrv_refresh_limits(bs, NULL);
11778d24cce1SFam Zheng }
11788d24cce1SFam Zheng 
117931ca6d07SKevin Wolf /*
118031ca6d07SKevin Wolf  * Opens the backing file for a BlockDriverState if not yet open
118131ca6d07SKevin Wolf  *
118231ca6d07SKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
118331ca6d07SKevin Wolf  * empty set of options. The reference to the QDict is transferred to this
118431ca6d07SKevin Wolf  * function (even on failure), so if the caller intends to reuse the dictionary,
118531ca6d07SKevin Wolf  * it needs to use QINCREF() before calling bdrv_file_open.
118631ca6d07SKevin Wolf  */
118734b5d2c6SMax Reitz int bdrv_open_backing_file(BlockDriverState *bs, QDict *options, Error **errp)
11889156df12SPaolo Bonzini {
11891ba4b6a5SBenoît Canet     char *backing_filename = g_malloc0(PATH_MAX);
1190317fc44eSKevin Wolf     int ret = 0;
11919156df12SPaolo Bonzini     BlockDriver *back_drv = NULL;
11928d24cce1SFam Zheng     BlockDriverState *backing_hd;
119334b5d2c6SMax Reitz     Error *local_err = NULL;
11949156df12SPaolo Bonzini 
11959156df12SPaolo Bonzini     if (bs->backing_hd != NULL) {
119631ca6d07SKevin Wolf         QDECREF(options);
11971ba4b6a5SBenoît Canet         goto free_exit;
11989156df12SPaolo Bonzini     }
11999156df12SPaolo Bonzini 
120031ca6d07SKevin Wolf     /* NULL means an empty set of options */
120131ca6d07SKevin Wolf     if (options == NULL) {
120231ca6d07SKevin Wolf         options = qdict_new();
120331ca6d07SKevin Wolf     }
120431ca6d07SKevin Wolf 
12059156df12SPaolo Bonzini     bs->open_flags &= ~BDRV_O_NO_BACKING;
12061cb6f506SKevin Wolf     if (qdict_haskey(options, "file.filename")) {
12071cb6f506SKevin Wolf         backing_filename[0] = '\0';
12081cb6f506SKevin Wolf     } else if (bs->backing_file[0] == '\0' && qdict_size(options) == 0) {
120931ca6d07SKevin Wolf         QDECREF(options);
12101ba4b6a5SBenoît Canet         goto free_exit;
1211dbecebddSFam Zheng     } else {
12121ba4b6a5SBenoît Canet         bdrv_get_full_backing_filename(bs, backing_filename, PATH_MAX);
12139156df12SPaolo Bonzini     }
12149156df12SPaolo Bonzini 
12158ee79e70SKevin Wolf     if (!bs->drv || !bs->drv->supports_backing) {
12168ee79e70SKevin Wolf         ret = -EINVAL;
12178ee79e70SKevin Wolf         error_setg(errp, "Driver doesn't support backing files");
12188ee79e70SKevin Wolf         QDECREF(options);
12198ee79e70SKevin Wolf         goto free_exit;
12208ee79e70SKevin Wolf     }
12218ee79e70SKevin Wolf 
12228d24cce1SFam Zheng     backing_hd = bdrv_new("", errp);
12238d24cce1SFam Zheng 
12249156df12SPaolo Bonzini     if (bs->backing_format[0] != '\0') {
12259156df12SPaolo Bonzini         back_drv = bdrv_find_format(bs->backing_format);
12269156df12SPaolo Bonzini     }
12279156df12SPaolo Bonzini 
1228f67503e5SMax Reitz     assert(bs->backing_hd == NULL);
12298d24cce1SFam Zheng     ret = bdrv_open(&backing_hd,
1230ddf5636dSMax Reitz                     *backing_filename ? backing_filename : NULL, NULL, options,
1231317fc44eSKevin Wolf                     bdrv_backing_flags(bs->open_flags), back_drv, &local_err);
12329156df12SPaolo Bonzini     if (ret < 0) {
12338d24cce1SFam Zheng         bdrv_unref(backing_hd);
12348d24cce1SFam Zheng         backing_hd = NULL;
12359156df12SPaolo Bonzini         bs->open_flags |= BDRV_O_NO_BACKING;
1236b04b6b6eSFam Zheng         error_setg(errp, "Could not open backing file: %s",
1237b04b6b6eSFam Zheng                    error_get_pretty(local_err));
1238b04b6b6eSFam Zheng         error_free(local_err);
12391ba4b6a5SBenoît Canet         goto free_exit;
12409156df12SPaolo Bonzini     }
12418d24cce1SFam Zheng     bdrv_set_backing_hd(bs, backing_hd);
1242d80ac658SPeter Feiner 
12431ba4b6a5SBenoît Canet free_exit:
12441ba4b6a5SBenoît Canet     g_free(backing_filename);
12451ba4b6a5SBenoît Canet     return ret;
12469156df12SPaolo Bonzini }
12479156df12SPaolo Bonzini 
1248b6ce07aaSKevin Wolf /*
1249da557aacSMax Reitz  * Opens a disk image whose options are given as BlockdevRef in another block
1250da557aacSMax Reitz  * device's options.
1251da557aacSMax Reitz  *
1252da557aacSMax Reitz  * If allow_none is true, no image will be opened if filename is false and no
1253da557aacSMax Reitz  * BlockdevRef is given. *pbs will remain unchanged and 0 will be returned.
1254da557aacSMax Reitz  *
1255da557aacSMax Reitz  * bdrev_key specifies the key for the image's BlockdevRef in the options QDict.
1256da557aacSMax Reitz  * That QDict has to be flattened; therefore, if the BlockdevRef is a QDict
1257da557aacSMax Reitz  * itself, all options starting with "${bdref_key}." are considered part of the
1258da557aacSMax Reitz  * BlockdevRef.
1259da557aacSMax Reitz  *
1260da557aacSMax Reitz  * The BlockdevRef will be removed from the options QDict.
1261f67503e5SMax Reitz  *
1262f67503e5SMax Reitz  * To conform with the behavior of bdrv_open(), *pbs has to be NULL.
1263da557aacSMax Reitz  */
1264da557aacSMax Reitz int bdrv_open_image(BlockDriverState **pbs, const char *filename,
1265da557aacSMax Reitz                     QDict *options, const char *bdref_key, int flags,
1266f7d9fd8cSMax Reitz                     bool allow_none, Error **errp)
1267da557aacSMax Reitz {
1268da557aacSMax Reitz     QDict *image_options;
1269da557aacSMax Reitz     int ret;
1270da557aacSMax Reitz     char *bdref_key_dot;
1271da557aacSMax Reitz     const char *reference;
1272da557aacSMax Reitz 
1273f67503e5SMax Reitz     assert(pbs);
1274f67503e5SMax Reitz     assert(*pbs == NULL);
1275f67503e5SMax Reitz 
1276da557aacSMax Reitz     bdref_key_dot = g_strdup_printf("%s.", bdref_key);
1277da557aacSMax Reitz     qdict_extract_subqdict(options, &image_options, bdref_key_dot);
1278da557aacSMax Reitz     g_free(bdref_key_dot);
1279da557aacSMax Reitz 
1280da557aacSMax Reitz     reference = qdict_get_try_str(options, bdref_key);
1281da557aacSMax Reitz     if (!filename && !reference && !qdict_size(image_options)) {
1282da557aacSMax Reitz         if (allow_none) {
1283da557aacSMax Reitz             ret = 0;
1284da557aacSMax Reitz         } else {
1285da557aacSMax Reitz             error_setg(errp, "A block device must be specified for \"%s\"",
1286da557aacSMax Reitz                        bdref_key);
1287da557aacSMax Reitz             ret = -EINVAL;
1288da557aacSMax Reitz         }
1289b20e61e0SMarkus Armbruster         QDECREF(image_options);
1290da557aacSMax Reitz         goto done;
1291da557aacSMax Reitz     }
1292da557aacSMax Reitz 
1293f7d9fd8cSMax Reitz     ret = bdrv_open(pbs, filename, reference, image_options, flags, NULL, errp);
1294da557aacSMax Reitz 
1295da557aacSMax Reitz done:
1296da557aacSMax Reitz     qdict_del(options, bdref_key);
1297da557aacSMax Reitz     return ret;
1298da557aacSMax Reitz }
1299da557aacSMax Reitz 
13006b8aeca5SChen Gang int bdrv_append_temp_snapshot(BlockDriverState *bs, int flags, Error **errp)
1301b998875dSKevin Wolf {
1302b998875dSKevin Wolf     /* TODO: extra byte is a hack to ensure MAX_PATH space on Windows. */
13031ba4b6a5SBenoît Canet     char *tmp_filename = g_malloc0(PATH_MAX + 1);
1304b998875dSKevin Wolf     int64_t total_size;
1305b998875dSKevin Wolf     BlockDriver *bdrv_qcow2;
130683d0521aSChunyan Liu     QemuOpts *opts = NULL;
1307b998875dSKevin Wolf     QDict *snapshot_options;
1308b998875dSKevin Wolf     BlockDriverState *bs_snapshot;
1309b998875dSKevin Wolf     Error *local_err;
1310b998875dSKevin Wolf     int ret;
1311b998875dSKevin Wolf 
1312b998875dSKevin Wolf     /* if snapshot, we create a temporary backing file and open it
1313b998875dSKevin Wolf        instead of opening 'filename' directly */
1314b998875dSKevin Wolf 
1315b998875dSKevin Wolf     /* Get the required size from the image */
1316f187743aSKevin Wolf     total_size = bdrv_getlength(bs);
1317f187743aSKevin Wolf     if (total_size < 0) {
13186b8aeca5SChen Gang         ret = total_size;
1319f187743aSKevin Wolf         error_setg_errno(errp, -total_size, "Could not get image size");
13201ba4b6a5SBenoît Canet         goto out;
1321f187743aSKevin Wolf     }
1322b998875dSKevin Wolf 
1323b998875dSKevin Wolf     /* Create the temporary image */
13241ba4b6a5SBenoît Canet     ret = get_tmp_filename(tmp_filename, PATH_MAX + 1);
1325b998875dSKevin Wolf     if (ret < 0) {
1326b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not get temporary filename");
13271ba4b6a5SBenoît Canet         goto out;
1328b998875dSKevin Wolf     }
1329b998875dSKevin Wolf 
1330b998875dSKevin Wolf     bdrv_qcow2 = bdrv_find_format("qcow2");
1331c282e1fdSChunyan Liu     opts = qemu_opts_create(bdrv_qcow2->create_opts, NULL, 0,
1332c282e1fdSChunyan Liu                             &error_abort);
133383d0521aSChunyan Liu     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, total_size);
1334c282e1fdSChunyan Liu     ret = bdrv_create(bdrv_qcow2, tmp_filename, opts, &local_err);
133583d0521aSChunyan Liu     qemu_opts_del(opts);
1336b998875dSKevin Wolf     if (ret < 0) {
1337b998875dSKevin Wolf         error_setg_errno(errp, -ret, "Could not create temporary overlay "
1338b998875dSKevin Wolf                          "'%s': %s", tmp_filename,
1339b998875dSKevin Wolf                          error_get_pretty(local_err));
1340b998875dSKevin Wolf         error_free(local_err);
13411ba4b6a5SBenoît Canet         goto out;
1342b998875dSKevin Wolf     }
1343b998875dSKevin Wolf 
1344b998875dSKevin Wolf     /* Prepare a new options QDict for the temporary file */
1345b998875dSKevin Wolf     snapshot_options = qdict_new();
1346b998875dSKevin Wolf     qdict_put(snapshot_options, "file.driver",
1347b998875dSKevin Wolf               qstring_from_str("file"));
1348b998875dSKevin Wolf     qdict_put(snapshot_options, "file.filename",
1349b998875dSKevin Wolf               qstring_from_str(tmp_filename));
1350b998875dSKevin Wolf 
135198522f63SKevin Wolf     bs_snapshot = bdrv_new("", &error_abort);
1352b998875dSKevin Wolf 
1353b998875dSKevin Wolf     ret = bdrv_open(&bs_snapshot, NULL, NULL, snapshot_options,
1354b1e6fc08SKevin Wolf                     flags, bdrv_qcow2, &local_err);
1355b998875dSKevin Wolf     if (ret < 0) {
1356b998875dSKevin Wolf         error_propagate(errp, local_err);
13571ba4b6a5SBenoît Canet         goto out;
1358b998875dSKevin Wolf     }
1359b998875dSKevin Wolf 
1360b998875dSKevin Wolf     bdrv_append(bs_snapshot, bs);
13611ba4b6a5SBenoît Canet 
13621ba4b6a5SBenoît Canet out:
13631ba4b6a5SBenoît Canet     g_free(tmp_filename);
13646b8aeca5SChen Gang     return ret;
1365b998875dSKevin Wolf }
1366b998875dSKevin Wolf 
1367da557aacSMax Reitz /*
1368b6ce07aaSKevin Wolf  * Opens a disk image (raw, qcow2, vmdk, ...)
1369de9c0cecSKevin Wolf  *
1370de9c0cecSKevin Wolf  * options is a QDict of options to pass to the block drivers, or NULL for an
1371de9c0cecSKevin Wolf  * empty set of options. The reference to the QDict belongs to the block layer
1372de9c0cecSKevin Wolf  * after the call (even on failure), so if the caller intends to reuse the
1373de9c0cecSKevin Wolf  * dictionary, it needs to use QINCREF() before calling bdrv_open.
1374f67503e5SMax Reitz  *
1375f67503e5SMax Reitz  * If *pbs is NULL, a new BDS will be created with a pointer to it stored there.
1376f67503e5SMax Reitz  * If it is not NULL, the referenced BDS will be reused.
1377ddf5636dSMax Reitz  *
1378ddf5636dSMax Reitz  * The reference parameter may be used to specify an existing block device which
1379ddf5636dSMax Reitz  * should be opened. If specified, neither options nor a filename may be given,
1380ddf5636dSMax Reitz  * nor can an existing BDS be reused (that is, *pbs has to be NULL).
1381b6ce07aaSKevin Wolf  */
1382ddf5636dSMax Reitz int bdrv_open(BlockDriverState **pbs, const char *filename,
1383ddf5636dSMax Reitz               const char *reference, QDict *options, int flags,
1384ddf5636dSMax Reitz               BlockDriver *drv, Error **errp)
1385ea2384d3Sbellard {
1386b6ce07aaSKevin Wolf     int ret;
1387f67503e5SMax Reitz     BlockDriverState *file = NULL, *bs;
138874fe54f2SKevin Wolf     const char *drvname;
138934b5d2c6SMax Reitz     Error *local_err = NULL;
1390b1e6fc08SKevin Wolf     int snapshot_flags = 0;
139133e3963eSbellard 
1392f67503e5SMax Reitz     assert(pbs);
1393f67503e5SMax Reitz 
1394ddf5636dSMax Reitz     if (reference) {
1395ddf5636dSMax Reitz         bool options_non_empty = options ? qdict_size(options) : false;
1396ddf5636dSMax Reitz         QDECREF(options);
1397ddf5636dSMax Reitz 
1398ddf5636dSMax Reitz         if (*pbs) {
1399ddf5636dSMax Reitz             error_setg(errp, "Cannot reuse an existing BDS when referencing "
1400ddf5636dSMax Reitz                        "another block device");
1401ddf5636dSMax Reitz             return -EINVAL;
1402ddf5636dSMax Reitz         }
1403ddf5636dSMax Reitz 
1404ddf5636dSMax Reitz         if (filename || options_non_empty) {
1405ddf5636dSMax Reitz             error_setg(errp, "Cannot reference an existing block device with "
1406ddf5636dSMax Reitz                        "additional options or a new filename");
1407ddf5636dSMax Reitz             return -EINVAL;
1408ddf5636dSMax Reitz         }
1409ddf5636dSMax Reitz 
1410ddf5636dSMax Reitz         bs = bdrv_lookup_bs(reference, reference, errp);
1411ddf5636dSMax Reitz         if (!bs) {
1412ddf5636dSMax Reitz             return -ENODEV;
1413ddf5636dSMax Reitz         }
1414ddf5636dSMax Reitz         bdrv_ref(bs);
1415ddf5636dSMax Reitz         *pbs = bs;
1416ddf5636dSMax Reitz         return 0;
1417ddf5636dSMax Reitz     }
1418ddf5636dSMax Reitz 
1419f67503e5SMax Reitz     if (*pbs) {
1420f67503e5SMax Reitz         bs = *pbs;
1421f67503e5SMax Reitz     } else {
142298522f63SKevin Wolf         bs = bdrv_new("", &error_abort);
1423f67503e5SMax Reitz     }
1424f67503e5SMax Reitz 
1425de9c0cecSKevin Wolf     /* NULL means an empty set of options */
1426de9c0cecSKevin Wolf     if (options == NULL) {
1427de9c0cecSKevin Wolf         options = qdict_new();
1428de9c0cecSKevin Wolf     }
1429de9c0cecSKevin Wolf 
143017b005f1SKevin Wolf     ret = bdrv_fill_options(&options, &filename, flags, drv, &local_err);
1431462f5bcfSKevin Wolf     if (local_err) {
1432462f5bcfSKevin Wolf         goto fail;
1433462f5bcfSKevin Wolf     }
1434462f5bcfSKevin Wolf 
143576c591b0SKevin Wolf     /* Find the right image format driver */
143676c591b0SKevin Wolf     drv = NULL;
143776c591b0SKevin Wolf     drvname = qdict_get_try_str(options, "driver");
143876c591b0SKevin Wolf     if (drvname) {
143976c591b0SKevin Wolf         drv = bdrv_find_format(drvname);
144076c591b0SKevin Wolf         qdict_del(options, "driver");
144176c591b0SKevin Wolf         if (!drv) {
144276c591b0SKevin Wolf             error_setg(errp, "Unknown driver: '%s'", drvname);
144376c591b0SKevin Wolf             ret = -EINVAL;
144476c591b0SKevin Wolf             goto fail;
144576c591b0SKevin Wolf         }
144676c591b0SKevin Wolf     }
144776c591b0SKevin Wolf 
144876c591b0SKevin Wolf     assert(drvname || !(flags & BDRV_O_PROTOCOL));
144976c591b0SKevin Wolf     if (drv && !drv->bdrv_file_open) {
145076c591b0SKevin Wolf         /* If the user explicitly wants a format driver here, we'll need to add
145176c591b0SKevin Wolf          * another layer for the protocol in bs->file */
145276c591b0SKevin Wolf         flags &= ~BDRV_O_PROTOCOL;
145376c591b0SKevin Wolf     }
145476c591b0SKevin Wolf 
1455de9c0cecSKevin Wolf     bs->options = options;
1456b6ad491aSKevin Wolf     options = qdict_clone_shallow(options);
1457de9c0cecSKevin Wolf 
1458f500a6d3SKevin Wolf     /* Open image file without format layer */
1459f4788adcSKevin Wolf     if ((flags & BDRV_O_PROTOCOL) == 0) {
1460be028adcSJeff Cody         if (flags & BDRV_O_RDWR) {
1461be028adcSJeff Cody             flags |= BDRV_O_ALLOW_RDWR;
1462be028adcSJeff Cody         }
1463b1e6fc08SKevin Wolf         if (flags & BDRV_O_SNAPSHOT) {
1464b1e6fc08SKevin Wolf             snapshot_flags = bdrv_temp_snapshot_flags(flags);
1465b1e6fc08SKevin Wolf             flags = bdrv_backing_flags(flags);
1466b1e6fc08SKevin Wolf         }
1467be028adcSJeff Cody 
1468f67503e5SMax Reitz         assert(file == NULL);
1469054963f8SMax Reitz         ret = bdrv_open_image(&file, filename, options, "file",
14700b50cc88SKevin Wolf                               bdrv_inherited_flags(flags),
14710b50cc88SKevin Wolf                               true, &local_err);
1472f500a6d3SKevin Wolf         if (ret < 0) {
14738bfea15dSKevin Wolf             goto fail;
1474f500a6d3SKevin Wolf         }
1475f4788adcSKevin Wolf     }
1476f500a6d3SKevin Wolf 
147776c591b0SKevin Wolf     /* Image format probing */
147876c591b0SKevin Wolf     if (!drv && file) {
147934b5d2c6SMax Reitz         ret = find_image_format(file, filename, &drv, &local_err);
148017b005f1SKevin Wolf         if (ret < 0) {
148117b005f1SKevin Wolf             goto fail;
148217b005f1SKevin Wolf         }
148376c591b0SKevin Wolf     } else if (!drv) {
14842a05cbe4SMax Reitz         error_setg(errp, "Must specify either driver or file");
14852a05cbe4SMax Reitz         ret = -EINVAL;
14868bfea15dSKevin Wolf         goto fail;
14872a05cbe4SMax Reitz     }
1488f500a6d3SKevin Wolf 
1489b6ce07aaSKevin Wolf     /* Open the image */
149034b5d2c6SMax Reitz     ret = bdrv_open_common(bs, file, options, flags, drv, &local_err);
1491b6ce07aaSKevin Wolf     if (ret < 0) {
14928bfea15dSKevin Wolf         goto fail;
14936987307cSChristoph Hellwig     }
14946987307cSChristoph Hellwig 
14952a05cbe4SMax Reitz     if (file && (bs->file != file)) {
14964f6fd349SFam Zheng         bdrv_unref(file);
1497f500a6d3SKevin Wolf         file = NULL;
1498f500a6d3SKevin Wolf     }
1499f500a6d3SKevin Wolf 
1500b6ce07aaSKevin Wolf     /* If there is a backing file, use it */
15019156df12SPaolo Bonzini     if ((flags & BDRV_O_NO_BACKING) == 0) {
150231ca6d07SKevin Wolf         QDict *backing_options;
150331ca6d07SKevin Wolf 
15045726d872SBenoît Canet         qdict_extract_subqdict(options, &backing_options, "backing.");
150534b5d2c6SMax Reitz         ret = bdrv_open_backing_file(bs, backing_options, &local_err);
1506b6ce07aaSKevin Wolf         if (ret < 0) {
1507b6ad491aSKevin Wolf             goto close_and_fail;
1508b6ce07aaSKevin Wolf         }
1509b6ce07aaSKevin Wolf     }
1510b6ce07aaSKevin Wolf 
151191af7014SMax Reitz     bdrv_refresh_filename(bs);
151291af7014SMax Reitz 
1513b998875dSKevin Wolf     /* For snapshot=on, create a temporary qcow2 overlay. bs points to the
1514b998875dSKevin Wolf      * temporary snapshot afterwards. */
1515b1e6fc08SKevin Wolf     if (snapshot_flags) {
15166b8aeca5SChen Gang         ret = bdrv_append_temp_snapshot(bs, snapshot_flags, &local_err);
1517b998875dSKevin Wolf         if (local_err) {
1518b998875dSKevin Wolf             goto close_and_fail;
1519b998875dSKevin Wolf         }
1520b998875dSKevin Wolf     }
1521b998875dSKevin Wolf 
1522b6ad491aSKevin Wolf     /* Check if any unknown options were used */
15235acd9d81SMax Reitz     if (options && (qdict_size(options) != 0)) {
1524b6ad491aSKevin Wolf         const QDictEntry *entry = qdict_first(options);
15255acd9d81SMax Reitz         if (flags & BDRV_O_PROTOCOL) {
15265acd9d81SMax Reitz             error_setg(errp, "Block protocol '%s' doesn't support the option "
15275acd9d81SMax Reitz                        "'%s'", drv->format_name, entry->key);
15285acd9d81SMax Reitz         } else {
152934b5d2c6SMax Reitz             error_setg(errp, "Block format '%s' used by device '%s' doesn't "
15305acd9d81SMax Reitz                        "support the option '%s'", drv->format_name,
15315acd9d81SMax Reitz                        bs->device_name, entry->key);
15325acd9d81SMax Reitz         }
1533b6ad491aSKevin Wolf 
1534b6ad491aSKevin Wolf         ret = -EINVAL;
1535b6ad491aSKevin Wolf         goto close_and_fail;
1536b6ad491aSKevin Wolf     }
1537b6ad491aSKevin Wolf 
1538b6ce07aaSKevin Wolf     if (!bdrv_key_required(bs)) {
15397d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
1540c3adb58fSMarkus Armbruster     } else if (!runstate_check(RUN_STATE_PRELAUNCH)
1541c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_INMIGRATE)
1542c3adb58fSMarkus Armbruster                && !runstate_check(RUN_STATE_PAUSED)) { /* HACK */
1543c3adb58fSMarkus Armbruster         error_setg(errp,
1544c3adb58fSMarkus Armbruster                    "Guest must be stopped for opening of encrypted image");
1545c3adb58fSMarkus Armbruster         ret = -EBUSY;
1546c3adb58fSMarkus Armbruster         goto close_and_fail;
1547b6ce07aaSKevin Wolf     }
1548b6ce07aaSKevin Wolf 
1549c3adb58fSMarkus Armbruster     QDECREF(options);
1550f67503e5SMax Reitz     *pbs = bs;
1551b6ce07aaSKevin Wolf     return 0;
1552b6ce07aaSKevin Wolf 
15538bfea15dSKevin Wolf fail:
1554f500a6d3SKevin Wolf     if (file != NULL) {
15554f6fd349SFam Zheng         bdrv_unref(file);
1556f500a6d3SKevin Wolf     }
1557de9c0cecSKevin Wolf     QDECREF(bs->options);
1558b6ad491aSKevin Wolf     QDECREF(options);
1559de9c0cecSKevin Wolf     bs->options = NULL;
1560f67503e5SMax Reitz     if (!*pbs) {
1561f67503e5SMax Reitz         /* If *pbs is NULL, a new BDS has been created in this function and
1562f67503e5SMax Reitz            needs to be freed now. Otherwise, it does not need to be closed,
1563f67503e5SMax Reitz            since it has not really been opened yet. */
1564f67503e5SMax Reitz         bdrv_unref(bs);
1565f67503e5SMax Reitz     }
156684d18f06SMarkus Armbruster     if (local_err) {
156734b5d2c6SMax Reitz         error_propagate(errp, local_err);
156834b5d2c6SMax Reitz     }
1569b6ad491aSKevin Wolf     return ret;
1570de9c0cecSKevin Wolf 
1571b6ad491aSKevin Wolf close_and_fail:
1572f67503e5SMax Reitz     /* See fail path, but now the BDS has to be always closed */
1573f67503e5SMax Reitz     if (*pbs) {
1574b6ad491aSKevin Wolf         bdrv_close(bs);
1575f67503e5SMax Reitz     } else {
1576f67503e5SMax Reitz         bdrv_unref(bs);
1577f67503e5SMax Reitz     }
1578b6ad491aSKevin Wolf     QDECREF(options);
157984d18f06SMarkus Armbruster     if (local_err) {
158034b5d2c6SMax Reitz         error_propagate(errp, local_err);
158134b5d2c6SMax Reitz     }
1582b6ce07aaSKevin Wolf     return ret;
1583b6ce07aaSKevin Wolf }
1584b6ce07aaSKevin Wolf 
1585e971aa12SJeff Cody typedef struct BlockReopenQueueEntry {
1586e971aa12SJeff Cody      bool prepared;
1587e971aa12SJeff Cody      BDRVReopenState state;
1588e971aa12SJeff Cody      QSIMPLEQ_ENTRY(BlockReopenQueueEntry) entry;
1589e971aa12SJeff Cody } BlockReopenQueueEntry;
1590e971aa12SJeff Cody 
1591e971aa12SJeff Cody /*
1592e971aa12SJeff Cody  * Adds a BlockDriverState to a simple queue for an atomic, transactional
1593e971aa12SJeff Cody  * reopen of multiple devices.
1594e971aa12SJeff Cody  *
1595e971aa12SJeff Cody  * bs_queue can either be an existing BlockReopenQueue that has had QSIMPLE_INIT
1596e971aa12SJeff Cody  * already performed, or alternatively may be NULL a new BlockReopenQueue will
1597e971aa12SJeff Cody  * be created and initialized. This newly created BlockReopenQueue should be
1598e971aa12SJeff Cody  * passed back in for subsequent calls that are intended to be of the same
1599e971aa12SJeff Cody  * atomic 'set'.
1600e971aa12SJeff Cody  *
1601e971aa12SJeff Cody  * bs is the BlockDriverState to add to the reopen queue.
1602e971aa12SJeff Cody  *
1603e971aa12SJeff Cody  * flags contains the open flags for the associated bs
1604e971aa12SJeff Cody  *
1605e971aa12SJeff Cody  * returns a pointer to bs_queue, which is either the newly allocated
1606e971aa12SJeff Cody  * bs_queue, or the existing bs_queue being used.
1607e971aa12SJeff Cody  *
1608e971aa12SJeff Cody  */
1609e971aa12SJeff Cody BlockReopenQueue *bdrv_reopen_queue(BlockReopenQueue *bs_queue,
1610e971aa12SJeff Cody                                     BlockDriverState *bs, int flags)
1611e971aa12SJeff Cody {
1612e971aa12SJeff Cody     assert(bs != NULL);
1613e971aa12SJeff Cody 
1614e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry;
1615e971aa12SJeff Cody     if (bs_queue == NULL) {
1616e971aa12SJeff Cody         bs_queue = g_new0(BlockReopenQueue, 1);
1617e971aa12SJeff Cody         QSIMPLEQ_INIT(bs_queue);
1618e971aa12SJeff Cody     }
1619e971aa12SJeff Cody 
1620f1f25a2eSKevin Wolf     /* bdrv_open() masks this flag out */
1621f1f25a2eSKevin Wolf     flags &= ~BDRV_O_PROTOCOL;
1622f1f25a2eSKevin Wolf 
1623e971aa12SJeff Cody     if (bs->file) {
1624f1f25a2eSKevin Wolf         bdrv_reopen_queue(bs_queue, bs->file, bdrv_inherited_flags(flags));
1625e971aa12SJeff Cody     }
1626e971aa12SJeff Cody 
1627e971aa12SJeff Cody     bs_entry = g_new0(BlockReopenQueueEntry, 1);
1628e971aa12SJeff Cody     QSIMPLEQ_INSERT_TAIL(bs_queue, bs_entry, entry);
1629e971aa12SJeff Cody 
1630e971aa12SJeff Cody     bs_entry->state.bs = bs;
1631e971aa12SJeff Cody     bs_entry->state.flags = flags;
1632e971aa12SJeff Cody 
1633e971aa12SJeff Cody     return bs_queue;
1634e971aa12SJeff Cody }
1635e971aa12SJeff Cody 
1636e971aa12SJeff Cody /*
1637e971aa12SJeff Cody  * Reopen multiple BlockDriverStates atomically & transactionally.
1638e971aa12SJeff Cody  *
1639e971aa12SJeff Cody  * The queue passed in (bs_queue) must have been built up previous
1640e971aa12SJeff Cody  * via bdrv_reopen_queue().
1641e971aa12SJeff Cody  *
1642e971aa12SJeff Cody  * Reopens all BDS specified in the queue, with the appropriate
1643e971aa12SJeff Cody  * flags.  All devices are prepared for reopen, and failure of any
1644e971aa12SJeff Cody  * device will cause all device changes to be abandonded, and intermediate
1645e971aa12SJeff Cody  * data cleaned up.
1646e971aa12SJeff Cody  *
1647e971aa12SJeff Cody  * If all devices prepare successfully, then the changes are committed
1648e971aa12SJeff Cody  * to all devices.
1649e971aa12SJeff Cody  *
1650e971aa12SJeff Cody  */
1651e971aa12SJeff Cody int bdrv_reopen_multiple(BlockReopenQueue *bs_queue, Error **errp)
1652e971aa12SJeff Cody {
1653e971aa12SJeff Cody     int ret = -1;
1654e971aa12SJeff Cody     BlockReopenQueueEntry *bs_entry, *next;
1655e971aa12SJeff Cody     Error *local_err = NULL;
1656e971aa12SJeff Cody 
1657e971aa12SJeff Cody     assert(bs_queue != NULL);
1658e971aa12SJeff Cody 
1659e971aa12SJeff Cody     bdrv_drain_all();
1660e971aa12SJeff Cody 
1661e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1662e971aa12SJeff Cody         if (bdrv_reopen_prepare(&bs_entry->state, bs_queue, &local_err)) {
1663e971aa12SJeff Cody             error_propagate(errp, local_err);
1664e971aa12SJeff Cody             goto cleanup;
1665e971aa12SJeff Cody         }
1666e971aa12SJeff Cody         bs_entry->prepared = true;
1667e971aa12SJeff Cody     }
1668e971aa12SJeff Cody 
1669e971aa12SJeff Cody     /* If we reach this point, we have success and just need to apply the
1670e971aa12SJeff Cody      * changes
1671e971aa12SJeff Cody      */
1672e971aa12SJeff Cody     QSIMPLEQ_FOREACH(bs_entry, bs_queue, entry) {
1673e971aa12SJeff Cody         bdrv_reopen_commit(&bs_entry->state);
1674e971aa12SJeff Cody     }
1675e971aa12SJeff Cody 
1676e971aa12SJeff Cody     ret = 0;
1677e971aa12SJeff Cody 
1678e971aa12SJeff Cody cleanup:
1679e971aa12SJeff Cody     QSIMPLEQ_FOREACH_SAFE(bs_entry, bs_queue, entry, next) {
1680e971aa12SJeff Cody         if (ret && bs_entry->prepared) {
1681e971aa12SJeff Cody             bdrv_reopen_abort(&bs_entry->state);
1682e971aa12SJeff Cody         }
1683e971aa12SJeff Cody         g_free(bs_entry);
1684e971aa12SJeff Cody     }
1685e971aa12SJeff Cody     g_free(bs_queue);
1686e971aa12SJeff Cody     return ret;
1687e971aa12SJeff Cody }
1688e971aa12SJeff Cody 
1689e971aa12SJeff Cody 
1690e971aa12SJeff Cody /* Reopen a single BlockDriverState with the specified flags. */
1691e971aa12SJeff Cody int bdrv_reopen(BlockDriverState *bs, int bdrv_flags, Error **errp)
1692e971aa12SJeff Cody {
1693e971aa12SJeff Cody     int ret = -1;
1694e971aa12SJeff Cody     Error *local_err = NULL;
1695e971aa12SJeff Cody     BlockReopenQueue *queue = bdrv_reopen_queue(NULL, bs, bdrv_flags);
1696e971aa12SJeff Cody 
1697e971aa12SJeff Cody     ret = bdrv_reopen_multiple(queue, &local_err);
1698e971aa12SJeff Cody     if (local_err != NULL) {
1699e971aa12SJeff Cody         error_propagate(errp, local_err);
1700e971aa12SJeff Cody     }
1701e971aa12SJeff Cody     return ret;
1702e971aa12SJeff Cody }
1703e971aa12SJeff Cody 
1704e971aa12SJeff Cody 
1705e971aa12SJeff Cody /*
1706e971aa12SJeff Cody  * Prepares a BlockDriverState for reopen. All changes are staged in the
1707e971aa12SJeff Cody  * 'opaque' field of the BDRVReopenState, which is used and allocated by
1708e971aa12SJeff Cody  * the block driver layer .bdrv_reopen_prepare()
1709e971aa12SJeff Cody  *
1710e971aa12SJeff Cody  * bs is the BlockDriverState to reopen
1711e971aa12SJeff Cody  * flags are the new open flags
1712e971aa12SJeff Cody  * queue is the reopen queue
1713e971aa12SJeff Cody  *
1714e971aa12SJeff Cody  * Returns 0 on success, non-zero on error.  On error errp will be set
1715e971aa12SJeff Cody  * as well.
1716e971aa12SJeff Cody  *
1717e971aa12SJeff Cody  * On failure, bdrv_reopen_abort() will be called to clean up any data.
1718e971aa12SJeff Cody  * It is the responsibility of the caller to then call the abort() or
1719e971aa12SJeff Cody  * commit() for any other BDS that have been left in a prepare() state
1720e971aa12SJeff Cody  *
1721e971aa12SJeff Cody  */
1722e971aa12SJeff Cody int bdrv_reopen_prepare(BDRVReopenState *reopen_state, BlockReopenQueue *queue,
1723e971aa12SJeff Cody                         Error **errp)
1724e971aa12SJeff Cody {
1725e971aa12SJeff Cody     int ret = -1;
1726e971aa12SJeff Cody     Error *local_err = NULL;
1727e971aa12SJeff Cody     BlockDriver *drv;
1728e971aa12SJeff Cody 
1729e971aa12SJeff Cody     assert(reopen_state != NULL);
1730e971aa12SJeff Cody     assert(reopen_state->bs->drv != NULL);
1731e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1732e971aa12SJeff Cody 
1733e971aa12SJeff Cody     /* if we are to stay read-only, do not allow permission change
1734e971aa12SJeff Cody      * to r/w */
1735e971aa12SJeff Cody     if (!(reopen_state->bs->open_flags & BDRV_O_ALLOW_RDWR) &&
1736e971aa12SJeff Cody         reopen_state->flags & BDRV_O_RDWR) {
1737e971aa12SJeff Cody         error_set(errp, QERR_DEVICE_IS_READ_ONLY,
1738e971aa12SJeff Cody                   reopen_state->bs->device_name);
1739e971aa12SJeff Cody         goto error;
1740e971aa12SJeff Cody     }
1741e971aa12SJeff Cody 
1742e971aa12SJeff Cody 
1743e971aa12SJeff Cody     ret = bdrv_flush(reopen_state->bs);
1744e971aa12SJeff Cody     if (ret) {
1745e971aa12SJeff Cody         error_set(errp, ERROR_CLASS_GENERIC_ERROR, "Error (%s) flushing drive",
1746e971aa12SJeff Cody                   strerror(-ret));
1747e971aa12SJeff Cody         goto error;
1748e971aa12SJeff Cody     }
1749e971aa12SJeff Cody 
1750e971aa12SJeff Cody     if (drv->bdrv_reopen_prepare) {
1751e971aa12SJeff Cody         ret = drv->bdrv_reopen_prepare(reopen_state, queue, &local_err);
1752e971aa12SJeff Cody         if (ret) {
1753e971aa12SJeff Cody             if (local_err != NULL) {
1754e971aa12SJeff Cody                 error_propagate(errp, local_err);
1755e971aa12SJeff Cody             } else {
1756d8b6895fSLuiz Capitulino                 error_setg(errp, "failed while preparing to reopen image '%s'",
1757e971aa12SJeff Cody                            reopen_state->bs->filename);
1758e971aa12SJeff Cody             }
1759e971aa12SJeff Cody             goto error;
1760e971aa12SJeff Cody         }
1761e971aa12SJeff Cody     } else {
1762e971aa12SJeff Cody         /* It is currently mandatory to have a bdrv_reopen_prepare()
1763e971aa12SJeff Cody          * handler for each supported drv. */
1764e971aa12SJeff Cody         error_set(errp, QERR_BLOCK_FORMAT_FEATURE_NOT_SUPPORTED,
1765e971aa12SJeff Cody                   drv->format_name, reopen_state->bs->device_name,
1766e971aa12SJeff Cody                  "reopening of file");
1767e971aa12SJeff Cody         ret = -1;
1768e971aa12SJeff Cody         goto error;
1769e971aa12SJeff Cody     }
1770e971aa12SJeff Cody 
1771e971aa12SJeff Cody     ret = 0;
1772e971aa12SJeff Cody 
1773e971aa12SJeff Cody error:
1774e971aa12SJeff Cody     return ret;
1775e971aa12SJeff Cody }
1776e971aa12SJeff Cody 
1777e971aa12SJeff Cody /*
1778e971aa12SJeff Cody  * Takes the staged changes for the reopen from bdrv_reopen_prepare(), and
1779e971aa12SJeff Cody  * makes them final by swapping the staging BlockDriverState contents into
1780e971aa12SJeff Cody  * the active BlockDriverState contents.
1781e971aa12SJeff Cody  */
1782e971aa12SJeff Cody void bdrv_reopen_commit(BDRVReopenState *reopen_state)
1783e971aa12SJeff Cody {
1784e971aa12SJeff Cody     BlockDriver *drv;
1785e971aa12SJeff Cody 
1786e971aa12SJeff Cody     assert(reopen_state != NULL);
1787e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1788e971aa12SJeff Cody     assert(drv != NULL);
1789e971aa12SJeff Cody 
1790e971aa12SJeff Cody     /* If there are any driver level actions to take */
1791e971aa12SJeff Cody     if (drv->bdrv_reopen_commit) {
1792e971aa12SJeff Cody         drv->bdrv_reopen_commit(reopen_state);
1793e971aa12SJeff Cody     }
1794e971aa12SJeff Cody 
1795e971aa12SJeff Cody     /* set BDS specific flags now */
1796e971aa12SJeff Cody     reopen_state->bs->open_flags         = reopen_state->flags;
1797e971aa12SJeff Cody     reopen_state->bs->enable_write_cache = !!(reopen_state->flags &
1798e971aa12SJeff Cody                                               BDRV_O_CACHE_WB);
1799e971aa12SJeff Cody     reopen_state->bs->read_only = !(reopen_state->flags & BDRV_O_RDWR);
1800355ef4acSKevin Wolf 
18013baca891SKevin Wolf     bdrv_refresh_limits(reopen_state->bs, NULL);
1802e971aa12SJeff Cody }
1803e971aa12SJeff Cody 
1804e971aa12SJeff Cody /*
1805e971aa12SJeff Cody  * Abort the reopen, and delete and free the staged changes in
1806e971aa12SJeff Cody  * reopen_state
1807e971aa12SJeff Cody  */
1808e971aa12SJeff Cody void bdrv_reopen_abort(BDRVReopenState *reopen_state)
1809e971aa12SJeff Cody {
1810e971aa12SJeff Cody     BlockDriver *drv;
1811e971aa12SJeff Cody 
1812e971aa12SJeff Cody     assert(reopen_state != NULL);
1813e971aa12SJeff Cody     drv = reopen_state->bs->drv;
1814e971aa12SJeff Cody     assert(drv != NULL);
1815e971aa12SJeff Cody 
1816e971aa12SJeff Cody     if (drv->bdrv_reopen_abort) {
1817e971aa12SJeff Cody         drv->bdrv_reopen_abort(reopen_state);
1818e971aa12SJeff Cody     }
1819e971aa12SJeff Cody }
1820e971aa12SJeff Cody 
1821e971aa12SJeff Cody 
1822fc01f7e7Sbellard void bdrv_close(BlockDriverState *bs)
1823fc01f7e7Sbellard {
182433384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
182533384421SMax Reitz 
18263e914655SPaolo Bonzini     if (bs->job) {
18273e914655SPaolo Bonzini         block_job_cancel_sync(bs->job);
18283e914655SPaolo Bonzini     }
182958fda173SStefan Hajnoczi     bdrv_drain_all(); /* complete I/O */
183058fda173SStefan Hajnoczi     bdrv_flush(bs);
183158fda173SStefan Hajnoczi     bdrv_drain_all(); /* in case flush left pending I/O */
1832d7d512f6SPaolo Bonzini     notifier_list_notify(&bs->close_notifiers, bs);
18337094f12fSKevin Wolf 
18343cbc002cSPaolo Bonzini     if (bs->drv) {
1835557df6acSStefan Hajnoczi         if (bs->backing_hd) {
1836826b6ca0SFam Zheng             BlockDriverState *backing_hd = bs->backing_hd;
1837826b6ca0SFam Zheng             bdrv_set_backing_hd(bs, NULL);
1838826b6ca0SFam Zheng             bdrv_unref(backing_hd);
1839557df6acSStefan Hajnoczi         }
1840ea2384d3Sbellard         bs->drv->bdrv_close(bs);
18417267c094SAnthony Liguori         g_free(bs->opaque);
1842ea2384d3Sbellard         bs->opaque = NULL;
1843ea2384d3Sbellard         bs->drv = NULL;
184453fec9d3SStefan Hajnoczi         bs->copy_on_read = 0;
1845a275fa42SPaolo Bonzini         bs->backing_file[0] = '\0';
1846a275fa42SPaolo Bonzini         bs->backing_format[0] = '\0';
18476405875cSPaolo Bonzini         bs->total_sectors = 0;
18486405875cSPaolo Bonzini         bs->encrypted = 0;
18496405875cSPaolo Bonzini         bs->valid_key = 0;
18506405875cSPaolo Bonzini         bs->sg = 0;
18516405875cSPaolo Bonzini         bs->growable = 0;
18520d51b4deSAsias He         bs->zero_beyond_eof = false;
1853de9c0cecSKevin Wolf         QDECREF(bs->options);
1854de9c0cecSKevin Wolf         bs->options = NULL;
185591af7014SMax Reitz         QDECREF(bs->full_open_options);
185691af7014SMax Reitz         bs->full_open_options = NULL;
1857b338082bSbellard 
185866f82ceeSKevin Wolf         if (bs->file != NULL) {
18594f6fd349SFam Zheng             bdrv_unref(bs->file);
18600ac9377dSPaolo Bonzini             bs->file = NULL;
186166f82ceeSKevin Wolf         }
18629ca11154SPavel Hrdina     }
186366f82ceeSKevin Wolf 
18647d4b4ba5SMarkus Armbruster     bdrv_dev_change_media_cb(bs, false);
186598f90dbaSZhi Yong Wu 
186698f90dbaSZhi Yong Wu     /*throttling disk I/O limits*/
186798f90dbaSZhi Yong Wu     if (bs->io_limits_enabled) {
186898f90dbaSZhi Yong Wu         bdrv_io_limits_disable(bs);
186998f90dbaSZhi Yong Wu     }
187033384421SMax Reitz 
187133384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
187233384421SMax Reitz         g_free(ban);
187333384421SMax Reitz     }
187433384421SMax Reitz     QLIST_INIT(&bs->aio_notifiers);
1875b338082bSbellard }
1876b338082bSbellard 
18772bc93fedSMORITA Kazutaka void bdrv_close_all(void)
18782bc93fedSMORITA Kazutaka {
18792bc93fedSMORITA Kazutaka     BlockDriverState *bs;
18802bc93fedSMORITA Kazutaka 
1881dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
1882ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
1883ed78cda3SStefan Hajnoczi 
1884ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
18852bc93fedSMORITA Kazutaka         bdrv_close(bs);
1886ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
18872bc93fedSMORITA Kazutaka     }
18882bc93fedSMORITA Kazutaka }
18892bc93fedSMORITA Kazutaka 
189088266f5aSStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
189188266f5aSStefan Hajnoczi static bool bdrv_requests_pending(BlockDriverState *bs)
189288266f5aSStefan Hajnoczi {
189388266f5aSStefan Hajnoczi     if (!QLIST_EMPTY(&bs->tracked_requests)) {
189488266f5aSStefan Hajnoczi         return true;
189588266f5aSStefan Hajnoczi     }
1896cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[0])) {
1897cc0681c4SBenoît Canet         return true;
1898cc0681c4SBenoît Canet     }
1899cc0681c4SBenoît Canet     if (!qemu_co_queue_empty(&bs->throttled_reqs[1])) {
190088266f5aSStefan Hajnoczi         return true;
190188266f5aSStefan Hajnoczi     }
190288266f5aSStefan Hajnoczi     if (bs->file && bdrv_requests_pending(bs->file)) {
190388266f5aSStefan Hajnoczi         return true;
190488266f5aSStefan Hajnoczi     }
190588266f5aSStefan Hajnoczi     if (bs->backing_hd && bdrv_requests_pending(bs->backing_hd)) {
190688266f5aSStefan Hajnoczi         return true;
190788266f5aSStefan Hajnoczi     }
190888266f5aSStefan Hajnoczi     return false;
190988266f5aSStefan Hajnoczi }
191088266f5aSStefan Hajnoczi 
1911922453bcSStefan Hajnoczi /*
1912922453bcSStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
1913922453bcSStefan Hajnoczi  *
1914922453bcSStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
1915922453bcSStefan Hajnoczi  * after calling this function.
19164c355d53SZhi Yong Wu  *
19174c355d53SZhi Yong Wu  * Note that completion of an asynchronous I/O operation can trigger any
19184c355d53SZhi Yong Wu  * number of other I/O operations on other devices---for example a coroutine
19194c355d53SZhi Yong Wu  * can be arbitrarily complex and a constant flow of I/O can come until the
19204c355d53SZhi Yong Wu  * coroutine is complete.  Because of this, it is not possible to have a
19214c355d53SZhi Yong Wu  * function to drain a single device's I/O queue.
1922922453bcSStefan Hajnoczi  */
1923922453bcSStefan Hajnoczi void bdrv_drain_all(void)
1924922453bcSStefan Hajnoczi {
192588266f5aSStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
192688266f5aSStefan Hajnoczi     bool busy = true;
1927922453bcSStefan Hajnoczi     BlockDriverState *bs;
1928922453bcSStefan Hajnoczi 
192988266f5aSStefan Hajnoczi     while (busy) {
19309b536adcSStefan Hajnoczi         busy = false;
1931922453bcSStefan Hajnoczi 
19329b536adcSStefan Hajnoczi         QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
19339b536adcSStefan Hajnoczi             AioContext *aio_context = bdrv_get_aio_context(bs);
19349b536adcSStefan Hajnoczi             bool bs_busy;
19359b536adcSStefan Hajnoczi 
19369b536adcSStefan Hajnoczi             aio_context_acquire(aio_context);
1937448ad91dSMing Lei             bdrv_flush_io_queue(bs);
19389b536adcSStefan Hajnoczi             bdrv_start_throttled_reqs(bs);
19399b536adcSStefan Hajnoczi             bs_busy = bdrv_requests_pending(bs);
19409b536adcSStefan Hajnoczi             bs_busy |= aio_poll(aio_context, bs_busy);
19419b536adcSStefan Hajnoczi             aio_context_release(aio_context);
19429b536adcSStefan Hajnoczi 
19439b536adcSStefan Hajnoczi             busy |= bs_busy;
19449b536adcSStefan Hajnoczi         }
1945922453bcSStefan Hajnoczi     }
1946922453bcSStefan Hajnoczi }
1947922453bcSStefan Hajnoczi 
1948dc364f4cSBenoît Canet /* make a BlockDriverState anonymous by removing from bdrv_state and
1949dc364f4cSBenoît Canet  * graph_bdrv_state list.
1950d22b2f41SRyan Harper    Also, NULL terminate the device_name to prevent double remove */
1951d22b2f41SRyan Harper void bdrv_make_anon(BlockDriverState *bs)
1952d22b2f41SRyan Harper {
1953d22b2f41SRyan Harper     if (bs->device_name[0] != '\0') {
1954dc364f4cSBenoît Canet         QTAILQ_REMOVE(&bdrv_states, bs, device_list);
1955d22b2f41SRyan Harper     }
1956d22b2f41SRyan Harper     bs->device_name[0] = '\0';
1957dc364f4cSBenoît Canet     if (bs->node_name[0] != '\0') {
1958dc364f4cSBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs, node_list);
1959dc364f4cSBenoît Canet     }
1960dc364f4cSBenoît Canet     bs->node_name[0] = '\0';
1961d22b2f41SRyan Harper }
1962d22b2f41SRyan Harper 
1963e023b2e2SPaolo Bonzini static void bdrv_rebind(BlockDriverState *bs)
1964e023b2e2SPaolo Bonzini {
1965e023b2e2SPaolo Bonzini     if (bs->drv && bs->drv->bdrv_rebind) {
1966e023b2e2SPaolo Bonzini         bs->drv->bdrv_rebind(bs);
1967e023b2e2SPaolo Bonzini     }
1968e023b2e2SPaolo Bonzini }
1969e023b2e2SPaolo Bonzini 
19704ddc07caSPaolo Bonzini static void bdrv_move_feature_fields(BlockDriverState *bs_dest,
19714ddc07caSPaolo Bonzini                                      BlockDriverState *bs_src)
19724ddc07caSPaolo Bonzini {
19734ddc07caSPaolo Bonzini     /* move some fields that need to stay attached to the device */
19744ddc07caSPaolo Bonzini 
19754ddc07caSPaolo Bonzini     /* dev info */
19764ddc07caSPaolo Bonzini     bs_dest->dev_ops            = bs_src->dev_ops;
19774ddc07caSPaolo Bonzini     bs_dest->dev_opaque         = bs_src->dev_opaque;
19784ddc07caSPaolo Bonzini     bs_dest->dev                = bs_src->dev;
19791b7fd729SPaolo Bonzini     bs_dest->guest_block_size   = bs_src->guest_block_size;
19804ddc07caSPaolo Bonzini     bs_dest->copy_on_read       = bs_src->copy_on_read;
19814ddc07caSPaolo Bonzini 
19824ddc07caSPaolo Bonzini     bs_dest->enable_write_cache = bs_src->enable_write_cache;
19834ddc07caSPaolo Bonzini 
1984cc0681c4SBenoît Canet     /* i/o throttled req */
1985cc0681c4SBenoît Canet     memcpy(&bs_dest->throttle_state,
1986cc0681c4SBenoît Canet            &bs_src->throttle_state,
1987cc0681c4SBenoît Canet            sizeof(ThrottleState));
1988cc0681c4SBenoît Canet     bs_dest->throttled_reqs[0]  = bs_src->throttled_reqs[0];
1989cc0681c4SBenoît Canet     bs_dest->throttled_reqs[1]  = bs_src->throttled_reqs[1];
19904ddc07caSPaolo Bonzini     bs_dest->io_limits_enabled  = bs_src->io_limits_enabled;
19914ddc07caSPaolo Bonzini 
19924ddc07caSPaolo Bonzini     /* r/w error */
19934ddc07caSPaolo Bonzini     bs_dest->on_read_error      = bs_src->on_read_error;
19944ddc07caSPaolo Bonzini     bs_dest->on_write_error     = bs_src->on_write_error;
19954ddc07caSPaolo Bonzini 
19964ddc07caSPaolo Bonzini     /* i/o status */
19974ddc07caSPaolo Bonzini     bs_dest->iostatus_enabled   = bs_src->iostatus_enabled;
19984ddc07caSPaolo Bonzini     bs_dest->iostatus           = bs_src->iostatus;
19994ddc07caSPaolo Bonzini 
20004ddc07caSPaolo Bonzini     /* dirty bitmap */
2001e4654d2dSFam Zheng     bs_dest->dirty_bitmaps      = bs_src->dirty_bitmaps;
20024ddc07caSPaolo Bonzini 
20039fcb0251SFam Zheng     /* reference count */
20049fcb0251SFam Zheng     bs_dest->refcnt             = bs_src->refcnt;
20059fcb0251SFam Zheng 
20064ddc07caSPaolo Bonzini     /* job */
20074ddc07caSPaolo Bonzini     bs_dest->job                = bs_src->job;
20084ddc07caSPaolo Bonzini 
20094ddc07caSPaolo Bonzini     /* keep the same entry in bdrv_states */
20104ddc07caSPaolo Bonzini     pstrcpy(bs_dest->device_name, sizeof(bs_dest->device_name),
20114ddc07caSPaolo Bonzini             bs_src->device_name);
2012dc364f4cSBenoît Canet     bs_dest->device_list = bs_src->device_list;
2013fbe40ff7SFam Zheng     memcpy(bs_dest->op_blockers, bs_src->op_blockers,
2014fbe40ff7SFam Zheng            sizeof(bs_dest->op_blockers));
20154ddc07caSPaolo Bonzini }
20164ddc07caSPaolo Bonzini 
20174ddc07caSPaolo Bonzini /*
20184ddc07caSPaolo Bonzini  * Swap bs contents for two image chains while they are live,
20194ddc07caSPaolo Bonzini  * while keeping required fields on the BlockDriverState that is
20204ddc07caSPaolo Bonzini  * actually attached to a device.
20214ddc07caSPaolo Bonzini  *
20224ddc07caSPaolo Bonzini  * This will modify the BlockDriverState fields, and swap contents
20234ddc07caSPaolo Bonzini  * between bs_new and bs_old. Both bs_new and bs_old are modified.
20244ddc07caSPaolo Bonzini  *
20254ddc07caSPaolo Bonzini  * bs_new is required to be anonymous.
20264ddc07caSPaolo Bonzini  *
20274ddc07caSPaolo Bonzini  * This function does not create any image files.
20284ddc07caSPaolo Bonzini  */
20294ddc07caSPaolo Bonzini void bdrv_swap(BlockDriverState *bs_new, BlockDriverState *bs_old)
20304ddc07caSPaolo Bonzini {
20314ddc07caSPaolo Bonzini     BlockDriverState tmp;
20324ddc07caSPaolo Bonzini 
203390ce8a06SBenoît Canet     /* The code needs to swap the node_name but simply swapping node_list won't
203490ce8a06SBenoît Canet      * work so first remove the nodes from the graph list, do the swap then
203590ce8a06SBenoît Canet      * insert them back if needed.
203690ce8a06SBenoît Canet      */
203790ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
203890ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_new, node_list);
203990ce8a06SBenoît Canet     }
204090ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
204190ce8a06SBenoît Canet         QTAILQ_REMOVE(&graph_bdrv_states, bs_old, node_list);
204290ce8a06SBenoît Canet     }
204390ce8a06SBenoît Canet 
20444ddc07caSPaolo Bonzini     /* bs_new must be anonymous and shouldn't have anything fancy enabled */
20454ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
2046e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs_new->dirty_bitmaps));
20474ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20484ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
20494ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2050cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20514ddc07caSPaolo Bonzini 
20524ddc07caSPaolo Bonzini     tmp = *bs_new;
20534ddc07caSPaolo Bonzini     *bs_new = *bs_old;
20544ddc07caSPaolo Bonzini     *bs_old = tmp;
20554ddc07caSPaolo Bonzini 
20564ddc07caSPaolo Bonzini     /* there are some fields that should not be swapped, move them back */
20574ddc07caSPaolo Bonzini     bdrv_move_feature_fields(&tmp, bs_old);
20584ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_old, bs_new);
20594ddc07caSPaolo Bonzini     bdrv_move_feature_fields(bs_new, &tmp);
20604ddc07caSPaolo Bonzini 
20614ddc07caSPaolo Bonzini     /* bs_new shouldn't be in bdrv_states even after the swap!  */
20624ddc07caSPaolo Bonzini     assert(bs_new->device_name[0] == '\0');
20634ddc07caSPaolo Bonzini 
20644ddc07caSPaolo Bonzini     /* Check a few fields that should remain attached to the device */
20654ddc07caSPaolo Bonzini     assert(bs_new->dev == NULL);
20664ddc07caSPaolo Bonzini     assert(bs_new->job == NULL);
20674ddc07caSPaolo Bonzini     assert(bs_new->io_limits_enabled == false);
2068cc0681c4SBenoît Canet     assert(!throttle_have_timer(&bs_new->throttle_state));
20694ddc07caSPaolo Bonzini 
207090ce8a06SBenoît Canet     /* insert the nodes back into the graph node list if needed */
207190ce8a06SBenoît Canet     if (bs_new->node_name[0] != '\0') {
207290ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_new, node_list);
207390ce8a06SBenoît Canet     }
207490ce8a06SBenoît Canet     if (bs_old->node_name[0] != '\0') {
207590ce8a06SBenoît Canet         QTAILQ_INSERT_TAIL(&graph_bdrv_states, bs_old, node_list);
207690ce8a06SBenoît Canet     }
207790ce8a06SBenoît Canet 
20784ddc07caSPaolo Bonzini     bdrv_rebind(bs_new);
20794ddc07caSPaolo Bonzini     bdrv_rebind(bs_old);
20804ddc07caSPaolo Bonzini }
20814ddc07caSPaolo Bonzini 
20828802d1fdSJeff Cody /*
20838802d1fdSJeff Cody  * Add new bs contents at the top of an image chain while the chain is
20848802d1fdSJeff Cody  * live, while keeping required fields on the top layer.
20858802d1fdSJeff Cody  *
20868802d1fdSJeff Cody  * This will modify the BlockDriverState fields, and swap contents
20878802d1fdSJeff Cody  * between bs_new and bs_top. Both bs_new and bs_top are modified.
20888802d1fdSJeff Cody  *
2089f6801b83SJeff Cody  * bs_new is required to be anonymous.
2090f6801b83SJeff Cody  *
20918802d1fdSJeff Cody  * This function does not create any image files.
20928802d1fdSJeff Cody  */
20938802d1fdSJeff Cody void bdrv_append(BlockDriverState *bs_new, BlockDriverState *bs_top)
20948802d1fdSJeff Cody {
20954ddc07caSPaolo Bonzini     bdrv_swap(bs_new, bs_top);
20968802d1fdSJeff Cody 
20978802d1fdSJeff Cody     /* The contents of 'tmp' will become bs_top, as we are
20988802d1fdSJeff Cody      * swapping bs_new and bs_top contents. */
20998d24cce1SFam Zheng     bdrv_set_backing_hd(bs_top, bs_new);
21008802d1fdSJeff Cody }
21018802d1fdSJeff Cody 
21024f6fd349SFam Zheng static void bdrv_delete(BlockDriverState *bs)
2103b338082bSbellard {
2104fa879d62SMarkus Armbruster     assert(!bs->dev);
21053e914655SPaolo Bonzini     assert(!bs->job);
21063718d8abSFam Zheng     assert(bdrv_op_blocker_is_empty(bs));
21074f6fd349SFam Zheng     assert(!bs->refcnt);
2108e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
210918846deeSMarkus Armbruster 
2110e1b5c52eSStefan Hajnoczi     bdrv_close(bs);
2111e1b5c52eSStefan Hajnoczi 
21121b7bdbc1SStefan Hajnoczi     /* remove from list, if necessary */
2113d22b2f41SRyan Harper     bdrv_make_anon(bs);
211434c6f050Saurel32 
21153ae59580SMarkus Armbruster     drive_info_del(drive_get_by_blockdev(bs));
21167267c094SAnthony Liguori     g_free(bs);
2117fc01f7e7Sbellard }
2118fc01f7e7Sbellard 
2119fa879d62SMarkus Armbruster int bdrv_attach_dev(BlockDriverState *bs, void *dev)
2120fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
212118846deeSMarkus Armbruster {
2122fa879d62SMarkus Armbruster     if (bs->dev) {
212318846deeSMarkus Armbruster         return -EBUSY;
212418846deeSMarkus Armbruster     }
2125fa879d62SMarkus Armbruster     bs->dev = dev;
212628a7282aSLuiz Capitulino     bdrv_iostatus_reset(bs);
21272a87151fSStefan Hajnoczi 
21282a87151fSStefan Hajnoczi     /* We're expecting I/O from the device so bump up coroutine pool size */
21292a87151fSStefan Hajnoczi     qemu_coroutine_adjust_pool_size(COROUTINE_POOL_RESERVATION);
213018846deeSMarkus Armbruster     return 0;
213118846deeSMarkus Armbruster }
213218846deeSMarkus Armbruster 
2133fa879d62SMarkus Armbruster /* TODO qdevified devices don't use this, remove when devices are qdevified */
2134fa879d62SMarkus Armbruster void bdrv_attach_dev_nofail(BlockDriverState *bs, void *dev)
213518846deeSMarkus Armbruster {
2136fa879d62SMarkus Armbruster     if (bdrv_attach_dev(bs, dev) < 0) {
2137fa879d62SMarkus Armbruster         abort();
2138fa879d62SMarkus Armbruster     }
2139fa879d62SMarkus Armbruster }
2140fa879d62SMarkus Armbruster 
2141fa879d62SMarkus Armbruster void bdrv_detach_dev(BlockDriverState *bs, void *dev)
2142fa879d62SMarkus Armbruster /* TODO change to DeviceState *dev when all users are qdevified */
2143fa879d62SMarkus Armbruster {
2144fa879d62SMarkus Armbruster     assert(bs->dev == dev);
2145fa879d62SMarkus Armbruster     bs->dev = NULL;
21460e49de52SMarkus Armbruster     bs->dev_ops = NULL;
21470e49de52SMarkus Armbruster     bs->dev_opaque = NULL;
21481b7fd729SPaolo Bonzini     bs->guest_block_size = 512;
21492a87151fSStefan Hajnoczi     qemu_coroutine_adjust_pool_size(-COROUTINE_POOL_RESERVATION);
215018846deeSMarkus Armbruster }
215118846deeSMarkus Armbruster 
2152fa879d62SMarkus Armbruster /* TODO change to return DeviceState * when all users are qdevified */
2153fa879d62SMarkus Armbruster void *bdrv_get_attached_dev(BlockDriverState *bs)
215418846deeSMarkus Armbruster {
2155fa879d62SMarkus Armbruster     return bs->dev;
215618846deeSMarkus Armbruster }
215718846deeSMarkus Armbruster 
21580e49de52SMarkus Armbruster void bdrv_set_dev_ops(BlockDriverState *bs, const BlockDevOps *ops,
21590e49de52SMarkus Armbruster                       void *opaque)
21600e49de52SMarkus Armbruster {
21610e49de52SMarkus Armbruster     bs->dev_ops = ops;
21620e49de52SMarkus Armbruster     bs->dev_opaque = opaque;
21630e49de52SMarkus Armbruster }
21640e49de52SMarkus Armbruster 
21657d4b4ba5SMarkus Armbruster static void bdrv_dev_change_media_cb(BlockDriverState *bs, bool load)
21660e49de52SMarkus Armbruster {
2167145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->change_media_cb) {
21686f382ed2SLuiz Capitulino         bool tray_was_closed = !bdrv_dev_is_tray_open(bs);
21697d4b4ba5SMarkus Armbruster         bs->dev_ops->change_media_cb(bs->dev_opaque, load);
21706f382ed2SLuiz Capitulino         if (tray_was_closed) {
21716f382ed2SLuiz Capitulino             /* tray open */
2172a5ee7bd4SWenchao Xia             qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
2173a5ee7bd4SWenchao Xia                                               true, &error_abort);
21746f382ed2SLuiz Capitulino         }
21756f382ed2SLuiz Capitulino         if (load) {
21766f382ed2SLuiz Capitulino             /* tray close */
2177a5ee7bd4SWenchao Xia             qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
2178a5ee7bd4SWenchao Xia                                               false, &error_abort);
21796f382ed2SLuiz Capitulino         }
2180145feb17SMarkus Armbruster     }
2181145feb17SMarkus Armbruster }
2182145feb17SMarkus Armbruster 
21832c6942faSMarkus Armbruster bool bdrv_dev_has_removable_media(BlockDriverState *bs)
21842c6942faSMarkus Armbruster {
21852c6942faSMarkus Armbruster     return !bs->dev || (bs->dev_ops && bs->dev_ops->change_media_cb);
21862c6942faSMarkus Armbruster }
21872c6942faSMarkus Armbruster 
2188025ccaa7SPaolo Bonzini void bdrv_dev_eject_request(BlockDriverState *bs, bool force)
2189025ccaa7SPaolo Bonzini {
2190025ccaa7SPaolo Bonzini     if (bs->dev_ops && bs->dev_ops->eject_request_cb) {
2191025ccaa7SPaolo Bonzini         bs->dev_ops->eject_request_cb(bs->dev_opaque, force);
2192025ccaa7SPaolo Bonzini     }
2193025ccaa7SPaolo Bonzini }
2194025ccaa7SPaolo Bonzini 
2195e4def80bSMarkus Armbruster bool bdrv_dev_is_tray_open(BlockDriverState *bs)
2196e4def80bSMarkus Armbruster {
2197e4def80bSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_tray_open) {
2198e4def80bSMarkus Armbruster         return bs->dev_ops->is_tray_open(bs->dev_opaque);
2199e4def80bSMarkus Armbruster     }
2200e4def80bSMarkus Armbruster     return false;
2201e4def80bSMarkus Armbruster }
2202e4def80bSMarkus Armbruster 
2203145feb17SMarkus Armbruster static void bdrv_dev_resize_cb(BlockDriverState *bs)
2204145feb17SMarkus Armbruster {
2205145feb17SMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->resize_cb) {
2206145feb17SMarkus Armbruster         bs->dev_ops->resize_cb(bs->dev_opaque);
22070e49de52SMarkus Armbruster     }
22080e49de52SMarkus Armbruster }
22090e49de52SMarkus Armbruster 
2210f107639aSMarkus Armbruster bool bdrv_dev_is_medium_locked(BlockDriverState *bs)
2211f107639aSMarkus Armbruster {
2212f107639aSMarkus Armbruster     if (bs->dev_ops && bs->dev_ops->is_medium_locked) {
2213f107639aSMarkus Armbruster         return bs->dev_ops->is_medium_locked(bs->dev_opaque);
2214f107639aSMarkus Armbruster     }
2215f107639aSMarkus Armbruster     return false;
2216f107639aSMarkus Armbruster }
2217f107639aSMarkus Armbruster 
2218e97fc193Saliguori /*
2219e97fc193Saliguori  * Run consistency checks on an image
2220e97fc193Saliguori  *
2221e076f338SKevin Wolf  * Returns 0 if the check could be completed (it doesn't mean that the image is
2222a1c7273bSStefan Weil  * free of errors) or -errno when an internal error occurred. The results of the
2223e076f338SKevin Wolf  * check are stored in res.
2224e97fc193Saliguori  */
22254534ff54SKevin Wolf int bdrv_check(BlockDriverState *bs, BdrvCheckResult *res, BdrvCheckMode fix)
2226e97fc193Saliguori {
2227908bcd54SMax Reitz     if (bs->drv == NULL) {
2228908bcd54SMax Reitz         return -ENOMEDIUM;
2229908bcd54SMax Reitz     }
2230e97fc193Saliguori     if (bs->drv->bdrv_check == NULL) {
2231e97fc193Saliguori         return -ENOTSUP;
2232e97fc193Saliguori     }
2233e97fc193Saliguori 
2234e076f338SKevin Wolf     memset(res, 0, sizeof(*res));
22354534ff54SKevin Wolf     return bs->drv->bdrv_check(bs, res, fix);
2236e97fc193Saliguori }
2237e97fc193Saliguori 
22388a426614SKevin Wolf #define COMMIT_BUF_SECTORS 2048
22398a426614SKevin Wolf 
224033e3963eSbellard /* commit COW file into the raw image */
224133e3963eSbellard int bdrv_commit(BlockDriverState *bs)
224233e3963eSbellard {
224319cb3738Sbellard     BlockDriver *drv = bs->drv;
224472706ea4SJeff Cody     int64_t sector, total_sectors, length, backing_length;
22458a426614SKevin Wolf     int n, ro, open_flags;
22460bce597dSJeff Cody     int ret = 0;
224772706ea4SJeff Cody     uint8_t *buf = NULL;
2248c2cba3d9SJim Meyering     char filename[PATH_MAX];
224933e3963eSbellard 
225019cb3738Sbellard     if (!drv)
225119cb3738Sbellard         return -ENOMEDIUM;
225233e3963eSbellard 
22534dca4b63SNaphtali Sprei     if (!bs->backing_hd) {
22544dca4b63SNaphtali Sprei         return -ENOTSUP;
22554dca4b63SNaphtali Sprei     }
22564dca4b63SNaphtali Sprei 
22573718d8abSFam Zheng     if (bdrv_op_is_blocked(bs, BLOCK_OP_TYPE_COMMIT, NULL) ||
22583718d8abSFam Zheng         bdrv_op_is_blocked(bs->backing_hd, BLOCK_OP_TYPE_COMMIT, NULL)) {
22592d3735d3SStefan Hajnoczi         return -EBUSY;
22602d3735d3SStefan Hajnoczi     }
22612d3735d3SStefan Hajnoczi 
22624dca4b63SNaphtali Sprei     ro = bs->backing_hd->read_only;
2263c2cba3d9SJim Meyering     /* Use pstrcpy (not strncpy): filename must be NUL-terminated. */
2264c2cba3d9SJim Meyering     pstrcpy(filename, sizeof(filename), bs->backing_hd->filename);
22654dca4b63SNaphtali Sprei     open_flags =  bs->backing_hd->open_flags;
22664dca4b63SNaphtali Sprei 
22674dca4b63SNaphtali Sprei     if (ro) {
22680bce597dSJeff Cody         if (bdrv_reopen(bs->backing_hd, open_flags | BDRV_O_RDWR, NULL)) {
22690bce597dSJeff Cody             return -EACCES;
22704dca4b63SNaphtali Sprei         }
2271ea2384d3Sbellard     }
2272ea2384d3Sbellard 
227372706ea4SJeff Cody     length = bdrv_getlength(bs);
227472706ea4SJeff Cody     if (length < 0) {
227572706ea4SJeff Cody         ret = length;
227672706ea4SJeff Cody         goto ro_cleanup;
227772706ea4SJeff Cody     }
227872706ea4SJeff Cody 
227972706ea4SJeff Cody     backing_length = bdrv_getlength(bs->backing_hd);
228072706ea4SJeff Cody     if (backing_length < 0) {
228172706ea4SJeff Cody         ret = backing_length;
228272706ea4SJeff Cody         goto ro_cleanup;
228372706ea4SJeff Cody     }
228472706ea4SJeff Cody 
228572706ea4SJeff Cody     /* If our top snapshot is larger than the backing file image,
228672706ea4SJeff Cody      * grow the backing file image if possible.  If not possible,
228772706ea4SJeff Cody      * we must return an error */
228872706ea4SJeff Cody     if (length > backing_length) {
228972706ea4SJeff Cody         ret = bdrv_truncate(bs->backing_hd, length);
229072706ea4SJeff Cody         if (ret < 0) {
229172706ea4SJeff Cody             goto ro_cleanup;
229272706ea4SJeff Cody         }
229372706ea4SJeff Cody     }
229472706ea4SJeff Cody 
229572706ea4SJeff Cody     total_sectors = length >> BDRV_SECTOR_BITS;
2296857d4f46SKevin Wolf 
2297857d4f46SKevin Wolf     /* qemu_try_blockalign() for bs will choose an alignment that works for
2298857d4f46SKevin Wolf      * bs->backing_hd as well, so no need to compare the alignment manually. */
2299857d4f46SKevin Wolf     buf = qemu_try_blockalign(bs, COMMIT_BUF_SECTORS * BDRV_SECTOR_SIZE);
2300857d4f46SKevin Wolf     if (buf == NULL) {
2301857d4f46SKevin Wolf         ret = -ENOMEM;
2302857d4f46SKevin Wolf         goto ro_cleanup;
2303857d4f46SKevin Wolf     }
23048a426614SKevin Wolf 
23058a426614SKevin Wolf     for (sector = 0; sector < total_sectors; sector += n) {
2306d663640cSPaolo Bonzini         ret = bdrv_is_allocated(bs, sector, COMMIT_BUF_SECTORS, &n);
2307d663640cSPaolo Bonzini         if (ret < 0) {
2308d663640cSPaolo Bonzini             goto ro_cleanup;
2309d663640cSPaolo Bonzini         }
2310d663640cSPaolo Bonzini         if (ret) {
2311dabfa6ccSKevin Wolf             ret = bdrv_read(bs, sector, buf, n);
2312dabfa6ccSKevin Wolf             if (ret < 0) {
23134dca4b63SNaphtali Sprei                 goto ro_cleanup;
231433e3963eSbellard             }
231533e3963eSbellard 
2316dabfa6ccSKevin Wolf             ret = bdrv_write(bs->backing_hd, sector, buf, n);
2317dabfa6ccSKevin Wolf             if (ret < 0) {
23184dca4b63SNaphtali Sprei                 goto ro_cleanup;
231933e3963eSbellard             }
232033e3963eSbellard         }
232133e3963eSbellard     }
232295389c86Sbellard 
23231d44952fSChristoph Hellwig     if (drv->bdrv_make_empty) {
23241d44952fSChristoph Hellwig         ret = drv->bdrv_make_empty(bs);
2325dabfa6ccSKevin Wolf         if (ret < 0) {
2326dabfa6ccSKevin Wolf             goto ro_cleanup;
2327dabfa6ccSKevin Wolf         }
23281d44952fSChristoph Hellwig         bdrv_flush(bs);
23291d44952fSChristoph Hellwig     }
233095389c86Sbellard 
23313f5075aeSChristoph Hellwig     /*
23323f5075aeSChristoph Hellwig      * Make sure all data we wrote to the backing device is actually
23333f5075aeSChristoph Hellwig      * stable on disk.
23343f5075aeSChristoph Hellwig      */
2335dabfa6ccSKevin Wolf     if (bs->backing_hd) {
23363f5075aeSChristoph Hellwig         bdrv_flush(bs->backing_hd);
2337dabfa6ccSKevin Wolf     }
23384dca4b63SNaphtali Sprei 
2339dabfa6ccSKevin Wolf     ret = 0;
23404dca4b63SNaphtali Sprei ro_cleanup:
2341857d4f46SKevin Wolf     qemu_vfree(buf);
23424dca4b63SNaphtali Sprei 
23434dca4b63SNaphtali Sprei     if (ro) {
23440bce597dSJeff Cody         /* ignoring error return here */
23450bce597dSJeff Cody         bdrv_reopen(bs->backing_hd, open_flags & ~BDRV_O_RDWR, NULL);
23464dca4b63SNaphtali Sprei     }
23474dca4b63SNaphtali Sprei 
23481d44952fSChristoph Hellwig     return ret;
234933e3963eSbellard }
235033e3963eSbellard 
2351e8877497SStefan Hajnoczi int bdrv_commit_all(void)
23526ab4b5abSMarkus Armbruster {
23536ab4b5abSMarkus Armbruster     BlockDriverState *bs;
23546ab4b5abSMarkus Armbruster 
2355dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
2356ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
2357ed78cda3SStefan Hajnoczi 
2358ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
2359272d2d8eSJeff Cody         if (bs->drv && bs->backing_hd) {
2360e8877497SStefan Hajnoczi             int ret = bdrv_commit(bs);
2361e8877497SStefan Hajnoczi             if (ret < 0) {
2362ed78cda3SStefan Hajnoczi                 aio_context_release(aio_context);
2363e8877497SStefan Hajnoczi                 return ret;
23646ab4b5abSMarkus Armbruster             }
23656ab4b5abSMarkus Armbruster         }
2366ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
2367272d2d8eSJeff Cody     }
2368e8877497SStefan Hajnoczi     return 0;
2369e8877497SStefan Hajnoczi }
23706ab4b5abSMarkus Armbruster 
2371dbffbdcfSStefan Hajnoczi /**
2372dbffbdcfSStefan Hajnoczi  * Remove an active request from the tracked requests list
2373dbffbdcfSStefan Hajnoczi  *
2374dbffbdcfSStefan Hajnoczi  * This function should be called when a tracked request is completing.
2375dbffbdcfSStefan Hajnoczi  */
2376dbffbdcfSStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
2377dbffbdcfSStefan Hajnoczi {
23782dbafdc0SKevin Wolf     if (req->serialising) {
23792dbafdc0SKevin Wolf         req->bs->serialising_in_flight--;
23802dbafdc0SKevin Wolf     }
23812dbafdc0SKevin Wolf 
2382dbffbdcfSStefan Hajnoczi     QLIST_REMOVE(req, list);
2383f4658285SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
2384dbffbdcfSStefan Hajnoczi }
2385dbffbdcfSStefan Hajnoczi 
2386dbffbdcfSStefan Hajnoczi /**
2387dbffbdcfSStefan Hajnoczi  * Add an active request to the tracked requests list
2388dbffbdcfSStefan Hajnoczi  */
2389dbffbdcfSStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
2390dbffbdcfSStefan Hajnoczi                                   BlockDriverState *bs,
2391793ed47aSKevin Wolf                                   int64_t offset,
2392793ed47aSKevin Wolf                                   unsigned int bytes, bool is_write)
2393dbffbdcfSStefan Hajnoczi {
2394dbffbdcfSStefan Hajnoczi     *req = (BdrvTrackedRequest){
2395dbffbdcfSStefan Hajnoczi         .bs = bs,
2396793ed47aSKevin Wolf         .offset         = offset,
2397793ed47aSKevin Wolf         .bytes          = bytes,
2398dbffbdcfSStefan Hajnoczi         .is_write       = is_write,
23995f8b6491SStefan Hajnoczi         .co             = qemu_coroutine_self(),
24002dbafdc0SKevin Wolf         .serialising    = false,
24017327145fSKevin Wolf         .overlap_offset = offset,
24027327145fSKevin Wolf         .overlap_bytes  = bytes,
2403dbffbdcfSStefan Hajnoczi     };
2404dbffbdcfSStefan Hajnoczi 
2405f4658285SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
2406f4658285SStefan Hajnoczi 
2407dbffbdcfSStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
2408dbffbdcfSStefan Hajnoczi }
2409dbffbdcfSStefan Hajnoczi 
2410e96126ffSKevin Wolf static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
24112dbafdc0SKevin Wolf {
24127327145fSKevin Wolf     int64_t overlap_offset = req->offset & ~(align - 1);
2413e96126ffSKevin Wolf     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
24147327145fSKevin Wolf                                - overlap_offset;
24157327145fSKevin Wolf 
24162dbafdc0SKevin Wolf     if (!req->serialising) {
24172dbafdc0SKevin Wolf         req->bs->serialising_in_flight++;
24182dbafdc0SKevin Wolf         req->serialising = true;
24192dbafdc0SKevin Wolf     }
24207327145fSKevin Wolf 
24217327145fSKevin Wolf     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
24227327145fSKevin Wolf     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
24232dbafdc0SKevin Wolf }
24242dbafdc0SKevin Wolf 
2425d83947acSStefan Hajnoczi /**
2426d83947acSStefan Hajnoczi  * Round a region to cluster boundaries
2427d83947acSStefan Hajnoczi  */
2428343bded4SPaolo Bonzini void bdrv_round_to_clusters(BlockDriverState *bs,
2429d83947acSStefan Hajnoczi                             int64_t sector_num, int nb_sectors,
2430d83947acSStefan Hajnoczi                             int64_t *cluster_sector_num,
2431d83947acSStefan Hajnoczi                             int *cluster_nb_sectors)
2432d83947acSStefan Hajnoczi {
2433d83947acSStefan Hajnoczi     BlockDriverInfo bdi;
2434d83947acSStefan Hajnoczi 
2435d83947acSStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
2436d83947acSStefan Hajnoczi         *cluster_sector_num = sector_num;
2437d83947acSStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
2438d83947acSStefan Hajnoczi     } else {
2439d83947acSStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
2440d83947acSStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
2441d83947acSStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
2442d83947acSStefan Hajnoczi                                             nb_sectors, c);
2443d83947acSStefan Hajnoczi     }
2444d83947acSStefan Hajnoczi }
2445d83947acSStefan Hajnoczi 
24467327145fSKevin Wolf static int bdrv_get_cluster_size(BlockDriverState *bs)
2447793ed47aSKevin Wolf {
2448793ed47aSKevin Wolf     BlockDriverInfo bdi;
24497327145fSKevin Wolf     int ret;
2450793ed47aSKevin Wolf 
24517327145fSKevin Wolf     ret = bdrv_get_info(bs, &bdi);
24527327145fSKevin Wolf     if (ret < 0 || bdi.cluster_size == 0) {
24537327145fSKevin Wolf         return bs->request_alignment;
2454793ed47aSKevin Wolf     } else {
24557327145fSKevin Wolf         return bdi.cluster_size;
2456793ed47aSKevin Wolf     }
2457793ed47aSKevin Wolf }
2458793ed47aSKevin Wolf 
2459f4658285SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
2460793ed47aSKevin Wolf                                      int64_t offset, unsigned int bytes)
2461793ed47aSKevin Wolf {
2462d83947acSStefan Hajnoczi     /*        aaaa   bbbb */
24637327145fSKevin Wolf     if (offset >= req->overlap_offset + req->overlap_bytes) {
2464d83947acSStefan Hajnoczi         return false;
2465d83947acSStefan Hajnoczi     }
2466d83947acSStefan Hajnoczi     /* bbbb   aaaa        */
24677327145fSKevin Wolf     if (req->overlap_offset >= offset + bytes) {
2468d83947acSStefan Hajnoczi         return false;
2469d83947acSStefan Hajnoczi     }
2470d83947acSStefan Hajnoczi     return true;
2471f4658285SStefan Hajnoczi }
2472f4658285SStefan Hajnoczi 
247328de2dcdSKevin Wolf static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
2474f4658285SStefan Hajnoczi {
24752dbafdc0SKevin Wolf     BlockDriverState *bs = self->bs;
2476f4658285SStefan Hajnoczi     BdrvTrackedRequest *req;
2477f4658285SStefan Hajnoczi     bool retry;
247828de2dcdSKevin Wolf     bool waited = false;
2479f4658285SStefan Hajnoczi 
24802dbafdc0SKevin Wolf     if (!bs->serialising_in_flight) {
248128de2dcdSKevin Wolf         return false;
24822dbafdc0SKevin Wolf     }
24832dbafdc0SKevin Wolf 
2484f4658285SStefan Hajnoczi     do {
2485f4658285SStefan Hajnoczi         retry = false;
2486f4658285SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
24872dbafdc0SKevin Wolf             if (req == self || (!req->serialising && !self->serialising)) {
248865afd211SKevin Wolf                 continue;
248965afd211SKevin Wolf             }
24907327145fSKevin Wolf             if (tracked_request_overlaps(req, self->overlap_offset,
24917327145fSKevin Wolf                                          self->overlap_bytes))
24927327145fSKevin Wolf             {
24935f8b6491SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
24945f8b6491SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
24955f8b6491SStefan Hajnoczi                  * never happen since it means deadlock.
24965f8b6491SStefan Hajnoczi                  */
24975f8b6491SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
24985f8b6491SStefan Hajnoczi 
24996460440fSKevin Wolf                 /* If the request is already (indirectly) waiting for us, or
25006460440fSKevin Wolf                  * will wait for us as soon as it wakes up, then just go on
25016460440fSKevin Wolf                  * (instead of producing a deadlock in the former case). */
25026460440fSKevin Wolf                 if (!req->waiting_for) {
25036460440fSKevin Wolf                     self->waiting_for = req;
2504f4658285SStefan Hajnoczi                     qemu_co_queue_wait(&req->wait_queue);
25056460440fSKevin Wolf                     self->waiting_for = NULL;
2506f4658285SStefan Hajnoczi                     retry = true;
250728de2dcdSKevin Wolf                     waited = true;
2508f4658285SStefan Hajnoczi                     break;
2509f4658285SStefan Hajnoczi                 }
2510f4658285SStefan Hajnoczi             }
25116460440fSKevin Wolf         }
2512f4658285SStefan Hajnoczi     } while (retry);
251328de2dcdSKevin Wolf 
251428de2dcdSKevin Wolf     return waited;
2515f4658285SStefan Hajnoczi }
2516f4658285SStefan Hajnoczi 
2517756e6736SKevin Wolf /*
2518756e6736SKevin Wolf  * Return values:
2519756e6736SKevin Wolf  * 0        - success
2520756e6736SKevin Wolf  * -EINVAL  - backing format specified, but no file
2521756e6736SKevin Wolf  * -ENOSPC  - can't update the backing file because no space is left in the
2522756e6736SKevin Wolf  *            image file header
2523756e6736SKevin Wolf  * -ENOTSUP - format driver doesn't support changing the backing file
2524756e6736SKevin Wolf  */
2525756e6736SKevin Wolf int bdrv_change_backing_file(BlockDriverState *bs,
2526756e6736SKevin Wolf     const char *backing_file, const char *backing_fmt)
2527756e6736SKevin Wolf {
2528756e6736SKevin Wolf     BlockDriver *drv = bs->drv;
2529469ef350SPaolo Bonzini     int ret;
2530756e6736SKevin Wolf 
25315f377794SPaolo Bonzini     /* Backing file format doesn't make sense without a backing file */
25325f377794SPaolo Bonzini     if (backing_fmt && !backing_file) {
25335f377794SPaolo Bonzini         return -EINVAL;
25345f377794SPaolo Bonzini     }
25355f377794SPaolo Bonzini 
2536756e6736SKevin Wolf     if (drv->bdrv_change_backing_file != NULL) {
2537469ef350SPaolo Bonzini         ret = drv->bdrv_change_backing_file(bs, backing_file, backing_fmt);
2538756e6736SKevin Wolf     } else {
2539469ef350SPaolo Bonzini         ret = -ENOTSUP;
2540756e6736SKevin Wolf     }
2541469ef350SPaolo Bonzini 
2542469ef350SPaolo Bonzini     if (ret == 0) {
2543469ef350SPaolo Bonzini         pstrcpy(bs->backing_file, sizeof(bs->backing_file), backing_file ?: "");
2544469ef350SPaolo Bonzini         pstrcpy(bs->backing_format, sizeof(bs->backing_format), backing_fmt ?: "");
2545469ef350SPaolo Bonzini     }
2546469ef350SPaolo Bonzini     return ret;
2547756e6736SKevin Wolf }
2548756e6736SKevin Wolf 
25496ebdcee2SJeff Cody /*
25506ebdcee2SJeff Cody  * Finds the image layer in the chain that has 'bs' as its backing file.
25516ebdcee2SJeff Cody  *
25526ebdcee2SJeff Cody  * active is the current topmost image.
25536ebdcee2SJeff Cody  *
25546ebdcee2SJeff Cody  * Returns NULL if bs is not found in active's image chain,
25556ebdcee2SJeff Cody  * or if active == bs.
25564caf0fcdSJeff Cody  *
25574caf0fcdSJeff Cody  * Returns the bottommost base image if bs == NULL.
25586ebdcee2SJeff Cody  */
25596ebdcee2SJeff Cody BlockDriverState *bdrv_find_overlay(BlockDriverState *active,
25606ebdcee2SJeff Cody                                     BlockDriverState *bs)
25616ebdcee2SJeff Cody {
25624caf0fcdSJeff Cody     while (active && bs != active->backing_hd) {
25634caf0fcdSJeff Cody         active = active->backing_hd;
25646ebdcee2SJeff Cody     }
25656ebdcee2SJeff Cody 
25664caf0fcdSJeff Cody     return active;
25676ebdcee2SJeff Cody }
25686ebdcee2SJeff Cody 
25694caf0fcdSJeff Cody /* Given a BDS, searches for the base layer. */
25704caf0fcdSJeff Cody BlockDriverState *bdrv_find_base(BlockDriverState *bs)
25714caf0fcdSJeff Cody {
25724caf0fcdSJeff Cody     return bdrv_find_overlay(bs, NULL);
25736ebdcee2SJeff Cody }
25746ebdcee2SJeff Cody 
25756ebdcee2SJeff Cody typedef struct BlkIntermediateStates {
25766ebdcee2SJeff Cody     BlockDriverState *bs;
25776ebdcee2SJeff Cody     QSIMPLEQ_ENTRY(BlkIntermediateStates) entry;
25786ebdcee2SJeff Cody } BlkIntermediateStates;
25796ebdcee2SJeff Cody 
25806ebdcee2SJeff Cody 
25816ebdcee2SJeff Cody /*
25826ebdcee2SJeff Cody  * Drops images above 'base' up to and including 'top', and sets the image
25836ebdcee2SJeff Cody  * above 'top' to have base as its backing file.
25846ebdcee2SJeff Cody  *
25856ebdcee2SJeff Cody  * Requires that the overlay to 'top' is opened r/w, so that the backing file
25866ebdcee2SJeff Cody  * information in 'bs' can be properly updated.
25876ebdcee2SJeff Cody  *
25886ebdcee2SJeff Cody  * E.g., this will convert the following chain:
25896ebdcee2SJeff Cody  * bottom <- base <- intermediate <- top <- active
25906ebdcee2SJeff Cody  *
25916ebdcee2SJeff Cody  * to
25926ebdcee2SJeff Cody  *
25936ebdcee2SJeff Cody  * bottom <- base <- active
25946ebdcee2SJeff Cody  *
25956ebdcee2SJeff Cody  * It is allowed for bottom==base, in which case it converts:
25966ebdcee2SJeff Cody  *
25976ebdcee2SJeff Cody  * base <- intermediate <- top <- active
25986ebdcee2SJeff Cody  *
25996ebdcee2SJeff Cody  * to
26006ebdcee2SJeff Cody  *
26016ebdcee2SJeff Cody  * base <- active
26026ebdcee2SJeff Cody  *
260354e26900SJeff Cody  * If backing_file_str is non-NULL, it will be used when modifying top's
260454e26900SJeff Cody  * overlay image metadata.
260554e26900SJeff Cody  *
26066ebdcee2SJeff Cody  * Error conditions:
26076ebdcee2SJeff Cody  *  if active == top, that is considered an error
26086ebdcee2SJeff Cody  *
26096ebdcee2SJeff Cody  */
26106ebdcee2SJeff Cody int bdrv_drop_intermediate(BlockDriverState *active, BlockDriverState *top,
261154e26900SJeff Cody                            BlockDriverState *base, const char *backing_file_str)
26126ebdcee2SJeff Cody {
26136ebdcee2SJeff Cody     BlockDriverState *intermediate;
26146ebdcee2SJeff Cody     BlockDriverState *base_bs = NULL;
26156ebdcee2SJeff Cody     BlockDriverState *new_top_bs = NULL;
26166ebdcee2SJeff Cody     BlkIntermediateStates *intermediate_state, *next;
26176ebdcee2SJeff Cody     int ret = -EIO;
26186ebdcee2SJeff Cody 
26196ebdcee2SJeff Cody     QSIMPLEQ_HEAD(states_to_delete, BlkIntermediateStates) states_to_delete;
26206ebdcee2SJeff Cody     QSIMPLEQ_INIT(&states_to_delete);
26216ebdcee2SJeff Cody 
26226ebdcee2SJeff Cody     if (!top->drv || !base->drv) {
26236ebdcee2SJeff Cody         goto exit;
26246ebdcee2SJeff Cody     }
26256ebdcee2SJeff Cody 
26266ebdcee2SJeff Cody     new_top_bs = bdrv_find_overlay(active, top);
26276ebdcee2SJeff Cody 
26286ebdcee2SJeff Cody     if (new_top_bs == NULL) {
26296ebdcee2SJeff Cody         /* we could not find the image above 'top', this is an error */
26306ebdcee2SJeff Cody         goto exit;
26316ebdcee2SJeff Cody     }
26326ebdcee2SJeff Cody 
26336ebdcee2SJeff Cody     /* special case of new_top_bs->backing_hd already pointing to base - nothing
26346ebdcee2SJeff Cody      * to do, no intermediate images */
26356ebdcee2SJeff Cody     if (new_top_bs->backing_hd == base) {
26366ebdcee2SJeff Cody         ret = 0;
26376ebdcee2SJeff Cody         goto exit;
26386ebdcee2SJeff Cody     }
26396ebdcee2SJeff Cody 
26406ebdcee2SJeff Cody     intermediate = top;
26416ebdcee2SJeff Cody 
26426ebdcee2SJeff Cody     /* now we will go down through the list, and add each BDS we find
26436ebdcee2SJeff Cody      * into our deletion queue, until we hit the 'base'
26446ebdcee2SJeff Cody      */
26456ebdcee2SJeff Cody     while (intermediate) {
26465839e53bSMarkus Armbruster         intermediate_state = g_new0(BlkIntermediateStates, 1);
26476ebdcee2SJeff Cody         intermediate_state->bs = intermediate;
26486ebdcee2SJeff Cody         QSIMPLEQ_INSERT_TAIL(&states_to_delete, intermediate_state, entry);
26496ebdcee2SJeff Cody 
26506ebdcee2SJeff Cody         if (intermediate->backing_hd == base) {
26516ebdcee2SJeff Cody             base_bs = intermediate->backing_hd;
26526ebdcee2SJeff Cody             break;
26536ebdcee2SJeff Cody         }
26546ebdcee2SJeff Cody         intermediate = intermediate->backing_hd;
26556ebdcee2SJeff Cody     }
26566ebdcee2SJeff Cody     if (base_bs == NULL) {
26576ebdcee2SJeff Cody         /* something went wrong, we did not end at the base. safely
26586ebdcee2SJeff Cody          * unravel everything, and exit with error */
26596ebdcee2SJeff Cody         goto exit;
26606ebdcee2SJeff Cody     }
26616ebdcee2SJeff Cody 
26626ebdcee2SJeff Cody     /* success - we can delete the intermediate states, and link top->base */
266354e26900SJeff Cody     backing_file_str = backing_file_str ? backing_file_str : base_bs->filename;
266454e26900SJeff Cody     ret = bdrv_change_backing_file(new_top_bs, backing_file_str,
26656ebdcee2SJeff Cody                                    base_bs->drv ? base_bs->drv->format_name : "");
26666ebdcee2SJeff Cody     if (ret) {
26676ebdcee2SJeff Cody         goto exit;
26686ebdcee2SJeff Cody     }
2669920beae1SFam Zheng     bdrv_set_backing_hd(new_top_bs, base_bs);
26706ebdcee2SJeff Cody 
26716ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
26726ebdcee2SJeff Cody         /* so that bdrv_close() does not recursively close the chain */
2673920beae1SFam Zheng         bdrv_set_backing_hd(intermediate_state->bs, NULL);
26744f6fd349SFam Zheng         bdrv_unref(intermediate_state->bs);
26756ebdcee2SJeff Cody     }
26766ebdcee2SJeff Cody     ret = 0;
26776ebdcee2SJeff Cody 
26786ebdcee2SJeff Cody exit:
26796ebdcee2SJeff Cody     QSIMPLEQ_FOREACH_SAFE(intermediate_state, &states_to_delete, entry, next) {
26806ebdcee2SJeff Cody         g_free(intermediate_state);
26816ebdcee2SJeff Cody     }
26826ebdcee2SJeff Cody     return ret;
26836ebdcee2SJeff Cody }
26846ebdcee2SJeff Cody 
26856ebdcee2SJeff Cody 
268671d0770cSaliguori static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
268771d0770cSaliguori                                    size_t size)
268871d0770cSaliguori {
268971d0770cSaliguori     int64_t len;
269071d0770cSaliguori 
26911dd3a447SKevin Wolf     if (size > INT_MAX) {
26921dd3a447SKevin Wolf         return -EIO;
26931dd3a447SKevin Wolf     }
26941dd3a447SKevin Wolf 
269571d0770cSaliguori     if (!bdrv_is_inserted(bs))
269671d0770cSaliguori         return -ENOMEDIUM;
269771d0770cSaliguori 
269871d0770cSaliguori     if (bs->growable)
269971d0770cSaliguori         return 0;
270071d0770cSaliguori 
270171d0770cSaliguori     len = bdrv_getlength(bs);
270271d0770cSaliguori 
2703fbb7b4e0SKevin Wolf     if (offset < 0)
2704fbb7b4e0SKevin Wolf         return -EIO;
2705fbb7b4e0SKevin Wolf 
2706fbb7b4e0SKevin Wolf     if ((offset > len) || (len - offset < size))
270771d0770cSaliguori         return -EIO;
270871d0770cSaliguori 
270971d0770cSaliguori     return 0;
271071d0770cSaliguori }
271171d0770cSaliguori 
271271d0770cSaliguori static int bdrv_check_request(BlockDriverState *bs, int64_t sector_num,
271371d0770cSaliguori                               int nb_sectors)
271471d0770cSaliguori {
271554db38a4SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
27168f4754edSKevin Wolf         return -EIO;
27178f4754edSKevin Wolf     }
27188f4754edSKevin Wolf 
2719eb5a3165SJes Sorensen     return bdrv_check_byte_request(bs, sector_num * BDRV_SECTOR_SIZE,
2720eb5a3165SJes Sorensen                                    nb_sectors * BDRV_SECTOR_SIZE);
272171d0770cSaliguori }
272271d0770cSaliguori 
27231c9805a3SStefan Hajnoczi typedef struct RwCo {
27241c9805a3SStefan Hajnoczi     BlockDriverState *bs;
2725775aa8b6SKevin Wolf     int64_t offset;
27261c9805a3SStefan Hajnoczi     QEMUIOVector *qiov;
27271c9805a3SStefan Hajnoczi     bool is_write;
27281c9805a3SStefan Hajnoczi     int ret;
27294105eaaaSPeter Lieven     BdrvRequestFlags flags;
27301c9805a3SStefan Hajnoczi } RwCo;
27311c9805a3SStefan Hajnoczi 
27321c9805a3SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
2733fc01f7e7Sbellard {
27341c9805a3SStefan Hajnoczi     RwCo *rwco = opaque;
2735fc01f7e7Sbellard 
27361c9805a3SStefan Hajnoczi     if (!rwco->is_write) {
2737775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_preadv(rwco->bs, rwco->offset,
2738775aa8b6SKevin Wolf                                       rwco->qiov->size, rwco->qiov,
27394105eaaaSPeter Lieven                                       rwco->flags);
27401c9805a3SStefan Hajnoczi     } else {
2741775aa8b6SKevin Wolf         rwco->ret = bdrv_co_do_pwritev(rwco->bs, rwco->offset,
2742775aa8b6SKevin Wolf                                        rwco->qiov->size, rwco->qiov,
27434105eaaaSPeter Lieven                                        rwco->flags);
27441c9805a3SStefan Hajnoczi     }
27451c9805a3SStefan Hajnoczi }
2746e7a8a783SKevin Wolf 
27471c9805a3SStefan Hajnoczi /*
27488d3b1a2dSKevin Wolf  * Process a vectored synchronous request using coroutines
27491c9805a3SStefan Hajnoczi  */
2750775aa8b6SKevin Wolf static int bdrv_prwv_co(BlockDriverState *bs, int64_t offset,
27514105eaaaSPeter Lieven                         QEMUIOVector *qiov, bool is_write,
27524105eaaaSPeter Lieven                         BdrvRequestFlags flags)
27531c9805a3SStefan Hajnoczi {
27541c9805a3SStefan Hajnoczi     Coroutine *co;
27551c9805a3SStefan Hajnoczi     RwCo rwco = {
27561c9805a3SStefan Hajnoczi         .bs = bs,
2757775aa8b6SKevin Wolf         .offset = offset,
27588d3b1a2dSKevin Wolf         .qiov = qiov,
27591c9805a3SStefan Hajnoczi         .is_write = is_write,
27601c9805a3SStefan Hajnoczi         .ret = NOT_DONE,
27614105eaaaSPeter Lieven         .flags = flags,
27621c9805a3SStefan Hajnoczi     };
27631c9805a3SStefan Hajnoczi 
2764498e386cSZhi Yong Wu     /**
2765498e386cSZhi Yong Wu      * In sync call context, when the vcpu is blocked, this throttling timer
2766498e386cSZhi Yong Wu      * will not fire; so the I/O throttling function has to be disabled here
2767498e386cSZhi Yong Wu      * if it has been enabled.
2768498e386cSZhi Yong Wu      */
2769498e386cSZhi Yong Wu     if (bs->io_limits_enabled) {
2770498e386cSZhi Yong Wu         fprintf(stderr, "Disabling I/O throttling on '%s' due "
2771498e386cSZhi Yong Wu                         "to synchronous I/O.\n", bdrv_get_device_name(bs));
2772498e386cSZhi Yong Wu         bdrv_io_limits_disable(bs);
2773498e386cSZhi Yong Wu     }
2774498e386cSZhi Yong Wu 
27751c9805a3SStefan Hajnoczi     if (qemu_in_coroutine()) {
27761c9805a3SStefan Hajnoczi         /* Fast-path if already in coroutine context */
27771c9805a3SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
27781c9805a3SStefan Hajnoczi     } else {
27792572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
27802572b37aSStefan Hajnoczi 
27811c9805a3SStefan Hajnoczi         co = qemu_coroutine_create(bdrv_rw_co_entry);
27821c9805a3SStefan Hajnoczi         qemu_coroutine_enter(co, &rwco);
27831c9805a3SStefan Hajnoczi         while (rwco.ret == NOT_DONE) {
27842572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
27851c9805a3SStefan Hajnoczi         }
27861c9805a3SStefan Hajnoczi     }
27871c9805a3SStefan Hajnoczi     return rwco.ret;
2788e7a8a783SKevin Wolf }
2789e7a8a783SKevin Wolf 
27908d3b1a2dSKevin Wolf /*
27918d3b1a2dSKevin Wolf  * Process a synchronous request using coroutines
27928d3b1a2dSKevin Wolf  */
27938d3b1a2dSKevin Wolf static int bdrv_rw_co(BlockDriverState *bs, int64_t sector_num, uint8_t *buf,
27944105eaaaSPeter Lieven                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
27958d3b1a2dSKevin Wolf {
27968d3b1a2dSKevin Wolf     QEMUIOVector qiov;
27978d3b1a2dSKevin Wolf     struct iovec iov = {
27988d3b1a2dSKevin Wolf         .iov_base = (void *)buf,
27998d3b1a2dSKevin Wolf         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
28008d3b1a2dSKevin Wolf     };
28018d3b1a2dSKevin Wolf 
2802da15ee51SKevin Wolf     if (nb_sectors < 0 || nb_sectors > INT_MAX / BDRV_SECTOR_SIZE) {
2803da15ee51SKevin Wolf         return -EINVAL;
2804da15ee51SKevin Wolf     }
2805da15ee51SKevin Wolf 
28068d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2807775aa8b6SKevin Wolf     return bdrv_prwv_co(bs, sector_num << BDRV_SECTOR_BITS,
2808775aa8b6SKevin Wolf                         &qiov, is_write, flags);
28098d3b1a2dSKevin Wolf }
28108d3b1a2dSKevin Wolf 
28111c9805a3SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
28121c9805a3SStefan Hajnoczi int bdrv_read(BlockDriverState *bs, int64_t sector_num,
28131c9805a3SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
28141c9805a3SStefan Hajnoczi {
28154105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, buf, nb_sectors, false, 0);
281683f64091Sbellard }
2817fc01f7e7Sbellard 
281807d27a44SMarkus Armbruster /* Just like bdrv_read(), but with I/O throttling temporarily disabled */
281907d27a44SMarkus Armbruster int bdrv_read_unthrottled(BlockDriverState *bs, int64_t sector_num,
282007d27a44SMarkus Armbruster                           uint8_t *buf, int nb_sectors)
282107d27a44SMarkus Armbruster {
282207d27a44SMarkus Armbruster     bool enabled;
282307d27a44SMarkus Armbruster     int ret;
282407d27a44SMarkus Armbruster 
282507d27a44SMarkus Armbruster     enabled = bs->io_limits_enabled;
282607d27a44SMarkus Armbruster     bs->io_limits_enabled = false;
28274e7395e8SPeter Lieven     ret = bdrv_read(bs, sector_num, buf, nb_sectors);
282807d27a44SMarkus Armbruster     bs->io_limits_enabled = enabled;
282907d27a44SMarkus Armbruster     return ret;
283007d27a44SMarkus Armbruster }
283107d27a44SMarkus Armbruster 
283219cb3738Sbellard /* Return < 0 if error. Important errors are:
283319cb3738Sbellard   -EIO         generic I/O error (may happen for all errors)
283419cb3738Sbellard   -ENOMEDIUM   No media inserted.
283519cb3738Sbellard   -EINVAL      Invalid sector number or nb_sectors
283619cb3738Sbellard   -EACCES      Trying to write a read-only device
283719cb3738Sbellard */
2838fc01f7e7Sbellard int bdrv_write(BlockDriverState *bs, int64_t sector_num,
2839fc01f7e7Sbellard                const uint8_t *buf, int nb_sectors)
2840fc01f7e7Sbellard {
28414105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
284283f64091Sbellard }
284383f64091Sbellard 
2844aa7bfbffSPeter Lieven int bdrv_write_zeroes(BlockDriverState *bs, int64_t sector_num,
2845aa7bfbffSPeter Lieven                       int nb_sectors, BdrvRequestFlags flags)
28464105eaaaSPeter Lieven {
28474105eaaaSPeter Lieven     return bdrv_rw_co(bs, sector_num, NULL, nb_sectors, true,
2848aa7bfbffSPeter Lieven                       BDRV_REQ_ZERO_WRITE | flags);
28498d3b1a2dSKevin Wolf }
28508d3b1a2dSKevin Wolf 
2851d75cbb5eSPeter Lieven /*
2852d75cbb5eSPeter Lieven  * Completely zero out a block device with the help of bdrv_write_zeroes.
2853d75cbb5eSPeter Lieven  * The operation is sped up by checking the block status and only writing
2854d75cbb5eSPeter Lieven  * zeroes to the device if they currently do not return zeroes. Optional
2855d75cbb5eSPeter Lieven  * flags are passed through to bdrv_write_zeroes (e.g. BDRV_REQ_MAY_UNMAP).
2856d75cbb5eSPeter Lieven  *
2857d75cbb5eSPeter Lieven  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
2858d75cbb5eSPeter Lieven  */
2859d75cbb5eSPeter Lieven int bdrv_make_zero(BlockDriverState *bs, BdrvRequestFlags flags)
2860d75cbb5eSPeter Lieven {
2861d32f7c10SMarkus Armbruster     int64_t target_sectors, ret, nb_sectors, sector_num = 0;
2862d75cbb5eSPeter Lieven     int n;
2863d75cbb5eSPeter Lieven 
2864d32f7c10SMarkus Armbruster     target_sectors = bdrv_nb_sectors(bs);
2865d32f7c10SMarkus Armbruster     if (target_sectors < 0) {
2866d32f7c10SMarkus Armbruster         return target_sectors;
28679ce10c0bSKevin Wolf     }
28689ce10c0bSKevin Wolf 
2869d75cbb5eSPeter Lieven     for (;;) {
2870d32f7c10SMarkus Armbruster         nb_sectors = target_sectors - sector_num;
2871d75cbb5eSPeter Lieven         if (nb_sectors <= 0) {
2872d75cbb5eSPeter Lieven             return 0;
2873d75cbb5eSPeter Lieven         }
2874d75cbb5eSPeter Lieven         if (nb_sectors > INT_MAX) {
2875d75cbb5eSPeter Lieven             nb_sectors = INT_MAX;
2876d75cbb5eSPeter Lieven         }
2877d75cbb5eSPeter Lieven         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n);
28783d94ce60SPeter Lieven         if (ret < 0) {
28793d94ce60SPeter Lieven             error_report("error getting block status at sector %" PRId64 ": %s",
28803d94ce60SPeter Lieven                          sector_num, strerror(-ret));
28813d94ce60SPeter Lieven             return ret;
28823d94ce60SPeter Lieven         }
2883d75cbb5eSPeter Lieven         if (ret & BDRV_BLOCK_ZERO) {
2884d75cbb5eSPeter Lieven             sector_num += n;
2885d75cbb5eSPeter Lieven             continue;
2886d75cbb5eSPeter Lieven         }
2887d75cbb5eSPeter Lieven         ret = bdrv_write_zeroes(bs, sector_num, n, flags);
2888d75cbb5eSPeter Lieven         if (ret < 0) {
2889d75cbb5eSPeter Lieven             error_report("error writing zeroes at sector %" PRId64 ": %s",
2890d75cbb5eSPeter Lieven                          sector_num, strerror(-ret));
2891d75cbb5eSPeter Lieven             return ret;
2892d75cbb5eSPeter Lieven         }
2893d75cbb5eSPeter Lieven         sector_num += n;
2894d75cbb5eSPeter Lieven     }
2895d75cbb5eSPeter Lieven }
2896d75cbb5eSPeter Lieven 
2897a3ef6571SKevin Wolf int bdrv_pread(BlockDriverState *bs, int64_t offset, void *buf, int bytes)
289883f64091Sbellard {
2899a3ef6571SKevin Wolf     QEMUIOVector qiov;
2900a3ef6571SKevin Wolf     struct iovec iov = {
2901a3ef6571SKevin Wolf         .iov_base = (void *)buf,
2902a3ef6571SKevin Wolf         .iov_len = bytes,
2903a3ef6571SKevin Wolf     };
29049a8c4cceSKevin Wolf     int ret;
290583f64091Sbellard 
2906a3ef6571SKevin Wolf     if (bytes < 0) {
2907a3ef6571SKevin Wolf         return -EINVAL;
290883f64091Sbellard     }
290983f64091Sbellard 
2910a3ef6571SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2911a3ef6571SKevin Wolf     ret = bdrv_prwv_co(bs, offset, &qiov, false, 0);
2912a3ef6571SKevin Wolf     if (ret < 0) {
29139a8c4cceSKevin Wolf         return ret;
291483f64091Sbellard     }
291583f64091Sbellard 
2916a3ef6571SKevin Wolf     return bytes;
291783f64091Sbellard }
291883f64091Sbellard 
29198d3b1a2dSKevin Wolf int bdrv_pwritev(BlockDriverState *bs, int64_t offset, QEMUIOVector *qiov)
292083f64091Sbellard {
29219a8c4cceSKevin Wolf     int ret;
292283f64091Sbellard 
29238407d5d7SKevin Wolf     ret = bdrv_prwv_co(bs, offset, qiov, true, 0);
29248d3b1a2dSKevin Wolf     if (ret < 0) {
29259a8c4cceSKevin Wolf         return ret;
29268d3b1a2dSKevin Wolf     }
29278d3b1a2dSKevin Wolf 
29288d3b1a2dSKevin Wolf     return qiov->size;
29298d3b1a2dSKevin Wolf }
29308d3b1a2dSKevin Wolf 
29318d3b1a2dSKevin Wolf int bdrv_pwrite(BlockDriverState *bs, int64_t offset,
29328407d5d7SKevin Wolf                 const void *buf, int bytes)
29338d3b1a2dSKevin Wolf {
29348d3b1a2dSKevin Wolf     QEMUIOVector qiov;
29358d3b1a2dSKevin Wolf     struct iovec iov = {
29368d3b1a2dSKevin Wolf         .iov_base   = (void *) buf,
29378407d5d7SKevin Wolf         .iov_len    = bytes,
29388d3b1a2dSKevin Wolf     };
29398d3b1a2dSKevin Wolf 
29408407d5d7SKevin Wolf     if (bytes < 0) {
29418407d5d7SKevin Wolf         return -EINVAL;
29428407d5d7SKevin Wolf     }
29438407d5d7SKevin Wolf 
29448d3b1a2dSKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
29458d3b1a2dSKevin Wolf     return bdrv_pwritev(bs, offset, &qiov);
294683f64091Sbellard }
294783f64091Sbellard 
2948f08145feSKevin Wolf /*
2949f08145feSKevin Wolf  * Writes to the file and ensures that no writes are reordered across this
2950f08145feSKevin Wolf  * request (acts as a barrier)
2951f08145feSKevin Wolf  *
2952f08145feSKevin Wolf  * Returns 0 on success, -errno in error cases.
2953f08145feSKevin Wolf  */
2954f08145feSKevin Wolf int bdrv_pwrite_sync(BlockDriverState *bs, int64_t offset,
2955f08145feSKevin Wolf     const void *buf, int count)
2956f08145feSKevin Wolf {
2957f08145feSKevin Wolf     int ret;
2958f08145feSKevin Wolf 
2959f08145feSKevin Wolf     ret = bdrv_pwrite(bs, offset, buf, count);
2960f08145feSKevin Wolf     if (ret < 0) {
2961f08145feSKevin Wolf         return ret;
2962f08145feSKevin Wolf     }
2963f08145feSKevin Wolf 
2964f05fa4adSPaolo Bonzini     /* No flush needed for cache modes that already do it */
2965f05fa4adSPaolo Bonzini     if (bs->enable_write_cache) {
2966f08145feSKevin Wolf         bdrv_flush(bs);
2967f08145feSKevin Wolf     }
2968f08145feSKevin Wolf 
2969f08145feSKevin Wolf     return 0;
2970f08145feSKevin Wolf }
2971f08145feSKevin Wolf 
2972470c0504SStefan Hajnoczi static int coroutine_fn bdrv_co_do_copy_on_readv(BlockDriverState *bs,
2973ab185921SStefan Hajnoczi         int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
2974ab185921SStefan Hajnoczi {
2975ab185921SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
2976ab185921SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
2977ab185921SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
2978ab185921SStefan Hajnoczi      * where anything might happen inside guest memory.
2979ab185921SStefan Hajnoczi      */
2980ab185921SStefan Hajnoczi     void *bounce_buffer;
2981ab185921SStefan Hajnoczi 
298279c053bdSStefan Hajnoczi     BlockDriver *drv = bs->drv;
2983ab185921SStefan Hajnoczi     struct iovec iov;
2984ab185921SStefan Hajnoczi     QEMUIOVector bounce_qiov;
2985ab185921SStefan Hajnoczi     int64_t cluster_sector_num;
2986ab185921SStefan Hajnoczi     int cluster_nb_sectors;
2987ab185921SStefan Hajnoczi     size_t skip_bytes;
2988ab185921SStefan Hajnoczi     int ret;
2989ab185921SStefan Hajnoczi 
2990ab185921SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
2991ab185921SStefan Hajnoczi      * allocating cluster in the image file.
2992ab185921SStefan Hajnoczi      */
2993343bded4SPaolo Bonzini     bdrv_round_to_clusters(bs, sector_num, nb_sectors,
2994ab185921SStefan Hajnoczi                            &cluster_sector_num, &cluster_nb_sectors);
2995ab185921SStefan Hajnoczi 
2996470c0504SStefan Hajnoczi     trace_bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors,
2997ab185921SStefan Hajnoczi                                    cluster_sector_num, cluster_nb_sectors);
2998ab185921SStefan Hajnoczi 
2999ab185921SStefan Hajnoczi     iov.iov_len = cluster_nb_sectors * BDRV_SECTOR_SIZE;
3000857d4f46SKevin Wolf     iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
3001857d4f46SKevin Wolf     if (bounce_buffer == NULL) {
3002857d4f46SKevin Wolf         ret = -ENOMEM;
3003857d4f46SKevin Wolf         goto err;
3004857d4f46SKevin Wolf     }
3005857d4f46SKevin Wolf 
3006ab185921SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
3007ab185921SStefan Hajnoczi 
300879c053bdSStefan Hajnoczi     ret = drv->bdrv_co_readv(bs, cluster_sector_num, cluster_nb_sectors,
3009ab185921SStefan Hajnoczi                              &bounce_qiov);
3010ab185921SStefan Hajnoczi     if (ret < 0) {
3011ab185921SStefan Hajnoczi         goto err;
3012ab185921SStefan Hajnoczi     }
3013ab185921SStefan Hajnoczi 
301479c053bdSStefan Hajnoczi     if (drv->bdrv_co_write_zeroes &&
301579c053bdSStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
3016621f0589SKevin Wolf         ret = bdrv_co_do_write_zeroes(bs, cluster_sector_num,
3017aa7bfbffSPeter Lieven                                       cluster_nb_sectors, 0);
301879c053bdSStefan Hajnoczi     } else {
3019f05fa4adSPaolo Bonzini         /* This does not change the data on the disk, it is not necessary
3020f05fa4adSPaolo Bonzini          * to flush even in cache=writethrough mode.
3021f05fa4adSPaolo Bonzini          */
302279c053bdSStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, cluster_sector_num, cluster_nb_sectors,
3023ab185921SStefan Hajnoczi                                   &bounce_qiov);
302479c053bdSStefan Hajnoczi     }
302579c053bdSStefan Hajnoczi 
3026ab185921SStefan Hajnoczi     if (ret < 0) {
3027ab185921SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
3028ab185921SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
3029ab185921SStefan Hajnoczi          * Simply report it in all cases.
3030ab185921SStefan Hajnoczi          */
3031ab185921SStefan Hajnoczi         goto err;
3032ab185921SStefan Hajnoczi     }
3033ab185921SStefan Hajnoczi 
3034ab185921SStefan Hajnoczi     skip_bytes = (sector_num - cluster_sector_num) * BDRV_SECTOR_SIZE;
303503396148SMichael Tokarev     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes,
3036ab185921SStefan Hajnoczi                         nb_sectors * BDRV_SECTOR_SIZE);
3037ab185921SStefan Hajnoczi 
3038ab185921SStefan Hajnoczi err:
3039ab185921SStefan Hajnoczi     qemu_vfree(bounce_buffer);
3040ab185921SStefan Hajnoczi     return ret;
3041ab185921SStefan Hajnoczi }
3042ab185921SStefan Hajnoczi 
3043c5fbe571SStefan Hajnoczi /*
3044d0c7f642SKevin Wolf  * Forwards an already correctly aligned request to the BlockDriver. This
3045d0c7f642SKevin Wolf  * handles copy on read and zeroing after EOF; any other features must be
3046d0c7f642SKevin Wolf  * implemented by the caller.
3047c5fbe571SStefan Hajnoczi  */
3048d0c7f642SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BlockDriverState *bs,
304965afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
3050ec746e10SKevin Wolf     int64_t align, QEMUIOVector *qiov, int flags)
3051da1fa91dSKevin Wolf {
3052da1fa91dSKevin Wolf     BlockDriver *drv = bs->drv;
3053dbffbdcfSStefan Hajnoczi     int ret;
3054da1fa91dSKevin Wolf 
3055d0c7f642SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3056d0c7f642SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3057da1fa91dSKevin Wolf 
3058d0c7f642SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3059d0c7f642SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
30608eb029c2SKevin Wolf     assert(!qiov || bytes == qiov->size);
3061d0c7f642SKevin Wolf 
3062d0c7f642SKevin Wolf     /* Handle Copy on Read and associated serialisation */
3063470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
30647327145fSKevin Wolf         /* If we touch the same cluster it counts as an overlap.  This
30657327145fSKevin Wolf          * guarantees that allocating writes will be serialized and not race
30667327145fSKevin Wolf          * with each other for the same cluster.  For example, in copy-on-read
30677327145fSKevin Wolf          * it ensures that the CoR read and write operations are atomic and
30687327145fSKevin Wolf          * guest writes cannot interleave between them. */
30697327145fSKevin Wolf         mark_request_serialising(req, bdrv_get_cluster_size(bs));
3070470c0504SStefan Hajnoczi     }
3071470c0504SStefan Hajnoczi 
30722dbafdc0SKevin Wolf     wait_serialising_requests(req);
3073f4658285SStefan Hajnoczi 
3074470c0504SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
3075ab185921SStefan Hajnoczi         int pnum;
3076ab185921SStefan Hajnoczi 
3077bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(bs, sector_num, nb_sectors, &pnum);
3078ab185921SStefan Hajnoczi         if (ret < 0) {
3079ab185921SStefan Hajnoczi             goto out;
3080ab185921SStefan Hajnoczi         }
3081ab185921SStefan Hajnoczi 
3082ab185921SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
3083470c0504SStefan Hajnoczi             ret = bdrv_co_do_copy_on_readv(bs, sector_num, nb_sectors, qiov);
3084ab185921SStefan Hajnoczi             goto out;
3085ab185921SStefan Hajnoczi         }
3086ab185921SStefan Hajnoczi     }
3087ab185921SStefan Hajnoczi 
3088d0c7f642SKevin Wolf     /* Forward the request to the BlockDriver */
3089893a8f62SMORITA Kazutaka     if (!(bs->zero_beyond_eof && bs->growable)) {
3090dbffbdcfSStefan Hajnoczi         ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
3091893a8f62SMORITA Kazutaka     } else {
3092893a8f62SMORITA Kazutaka         /* Read zeros after EOF of growable BDSes */
30934049082cSMarkus Armbruster         int64_t total_sectors, max_nb_sectors;
3094893a8f62SMORITA Kazutaka 
30954049082cSMarkus Armbruster         total_sectors = bdrv_nb_sectors(bs);
30964049082cSMarkus Armbruster         if (total_sectors < 0) {
30974049082cSMarkus Armbruster             ret = total_sectors;
3098893a8f62SMORITA Kazutaka             goto out;
3099893a8f62SMORITA Kazutaka         }
3100893a8f62SMORITA Kazutaka 
31015f5bcd80SKevin Wolf         max_nb_sectors = ROUND_UP(MAX(0, total_sectors - sector_num),
31025f5bcd80SKevin Wolf                                   align >> BDRV_SECTOR_BITS);
3103893a8f62SMORITA Kazutaka         if (max_nb_sectors > 0) {
310433f461e0SKevin Wolf             QEMUIOVector local_qiov;
310533f461e0SKevin Wolf             size_t local_sectors;
310633f461e0SKevin Wolf 
310733f461e0SKevin Wolf             max_nb_sectors = MIN(max_nb_sectors, SIZE_MAX / BDRV_SECTOR_BITS);
310833f461e0SKevin Wolf             local_sectors = MIN(max_nb_sectors, nb_sectors);
310933f461e0SKevin Wolf 
311033f461e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov);
311133f461e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0,
311233f461e0SKevin Wolf                               local_sectors * BDRV_SECTOR_SIZE);
311333f461e0SKevin Wolf 
311433f461e0SKevin Wolf             ret = drv->bdrv_co_readv(bs, sector_num, local_sectors,
311533f461e0SKevin Wolf                                      &local_qiov);
311633f461e0SKevin Wolf 
311733f461e0SKevin Wolf             qemu_iovec_destroy(&local_qiov);
3118893a8f62SMORITA Kazutaka         } else {
3119893a8f62SMORITA Kazutaka             ret = 0;
3120893a8f62SMORITA Kazutaka         }
3121893a8f62SMORITA Kazutaka 
3122893a8f62SMORITA Kazutaka         /* Reading beyond end of file is supposed to produce zeroes */
3123893a8f62SMORITA Kazutaka         if (ret == 0 && total_sectors < sector_num + nb_sectors) {
3124893a8f62SMORITA Kazutaka             uint64_t offset = MAX(0, total_sectors - sector_num);
3125893a8f62SMORITA Kazutaka             uint64_t bytes = (sector_num + nb_sectors - offset) *
3126893a8f62SMORITA Kazutaka                               BDRV_SECTOR_SIZE;
3127893a8f62SMORITA Kazutaka             qemu_iovec_memset(qiov, offset * BDRV_SECTOR_SIZE, 0, bytes);
3128893a8f62SMORITA Kazutaka         }
3129893a8f62SMORITA Kazutaka     }
3130ab185921SStefan Hajnoczi 
3131ab185921SStefan Hajnoczi out:
3132dbffbdcfSStefan Hajnoczi     return ret;
3133da1fa91dSKevin Wolf }
3134da1fa91dSKevin Wolf 
3135d0c7f642SKevin Wolf /*
3136d0c7f642SKevin Wolf  * Handle a read request in coroutine context
3137d0c7f642SKevin Wolf  */
31381b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_preadv(BlockDriverState *bs,
31391b0288aeSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3140d0c7f642SKevin Wolf     BdrvRequestFlags flags)
3141d0c7f642SKevin Wolf {
3142d0c7f642SKevin Wolf     BlockDriver *drv = bs->drv;
314365afd211SKevin Wolf     BdrvTrackedRequest req;
314465afd211SKevin Wolf 
31451b0288aeSKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
31461b0288aeSKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
31471b0288aeSKevin Wolf     uint8_t *head_buf = NULL;
31481b0288aeSKevin Wolf     uint8_t *tail_buf = NULL;
31491b0288aeSKevin Wolf     QEMUIOVector local_qiov;
31501b0288aeSKevin Wolf     bool use_local_qiov = false;
3151d0c7f642SKevin Wolf     int ret;
3152d0c7f642SKevin Wolf 
3153d0c7f642SKevin Wolf     if (!drv) {
3154d0c7f642SKevin Wolf         return -ENOMEDIUM;
3155d0c7f642SKevin Wolf     }
31561b0288aeSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3157d0c7f642SKevin Wolf         return -EIO;
3158d0c7f642SKevin Wolf     }
3159d0c7f642SKevin Wolf 
3160d0c7f642SKevin Wolf     if (bs->copy_on_read) {
3161d0c7f642SKevin Wolf         flags |= BDRV_REQ_COPY_ON_READ;
3162d0c7f642SKevin Wolf     }
3163d0c7f642SKevin Wolf 
3164d0c7f642SKevin Wolf     /* throttling disk I/O */
3165d0c7f642SKevin Wolf     if (bs->io_limits_enabled) {
3166d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, false);
3167d0c7f642SKevin Wolf     }
3168d0c7f642SKevin Wolf 
31691b0288aeSKevin Wolf     /* Align read if necessary by padding qiov */
31701b0288aeSKevin Wolf     if (offset & (align - 1)) {
31711b0288aeSKevin Wolf         head_buf = qemu_blockalign(bs, align);
31721b0288aeSKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
31731b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
31741b0288aeSKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
31751b0288aeSKevin Wolf         use_local_qiov = true;
31761b0288aeSKevin Wolf 
31771b0288aeSKevin Wolf         bytes += offset & (align - 1);
31781b0288aeSKevin Wolf         offset = offset & ~(align - 1);
31791b0288aeSKevin Wolf     }
31801b0288aeSKevin Wolf 
31811b0288aeSKevin Wolf     if ((offset + bytes) & (align - 1)) {
31821b0288aeSKevin Wolf         if (!use_local_qiov) {
31831b0288aeSKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
31841b0288aeSKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
31851b0288aeSKevin Wolf             use_local_qiov = true;
31861b0288aeSKevin Wolf         }
31871b0288aeSKevin Wolf         tail_buf = qemu_blockalign(bs, align);
31881b0288aeSKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf,
31891b0288aeSKevin Wolf                        align - ((offset + bytes) & (align - 1)));
31901b0288aeSKevin Wolf 
31911b0288aeSKevin Wolf         bytes = ROUND_UP(bytes, align);
31921b0288aeSKevin Wolf     }
31931b0288aeSKevin Wolf 
319465afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, false);
3195ec746e10SKevin Wolf     ret = bdrv_aligned_preadv(bs, &req, offset, bytes, align,
31961b0288aeSKevin Wolf                               use_local_qiov ? &local_qiov : qiov,
31971b0288aeSKevin Wolf                               flags);
319865afd211SKevin Wolf     tracked_request_end(&req);
31991b0288aeSKevin Wolf 
32001b0288aeSKevin Wolf     if (use_local_qiov) {
32011b0288aeSKevin Wolf         qemu_iovec_destroy(&local_qiov);
32021b0288aeSKevin Wolf         qemu_vfree(head_buf);
32031b0288aeSKevin Wolf         qemu_vfree(tail_buf);
32041b0288aeSKevin Wolf     }
32051b0288aeSKevin Wolf 
3206d0c7f642SKevin Wolf     return ret;
3207d0c7f642SKevin Wolf }
3208d0c7f642SKevin Wolf 
32091b0288aeSKevin Wolf static int coroutine_fn bdrv_co_do_readv(BlockDriverState *bs,
32101b0288aeSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
32111b0288aeSKevin Wolf     BdrvRequestFlags flags)
32121b0288aeSKevin Wolf {
32131b0288aeSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (UINT_MAX >> BDRV_SECTOR_BITS)) {
32141b0288aeSKevin Wolf         return -EINVAL;
32151b0288aeSKevin Wolf     }
32161b0288aeSKevin Wolf 
32171b0288aeSKevin Wolf     return bdrv_co_do_preadv(bs, sector_num << BDRV_SECTOR_BITS,
32181b0288aeSKevin Wolf                              nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
32191b0288aeSKevin Wolf }
32201b0288aeSKevin Wolf 
3221c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_readv(BlockDriverState *bs, int64_t sector_num,
3222da1fa91dSKevin Wolf     int nb_sectors, QEMUIOVector *qiov)
3223da1fa91dSKevin Wolf {
3224c5fbe571SStefan Hajnoczi     trace_bdrv_co_readv(bs, sector_num, nb_sectors);
3225da1fa91dSKevin Wolf 
3226470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov, 0);
3227470c0504SStefan Hajnoczi }
3228470c0504SStefan Hajnoczi 
3229470c0504SStefan Hajnoczi int coroutine_fn bdrv_co_copy_on_readv(BlockDriverState *bs,
3230470c0504SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov)
3231470c0504SStefan Hajnoczi {
3232470c0504SStefan Hajnoczi     trace_bdrv_co_copy_on_readv(bs, sector_num, nb_sectors);
3233470c0504SStefan Hajnoczi 
3234470c0504SStefan Hajnoczi     return bdrv_co_do_readv(bs, sector_num, nb_sectors, qiov,
3235470c0504SStefan Hajnoczi                             BDRV_REQ_COPY_ON_READ);
3236c5fbe571SStefan Hajnoczi }
3237c5fbe571SStefan Hajnoczi 
3238c31cb707SPeter Lieven /* if no limit is specified in the BlockLimits use a default
3239c31cb707SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
3240c31cb707SPeter Lieven  */
3241c31cb707SPeter Lieven #define MAX_WRITE_ZEROES_DEFAULT 32768
3242c31cb707SPeter Lieven 
3243f08f2ddaSStefan Hajnoczi static int coroutine_fn bdrv_co_do_write_zeroes(BlockDriverState *bs,
3244aa7bfbffSPeter Lieven     int64_t sector_num, int nb_sectors, BdrvRequestFlags flags)
3245f08f2ddaSStefan Hajnoczi {
3246f08f2ddaSStefan Hajnoczi     BlockDriver *drv = bs->drv;
3247f08f2ddaSStefan Hajnoczi     QEMUIOVector qiov;
3248c31cb707SPeter Lieven     struct iovec iov = {0};
3249c31cb707SPeter Lieven     int ret = 0;
3250f08f2ddaSStefan Hajnoczi 
3251c31cb707SPeter Lieven     int max_write_zeroes = bs->bl.max_write_zeroes ?
3252c31cb707SPeter Lieven                            bs->bl.max_write_zeroes : MAX_WRITE_ZEROES_DEFAULT;
3253621f0589SKevin Wolf 
3254c31cb707SPeter Lieven     while (nb_sectors > 0 && !ret) {
3255c31cb707SPeter Lieven         int num = nb_sectors;
3256c31cb707SPeter Lieven 
3257b8d71c09SPaolo Bonzini         /* Align request.  Block drivers can expect the "bulk" of the request
3258b8d71c09SPaolo Bonzini          * to be aligned.
3259b8d71c09SPaolo Bonzini          */
3260b8d71c09SPaolo Bonzini         if (bs->bl.write_zeroes_alignment
3261b8d71c09SPaolo Bonzini             && num > bs->bl.write_zeroes_alignment) {
3262b8d71c09SPaolo Bonzini             if (sector_num % bs->bl.write_zeroes_alignment != 0) {
3263b8d71c09SPaolo Bonzini                 /* Make a small request up to the first aligned sector.  */
3264c31cb707SPeter Lieven                 num = bs->bl.write_zeroes_alignment;
3265c31cb707SPeter Lieven                 num -= sector_num % bs->bl.write_zeroes_alignment;
3266b8d71c09SPaolo Bonzini             } else if ((sector_num + num) % bs->bl.write_zeroes_alignment != 0) {
3267b8d71c09SPaolo Bonzini                 /* Shorten the request to the last aligned sector.  num cannot
3268b8d71c09SPaolo Bonzini                  * underflow because num > bs->bl.write_zeroes_alignment.
3269b8d71c09SPaolo Bonzini                  */
3270b8d71c09SPaolo Bonzini                 num -= (sector_num + num) % bs->bl.write_zeroes_alignment;
3271b8d71c09SPaolo Bonzini             }
3272c31cb707SPeter Lieven         }
3273c31cb707SPeter Lieven 
3274c31cb707SPeter Lieven         /* limit request size */
3275c31cb707SPeter Lieven         if (num > max_write_zeroes) {
3276c31cb707SPeter Lieven             num = max_write_zeroes;
3277c31cb707SPeter Lieven         }
3278c31cb707SPeter Lieven 
3279c31cb707SPeter Lieven         ret = -ENOTSUP;
3280f08f2ddaSStefan Hajnoczi         /* First try the efficient write zeroes operation */
3281f08f2ddaSStefan Hajnoczi         if (drv->bdrv_co_write_zeroes) {
3282c31cb707SPeter Lieven             ret = drv->bdrv_co_write_zeroes(bs, sector_num, num, flags);
3283f08f2ddaSStefan Hajnoczi         }
3284f08f2ddaSStefan Hajnoczi 
3285c31cb707SPeter Lieven         if (ret == -ENOTSUP) {
3286f08f2ddaSStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
3287c31cb707SPeter Lieven             iov.iov_len = num * BDRV_SECTOR_SIZE;
3288c31cb707SPeter Lieven             if (iov.iov_base == NULL) {
3289857d4f46SKevin Wolf                 iov.iov_base = qemu_try_blockalign(bs, num * BDRV_SECTOR_SIZE);
3290857d4f46SKevin Wolf                 if (iov.iov_base == NULL) {
3291857d4f46SKevin Wolf                     ret = -ENOMEM;
3292857d4f46SKevin Wolf                     goto fail;
3293857d4f46SKevin Wolf                 }
3294b8d71c09SPaolo Bonzini                 memset(iov.iov_base, 0, num * BDRV_SECTOR_SIZE);
3295c31cb707SPeter Lieven             }
3296f08f2ddaSStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
3297f08f2ddaSStefan Hajnoczi 
3298c31cb707SPeter Lieven             ret = drv->bdrv_co_writev(bs, sector_num, num, &qiov);
3299b8d71c09SPaolo Bonzini 
3300b8d71c09SPaolo Bonzini             /* Keep bounce buffer around if it is big enough for all
3301b8d71c09SPaolo Bonzini              * all future requests.
3302b8d71c09SPaolo Bonzini              */
3303b8d71c09SPaolo Bonzini             if (num < max_write_zeroes) {
3304b8d71c09SPaolo Bonzini                 qemu_vfree(iov.iov_base);
3305b8d71c09SPaolo Bonzini                 iov.iov_base = NULL;
3306b8d71c09SPaolo Bonzini             }
3307c31cb707SPeter Lieven         }
3308c31cb707SPeter Lieven 
3309c31cb707SPeter Lieven         sector_num += num;
3310c31cb707SPeter Lieven         nb_sectors -= num;
3311c31cb707SPeter Lieven     }
3312f08f2ddaSStefan Hajnoczi 
3313857d4f46SKevin Wolf fail:
3314f08f2ddaSStefan Hajnoczi     qemu_vfree(iov.iov_base);
3315f08f2ddaSStefan Hajnoczi     return ret;
3316f08f2ddaSStefan Hajnoczi }
3317f08f2ddaSStefan Hajnoczi 
3318c5fbe571SStefan Hajnoczi /*
3319b404f720SKevin Wolf  * Forwards an already correctly aligned write request to the BlockDriver.
3320c5fbe571SStefan Hajnoczi  */
3321b404f720SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BlockDriverState *bs,
332265afd211SKevin Wolf     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
332365afd211SKevin Wolf     QEMUIOVector *qiov, int flags)
3324c5fbe571SStefan Hajnoczi {
3325c5fbe571SStefan Hajnoczi     BlockDriver *drv = bs->drv;
332628de2dcdSKevin Wolf     bool waited;
33276b7cb247SStefan Hajnoczi     int ret;
3328da1fa91dSKevin Wolf 
3329b404f720SKevin Wolf     int64_t sector_num = offset >> BDRV_SECTOR_BITS;
3330b404f720SKevin Wolf     unsigned int nb_sectors = bytes >> BDRV_SECTOR_BITS;
3331da1fa91dSKevin Wolf 
3332b404f720SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
3333b404f720SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
33348eb029c2SKevin Wolf     assert(!qiov || bytes == qiov->size);
3335cc0681c4SBenoît Canet 
333628de2dcdSKevin Wolf     waited = wait_serialising_requests(req);
333728de2dcdSKevin Wolf     assert(!waited || !req->serialising);
3338af91f9a7SKevin Wolf     assert(req->overlap_offset <= offset);
3339af91f9a7SKevin Wolf     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
3340244eadefSKevin Wolf 
334165afd211SKevin Wolf     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
3342d616b224SStefan Hajnoczi 
3343465bee1dSPeter Lieven     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
3344465bee1dSPeter Lieven         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_write_zeroes &&
3345465bee1dSPeter Lieven         qemu_iovec_is_zero(qiov)) {
3346465bee1dSPeter Lieven         flags |= BDRV_REQ_ZERO_WRITE;
3347465bee1dSPeter Lieven         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
3348465bee1dSPeter Lieven             flags |= BDRV_REQ_MAY_UNMAP;
3349465bee1dSPeter Lieven         }
3350465bee1dSPeter Lieven     }
3351465bee1dSPeter Lieven 
3352d616b224SStefan Hajnoczi     if (ret < 0) {
3353d616b224SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
3354d616b224SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
33559e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_ZERO);
3356aa7bfbffSPeter Lieven         ret = bdrv_co_do_write_zeroes(bs, sector_num, nb_sectors, flags);
3357f08f2ddaSStefan Hajnoczi     } else {
33589e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV);
33596b7cb247SStefan Hajnoczi         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
3360f08f2ddaSStefan Hajnoczi     }
33619e1cb96dSKevin Wolf     BLKDBG_EVENT(bs, BLKDBG_PWRITEV_DONE);
33626b7cb247SStefan Hajnoczi 
3363f05fa4adSPaolo Bonzini     if (ret == 0 && !bs->enable_write_cache) {
3364f05fa4adSPaolo Bonzini         ret = bdrv_co_flush(bs);
3365f05fa4adSPaolo Bonzini     }
3366f05fa4adSPaolo Bonzini 
33671755da16SPaolo Bonzini     bdrv_set_dirty(bs, sector_num, nb_sectors);
3368da1fa91dSKevin Wolf 
33695366d0c8SBenoît Canet     block_acct_highest_sector(&bs->stats, sector_num, nb_sectors);
33705e5a94b6SBenoît Canet 
3371df2a6f29SPaolo Bonzini     if (bs->growable && ret >= 0) {
3372df2a6f29SPaolo Bonzini         bs->total_sectors = MAX(bs->total_sectors, sector_num + nb_sectors);
3373df2a6f29SPaolo Bonzini     }
3374da1fa91dSKevin Wolf 
33756b7cb247SStefan Hajnoczi     return ret;
3376da1fa91dSKevin Wolf }
3377da1fa91dSKevin Wolf 
3378b404f720SKevin Wolf /*
3379b404f720SKevin Wolf  * Handle a write request in coroutine context
3380b404f720SKevin Wolf  */
33816601553eSKevin Wolf static int coroutine_fn bdrv_co_do_pwritev(BlockDriverState *bs,
33826601553eSKevin Wolf     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
3383b404f720SKevin Wolf     BdrvRequestFlags flags)
3384b404f720SKevin Wolf {
338565afd211SKevin Wolf     BdrvTrackedRequest req;
33863b8242e0SKevin Wolf     /* TODO Lift BDRV_SECTOR_SIZE restriction in BlockDriver interface */
33873b8242e0SKevin Wolf     uint64_t align = MAX(BDRV_SECTOR_SIZE, bs->request_alignment);
33883b8242e0SKevin Wolf     uint8_t *head_buf = NULL;
33893b8242e0SKevin Wolf     uint8_t *tail_buf = NULL;
33903b8242e0SKevin Wolf     QEMUIOVector local_qiov;
33913b8242e0SKevin Wolf     bool use_local_qiov = false;
3392b404f720SKevin Wolf     int ret;
3393b404f720SKevin Wolf 
3394b404f720SKevin Wolf     if (!bs->drv) {
3395b404f720SKevin Wolf         return -ENOMEDIUM;
3396b404f720SKevin Wolf     }
3397b404f720SKevin Wolf     if (bs->read_only) {
3398b404f720SKevin Wolf         return -EACCES;
3399b404f720SKevin Wolf     }
34006601553eSKevin Wolf     if (bdrv_check_byte_request(bs, offset, bytes)) {
3401b404f720SKevin Wolf         return -EIO;
3402b404f720SKevin Wolf     }
3403b404f720SKevin Wolf 
3404b404f720SKevin Wolf     /* throttling disk I/O */
3405b404f720SKevin Wolf     if (bs->io_limits_enabled) {
3406d5103588SKevin Wolf         bdrv_io_limits_intercept(bs, bytes, true);
3407b404f720SKevin Wolf     }
3408b404f720SKevin Wolf 
34093b8242e0SKevin Wolf     /*
34103b8242e0SKevin Wolf      * Align write if necessary by performing a read-modify-write cycle.
34113b8242e0SKevin Wolf      * Pad qiov with the read parts and be sure to have a tracked request not
34123b8242e0SKevin Wolf      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
34133b8242e0SKevin Wolf      */
341465afd211SKevin Wolf     tracked_request_begin(&req, bs, offset, bytes, true);
34153b8242e0SKevin Wolf 
34163b8242e0SKevin Wolf     if (offset & (align - 1)) {
34173b8242e0SKevin Wolf         QEMUIOVector head_qiov;
34183b8242e0SKevin Wolf         struct iovec head_iov;
34193b8242e0SKevin Wolf 
34203b8242e0SKevin Wolf         mark_request_serialising(&req, align);
34213b8242e0SKevin Wolf         wait_serialising_requests(&req);
34223b8242e0SKevin Wolf 
34233b8242e0SKevin Wolf         head_buf = qemu_blockalign(bs, align);
34243b8242e0SKevin Wolf         head_iov = (struct iovec) {
34253b8242e0SKevin Wolf             .iov_base   = head_buf,
34263b8242e0SKevin Wolf             .iov_len    = align,
34273b8242e0SKevin Wolf         };
34283b8242e0SKevin Wolf         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
34293b8242e0SKevin Wolf 
34309e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_HEAD);
34313b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, offset & ~(align - 1), align,
34323b8242e0SKevin Wolf                                   align, &head_qiov, 0);
34333b8242e0SKevin Wolf         if (ret < 0) {
34343b8242e0SKevin Wolf             goto fail;
34353b8242e0SKevin Wolf         }
34369e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
34373b8242e0SKevin Wolf 
34383b8242e0SKevin Wolf         qemu_iovec_init(&local_qiov, qiov->niov + 2);
34393b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
34403b8242e0SKevin Wolf         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
34413b8242e0SKevin Wolf         use_local_qiov = true;
34423b8242e0SKevin Wolf 
34433b8242e0SKevin Wolf         bytes += offset & (align - 1);
34443b8242e0SKevin Wolf         offset = offset & ~(align - 1);
34453b8242e0SKevin Wolf     }
34463b8242e0SKevin Wolf 
34473b8242e0SKevin Wolf     if ((offset + bytes) & (align - 1)) {
34483b8242e0SKevin Wolf         QEMUIOVector tail_qiov;
34493b8242e0SKevin Wolf         struct iovec tail_iov;
34503b8242e0SKevin Wolf         size_t tail_bytes;
345128de2dcdSKevin Wolf         bool waited;
34523b8242e0SKevin Wolf 
34533b8242e0SKevin Wolf         mark_request_serialising(&req, align);
345428de2dcdSKevin Wolf         waited = wait_serialising_requests(&req);
345528de2dcdSKevin Wolf         assert(!waited || !use_local_qiov);
34563b8242e0SKevin Wolf 
34573b8242e0SKevin Wolf         tail_buf = qemu_blockalign(bs, align);
34583b8242e0SKevin Wolf         tail_iov = (struct iovec) {
34593b8242e0SKevin Wolf             .iov_base   = tail_buf,
34603b8242e0SKevin Wolf             .iov_len    = align,
34613b8242e0SKevin Wolf         };
34623b8242e0SKevin Wolf         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
34633b8242e0SKevin Wolf 
34649e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_TAIL);
34653b8242e0SKevin Wolf         ret = bdrv_aligned_preadv(bs, &req, (offset + bytes) & ~(align - 1), align,
34663b8242e0SKevin Wolf                                   align, &tail_qiov, 0);
34673b8242e0SKevin Wolf         if (ret < 0) {
34683b8242e0SKevin Wolf             goto fail;
34693b8242e0SKevin Wolf         }
34709e1cb96dSKevin Wolf         BLKDBG_EVENT(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
34713b8242e0SKevin Wolf 
34723b8242e0SKevin Wolf         if (!use_local_qiov) {
34733b8242e0SKevin Wolf             qemu_iovec_init(&local_qiov, qiov->niov + 1);
34743b8242e0SKevin Wolf             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
34753b8242e0SKevin Wolf             use_local_qiov = true;
34763b8242e0SKevin Wolf         }
34773b8242e0SKevin Wolf 
34783b8242e0SKevin Wolf         tail_bytes = (offset + bytes) & (align - 1);
34793b8242e0SKevin Wolf         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
34803b8242e0SKevin Wolf 
34813b8242e0SKevin Wolf         bytes = ROUND_UP(bytes, align);
34823b8242e0SKevin Wolf     }
34833b8242e0SKevin Wolf 
34843b8242e0SKevin Wolf     ret = bdrv_aligned_pwritev(bs, &req, offset, bytes,
34853b8242e0SKevin Wolf                                use_local_qiov ? &local_qiov : qiov,
34863b8242e0SKevin Wolf                                flags);
34873b8242e0SKevin Wolf 
34883b8242e0SKevin Wolf fail:
348965afd211SKevin Wolf     tracked_request_end(&req);
3490b404f720SKevin Wolf 
34913b8242e0SKevin Wolf     if (use_local_qiov) {
34923b8242e0SKevin Wolf         qemu_iovec_destroy(&local_qiov);
349399c4a85cSKevin Wolf     }
34943b8242e0SKevin Wolf     qemu_vfree(head_buf);
34953b8242e0SKevin Wolf     qemu_vfree(tail_buf);
34963b8242e0SKevin Wolf 
3497b404f720SKevin Wolf     return ret;
3498b404f720SKevin Wolf }
3499b404f720SKevin Wolf 
35006601553eSKevin Wolf static int coroutine_fn bdrv_co_do_writev(BlockDriverState *bs,
35016601553eSKevin Wolf     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
35026601553eSKevin Wolf     BdrvRequestFlags flags)
35036601553eSKevin Wolf {
35046601553eSKevin Wolf     if (nb_sectors < 0 || nb_sectors > (INT_MAX >> BDRV_SECTOR_BITS)) {
35056601553eSKevin Wolf         return -EINVAL;
35066601553eSKevin Wolf     }
35076601553eSKevin Wolf 
35086601553eSKevin Wolf     return bdrv_co_do_pwritev(bs, sector_num << BDRV_SECTOR_BITS,
35096601553eSKevin Wolf                               nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
35106601553eSKevin Wolf }
35116601553eSKevin Wolf 
3512c5fbe571SStefan Hajnoczi int coroutine_fn bdrv_co_writev(BlockDriverState *bs, int64_t sector_num,
3513c5fbe571SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
3514c5fbe571SStefan Hajnoczi {
3515c5fbe571SStefan Hajnoczi     trace_bdrv_co_writev(bs, sector_num, nb_sectors);
3516c5fbe571SStefan Hajnoczi 
3517f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, qiov, 0);
3518f08f2ddaSStefan Hajnoczi }
3519f08f2ddaSStefan Hajnoczi 
3520f08f2ddaSStefan Hajnoczi int coroutine_fn bdrv_co_write_zeroes(BlockDriverState *bs,
3521aa7bfbffSPeter Lieven                                       int64_t sector_num, int nb_sectors,
3522aa7bfbffSPeter Lieven                                       BdrvRequestFlags flags)
3523f08f2ddaSStefan Hajnoczi {
352494d6ff21SPaolo Bonzini     trace_bdrv_co_write_zeroes(bs, sector_num, nb_sectors, flags);
3525f08f2ddaSStefan Hajnoczi 
3526d32f35cbSPeter Lieven     if (!(bs->open_flags & BDRV_O_UNMAP)) {
3527d32f35cbSPeter Lieven         flags &= ~BDRV_REQ_MAY_UNMAP;
3528d32f35cbSPeter Lieven     }
3529d32f35cbSPeter Lieven 
3530f08f2ddaSStefan Hajnoczi     return bdrv_co_do_writev(bs, sector_num, nb_sectors, NULL,
3531aa7bfbffSPeter Lieven                              BDRV_REQ_ZERO_WRITE | flags);
3532c5fbe571SStefan Hajnoczi }
3533c5fbe571SStefan Hajnoczi 
353483f64091Sbellard /**
353583f64091Sbellard  * Truncate file to 'offset' bytes (needed only for file protocols)
353683f64091Sbellard  */
353783f64091Sbellard int bdrv_truncate(BlockDriverState *bs, int64_t offset)
353883f64091Sbellard {
353983f64091Sbellard     BlockDriver *drv = bs->drv;
354051762288SStefan Hajnoczi     int ret;
354183f64091Sbellard     if (!drv)
354219cb3738Sbellard         return -ENOMEDIUM;
354383f64091Sbellard     if (!drv->bdrv_truncate)
354483f64091Sbellard         return -ENOTSUP;
354559f2689dSNaphtali Sprei     if (bs->read_only)
354659f2689dSNaphtali Sprei         return -EACCES;
35479c75e168SJeff Cody 
354851762288SStefan Hajnoczi     ret = drv->bdrv_truncate(bs, offset);
354951762288SStefan Hajnoczi     if (ret == 0) {
355051762288SStefan Hajnoczi         ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3551145feb17SMarkus Armbruster         bdrv_dev_resize_cb(bs);
355251762288SStefan Hajnoczi     }
355351762288SStefan Hajnoczi     return ret;
355483f64091Sbellard }
355583f64091Sbellard 
355683f64091Sbellard /**
35574a1d5e1fSFam Zheng  * Length of a allocated file in bytes. Sparse files are counted by actual
35584a1d5e1fSFam Zheng  * allocated space. Return < 0 if error or unknown.
35594a1d5e1fSFam Zheng  */
35604a1d5e1fSFam Zheng int64_t bdrv_get_allocated_file_size(BlockDriverState *bs)
35614a1d5e1fSFam Zheng {
35624a1d5e1fSFam Zheng     BlockDriver *drv = bs->drv;
35634a1d5e1fSFam Zheng     if (!drv) {
35644a1d5e1fSFam Zheng         return -ENOMEDIUM;
35654a1d5e1fSFam Zheng     }
35664a1d5e1fSFam Zheng     if (drv->bdrv_get_allocated_file_size) {
35674a1d5e1fSFam Zheng         return drv->bdrv_get_allocated_file_size(bs);
35684a1d5e1fSFam Zheng     }
35694a1d5e1fSFam Zheng     if (bs->file) {
35704a1d5e1fSFam Zheng         return bdrv_get_allocated_file_size(bs->file);
35714a1d5e1fSFam Zheng     }
35724a1d5e1fSFam Zheng     return -ENOTSUP;
35734a1d5e1fSFam Zheng }
35744a1d5e1fSFam Zheng 
35754a1d5e1fSFam Zheng /**
357665a9bb25SMarkus Armbruster  * Return number of sectors on success, -errno on error.
357783f64091Sbellard  */
357865a9bb25SMarkus Armbruster int64_t bdrv_nb_sectors(BlockDriverState *bs)
357983f64091Sbellard {
358083f64091Sbellard     BlockDriver *drv = bs->drv;
358165a9bb25SMarkus Armbruster 
358283f64091Sbellard     if (!drv)
358319cb3738Sbellard         return -ENOMEDIUM;
358451762288SStefan Hajnoczi 
3585b94a2610SKevin Wolf     if (drv->has_variable_length) {
3586b94a2610SKevin Wolf         int ret = refresh_total_sectors(bs, bs->total_sectors);
3587b94a2610SKevin Wolf         if (ret < 0) {
3588b94a2610SKevin Wolf             return ret;
3589fc01f7e7Sbellard         }
359046a4e4e6SStefan Hajnoczi     }
359165a9bb25SMarkus Armbruster     return bs->total_sectors;
359265a9bb25SMarkus Armbruster }
359365a9bb25SMarkus Armbruster 
359465a9bb25SMarkus Armbruster /**
359565a9bb25SMarkus Armbruster  * Return length in bytes on success, -errno on error.
359665a9bb25SMarkus Armbruster  * The length is always a multiple of BDRV_SECTOR_SIZE.
359765a9bb25SMarkus Armbruster  */
359865a9bb25SMarkus Armbruster int64_t bdrv_getlength(BlockDriverState *bs)
359965a9bb25SMarkus Armbruster {
360065a9bb25SMarkus Armbruster     int64_t ret = bdrv_nb_sectors(bs);
360165a9bb25SMarkus Armbruster 
360265a9bb25SMarkus Armbruster     return ret < 0 ? ret : ret * BDRV_SECTOR_SIZE;
360346a4e4e6SStefan Hajnoczi }
3604fc01f7e7Sbellard 
360519cb3738Sbellard /* return 0 as number of sectors if no device present or error */
360696b8f136Sths void bdrv_get_geometry(BlockDriverState *bs, uint64_t *nb_sectors_ptr)
3607fc01f7e7Sbellard {
360865a9bb25SMarkus Armbruster     int64_t nb_sectors = bdrv_nb_sectors(bs);
360965a9bb25SMarkus Armbruster 
361065a9bb25SMarkus Armbruster     *nb_sectors_ptr = nb_sectors < 0 ? 0 : nb_sectors;
3611fc01f7e7Sbellard }
3612cf98951bSbellard 
3613ff06f5f3SPaolo Bonzini void bdrv_set_on_error(BlockDriverState *bs, BlockdevOnError on_read_error,
3614ff06f5f3SPaolo Bonzini                        BlockdevOnError on_write_error)
3615abd7f68dSMarkus Armbruster {
3616abd7f68dSMarkus Armbruster     bs->on_read_error = on_read_error;
3617abd7f68dSMarkus Armbruster     bs->on_write_error = on_write_error;
3618abd7f68dSMarkus Armbruster }
3619abd7f68dSMarkus Armbruster 
36201ceee0d5SPaolo Bonzini BlockdevOnError bdrv_get_on_error(BlockDriverState *bs, bool is_read)
3621abd7f68dSMarkus Armbruster {
3622abd7f68dSMarkus Armbruster     return is_read ? bs->on_read_error : bs->on_write_error;
3623abd7f68dSMarkus Armbruster }
3624abd7f68dSMarkus Armbruster 
36253e1caa5fSPaolo Bonzini BlockErrorAction bdrv_get_error_action(BlockDriverState *bs, bool is_read, int error)
36263e1caa5fSPaolo Bonzini {
36273e1caa5fSPaolo Bonzini     BlockdevOnError on_err = is_read ? bs->on_read_error : bs->on_write_error;
36283e1caa5fSPaolo Bonzini 
36293e1caa5fSPaolo Bonzini     switch (on_err) {
36303e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_ENOSPC:
3631a589569fSWenchao Xia         return (error == ENOSPC) ?
3632a589569fSWenchao Xia                BLOCK_ERROR_ACTION_STOP : BLOCK_ERROR_ACTION_REPORT;
36333e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_STOP:
3634a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_STOP;
36353e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_REPORT:
3636a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_REPORT;
36373e1caa5fSPaolo Bonzini     case BLOCKDEV_ON_ERROR_IGNORE:
3638a589569fSWenchao Xia         return BLOCK_ERROR_ACTION_IGNORE;
36393e1caa5fSPaolo Bonzini     default:
36403e1caa5fSPaolo Bonzini         abort();
36413e1caa5fSPaolo Bonzini     }
36423e1caa5fSPaolo Bonzini }
36433e1caa5fSPaolo Bonzini 
3644c7c2ff0cSLuiz Capitulino static void send_qmp_error_event(BlockDriverState *bs,
3645c7c2ff0cSLuiz Capitulino                                  BlockErrorAction action,
3646c7c2ff0cSLuiz Capitulino                                  bool is_read, int error)
3647c7c2ff0cSLuiz Capitulino {
3648c7c2ff0cSLuiz Capitulino     BlockErrorAction ac;
3649c7c2ff0cSLuiz Capitulino 
3650c7c2ff0cSLuiz Capitulino     ac = is_read ? IO_OPERATION_TYPE_READ : IO_OPERATION_TYPE_WRITE;
3651c7c2ff0cSLuiz Capitulino     qapi_event_send_block_io_error(bdrv_get_device_name(bs), ac, action,
3652c7c2ff0cSLuiz Capitulino                                    bdrv_iostatus_is_enabled(bs),
3653624ff573SLuiz Capitulino                                    error == ENOSPC, strerror(error),
3654624ff573SLuiz Capitulino                                    &error_abort);
3655c7c2ff0cSLuiz Capitulino }
3656c7c2ff0cSLuiz Capitulino 
36573e1caa5fSPaolo Bonzini /* This is done by device models because, while the block layer knows
36583e1caa5fSPaolo Bonzini  * about the error, it does not know whether an operation comes from
36593e1caa5fSPaolo Bonzini  * the device or the block layer (from a job, for example).
36603e1caa5fSPaolo Bonzini  */
36613e1caa5fSPaolo Bonzini void bdrv_error_action(BlockDriverState *bs, BlockErrorAction action,
36623e1caa5fSPaolo Bonzini                        bool is_read, int error)
36633e1caa5fSPaolo Bonzini {
36643e1caa5fSPaolo Bonzini     assert(error >= 0);
36652bd3bce8SPaolo Bonzini 
3666a589569fSWenchao Xia     if (action == BLOCK_ERROR_ACTION_STOP) {
36672bd3bce8SPaolo Bonzini         /* First set the iostatus, so that "info block" returns an iostatus
36682bd3bce8SPaolo Bonzini          * that matches the events raised so far (an additional error iostatus
36692bd3bce8SPaolo Bonzini          * is fine, but not a lost one).
36702bd3bce8SPaolo Bonzini          */
36713e1caa5fSPaolo Bonzini         bdrv_iostatus_set_err(bs, error);
36722bd3bce8SPaolo Bonzini 
36732bd3bce8SPaolo Bonzini         /* Then raise the request to stop the VM and the event.
36742bd3bce8SPaolo Bonzini          * qemu_system_vmstop_request_prepare has two effects.  First,
36752bd3bce8SPaolo Bonzini          * it ensures that the STOP event always comes after the
36762bd3bce8SPaolo Bonzini          * BLOCK_IO_ERROR event.  Second, it ensures that even if management
36772bd3bce8SPaolo Bonzini          * can observe the STOP event and do a "cont" before the STOP
36782bd3bce8SPaolo Bonzini          * event is issued, the VM will not stop.  In this case, vm_start()
36792bd3bce8SPaolo Bonzini          * also ensures that the STOP/RESUME pair of events is emitted.
36802bd3bce8SPaolo Bonzini          */
36812bd3bce8SPaolo Bonzini         qemu_system_vmstop_request_prepare();
3682c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
36832bd3bce8SPaolo Bonzini         qemu_system_vmstop_request(RUN_STATE_IO_ERROR);
36842bd3bce8SPaolo Bonzini     } else {
3685c7c2ff0cSLuiz Capitulino         send_qmp_error_event(bs, action, is_read, error);
36863e1caa5fSPaolo Bonzini     }
36873e1caa5fSPaolo Bonzini }
36883e1caa5fSPaolo Bonzini 
3689b338082bSbellard int bdrv_is_read_only(BlockDriverState *bs)
3690b338082bSbellard {
3691b338082bSbellard     return bs->read_only;
3692b338082bSbellard }
3693b338082bSbellard 
3694985a03b0Sths int bdrv_is_sg(BlockDriverState *bs)
3695985a03b0Sths {
3696985a03b0Sths     return bs->sg;
3697985a03b0Sths }
3698985a03b0Sths 
3699e900a7b7SChristoph Hellwig int bdrv_enable_write_cache(BlockDriverState *bs)
3700e900a7b7SChristoph Hellwig {
3701e900a7b7SChristoph Hellwig     return bs->enable_write_cache;
3702e900a7b7SChristoph Hellwig }
3703e900a7b7SChristoph Hellwig 
3704425b0148SPaolo Bonzini void bdrv_set_enable_write_cache(BlockDriverState *bs, bool wce)
3705425b0148SPaolo Bonzini {
3706425b0148SPaolo Bonzini     bs->enable_write_cache = wce;
370755b110f2SJeff Cody 
370855b110f2SJeff Cody     /* so a reopen() will preserve wce */
370955b110f2SJeff Cody     if (wce) {
371055b110f2SJeff Cody         bs->open_flags |= BDRV_O_CACHE_WB;
371155b110f2SJeff Cody     } else {
371255b110f2SJeff Cody         bs->open_flags &= ~BDRV_O_CACHE_WB;
371355b110f2SJeff Cody     }
3714425b0148SPaolo Bonzini }
3715425b0148SPaolo Bonzini 
3716ea2384d3Sbellard int bdrv_is_encrypted(BlockDriverState *bs)
3717ea2384d3Sbellard {
3718ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted)
3719ea2384d3Sbellard         return 1;
3720ea2384d3Sbellard     return bs->encrypted;
3721ea2384d3Sbellard }
3722ea2384d3Sbellard 
3723c0f4ce77Saliguori int bdrv_key_required(BlockDriverState *bs)
3724c0f4ce77Saliguori {
3725c0f4ce77Saliguori     BlockDriverState *backing_hd = bs->backing_hd;
3726c0f4ce77Saliguori 
3727c0f4ce77Saliguori     if (backing_hd && backing_hd->encrypted && !backing_hd->valid_key)
3728c0f4ce77Saliguori         return 1;
3729c0f4ce77Saliguori     return (bs->encrypted && !bs->valid_key);
3730c0f4ce77Saliguori }
3731c0f4ce77Saliguori 
3732ea2384d3Sbellard int bdrv_set_key(BlockDriverState *bs, const char *key)
3733ea2384d3Sbellard {
3734ea2384d3Sbellard     int ret;
3735ea2384d3Sbellard     if (bs->backing_hd && bs->backing_hd->encrypted) {
3736ea2384d3Sbellard         ret = bdrv_set_key(bs->backing_hd, key);
3737ea2384d3Sbellard         if (ret < 0)
3738ea2384d3Sbellard             return ret;
3739ea2384d3Sbellard         if (!bs->encrypted)
3740ea2384d3Sbellard             return 0;
3741ea2384d3Sbellard     }
3742fd04a2aeSShahar Havivi     if (!bs->encrypted) {
3743fd04a2aeSShahar Havivi         return -EINVAL;
3744fd04a2aeSShahar Havivi     } else if (!bs->drv || !bs->drv->bdrv_set_key) {
3745fd04a2aeSShahar Havivi         return -ENOMEDIUM;
3746fd04a2aeSShahar Havivi     }
3747c0f4ce77Saliguori     ret = bs->drv->bdrv_set_key(bs, key);
3748bb5fc20fSaliguori     if (ret < 0) {
3749bb5fc20fSaliguori         bs->valid_key = 0;
3750bb5fc20fSaliguori     } else if (!bs->valid_key) {
3751bb5fc20fSaliguori         bs->valid_key = 1;
3752bb5fc20fSaliguori         /* call the change callback now, we skipped it on open */
37537d4b4ba5SMarkus Armbruster         bdrv_dev_change_media_cb(bs, true);
3754bb5fc20fSaliguori     }
3755c0f4ce77Saliguori     return ret;
3756ea2384d3Sbellard }
3757ea2384d3Sbellard 
3758f8d6bba1SMarkus Armbruster const char *bdrv_get_format_name(BlockDriverState *bs)
3759ea2384d3Sbellard {
3760f8d6bba1SMarkus Armbruster     return bs->drv ? bs->drv->format_name : NULL;
3761ea2384d3Sbellard }
3762ea2384d3Sbellard 
3763ada42401SStefan Hajnoczi static int qsort_strcmp(const void *a, const void *b)
3764ada42401SStefan Hajnoczi {
3765ada42401SStefan Hajnoczi     return strcmp(a, b);
3766ada42401SStefan Hajnoczi }
3767ada42401SStefan Hajnoczi 
3768ea2384d3Sbellard void bdrv_iterate_format(void (*it)(void *opaque, const char *name),
3769ea2384d3Sbellard                          void *opaque)
3770ea2384d3Sbellard {
3771ea2384d3Sbellard     BlockDriver *drv;
3772e855e4fbSJeff Cody     int count = 0;
3773ada42401SStefan Hajnoczi     int i;
3774e855e4fbSJeff Cody     const char **formats = NULL;
3775ea2384d3Sbellard 
37768a22f02aSStefan Hajnoczi     QLIST_FOREACH(drv, &bdrv_drivers, list) {
3777e855e4fbSJeff Cody         if (drv->format_name) {
3778e855e4fbSJeff Cody             bool found = false;
3779e855e4fbSJeff Cody             int i = count;
3780e855e4fbSJeff Cody             while (formats && i && !found) {
3781e855e4fbSJeff Cody                 found = !strcmp(formats[--i], drv->format_name);
3782e855e4fbSJeff Cody             }
3783e855e4fbSJeff Cody 
3784e855e4fbSJeff Cody             if (!found) {
37855839e53bSMarkus Armbruster                 formats = g_renew(const char *, formats, count + 1);
3786e855e4fbSJeff Cody                 formats[count++] = drv->format_name;
3787ea2384d3Sbellard             }
3788ea2384d3Sbellard         }
3789e855e4fbSJeff Cody     }
3790ada42401SStefan Hajnoczi 
3791ada42401SStefan Hajnoczi     qsort(formats, count, sizeof(formats[0]), qsort_strcmp);
3792ada42401SStefan Hajnoczi 
3793ada42401SStefan Hajnoczi     for (i = 0; i < count; i++) {
3794ada42401SStefan Hajnoczi         it(opaque, formats[i]);
3795ada42401SStefan Hajnoczi     }
3796ada42401SStefan Hajnoczi 
3797e855e4fbSJeff Cody     g_free(formats);
3798e855e4fbSJeff Cody }
3799ea2384d3Sbellard 
3800dc364f4cSBenoît Canet /* This function is to find block backend bs */
3801b338082bSbellard BlockDriverState *bdrv_find(const char *name)
3802b338082bSbellard {
3803b338082bSbellard     BlockDriverState *bs;
3804b338082bSbellard 
3805dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
38061b7bdbc1SStefan Hajnoczi         if (!strcmp(name, bs->device_name)) {
3807b338082bSbellard             return bs;
3808b338082bSbellard         }
38091b7bdbc1SStefan Hajnoczi     }
3810b338082bSbellard     return NULL;
3811b338082bSbellard }
3812b338082bSbellard 
3813dc364f4cSBenoît Canet /* This function is to find a node in the bs graph */
3814dc364f4cSBenoît Canet BlockDriverState *bdrv_find_node(const char *node_name)
3815dc364f4cSBenoît Canet {
3816dc364f4cSBenoît Canet     BlockDriverState *bs;
3817dc364f4cSBenoît Canet 
3818dc364f4cSBenoît Canet     assert(node_name);
3819dc364f4cSBenoît Canet 
3820dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3821dc364f4cSBenoît Canet         if (!strcmp(node_name, bs->node_name)) {
3822dc364f4cSBenoît Canet             return bs;
3823dc364f4cSBenoît Canet         }
3824dc364f4cSBenoît Canet     }
3825dc364f4cSBenoît Canet     return NULL;
3826dc364f4cSBenoît Canet }
3827dc364f4cSBenoît Canet 
3828c13163fbSBenoît Canet /* Put this QMP function here so it can access the static graph_bdrv_states. */
3829c13163fbSBenoît Canet BlockDeviceInfoList *bdrv_named_nodes_list(void)
3830c13163fbSBenoît Canet {
3831c13163fbSBenoît Canet     BlockDeviceInfoList *list, *entry;
3832c13163fbSBenoît Canet     BlockDriverState *bs;
3833c13163fbSBenoît Canet 
3834c13163fbSBenoît Canet     list = NULL;
3835c13163fbSBenoît Canet     QTAILQ_FOREACH(bs, &graph_bdrv_states, node_list) {
3836c13163fbSBenoît Canet         entry = g_malloc0(sizeof(*entry));
3837c13163fbSBenoît Canet         entry->value = bdrv_block_device_info(bs);
3838c13163fbSBenoît Canet         entry->next = list;
3839c13163fbSBenoît Canet         list = entry;
3840c13163fbSBenoît Canet     }
3841c13163fbSBenoît Canet 
3842c13163fbSBenoît Canet     return list;
3843c13163fbSBenoît Canet }
3844c13163fbSBenoît Canet 
384512d3ba82SBenoît Canet BlockDriverState *bdrv_lookup_bs(const char *device,
384612d3ba82SBenoît Canet                                  const char *node_name,
384712d3ba82SBenoît Canet                                  Error **errp)
384812d3ba82SBenoît Canet {
384912d3ba82SBenoît Canet     BlockDriverState *bs = NULL;
385012d3ba82SBenoît Canet 
385112d3ba82SBenoît Canet     if (device) {
385212d3ba82SBenoît Canet         bs = bdrv_find(device);
385312d3ba82SBenoît Canet 
3854dd67fa50SBenoît Canet         if (bs) {
385512d3ba82SBenoît Canet             return bs;
385612d3ba82SBenoît Canet         }
3857dd67fa50SBenoît Canet     }
385812d3ba82SBenoît Canet 
3859dd67fa50SBenoît Canet     if (node_name) {
386012d3ba82SBenoît Canet         bs = bdrv_find_node(node_name);
386112d3ba82SBenoît Canet 
3862dd67fa50SBenoît Canet         if (bs) {
3863dd67fa50SBenoît Canet             return bs;
3864dd67fa50SBenoît Canet         }
386512d3ba82SBenoît Canet     }
386612d3ba82SBenoît Canet 
3867dd67fa50SBenoît Canet     error_setg(errp, "Cannot find device=%s nor node_name=%s",
3868dd67fa50SBenoît Canet                      device ? device : "",
3869dd67fa50SBenoît Canet                      node_name ? node_name : "");
3870dd67fa50SBenoît Canet     return NULL;
387112d3ba82SBenoît Canet }
387212d3ba82SBenoît Canet 
38735a6684d2SJeff Cody /* If 'base' is in the same chain as 'top', return true. Otherwise,
38745a6684d2SJeff Cody  * return false.  If either argument is NULL, return false. */
38755a6684d2SJeff Cody bool bdrv_chain_contains(BlockDriverState *top, BlockDriverState *base)
38765a6684d2SJeff Cody {
38775a6684d2SJeff Cody     while (top && top != base) {
38785a6684d2SJeff Cody         top = top->backing_hd;
38795a6684d2SJeff Cody     }
38805a6684d2SJeff Cody 
38815a6684d2SJeff Cody     return top != NULL;
38825a6684d2SJeff Cody }
38835a6684d2SJeff Cody 
38842f399b0aSMarkus Armbruster BlockDriverState *bdrv_next(BlockDriverState *bs)
38852f399b0aSMarkus Armbruster {
38862f399b0aSMarkus Armbruster     if (!bs) {
38872f399b0aSMarkus Armbruster         return QTAILQ_FIRST(&bdrv_states);
38882f399b0aSMarkus Armbruster     }
3889dc364f4cSBenoît Canet     return QTAILQ_NEXT(bs, device_list);
38902f399b0aSMarkus Armbruster }
38912f399b0aSMarkus Armbruster 
389251de9760Saliguori void bdrv_iterate(void (*it)(void *opaque, BlockDriverState *bs), void *opaque)
389381d0912dSbellard {
389481d0912dSbellard     BlockDriverState *bs;
389581d0912dSbellard 
3896dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
389751de9760Saliguori         it(opaque, bs);
389881d0912dSbellard     }
389981d0912dSbellard }
390081d0912dSbellard 
3901ea2384d3Sbellard const char *bdrv_get_device_name(BlockDriverState *bs)
3902ea2384d3Sbellard {
3903ea2384d3Sbellard     return bs->device_name;
3904ea2384d3Sbellard }
3905ea2384d3Sbellard 
3906c8433287SMarkus Armbruster int bdrv_get_flags(BlockDriverState *bs)
3907c8433287SMarkus Armbruster {
3908c8433287SMarkus Armbruster     return bs->open_flags;
3909c8433287SMarkus Armbruster }
3910c8433287SMarkus Armbruster 
3911f0f0fdfeSKevin Wolf int bdrv_flush_all(void)
3912c6ca28d6Saliguori {
3913c6ca28d6Saliguori     BlockDriverState *bs;
3914f0f0fdfeSKevin Wolf     int result = 0;
3915c6ca28d6Saliguori 
3916dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
3917ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
3918ed78cda3SStefan Hajnoczi         int ret;
3919ed78cda3SStefan Hajnoczi 
3920ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
3921ed78cda3SStefan Hajnoczi         ret = bdrv_flush(bs);
3922f0f0fdfeSKevin Wolf         if (ret < 0 && !result) {
3923f0f0fdfeSKevin Wolf             result = ret;
3924c6ca28d6Saliguori         }
3925ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
39261b7bdbc1SStefan Hajnoczi     }
3927c6ca28d6Saliguori 
3928f0f0fdfeSKevin Wolf     return result;
3929f0f0fdfeSKevin Wolf }
3930f0f0fdfeSKevin Wolf 
39313ac21627SPeter Lieven int bdrv_has_zero_init_1(BlockDriverState *bs)
39323ac21627SPeter Lieven {
39333ac21627SPeter Lieven     return 1;
39343ac21627SPeter Lieven }
39353ac21627SPeter Lieven 
3936f2feebbdSKevin Wolf int bdrv_has_zero_init(BlockDriverState *bs)
3937f2feebbdSKevin Wolf {
3938f2feebbdSKevin Wolf     assert(bs->drv);
3939f2feebbdSKevin Wolf 
394011212d8fSPaolo Bonzini     /* If BS is a copy on write image, it is initialized to
394111212d8fSPaolo Bonzini        the contents of the base image, which may not be zeroes.  */
394211212d8fSPaolo Bonzini     if (bs->backing_hd) {
394311212d8fSPaolo Bonzini         return 0;
394411212d8fSPaolo Bonzini     }
3945336c1c12SKevin Wolf     if (bs->drv->bdrv_has_zero_init) {
3946336c1c12SKevin Wolf         return bs->drv->bdrv_has_zero_init(bs);
3947f2feebbdSKevin Wolf     }
3948f2feebbdSKevin Wolf 
39493ac21627SPeter Lieven     /* safe default */
39503ac21627SPeter Lieven     return 0;
3951f2feebbdSKevin Wolf }
3952f2feebbdSKevin Wolf 
39534ce78691SPeter Lieven bool bdrv_unallocated_blocks_are_zero(BlockDriverState *bs)
39544ce78691SPeter Lieven {
39554ce78691SPeter Lieven     BlockDriverInfo bdi;
39564ce78691SPeter Lieven 
39574ce78691SPeter Lieven     if (bs->backing_hd) {
39584ce78691SPeter Lieven         return false;
39594ce78691SPeter Lieven     }
39604ce78691SPeter Lieven 
39614ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
39624ce78691SPeter Lieven         return bdi.unallocated_blocks_are_zero;
39634ce78691SPeter Lieven     }
39644ce78691SPeter Lieven 
39654ce78691SPeter Lieven     return false;
39664ce78691SPeter Lieven }
39674ce78691SPeter Lieven 
39684ce78691SPeter Lieven bool bdrv_can_write_zeroes_with_unmap(BlockDriverState *bs)
39694ce78691SPeter Lieven {
39704ce78691SPeter Lieven     BlockDriverInfo bdi;
39714ce78691SPeter Lieven 
39724ce78691SPeter Lieven     if (bs->backing_hd || !(bs->open_flags & BDRV_O_UNMAP)) {
39734ce78691SPeter Lieven         return false;
39744ce78691SPeter Lieven     }
39754ce78691SPeter Lieven 
39764ce78691SPeter Lieven     if (bdrv_get_info(bs, &bdi) == 0) {
39774ce78691SPeter Lieven         return bdi.can_write_zeroes_with_unmap;
39784ce78691SPeter Lieven     }
39794ce78691SPeter Lieven 
39804ce78691SPeter Lieven     return false;
39814ce78691SPeter Lieven }
39824ce78691SPeter Lieven 
3983b6b8a333SPaolo Bonzini typedef struct BdrvCoGetBlockStatusData {
3984376ae3f1SStefan Hajnoczi     BlockDriverState *bs;
3985b35b2bbaSMiroslav Rezanina     BlockDriverState *base;
3986376ae3f1SStefan Hajnoczi     int64_t sector_num;
3987376ae3f1SStefan Hajnoczi     int nb_sectors;
3988376ae3f1SStefan Hajnoczi     int *pnum;
3989b6b8a333SPaolo Bonzini     int64_t ret;
3990376ae3f1SStefan Hajnoczi     bool done;
3991b6b8a333SPaolo Bonzini } BdrvCoGetBlockStatusData;
3992376ae3f1SStefan Hajnoczi 
3993f58c7b35Sths /*
3994f58c7b35Sths  * Returns true iff the specified sector is present in the disk image. Drivers
3995f58c7b35Sths  * not implementing the functionality are assumed to not support backing files,
3996f58c7b35Sths  * hence all their sectors are reported as allocated.
3997f58c7b35Sths  *
3998bd9533e3SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
3999bd9533e3SStefan Hajnoczi  * and 'pnum' is set to 0.
4000bd9533e3SStefan Hajnoczi  *
4001f58c7b35Sths  * 'pnum' is set to the number of sectors (including and immediately following
4002f58c7b35Sths  * the specified sector) that are known to be in the same
4003f58c7b35Sths  * allocated/unallocated state.
4004f58c7b35Sths  *
4005bd9533e3SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
4006bd9533e3SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
4007f58c7b35Sths  */
4008b6b8a333SPaolo Bonzini static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
4009bdad13b9SPaolo Bonzini                                                      int64_t sector_num,
4010060f51c9SStefan Hajnoczi                                                      int nb_sectors, int *pnum)
4011f58c7b35Sths {
401230a7f2fcSMarkus Armbruster     int64_t total_sectors;
4013f58c7b35Sths     int64_t n;
40145daa74a6SPaolo Bonzini     int64_t ret, ret2;
4015bd9533e3SStefan Hajnoczi 
401630a7f2fcSMarkus Armbruster     total_sectors = bdrv_nb_sectors(bs);
401730a7f2fcSMarkus Armbruster     if (total_sectors < 0) {
401830a7f2fcSMarkus Armbruster         return total_sectors;
4019617ccb46SPaolo Bonzini     }
4020617ccb46SPaolo Bonzini 
402130a7f2fcSMarkus Armbruster     if (sector_num >= total_sectors) {
40226aebab14SStefan Hajnoczi         *pnum = 0;
40236aebab14SStefan Hajnoczi         return 0;
40246aebab14SStefan Hajnoczi     }
4025bd9533e3SStefan Hajnoczi 
402630a7f2fcSMarkus Armbruster     n = total_sectors - sector_num;
4027bd9533e3SStefan Hajnoczi     if (n < nb_sectors) {
4028bd9533e3SStefan Hajnoczi         nb_sectors = n;
4029bd9533e3SStefan Hajnoczi     }
4030bd9533e3SStefan Hajnoczi 
4031b6b8a333SPaolo Bonzini     if (!bs->drv->bdrv_co_get_block_status) {
4032bd9533e3SStefan Hajnoczi         *pnum = nb_sectors;
4033e88ae226SKevin Wolf         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
4034918e92d7SPaolo Bonzini         if (bs->drv->protocol_name) {
4035918e92d7SPaolo Bonzini             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
4036918e92d7SPaolo Bonzini         }
4037918e92d7SPaolo Bonzini         return ret;
40386aebab14SStefan Hajnoczi     }
40396aebab14SStefan Hajnoczi 
4040415b5b01SPaolo Bonzini     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum);
4041415b5b01SPaolo Bonzini     if (ret < 0) {
40423e0a233dSPeter Lieven         *pnum = 0;
4043415b5b01SPaolo Bonzini         return ret;
4044415b5b01SPaolo Bonzini     }
4045415b5b01SPaolo Bonzini 
404692bc50a5SPeter Lieven     if (ret & BDRV_BLOCK_RAW) {
404792bc50a5SPeter Lieven         assert(ret & BDRV_BLOCK_OFFSET_VALID);
404892bc50a5SPeter Lieven         return bdrv_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
404992bc50a5SPeter Lieven                                      *pnum, pnum);
405092bc50a5SPeter Lieven     }
405192bc50a5SPeter Lieven 
4052e88ae226SKevin Wolf     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
4053e88ae226SKevin Wolf         ret |= BDRV_BLOCK_ALLOCATED;
4054e88ae226SKevin Wolf     }
4055e88ae226SKevin Wolf 
4056c3d86884SPeter Lieven     if (!(ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO)) {
4057c3d86884SPeter Lieven         if (bdrv_unallocated_blocks_are_zero(bs)) {
4058415b5b01SPaolo Bonzini             ret |= BDRV_BLOCK_ZERO;
40591f9db224SPeter Lieven         } else if (bs->backing_hd) {
4060f0ad5712SPaolo Bonzini             BlockDriverState *bs2 = bs->backing_hd;
406130a7f2fcSMarkus Armbruster             int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
406230a7f2fcSMarkus Armbruster             if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
4063f0ad5712SPaolo Bonzini                 ret |= BDRV_BLOCK_ZERO;
4064f0ad5712SPaolo Bonzini             }
4065f0ad5712SPaolo Bonzini         }
4066415b5b01SPaolo Bonzini     }
40675daa74a6SPaolo Bonzini 
40685daa74a6SPaolo Bonzini     if (bs->file &&
40695daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
40705daa74a6SPaolo Bonzini         (ret & BDRV_BLOCK_OFFSET_VALID)) {
40715daa74a6SPaolo Bonzini         ret2 = bdrv_co_get_block_status(bs->file, ret >> BDRV_SECTOR_BITS,
40725daa74a6SPaolo Bonzini                                         *pnum, pnum);
40735daa74a6SPaolo Bonzini         if (ret2 >= 0) {
40745daa74a6SPaolo Bonzini             /* Ignore errors.  This is just providing extra information, it
40755daa74a6SPaolo Bonzini              * is useful but not necessary.
40765daa74a6SPaolo Bonzini              */
40775daa74a6SPaolo Bonzini             ret |= (ret2 & BDRV_BLOCK_ZERO);
40785daa74a6SPaolo Bonzini         }
40795daa74a6SPaolo Bonzini     }
40805daa74a6SPaolo Bonzini 
4081415b5b01SPaolo Bonzini     return ret;
4082060f51c9SStefan Hajnoczi }
4083060f51c9SStefan Hajnoczi 
4084b6b8a333SPaolo Bonzini /* Coroutine wrapper for bdrv_get_block_status() */
4085b6b8a333SPaolo Bonzini static void coroutine_fn bdrv_get_block_status_co_entry(void *opaque)
4086060f51c9SStefan Hajnoczi {
4087b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData *data = opaque;
4088060f51c9SStefan Hajnoczi     BlockDriverState *bs = data->bs;
4089060f51c9SStefan Hajnoczi 
4090b6b8a333SPaolo Bonzini     data->ret = bdrv_co_get_block_status(bs, data->sector_num, data->nb_sectors,
4091060f51c9SStefan Hajnoczi                                          data->pnum);
4092060f51c9SStefan Hajnoczi     data->done = true;
4093060f51c9SStefan Hajnoczi }
4094060f51c9SStefan Hajnoczi 
4095060f51c9SStefan Hajnoczi /*
4096b6b8a333SPaolo Bonzini  * Synchronous wrapper around bdrv_co_get_block_status().
4097060f51c9SStefan Hajnoczi  *
4098b6b8a333SPaolo Bonzini  * See bdrv_co_get_block_status() for details.
4099060f51c9SStefan Hajnoczi  */
4100b6b8a333SPaolo Bonzini int64_t bdrv_get_block_status(BlockDriverState *bs, int64_t sector_num,
4101b6b8a333SPaolo Bonzini                               int nb_sectors, int *pnum)
4102060f51c9SStefan Hajnoczi {
4103376ae3f1SStefan Hajnoczi     Coroutine *co;
4104b6b8a333SPaolo Bonzini     BdrvCoGetBlockStatusData data = {
4105376ae3f1SStefan Hajnoczi         .bs = bs,
4106376ae3f1SStefan Hajnoczi         .sector_num = sector_num,
4107376ae3f1SStefan Hajnoczi         .nb_sectors = nb_sectors,
4108376ae3f1SStefan Hajnoczi         .pnum = pnum,
4109376ae3f1SStefan Hajnoczi         .done = false,
4110376ae3f1SStefan Hajnoczi     };
4111376ae3f1SStefan Hajnoczi 
4112bdad13b9SPaolo Bonzini     if (qemu_in_coroutine()) {
4113bdad13b9SPaolo Bonzini         /* Fast-path if already in coroutine context */
4114b6b8a333SPaolo Bonzini         bdrv_get_block_status_co_entry(&data);
4115bdad13b9SPaolo Bonzini     } else {
41162572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
41172572b37aSStefan Hajnoczi 
4118b6b8a333SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_co_entry);
4119376ae3f1SStefan Hajnoczi         qemu_coroutine_enter(co, &data);
4120376ae3f1SStefan Hajnoczi         while (!data.done) {
41212572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
4122376ae3f1SStefan Hajnoczi         }
4123bdad13b9SPaolo Bonzini     }
4124376ae3f1SStefan Hajnoczi     return data.ret;
4125376ae3f1SStefan Hajnoczi }
4126f58c7b35Sths 
4127b6b8a333SPaolo Bonzini int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
4128b6b8a333SPaolo Bonzini                                    int nb_sectors, int *pnum)
4129b6b8a333SPaolo Bonzini {
41304333bb71SPaolo Bonzini     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum);
41314333bb71SPaolo Bonzini     if (ret < 0) {
41324333bb71SPaolo Bonzini         return ret;
41334333bb71SPaolo Bonzini     }
413401fb2705SKevin Wolf     return !!(ret & BDRV_BLOCK_ALLOCATED);
4135b6b8a333SPaolo Bonzini }
4136b6b8a333SPaolo Bonzini 
4137188a7bbfSPaolo Bonzini /*
4138188a7bbfSPaolo Bonzini  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
4139188a7bbfSPaolo Bonzini  *
4140188a7bbfSPaolo Bonzini  * Return true if the given sector is allocated in any image between
4141188a7bbfSPaolo Bonzini  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
4142188a7bbfSPaolo Bonzini  * sector is allocated in any image of the chain.  Return false otherwise.
4143188a7bbfSPaolo Bonzini  *
4144188a7bbfSPaolo Bonzini  * 'pnum' is set to the number of sectors (including and immediately following
4145188a7bbfSPaolo Bonzini  *  the specified sector) that are known to be in the same
4146188a7bbfSPaolo Bonzini  *  allocated/unallocated state.
4147188a7bbfSPaolo Bonzini  *
4148188a7bbfSPaolo Bonzini  */
41494f578637SPaolo Bonzini int bdrv_is_allocated_above(BlockDriverState *top,
4150188a7bbfSPaolo Bonzini                             BlockDriverState *base,
4151188a7bbfSPaolo Bonzini                             int64_t sector_num,
4152188a7bbfSPaolo Bonzini                             int nb_sectors, int *pnum)
4153188a7bbfSPaolo Bonzini {
4154188a7bbfSPaolo Bonzini     BlockDriverState *intermediate;
4155188a7bbfSPaolo Bonzini     int ret, n = nb_sectors;
4156188a7bbfSPaolo Bonzini 
4157188a7bbfSPaolo Bonzini     intermediate = top;
4158188a7bbfSPaolo Bonzini     while (intermediate && intermediate != base) {
4159188a7bbfSPaolo Bonzini         int pnum_inter;
4160bdad13b9SPaolo Bonzini         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
4161188a7bbfSPaolo Bonzini                                 &pnum_inter);
4162188a7bbfSPaolo Bonzini         if (ret < 0) {
4163188a7bbfSPaolo Bonzini             return ret;
4164188a7bbfSPaolo Bonzini         } else if (ret) {
4165188a7bbfSPaolo Bonzini             *pnum = pnum_inter;
4166188a7bbfSPaolo Bonzini             return 1;
4167188a7bbfSPaolo Bonzini         }
4168188a7bbfSPaolo Bonzini 
4169188a7bbfSPaolo Bonzini         /*
4170188a7bbfSPaolo Bonzini          * [sector_num, nb_sectors] is unallocated on top but intermediate
4171188a7bbfSPaolo Bonzini          * might have
4172188a7bbfSPaolo Bonzini          *
4173188a7bbfSPaolo Bonzini          * [sector_num+x, nr_sectors] allocated.
4174188a7bbfSPaolo Bonzini          */
417563ba17d3SVishvananda Ishaya         if (n > pnum_inter &&
417663ba17d3SVishvananda Ishaya             (intermediate == top ||
417763ba17d3SVishvananda Ishaya              sector_num + pnum_inter < intermediate->total_sectors)) {
4178188a7bbfSPaolo Bonzini             n = pnum_inter;
4179188a7bbfSPaolo Bonzini         }
4180188a7bbfSPaolo Bonzini 
4181188a7bbfSPaolo Bonzini         intermediate = intermediate->backing_hd;
4182188a7bbfSPaolo Bonzini     }
4183188a7bbfSPaolo Bonzini 
4184188a7bbfSPaolo Bonzini     *pnum = n;
4185188a7bbfSPaolo Bonzini     return 0;
4186188a7bbfSPaolo Bonzini }
4187188a7bbfSPaolo Bonzini 
4188045df330Saliguori const char *bdrv_get_encrypted_filename(BlockDriverState *bs)
4189045df330Saliguori {
4190045df330Saliguori     if (bs->backing_hd && bs->backing_hd->encrypted)
4191045df330Saliguori         return bs->backing_file;
4192045df330Saliguori     else if (bs->encrypted)
4193045df330Saliguori         return bs->filename;
4194045df330Saliguori     else
4195045df330Saliguori         return NULL;
4196045df330Saliguori }
4197045df330Saliguori 
419883f64091Sbellard void bdrv_get_backing_filename(BlockDriverState *bs,
419983f64091Sbellard                                char *filename, int filename_size)
420083f64091Sbellard {
420183f64091Sbellard     pstrcpy(filename, filename_size, bs->backing_file);
420283f64091Sbellard }
420383f64091Sbellard 
4204faea38e7Sbellard int bdrv_write_compressed(BlockDriverState *bs, int64_t sector_num,
4205faea38e7Sbellard                           const uint8_t *buf, int nb_sectors)
4206faea38e7Sbellard {
4207faea38e7Sbellard     BlockDriver *drv = bs->drv;
4208faea38e7Sbellard     if (!drv)
420919cb3738Sbellard         return -ENOMEDIUM;
4210faea38e7Sbellard     if (!drv->bdrv_write_compressed)
4211faea38e7Sbellard         return -ENOTSUP;
4212fbb7b4e0SKevin Wolf     if (bdrv_check_request(bs, sector_num, nb_sectors))
4213fbb7b4e0SKevin Wolf         return -EIO;
42147cd1e32aSlirans@il.ibm.com 
4215e4654d2dSFam Zheng     assert(QLIST_EMPTY(&bs->dirty_bitmaps));
42167cd1e32aSlirans@il.ibm.com 
4217faea38e7Sbellard     return drv->bdrv_write_compressed(bs, sector_num, buf, nb_sectors);
4218faea38e7Sbellard }
4219faea38e7Sbellard 
4220faea38e7Sbellard int bdrv_get_info(BlockDriverState *bs, BlockDriverInfo *bdi)
4221faea38e7Sbellard {
4222faea38e7Sbellard     BlockDriver *drv = bs->drv;
4223faea38e7Sbellard     if (!drv)
422419cb3738Sbellard         return -ENOMEDIUM;
4225faea38e7Sbellard     if (!drv->bdrv_get_info)
4226faea38e7Sbellard         return -ENOTSUP;
4227faea38e7Sbellard     memset(bdi, 0, sizeof(*bdi));
4228faea38e7Sbellard     return drv->bdrv_get_info(bs, bdi);
4229faea38e7Sbellard }
4230faea38e7Sbellard 
4231eae041feSMax Reitz ImageInfoSpecific *bdrv_get_specific_info(BlockDriverState *bs)
4232eae041feSMax Reitz {
4233eae041feSMax Reitz     BlockDriver *drv = bs->drv;
4234eae041feSMax Reitz     if (drv && drv->bdrv_get_specific_info) {
4235eae041feSMax Reitz         return drv->bdrv_get_specific_info(bs);
4236eae041feSMax Reitz     }
4237eae041feSMax Reitz     return NULL;
4238eae041feSMax Reitz }
4239eae041feSMax Reitz 
424045566e9cSChristoph Hellwig int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
424145566e9cSChristoph Hellwig                       int64_t pos, int size)
4242178e08a5Saliguori {
4243cf8074b3SKevin Wolf     QEMUIOVector qiov;
4244cf8074b3SKevin Wolf     struct iovec iov = {
4245cf8074b3SKevin Wolf         .iov_base   = (void *) buf,
4246cf8074b3SKevin Wolf         .iov_len    = size,
4247cf8074b3SKevin Wolf     };
4248cf8074b3SKevin Wolf 
4249cf8074b3SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
4250cf8074b3SKevin Wolf     return bdrv_writev_vmstate(bs, &qiov, pos);
4251cf8074b3SKevin Wolf }
4252cf8074b3SKevin Wolf 
4253cf8074b3SKevin Wolf int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
4254cf8074b3SKevin Wolf {
4255178e08a5Saliguori     BlockDriver *drv = bs->drv;
4256cf8074b3SKevin Wolf 
4257cf8074b3SKevin Wolf     if (!drv) {
4258178e08a5Saliguori         return -ENOMEDIUM;
4259cf8074b3SKevin Wolf     } else if (drv->bdrv_save_vmstate) {
4260cf8074b3SKevin Wolf         return drv->bdrv_save_vmstate(bs, qiov, pos);
4261cf8074b3SKevin Wolf     } else if (bs->file) {
4262cf8074b3SKevin Wolf         return bdrv_writev_vmstate(bs->file, qiov, pos);
4263cf8074b3SKevin Wolf     }
4264cf8074b3SKevin Wolf 
42657cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4266178e08a5Saliguori }
4267178e08a5Saliguori 
426845566e9cSChristoph Hellwig int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
426945566e9cSChristoph Hellwig                       int64_t pos, int size)
4270178e08a5Saliguori {
4271178e08a5Saliguori     BlockDriver *drv = bs->drv;
4272178e08a5Saliguori     if (!drv)
4273178e08a5Saliguori         return -ENOMEDIUM;
42747cdb1f6dSMORITA Kazutaka     if (drv->bdrv_load_vmstate)
427545566e9cSChristoph Hellwig         return drv->bdrv_load_vmstate(bs, buf, pos, size);
42767cdb1f6dSMORITA Kazutaka     if (bs->file)
42777cdb1f6dSMORITA Kazutaka         return bdrv_load_vmstate(bs->file, buf, pos, size);
42787cdb1f6dSMORITA Kazutaka     return -ENOTSUP;
4279178e08a5Saliguori }
4280178e08a5Saliguori 
42818b9b0cc2SKevin Wolf void bdrv_debug_event(BlockDriverState *bs, BlkDebugEvent event)
42828b9b0cc2SKevin Wolf {
4283bf736fe3SKevin Wolf     if (!bs || !bs->drv || !bs->drv->bdrv_debug_event) {
42848b9b0cc2SKevin Wolf         return;
42858b9b0cc2SKevin Wolf     }
42868b9b0cc2SKevin Wolf 
4287bf736fe3SKevin Wolf     bs->drv->bdrv_debug_event(bs, event);
428841c695c7SKevin Wolf }
42898b9b0cc2SKevin Wolf 
429041c695c7SKevin Wolf int bdrv_debug_breakpoint(BlockDriverState *bs, const char *event,
429141c695c7SKevin Wolf                           const char *tag)
429241c695c7SKevin Wolf {
429341c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_breakpoint) {
429441c695c7SKevin Wolf         bs = bs->file;
429541c695c7SKevin Wolf     }
429641c695c7SKevin Wolf 
429741c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_breakpoint) {
429841c695c7SKevin Wolf         return bs->drv->bdrv_debug_breakpoint(bs, event, tag);
429941c695c7SKevin Wolf     }
430041c695c7SKevin Wolf 
430141c695c7SKevin Wolf     return -ENOTSUP;
430241c695c7SKevin Wolf }
430341c695c7SKevin Wolf 
43044cc70e93SFam Zheng int bdrv_debug_remove_breakpoint(BlockDriverState *bs, const char *tag)
43054cc70e93SFam Zheng {
43064cc70e93SFam Zheng     while (bs && bs->drv && !bs->drv->bdrv_debug_remove_breakpoint) {
43074cc70e93SFam Zheng         bs = bs->file;
43084cc70e93SFam Zheng     }
43094cc70e93SFam Zheng 
43104cc70e93SFam Zheng     if (bs && bs->drv && bs->drv->bdrv_debug_remove_breakpoint) {
43114cc70e93SFam Zheng         return bs->drv->bdrv_debug_remove_breakpoint(bs, tag);
43124cc70e93SFam Zheng     }
43134cc70e93SFam Zheng 
43144cc70e93SFam Zheng     return -ENOTSUP;
43154cc70e93SFam Zheng }
43164cc70e93SFam Zheng 
431741c695c7SKevin Wolf int bdrv_debug_resume(BlockDriverState *bs, const char *tag)
431841c695c7SKevin Wolf {
4319938789eaSMax Reitz     while (bs && (!bs->drv || !bs->drv->bdrv_debug_resume)) {
432041c695c7SKevin Wolf         bs = bs->file;
432141c695c7SKevin Wolf     }
432241c695c7SKevin Wolf 
432341c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_resume) {
432441c695c7SKevin Wolf         return bs->drv->bdrv_debug_resume(bs, tag);
432541c695c7SKevin Wolf     }
432641c695c7SKevin Wolf 
432741c695c7SKevin Wolf     return -ENOTSUP;
432841c695c7SKevin Wolf }
432941c695c7SKevin Wolf 
433041c695c7SKevin Wolf bool bdrv_debug_is_suspended(BlockDriverState *bs, const char *tag)
433141c695c7SKevin Wolf {
433241c695c7SKevin Wolf     while (bs && bs->drv && !bs->drv->bdrv_debug_is_suspended) {
433341c695c7SKevin Wolf         bs = bs->file;
433441c695c7SKevin Wolf     }
433541c695c7SKevin Wolf 
433641c695c7SKevin Wolf     if (bs && bs->drv && bs->drv->bdrv_debug_is_suspended) {
433741c695c7SKevin Wolf         return bs->drv->bdrv_debug_is_suspended(bs, tag);
433841c695c7SKevin Wolf     }
433941c695c7SKevin Wolf 
434041c695c7SKevin Wolf     return false;
43418b9b0cc2SKevin Wolf }
43428b9b0cc2SKevin Wolf 
4343199630b6SBlue Swirl int bdrv_is_snapshot(BlockDriverState *bs)
4344199630b6SBlue Swirl {
4345199630b6SBlue Swirl     return !!(bs->open_flags & BDRV_O_SNAPSHOT);
4346199630b6SBlue Swirl }
4347199630b6SBlue Swirl 
4348b1b1d783SJeff Cody /* backing_file can either be relative, or absolute, or a protocol.  If it is
4349b1b1d783SJeff Cody  * relative, it must be relative to the chain.  So, passing in bs->filename
4350b1b1d783SJeff Cody  * from a BDS as backing_file should not be done, as that may be relative to
4351b1b1d783SJeff Cody  * the CWD rather than the chain. */
4352e8a6bb9cSMarcelo Tosatti BlockDriverState *bdrv_find_backing_image(BlockDriverState *bs,
4353e8a6bb9cSMarcelo Tosatti         const char *backing_file)
4354e8a6bb9cSMarcelo Tosatti {
4355b1b1d783SJeff Cody     char *filename_full = NULL;
4356b1b1d783SJeff Cody     char *backing_file_full = NULL;
4357b1b1d783SJeff Cody     char *filename_tmp = NULL;
4358b1b1d783SJeff Cody     int is_protocol = 0;
4359b1b1d783SJeff Cody     BlockDriverState *curr_bs = NULL;
4360b1b1d783SJeff Cody     BlockDriverState *retval = NULL;
4361b1b1d783SJeff Cody 
4362b1b1d783SJeff Cody     if (!bs || !bs->drv || !backing_file) {
4363e8a6bb9cSMarcelo Tosatti         return NULL;
4364e8a6bb9cSMarcelo Tosatti     }
4365e8a6bb9cSMarcelo Tosatti 
4366b1b1d783SJeff Cody     filename_full     = g_malloc(PATH_MAX);
4367b1b1d783SJeff Cody     backing_file_full = g_malloc(PATH_MAX);
4368b1b1d783SJeff Cody     filename_tmp      = g_malloc(PATH_MAX);
4369b1b1d783SJeff Cody 
4370b1b1d783SJeff Cody     is_protocol = path_has_protocol(backing_file);
4371b1b1d783SJeff Cody 
4372b1b1d783SJeff Cody     for (curr_bs = bs; curr_bs->backing_hd; curr_bs = curr_bs->backing_hd) {
4373b1b1d783SJeff Cody 
4374b1b1d783SJeff Cody         /* If either of the filename paths is actually a protocol, then
4375b1b1d783SJeff Cody          * compare unmodified paths; otherwise make paths relative */
4376b1b1d783SJeff Cody         if (is_protocol || path_has_protocol(curr_bs->backing_file)) {
4377b1b1d783SJeff Cody             if (strcmp(backing_file, curr_bs->backing_file) == 0) {
4378b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4379b1b1d783SJeff Cody                 break;
4380b1b1d783SJeff Cody             }
4381e8a6bb9cSMarcelo Tosatti         } else {
4382b1b1d783SJeff Cody             /* If not an absolute filename path, make it relative to the current
4383b1b1d783SJeff Cody              * image's filename path */
4384b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4385b1b1d783SJeff Cody                          backing_file);
4386b1b1d783SJeff Cody 
4387b1b1d783SJeff Cody             /* We are going to compare absolute pathnames */
4388b1b1d783SJeff Cody             if (!realpath(filename_tmp, filename_full)) {
4389b1b1d783SJeff Cody                 continue;
4390b1b1d783SJeff Cody             }
4391b1b1d783SJeff Cody 
4392b1b1d783SJeff Cody             /* We need to make sure the backing filename we are comparing against
4393b1b1d783SJeff Cody              * is relative to the current image filename (or absolute) */
4394b1b1d783SJeff Cody             path_combine(filename_tmp, PATH_MAX, curr_bs->filename,
4395b1b1d783SJeff Cody                          curr_bs->backing_file);
4396b1b1d783SJeff Cody 
4397b1b1d783SJeff Cody             if (!realpath(filename_tmp, backing_file_full)) {
4398b1b1d783SJeff Cody                 continue;
4399b1b1d783SJeff Cody             }
4400b1b1d783SJeff Cody 
4401b1b1d783SJeff Cody             if (strcmp(backing_file_full, filename_full) == 0) {
4402b1b1d783SJeff Cody                 retval = curr_bs->backing_hd;
4403b1b1d783SJeff Cody                 break;
4404b1b1d783SJeff Cody             }
4405e8a6bb9cSMarcelo Tosatti         }
4406e8a6bb9cSMarcelo Tosatti     }
4407e8a6bb9cSMarcelo Tosatti 
4408b1b1d783SJeff Cody     g_free(filename_full);
4409b1b1d783SJeff Cody     g_free(backing_file_full);
4410b1b1d783SJeff Cody     g_free(filename_tmp);
4411b1b1d783SJeff Cody     return retval;
4412e8a6bb9cSMarcelo Tosatti }
4413e8a6bb9cSMarcelo Tosatti 
4414f198fd1cSBenoît Canet int bdrv_get_backing_file_depth(BlockDriverState *bs)
4415f198fd1cSBenoît Canet {
4416f198fd1cSBenoît Canet     if (!bs->drv) {
4417f198fd1cSBenoît Canet         return 0;
4418f198fd1cSBenoît Canet     }
4419f198fd1cSBenoît Canet 
4420f198fd1cSBenoît Canet     if (!bs->backing_hd) {
4421f198fd1cSBenoît Canet         return 0;
4422f198fd1cSBenoît Canet     }
4423f198fd1cSBenoît Canet 
4424f198fd1cSBenoît Canet     return 1 + bdrv_get_backing_file_depth(bs->backing_hd);
4425f198fd1cSBenoît Canet }
4426f198fd1cSBenoît Canet 
4427ea2384d3Sbellard /**************************************************************/
442883f64091Sbellard /* async I/Os */
4429ea2384d3Sbellard 
44303b69e4b9Saliguori BlockDriverAIOCB *bdrv_aio_readv(BlockDriverState *bs, int64_t sector_num,
4431f141eafeSaliguori                                  QEMUIOVector *qiov, int nb_sectors,
443283f64091Sbellard                                  BlockDriverCompletionFunc *cb, void *opaque)
4433ea2384d3Sbellard {
4434bbf0a440SStefan Hajnoczi     trace_bdrv_aio_readv(bs, sector_num, nb_sectors, opaque);
4435bbf0a440SStefan Hajnoczi 
4436d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
44378c5873d6SStefan Hajnoczi                                  cb, opaque, false);
443883f64091Sbellard }
443983f64091Sbellard 
4440f141eafeSaliguori BlockDriverAIOCB *bdrv_aio_writev(BlockDriverState *bs, int64_t sector_num,
4441f141eafeSaliguori                                   QEMUIOVector *qiov, int nb_sectors,
444283f64091Sbellard                                   BlockDriverCompletionFunc *cb, void *opaque)
44437674e7bfSbellard {
4444bbf0a440SStefan Hajnoczi     trace_bdrv_aio_writev(bs, sector_num, nb_sectors, opaque);
4445bbf0a440SStefan Hajnoczi 
4446d20d9b7cSPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, qiov, nb_sectors, 0,
44478c5873d6SStefan Hajnoczi                                  cb, opaque, true);
444883f64091Sbellard }
444983f64091Sbellard 
4450d5ef94d4SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_write_zeroes(BlockDriverState *bs,
4451d5ef94d4SPaolo Bonzini         int64_t sector_num, int nb_sectors, BdrvRequestFlags flags,
4452d5ef94d4SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
4453d5ef94d4SPaolo Bonzini {
4454d5ef94d4SPaolo Bonzini     trace_bdrv_aio_write_zeroes(bs, sector_num, nb_sectors, flags, opaque);
4455d5ef94d4SPaolo Bonzini 
4456d5ef94d4SPaolo Bonzini     return bdrv_co_aio_rw_vector(bs, sector_num, NULL, nb_sectors,
4457d5ef94d4SPaolo Bonzini                                  BDRV_REQ_ZERO_WRITE | flags,
4458d5ef94d4SPaolo Bonzini                                  cb, opaque, true);
4459d5ef94d4SPaolo Bonzini }
4460d5ef94d4SPaolo Bonzini 
446140b4f539SKevin Wolf 
446240b4f539SKevin Wolf typedef struct MultiwriteCB {
446340b4f539SKevin Wolf     int error;
446440b4f539SKevin Wolf     int num_requests;
446540b4f539SKevin Wolf     int num_callbacks;
446640b4f539SKevin Wolf     struct {
446740b4f539SKevin Wolf         BlockDriverCompletionFunc *cb;
446840b4f539SKevin Wolf         void *opaque;
446940b4f539SKevin Wolf         QEMUIOVector *free_qiov;
447040b4f539SKevin Wolf     } callbacks[];
447140b4f539SKevin Wolf } MultiwriteCB;
447240b4f539SKevin Wolf 
447340b4f539SKevin Wolf static void multiwrite_user_cb(MultiwriteCB *mcb)
447440b4f539SKevin Wolf {
447540b4f539SKevin Wolf     int i;
447640b4f539SKevin Wolf 
447740b4f539SKevin Wolf     for (i = 0; i < mcb->num_callbacks; i++) {
447840b4f539SKevin Wolf         mcb->callbacks[i].cb(mcb->callbacks[i].opaque, mcb->error);
44791e1ea48dSStefan Hajnoczi         if (mcb->callbacks[i].free_qiov) {
44801e1ea48dSStefan Hajnoczi             qemu_iovec_destroy(mcb->callbacks[i].free_qiov);
44811e1ea48dSStefan Hajnoczi         }
44827267c094SAnthony Liguori         g_free(mcb->callbacks[i].free_qiov);
448340b4f539SKevin Wolf     }
448440b4f539SKevin Wolf }
448540b4f539SKevin Wolf 
448640b4f539SKevin Wolf static void multiwrite_cb(void *opaque, int ret)
448740b4f539SKevin Wolf {
448840b4f539SKevin Wolf     MultiwriteCB *mcb = opaque;
448940b4f539SKevin Wolf 
44906d519a5fSStefan Hajnoczi     trace_multiwrite_cb(mcb, ret);
44916d519a5fSStefan Hajnoczi 
4492cb6d3ca0SKevin Wolf     if (ret < 0 && !mcb->error) {
449340b4f539SKevin Wolf         mcb->error = ret;
449440b4f539SKevin Wolf     }
449540b4f539SKevin Wolf 
449640b4f539SKevin Wolf     mcb->num_requests--;
449740b4f539SKevin Wolf     if (mcb->num_requests == 0) {
449840b4f539SKevin Wolf         multiwrite_user_cb(mcb);
44997267c094SAnthony Liguori         g_free(mcb);
450040b4f539SKevin Wolf     }
450140b4f539SKevin Wolf }
450240b4f539SKevin Wolf 
450340b4f539SKevin Wolf static int multiwrite_req_compare(const void *a, const void *b)
450440b4f539SKevin Wolf {
450577be4366SChristoph Hellwig     const BlockRequest *req1 = a, *req2 = b;
450677be4366SChristoph Hellwig 
450777be4366SChristoph Hellwig     /*
450877be4366SChristoph Hellwig      * Note that we can't simply subtract req2->sector from req1->sector
450977be4366SChristoph Hellwig      * here as that could overflow the return value.
451077be4366SChristoph Hellwig      */
451177be4366SChristoph Hellwig     if (req1->sector > req2->sector) {
451277be4366SChristoph Hellwig         return 1;
451377be4366SChristoph Hellwig     } else if (req1->sector < req2->sector) {
451477be4366SChristoph Hellwig         return -1;
451577be4366SChristoph Hellwig     } else {
451677be4366SChristoph Hellwig         return 0;
451777be4366SChristoph Hellwig     }
451840b4f539SKevin Wolf }
451940b4f539SKevin Wolf 
452040b4f539SKevin Wolf /*
452140b4f539SKevin Wolf  * Takes a bunch of requests and tries to merge them. Returns the number of
452240b4f539SKevin Wolf  * requests that remain after merging.
452340b4f539SKevin Wolf  */
452440b4f539SKevin Wolf static int multiwrite_merge(BlockDriverState *bs, BlockRequest *reqs,
452540b4f539SKevin Wolf     int num_reqs, MultiwriteCB *mcb)
452640b4f539SKevin Wolf {
452740b4f539SKevin Wolf     int i, outidx;
452840b4f539SKevin Wolf 
452940b4f539SKevin Wolf     // Sort requests by start sector
453040b4f539SKevin Wolf     qsort(reqs, num_reqs, sizeof(*reqs), &multiwrite_req_compare);
453140b4f539SKevin Wolf 
453240b4f539SKevin Wolf     // Check if adjacent requests touch the same clusters. If so, combine them,
453340b4f539SKevin Wolf     // filling up gaps with zero sectors.
453440b4f539SKevin Wolf     outidx = 0;
453540b4f539SKevin Wolf     for (i = 1; i < num_reqs; i++) {
453640b4f539SKevin Wolf         int merge = 0;
453740b4f539SKevin Wolf         int64_t oldreq_last = reqs[outidx].sector + reqs[outidx].nb_sectors;
453840b4f539SKevin Wolf 
4539b6a127a1SPaolo Bonzini         // Handle exactly sequential writes and overlapping writes.
454040b4f539SKevin Wolf         if (reqs[i].sector <= oldreq_last) {
454140b4f539SKevin Wolf             merge = 1;
454240b4f539SKevin Wolf         }
454340b4f539SKevin Wolf 
4544e2a305fbSChristoph Hellwig         if (reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1 > IOV_MAX) {
4545e2a305fbSChristoph Hellwig             merge = 0;
4546e2a305fbSChristoph Hellwig         }
4547e2a305fbSChristoph Hellwig 
454840b4f539SKevin Wolf         if (merge) {
454940b4f539SKevin Wolf             size_t size;
45507267c094SAnthony Liguori             QEMUIOVector *qiov = g_malloc0(sizeof(*qiov));
455140b4f539SKevin Wolf             qemu_iovec_init(qiov,
455240b4f539SKevin Wolf                 reqs[outidx].qiov->niov + reqs[i].qiov->niov + 1);
455340b4f539SKevin Wolf 
455440b4f539SKevin Wolf             // Add the first request to the merged one. If the requests are
455540b4f539SKevin Wolf             // overlapping, drop the last sectors of the first request.
455640b4f539SKevin Wolf             size = (reqs[i].sector - reqs[outidx].sector) << 9;
45571b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[outidx].qiov, 0, size);
455840b4f539SKevin Wolf 
4559b6a127a1SPaolo Bonzini             // We should need to add any zeros between the two requests
4560b6a127a1SPaolo Bonzini             assert (reqs[i].sector <= oldreq_last);
456140b4f539SKevin Wolf 
456240b4f539SKevin Wolf             // Add the second request
45631b093c48SMichael Tokarev             qemu_iovec_concat(qiov, reqs[i].qiov, 0, reqs[i].qiov->size);
456440b4f539SKevin Wolf 
4565391827ebSStefan Hajnoczi             // Add tail of first request, if necessary
4566391827ebSStefan Hajnoczi             if (qiov->size < reqs[outidx].qiov->size) {
4567391827ebSStefan Hajnoczi                 qemu_iovec_concat(qiov, reqs[outidx].qiov, qiov->size,
4568391827ebSStefan Hajnoczi                                   reqs[outidx].qiov->size - qiov->size);
4569391827ebSStefan Hajnoczi             }
4570391827ebSStefan Hajnoczi 
4571cbf1dff2SKevin Wolf             reqs[outidx].nb_sectors = qiov->size >> 9;
457240b4f539SKevin Wolf             reqs[outidx].qiov = qiov;
457340b4f539SKevin Wolf 
457440b4f539SKevin Wolf             mcb->callbacks[i].free_qiov = reqs[outidx].qiov;
457540b4f539SKevin Wolf         } else {
457640b4f539SKevin Wolf             outidx++;
457740b4f539SKevin Wolf             reqs[outidx].sector     = reqs[i].sector;
457840b4f539SKevin Wolf             reqs[outidx].nb_sectors = reqs[i].nb_sectors;
457940b4f539SKevin Wolf             reqs[outidx].qiov       = reqs[i].qiov;
458040b4f539SKevin Wolf         }
458140b4f539SKevin Wolf     }
458240b4f539SKevin Wolf 
458340b4f539SKevin Wolf     return outidx + 1;
458440b4f539SKevin Wolf }
458540b4f539SKevin Wolf 
458640b4f539SKevin Wolf /*
458740b4f539SKevin Wolf  * Submit multiple AIO write requests at once.
458840b4f539SKevin Wolf  *
458940b4f539SKevin Wolf  * On success, the function returns 0 and all requests in the reqs array have
459040b4f539SKevin Wolf  * been submitted. In error case this function returns -1, and any of the
459140b4f539SKevin Wolf  * requests may or may not be submitted yet. In particular, this means that the
459240b4f539SKevin Wolf  * callback will be called for some of the requests, for others it won't. The
459340b4f539SKevin Wolf  * caller must check the error field of the BlockRequest to wait for the right
459440b4f539SKevin Wolf  * callbacks (if error != 0, no callback will be called).
459540b4f539SKevin Wolf  *
459640b4f539SKevin Wolf  * The implementation may modify the contents of the reqs array, e.g. to merge
459740b4f539SKevin Wolf  * requests. However, the fields opaque and error are left unmodified as they
459840b4f539SKevin Wolf  * are used to signal failure for a single request to the caller.
459940b4f539SKevin Wolf  */
460040b4f539SKevin Wolf int bdrv_aio_multiwrite(BlockDriverState *bs, BlockRequest *reqs, int num_reqs)
460140b4f539SKevin Wolf {
460240b4f539SKevin Wolf     MultiwriteCB *mcb;
460340b4f539SKevin Wolf     int i;
460440b4f539SKevin Wolf 
4605301db7c2SRyan Harper     /* don't submit writes if we don't have a medium */
4606301db7c2SRyan Harper     if (bs->drv == NULL) {
4607301db7c2SRyan Harper         for (i = 0; i < num_reqs; i++) {
4608301db7c2SRyan Harper             reqs[i].error = -ENOMEDIUM;
4609301db7c2SRyan Harper         }
4610301db7c2SRyan Harper         return -1;
4611301db7c2SRyan Harper     }
4612301db7c2SRyan Harper 
461340b4f539SKevin Wolf     if (num_reqs == 0) {
461440b4f539SKevin Wolf         return 0;
461540b4f539SKevin Wolf     }
461640b4f539SKevin Wolf 
461740b4f539SKevin Wolf     // Create MultiwriteCB structure
46187267c094SAnthony Liguori     mcb = g_malloc0(sizeof(*mcb) + num_reqs * sizeof(*mcb->callbacks));
461940b4f539SKevin Wolf     mcb->num_requests = 0;
462040b4f539SKevin Wolf     mcb->num_callbacks = num_reqs;
462140b4f539SKevin Wolf 
462240b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
462340b4f539SKevin Wolf         mcb->callbacks[i].cb = reqs[i].cb;
462440b4f539SKevin Wolf         mcb->callbacks[i].opaque = reqs[i].opaque;
462540b4f539SKevin Wolf     }
462640b4f539SKevin Wolf 
462740b4f539SKevin Wolf     // Check for mergable requests
462840b4f539SKevin Wolf     num_reqs = multiwrite_merge(bs, reqs, num_reqs, mcb);
462940b4f539SKevin Wolf 
46306d519a5fSStefan Hajnoczi     trace_bdrv_aio_multiwrite(mcb, mcb->num_callbacks, num_reqs);
46316d519a5fSStefan Hajnoczi 
4632df9309fbSPaolo Bonzini     /* Run the aio requests. */
4633df9309fbSPaolo Bonzini     mcb->num_requests = num_reqs;
463440b4f539SKevin Wolf     for (i = 0; i < num_reqs; i++) {
4635d20d9b7cSPaolo Bonzini         bdrv_co_aio_rw_vector(bs, reqs[i].sector, reqs[i].qiov,
4636d20d9b7cSPaolo Bonzini                               reqs[i].nb_sectors, reqs[i].flags,
4637d20d9b7cSPaolo Bonzini                               multiwrite_cb, mcb,
4638d20d9b7cSPaolo Bonzini                               true);
463940b4f539SKevin Wolf     }
464040b4f539SKevin Wolf 
464140b4f539SKevin Wolf     return 0;
464240b4f539SKevin Wolf }
464340b4f539SKevin Wolf 
464483f64091Sbellard void bdrv_aio_cancel(BlockDriverAIOCB *acb)
464583f64091Sbellard {
464602c50efeSFam Zheng     qemu_aio_ref(acb);
464702c50efeSFam Zheng     bdrv_aio_cancel_async(acb);
464802c50efeSFam Zheng     while (acb->refcnt > 1) {
464902c50efeSFam Zheng         if (acb->aiocb_info->get_aio_context) {
465002c50efeSFam Zheng             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
465102c50efeSFam Zheng         } else if (acb->bs) {
465202c50efeSFam Zheng             aio_poll(bdrv_get_aio_context(acb->bs), true);
465302c50efeSFam Zheng         } else {
465402c50efeSFam Zheng             abort();
465502c50efeSFam Zheng         }
465602c50efeSFam Zheng     }
46578007429aSFam Zheng     qemu_aio_unref(acb);
465802c50efeSFam Zheng }
465902c50efeSFam Zheng 
466002c50efeSFam Zheng /* Async version of aio cancel. The caller is not blocked if the acb implements
466102c50efeSFam Zheng  * cancel_async, otherwise we do nothing and let the request normally complete.
466202c50efeSFam Zheng  * In either case the completion callback must be called. */
466302c50efeSFam Zheng void bdrv_aio_cancel_async(BlockDriverAIOCB *acb)
466402c50efeSFam Zheng {
466502c50efeSFam Zheng     if (acb->aiocb_info->cancel_async) {
466602c50efeSFam Zheng         acb->aiocb_info->cancel_async(acb);
466702c50efeSFam Zheng     }
466883f64091Sbellard }
466983f64091Sbellard 
467083f64091Sbellard /**************************************************************/
467183f64091Sbellard /* async block device emulation */
467283f64091Sbellard 
4673c16b5a2cSChristoph Hellwig typedef struct BlockDriverAIOCBSync {
4674c16b5a2cSChristoph Hellwig     BlockDriverAIOCB common;
4675c16b5a2cSChristoph Hellwig     QEMUBH *bh;
4676c16b5a2cSChristoph Hellwig     int ret;
4677c16b5a2cSChristoph Hellwig     /* vector translation state */
4678c16b5a2cSChristoph Hellwig     QEMUIOVector *qiov;
4679c16b5a2cSChristoph Hellwig     uint8_t *bounce;
4680c16b5a2cSChristoph Hellwig     int is_write;
4681c16b5a2cSChristoph Hellwig } BlockDriverAIOCBSync;
4682c16b5a2cSChristoph Hellwig 
4683d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_aiocb_info = {
4684c16b5a2cSChristoph Hellwig     .aiocb_size         = sizeof(BlockDriverAIOCBSync),
4685c16b5a2cSChristoph Hellwig };
4686c16b5a2cSChristoph Hellwig 
468783f64091Sbellard static void bdrv_aio_bh_cb(void *opaque)
4688beac80cdSbellard {
4689ce1a14dcSpbrook     BlockDriverAIOCBSync *acb = opaque;
4690f141eafeSaliguori 
4691857d4f46SKevin Wolf     if (!acb->is_write && acb->ret >= 0) {
469203396148SMichael Tokarev         qemu_iovec_from_buf(acb->qiov, 0, acb->bounce, acb->qiov->size);
4693857d4f46SKevin Wolf     }
4694ceb42de8Saliguori     qemu_vfree(acb->bounce);
4695ce1a14dcSpbrook     acb->common.cb(acb->common.opaque, acb->ret);
46966a7ad299SDor Laor     qemu_bh_delete(acb->bh);
469736afc451SAvi Kivity     acb->bh = NULL;
46988007429aSFam Zheng     qemu_aio_unref(acb);
4699beac80cdSbellard }
4700beac80cdSbellard 
4701f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_rw_vector(BlockDriverState *bs,
4702f141eafeSaliguori                                             int64_t sector_num,
4703f141eafeSaliguori                                             QEMUIOVector *qiov,
4704f141eafeSaliguori                                             int nb_sectors,
4705f141eafeSaliguori                                             BlockDriverCompletionFunc *cb,
4706f141eafeSaliguori                                             void *opaque,
4707f141eafeSaliguori                                             int is_write)
4708f141eafeSaliguori 
4709ea2384d3Sbellard {
4710ce1a14dcSpbrook     BlockDriverAIOCBSync *acb;
471183f64091Sbellard 
4712d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_aiocb_info, bs, cb, opaque);
4713f141eafeSaliguori     acb->is_write = is_write;
4714f141eafeSaliguori     acb->qiov = qiov;
4715857d4f46SKevin Wolf     acb->bounce = qemu_try_blockalign(bs, qiov->size);
47162572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_aio_bh_cb, acb);
4717f141eafeSaliguori 
4718857d4f46SKevin Wolf     if (acb->bounce == NULL) {
4719857d4f46SKevin Wolf         acb->ret = -ENOMEM;
4720857d4f46SKevin Wolf     } else if (is_write) {
4721d5e6b161SMichael Tokarev         qemu_iovec_to_buf(acb->qiov, 0, acb->bounce, qiov->size);
47221ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_write(bs, sector_num, acb->bounce, nb_sectors);
4723f141eafeSaliguori     } else {
47241ed20acfSStefan Hajnoczi         acb->ret = bs->drv->bdrv_read(bs, sector_num, acb->bounce, nb_sectors);
4725f141eafeSaliguori     }
4726f141eafeSaliguori 
4727ce1a14dcSpbrook     qemu_bh_schedule(acb->bh);
4728f141eafeSaliguori 
4729ce1a14dcSpbrook     return &acb->common;
47307a6cba61Spbrook }
47317a6cba61Spbrook 
4732f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_readv_em(BlockDriverState *bs,
4733f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4734ce1a14dcSpbrook         BlockDriverCompletionFunc *cb, void *opaque)
473583f64091Sbellard {
4736f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 0);
473783f64091Sbellard }
473883f64091Sbellard 
4739f141eafeSaliguori static BlockDriverAIOCB *bdrv_aio_writev_em(BlockDriverState *bs,
4740f141eafeSaliguori         int64_t sector_num, QEMUIOVector *qiov, int nb_sectors,
4741f141eafeSaliguori         BlockDriverCompletionFunc *cb, void *opaque)
4742f141eafeSaliguori {
4743f141eafeSaliguori     return bdrv_aio_rw_vector(bs, sector_num, qiov, nb_sectors, cb, opaque, 1);
4744f141eafeSaliguori }
4745f141eafeSaliguori 
474668485420SKevin Wolf 
474768485420SKevin Wolf typedef struct BlockDriverAIOCBCoroutine {
474868485420SKevin Wolf     BlockDriverAIOCB common;
474968485420SKevin Wolf     BlockRequest req;
475068485420SKevin Wolf     bool is_write;
4751d318aea9SKevin Wolf     bool *done;
475268485420SKevin Wolf     QEMUBH* bh;
475368485420SKevin Wolf } BlockDriverAIOCBCoroutine;
475468485420SKevin Wolf 
4755d7331bedSStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
475668485420SKevin Wolf     .aiocb_size         = sizeof(BlockDriverAIOCBCoroutine),
475768485420SKevin Wolf };
475868485420SKevin Wolf 
475935246a68SPaolo Bonzini static void bdrv_co_em_bh(void *opaque)
476068485420SKevin Wolf {
476168485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb = opaque;
476268485420SKevin Wolf 
476368485420SKevin Wolf     acb->common.cb(acb->common.opaque, acb->req.error);
4764d318aea9SKevin Wolf 
476568485420SKevin Wolf     qemu_bh_delete(acb->bh);
47668007429aSFam Zheng     qemu_aio_unref(acb);
476768485420SKevin Wolf }
476868485420SKevin Wolf 
4769b2a61371SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
4770b2a61371SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
4771b2a61371SStefan Hajnoczi {
4772b2a61371SStefan Hajnoczi     BlockDriverAIOCBCoroutine *acb = opaque;
4773b2a61371SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
4774b2a61371SStefan Hajnoczi 
4775b2a61371SStefan Hajnoczi     if (!acb->is_write) {
4776b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_readv(bs, acb->req.sector,
4777d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4778b2a61371SStefan Hajnoczi     } else {
4779b2a61371SStefan Hajnoczi         acb->req.error = bdrv_co_do_writev(bs, acb->req.sector,
4780d20d9b7cSPaolo Bonzini             acb->req.nb_sectors, acb->req.qiov, acb->req.flags);
4781b2a61371SStefan Hajnoczi     }
4782b2a61371SStefan Hajnoczi 
47832572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
4784b2a61371SStefan Hajnoczi     qemu_bh_schedule(acb->bh);
4785b2a61371SStefan Hajnoczi }
4786b2a61371SStefan Hajnoczi 
478768485420SKevin Wolf static BlockDriverAIOCB *bdrv_co_aio_rw_vector(BlockDriverState *bs,
478868485420SKevin Wolf                                                int64_t sector_num,
478968485420SKevin Wolf                                                QEMUIOVector *qiov,
479068485420SKevin Wolf                                                int nb_sectors,
4791d20d9b7cSPaolo Bonzini                                                BdrvRequestFlags flags,
479268485420SKevin Wolf                                                BlockDriverCompletionFunc *cb,
479368485420SKevin Wolf                                                void *opaque,
47948c5873d6SStefan Hajnoczi                                                bool is_write)
479568485420SKevin Wolf {
479668485420SKevin Wolf     Coroutine *co;
479768485420SKevin Wolf     BlockDriverAIOCBCoroutine *acb;
479868485420SKevin Wolf 
4799d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
480068485420SKevin Wolf     acb->req.sector = sector_num;
480168485420SKevin Wolf     acb->req.nb_sectors = nb_sectors;
480268485420SKevin Wolf     acb->req.qiov = qiov;
4803d20d9b7cSPaolo Bonzini     acb->req.flags = flags;
480468485420SKevin Wolf     acb->is_write = is_write;
480568485420SKevin Wolf 
48068c5873d6SStefan Hajnoczi     co = qemu_coroutine_create(bdrv_co_do_rw);
480768485420SKevin Wolf     qemu_coroutine_enter(co, acb);
480868485420SKevin Wolf 
480968485420SKevin Wolf     return &acb->common;
481068485420SKevin Wolf }
481168485420SKevin Wolf 
481207f07615SPaolo Bonzini static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
4813b2e12bc6SChristoph Hellwig {
481407f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
481507f07615SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
4816b2e12bc6SChristoph Hellwig 
481707f07615SPaolo Bonzini     acb->req.error = bdrv_co_flush(bs);
48182572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
4819b2e12bc6SChristoph Hellwig     qemu_bh_schedule(acb->bh);
4820b2e12bc6SChristoph Hellwig }
4821b2e12bc6SChristoph Hellwig 
482207f07615SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_flush(BlockDriverState *bs,
4823016f5cf6SAlexander Graf         BlockDriverCompletionFunc *cb, void *opaque)
4824016f5cf6SAlexander Graf {
482507f07615SPaolo Bonzini     trace_bdrv_aio_flush(bs, opaque);
4826016f5cf6SAlexander Graf 
482707f07615SPaolo Bonzini     Coroutine *co;
482807f07615SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
4829016f5cf6SAlexander Graf 
4830d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
4831d318aea9SKevin Wolf 
483207f07615SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry);
483307f07615SPaolo Bonzini     qemu_coroutine_enter(co, acb);
4834016f5cf6SAlexander Graf 
4835016f5cf6SAlexander Graf     return &acb->common;
4836016f5cf6SAlexander Graf }
4837016f5cf6SAlexander Graf 
48384265d620SPaolo Bonzini static void coroutine_fn bdrv_aio_discard_co_entry(void *opaque)
48394265d620SPaolo Bonzini {
48404265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb = opaque;
48414265d620SPaolo Bonzini     BlockDriverState *bs = acb->common.bs;
48424265d620SPaolo Bonzini 
48434265d620SPaolo Bonzini     acb->req.error = bdrv_co_discard(bs, acb->req.sector, acb->req.nb_sectors);
48442572b37aSStefan Hajnoczi     acb->bh = aio_bh_new(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
48454265d620SPaolo Bonzini     qemu_bh_schedule(acb->bh);
48464265d620SPaolo Bonzini }
48474265d620SPaolo Bonzini 
48484265d620SPaolo Bonzini BlockDriverAIOCB *bdrv_aio_discard(BlockDriverState *bs,
48494265d620SPaolo Bonzini         int64_t sector_num, int nb_sectors,
48504265d620SPaolo Bonzini         BlockDriverCompletionFunc *cb, void *opaque)
48514265d620SPaolo Bonzini {
48524265d620SPaolo Bonzini     Coroutine *co;
48534265d620SPaolo Bonzini     BlockDriverAIOCBCoroutine *acb;
48544265d620SPaolo Bonzini 
48554265d620SPaolo Bonzini     trace_bdrv_aio_discard(bs, sector_num, nb_sectors, opaque);
48564265d620SPaolo Bonzini 
4857d7331bedSStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
48584265d620SPaolo Bonzini     acb->req.sector = sector_num;
48594265d620SPaolo Bonzini     acb->req.nb_sectors = nb_sectors;
48604265d620SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_discard_co_entry);
48614265d620SPaolo Bonzini     qemu_coroutine_enter(co, acb);
48624265d620SPaolo Bonzini 
48634265d620SPaolo Bonzini     return &acb->common;
48644265d620SPaolo Bonzini }
48654265d620SPaolo Bonzini 
4866ea2384d3Sbellard void bdrv_init(void)
4867ea2384d3Sbellard {
48685efa9d5aSAnthony Liguori     module_call_init(MODULE_INIT_BLOCK);
4869ea2384d3Sbellard }
4870ce1a14dcSpbrook 
4871eb852011SMarkus Armbruster void bdrv_init_with_whitelist(void)
4872eb852011SMarkus Armbruster {
4873eb852011SMarkus Armbruster     use_bdrv_whitelist = 1;
4874eb852011SMarkus Armbruster     bdrv_init();
4875eb852011SMarkus Armbruster }
4876eb852011SMarkus Armbruster 
4877d7331bedSStefan Hajnoczi void *qemu_aio_get(const AIOCBInfo *aiocb_info, BlockDriverState *bs,
48786bbff9a0Saliguori                    BlockDriverCompletionFunc *cb, void *opaque)
48796bbff9a0Saliguori {
4880ce1a14dcSpbrook     BlockDriverAIOCB *acb;
4881ce1a14dcSpbrook 
4882d7331bedSStefan Hajnoczi     acb = g_slice_alloc(aiocb_info->aiocb_size);
4883d7331bedSStefan Hajnoczi     acb->aiocb_info = aiocb_info;
4884ce1a14dcSpbrook     acb->bs = bs;
4885ce1a14dcSpbrook     acb->cb = cb;
4886ce1a14dcSpbrook     acb->opaque = opaque;
4887f197fe2bSFam Zheng     acb->refcnt = 1;
4888ce1a14dcSpbrook     return acb;
4889ce1a14dcSpbrook }
4890ce1a14dcSpbrook 
4891f197fe2bSFam Zheng void qemu_aio_ref(void *p)
4892f197fe2bSFam Zheng {
4893f197fe2bSFam Zheng     BlockDriverAIOCB *acb = p;
4894f197fe2bSFam Zheng     acb->refcnt++;
4895f197fe2bSFam Zheng }
4896f197fe2bSFam Zheng 
48978007429aSFam Zheng void qemu_aio_unref(void *p)
4898ce1a14dcSpbrook {
4899d37c975fSStefan Hajnoczi     BlockDriverAIOCB *acb = p;
4900f197fe2bSFam Zheng     assert(acb->refcnt > 0);
4901f197fe2bSFam Zheng     if (--acb->refcnt == 0) {
4902d7331bedSStefan Hajnoczi         g_slice_free1(acb->aiocb_info->aiocb_size, acb);
4903ce1a14dcSpbrook     }
4904f197fe2bSFam Zheng }
490519cb3738Sbellard 
490619cb3738Sbellard /**************************************************************/
4907f9f05dc5SKevin Wolf /* Coroutine block device emulation */
4908f9f05dc5SKevin Wolf 
4909f9f05dc5SKevin Wolf typedef struct CoroutineIOCompletion {
4910f9f05dc5SKevin Wolf     Coroutine *coroutine;
4911f9f05dc5SKevin Wolf     int ret;
4912f9f05dc5SKevin Wolf } CoroutineIOCompletion;
4913f9f05dc5SKevin Wolf 
4914f9f05dc5SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
4915f9f05dc5SKevin Wolf {
4916f9f05dc5SKevin Wolf     CoroutineIOCompletion *co = opaque;
4917f9f05dc5SKevin Wolf 
4918f9f05dc5SKevin Wolf     co->ret = ret;
4919f9f05dc5SKevin Wolf     qemu_coroutine_enter(co->coroutine, NULL);
4920f9f05dc5SKevin Wolf }
4921f9f05dc5SKevin Wolf 
4922f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_io_em(BlockDriverState *bs, int64_t sector_num,
4923f9f05dc5SKevin Wolf                                       int nb_sectors, QEMUIOVector *iov,
4924f9f05dc5SKevin Wolf                                       bool is_write)
4925f9f05dc5SKevin Wolf {
4926f9f05dc5SKevin Wolf     CoroutineIOCompletion co = {
4927f9f05dc5SKevin Wolf         .coroutine = qemu_coroutine_self(),
4928f9f05dc5SKevin Wolf     };
4929f9f05dc5SKevin Wolf     BlockDriverAIOCB *acb;
4930f9f05dc5SKevin Wolf 
4931f9f05dc5SKevin Wolf     if (is_write) {
4932a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_writev(bs, sector_num, iov, nb_sectors,
4933f9f05dc5SKevin Wolf                                        bdrv_co_io_em_complete, &co);
4934f9f05dc5SKevin Wolf     } else {
4935a652d160SStefan Hajnoczi         acb = bs->drv->bdrv_aio_readv(bs, sector_num, iov, nb_sectors,
4936f9f05dc5SKevin Wolf                                       bdrv_co_io_em_complete, &co);
4937f9f05dc5SKevin Wolf     }
4938f9f05dc5SKevin Wolf 
493959370aaaSStefan Hajnoczi     trace_bdrv_co_io_em(bs, sector_num, nb_sectors, is_write, acb);
4940f9f05dc5SKevin Wolf     if (!acb) {
4941f9f05dc5SKevin Wolf         return -EIO;
4942f9f05dc5SKevin Wolf     }
4943f9f05dc5SKevin Wolf     qemu_coroutine_yield();
4944f9f05dc5SKevin Wolf 
4945f9f05dc5SKevin Wolf     return co.ret;
4946f9f05dc5SKevin Wolf }
4947f9f05dc5SKevin Wolf 
4948f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_readv_em(BlockDriverState *bs,
4949f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4950f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4951f9f05dc5SKevin Wolf {
4952f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, false);
4953f9f05dc5SKevin Wolf }
4954f9f05dc5SKevin Wolf 
4955f9f05dc5SKevin Wolf static int coroutine_fn bdrv_co_writev_em(BlockDriverState *bs,
4956f9f05dc5SKevin Wolf                                          int64_t sector_num, int nb_sectors,
4957f9f05dc5SKevin Wolf                                          QEMUIOVector *iov)
4958f9f05dc5SKevin Wolf {
4959f9f05dc5SKevin Wolf     return bdrv_co_io_em(bs, sector_num, nb_sectors, iov, true);
4960f9f05dc5SKevin Wolf }
4961f9f05dc5SKevin Wolf 
496207f07615SPaolo Bonzini static void coroutine_fn bdrv_flush_co_entry(void *opaque)
4963e7a8a783SKevin Wolf {
496407f07615SPaolo Bonzini     RwCo *rwco = opaque;
496507f07615SPaolo Bonzini 
496607f07615SPaolo Bonzini     rwco->ret = bdrv_co_flush(rwco->bs);
496707f07615SPaolo Bonzini }
496807f07615SPaolo Bonzini 
496907f07615SPaolo Bonzini int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
497007f07615SPaolo Bonzini {
4971eb489bb1SKevin Wolf     int ret;
4972eb489bb1SKevin Wolf 
497329cdb251SPaolo Bonzini     if (!bs || !bdrv_is_inserted(bs) || bdrv_is_read_only(bs)) {
497407f07615SPaolo Bonzini         return 0;
4975eb489bb1SKevin Wolf     }
4976eb489bb1SKevin Wolf 
4977ca716364SKevin Wolf     /* Write back cached data to the OS even with cache=unsafe */
4978bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
4979eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_os) {
4980eb489bb1SKevin Wolf         ret = bs->drv->bdrv_co_flush_to_os(bs);
4981eb489bb1SKevin Wolf         if (ret < 0) {
4982eb489bb1SKevin Wolf             return ret;
4983eb489bb1SKevin Wolf         }
4984eb489bb1SKevin Wolf     }
4985eb489bb1SKevin Wolf 
4986ca716364SKevin Wolf     /* But don't actually force it to the disk with cache=unsafe */
4987ca716364SKevin Wolf     if (bs->open_flags & BDRV_O_NO_FLUSH) {
4988d4c82329SKevin Wolf         goto flush_parent;
4989ca716364SKevin Wolf     }
4990ca716364SKevin Wolf 
4991bf736fe3SKevin Wolf     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
4992eb489bb1SKevin Wolf     if (bs->drv->bdrv_co_flush_to_disk) {
499329cdb251SPaolo Bonzini         ret = bs->drv->bdrv_co_flush_to_disk(bs);
499407f07615SPaolo Bonzini     } else if (bs->drv->bdrv_aio_flush) {
499507f07615SPaolo Bonzini         BlockDriverAIOCB *acb;
4996e7a8a783SKevin Wolf         CoroutineIOCompletion co = {
4997e7a8a783SKevin Wolf             .coroutine = qemu_coroutine_self(),
4998e7a8a783SKevin Wolf         };
4999e7a8a783SKevin Wolf 
500007f07615SPaolo Bonzini         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
500107f07615SPaolo Bonzini         if (acb == NULL) {
500229cdb251SPaolo Bonzini             ret = -EIO;
500307f07615SPaolo Bonzini         } else {
5004e7a8a783SKevin Wolf             qemu_coroutine_yield();
500529cdb251SPaolo Bonzini             ret = co.ret;
5006e7a8a783SKevin Wolf         }
500707f07615SPaolo Bonzini     } else {
500807f07615SPaolo Bonzini         /*
500907f07615SPaolo Bonzini          * Some block drivers always operate in either writethrough or unsafe
501007f07615SPaolo Bonzini          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
501107f07615SPaolo Bonzini          * know how the server works (because the behaviour is hardcoded or
501207f07615SPaolo Bonzini          * depends on server-side configuration), so we can't ensure that
501307f07615SPaolo Bonzini          * everything is safe on disk. Returning an error doesn't work because
501407f07615SPaolo Bonzini          * that would break guests even if the server operates in writethrough
501507f07615SPaolo Bonzini          * mode.
501607f07615SPaolo Bonzini          *
501707f07615SPaolo Bonzini          * Let's hope the user knows what he's doing.
501807f07615SPaolo Bonzini          */
501929cdb251SPaolo Bonzini         ret = 0;
502007f07615SPaolo Bonzini     }
502129cdb251SPaolo Bonzini     if (ret < 0) {
502229cdb251SPaolo Bonzini         return ret;
502329cdb251SPaolo Bonzini     }
502429cdb251SPaolo Bonzini 
502529cdb251SPaolo Bonzini     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
502629cdb251SPaolo Bonzini      * in the case of cache=unsafe, so there are no useless flushes.
502729cdb251SPaolo Bonzini      */
5028d4c82329SKevin Wolf flush_parent:
502929cdb251SPaolo Bonzini     return bdrv_co_flush(bs->file);
503007f07615SPaolo Bonzini }
503107f07615SPaolo Bonzini 
50325a8a30dbSKevin Wolf void bdrv_invalidate_cache(BlockDriverState *bs, Error **errp)
50330f15423cSAnthony Liguori {
50345a8a30dbSKevin Wolf     Error *local_err = NULL;
50355a8a30dbSKevin Wolf     int ret;
50365a8a30dbSKevin Wolf 
50373456a8d1SKevin Wolf     if (!bs->drv)  {
50383456a8d1SKevin Wolf         return;
50390f15423cSAnthony Liguori     }
50403456a8d1SKevin Wolf 
50413456a8d1SKevin Wolf     if (bs->drv->bdrv_invalidate_cache) {
50425a8a30dbSKevin Wolf         bs->drv->bdrv_invalidate_cache(bs, &local_err);
50433456a8d1SKevin Wolf     } else if (bs->file) {
50445a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs->file, &local_err);
50455a8a30dbSKevin Wolf     }
50465a8a30dbSKevin Wolf     if (local_err) {
50475a8a30dbSKevin Wolf         error_propagate(errp, local_err);
50485a8a30dbSKevin Wolf         return;
50493456a8d1SKevin Wolf     }
50503456a8d1SKevin Wolf 
50515a8a30dbSKevin Wolf     ret = refresh_total_sectors(bs, bs->total_sectors);
50525a8a30dbSKevin Wolf     if (ret < 0) {
50535a8a30dbSKevin Wolf         error_setg_errno(errp, -ret, "Could not refresh total sector count");
50545a8a30dbSKevin Wolf         return;
50555a8a30dbSKevin Wolf     }
50560f15423cSAnthony Liguori }
50570f15423cSAnthony Liguori 
50585a8a30dbSKevin Wolf void bdrv_invalidate_cache_all(Error **errp)
50590f15423cSAnthony Liguori {
50600f15423cSAnthony Liguori     BlockDriverState *bs;
50615a8a30dbSKevin Wolf     Error *local_err = NULL;
50620f15423cSAnthony Liguori 
5063dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5064ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
5065ed78cda3SStefan Hajnoczi 
5066ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
50675a8a30dbSKevin Wolf         bdrv_invalidate_cache(bs, &local_err);
5068ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
50695a8a30dbSKevin Wolf         if (local_err) {
50705a8a30dbSKevin Wolf             error_propagate(errp, local_err);
50715a8a30dbSKevin Wolf             return;
50725a8a30dbSKevin Wolf         }
50730f15423cSAnthony Liguori     }
50740f15423cSAnthony Liguori }
50750f15423cSAnthony Liguori 
507607789269SBenoît Canet void bdrv_clear_incoming_migration_all(void)
507707789269SBenoît Canet {
507807789269SBenoît Canet     BlockDriverState *bs;
507907789269SBenoît Canet 
5080dc364f4cSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5081ed78cda3SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
5082ed78cda3SStefan Hajnoczi 
5083ed78cda3SStefan Hajnoczi         aio_context_acquire(aio_context);
508407789269SBenoît Canet         bs->open_flags = bs->open_flags & ~(BDRV_O_INCOMING);
5085ed78cda3SStefan Hajnoczi         aio_context_release(aio_context);
508607789269SBenoît Canet     }
508707789269SBenoît Canet }
508807789269SBenoît Canet 
508907f07615SPaolo Bonzini int bdrv_flush(BlockDriverState *bs)
509007f07615SPaolo Bonzini {
509107f07615SPaolo Bonzini     Coroutine *co;
509207f07615SPaolo Bonzini     RwCo rwco = {
509307f07615SPaolo Bonzini         .bs = bs,
509407f07615SPaolo Bonzini         .ret = NOT_DONE,
509507f07615SPaolo Bonzini     };
509607f07615SPaolo Bonzini 
509707f07615SPaolo Bonzini     if (qemu_in_coroutine()) {
509807f07615SPaolo Bonzini         /* Fast-path if already in coroutine context */
509907f07615SPaolo Bonzini         bdrv_flush_co_entry(&rwco);
510007f07615SPaolo Bonzini     } else {
51012572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
51022572b37aSStefan Hajnoczi 
510307f07615SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry);
510407f07615SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
510507f07615SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
51062572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
510707f07615SPaolo Bonzini         }
510807f07615SPaolo Bonzini     }
510907f07615SPaolo Bonzini 
511007f07615SPaolo Bonzini     return rwco.ret;
511107f07615SPaolo Bonzini }
5112e7a8a783SKevin Wolf 
5113775aa8b6SKevin Wolf typedef struct DiscardCo {
5114775aa8b6SKevin Wolf     BlockDriverState *bs;
5115775aa8b6SKevin Wolf     int64_t sector_num;
5116775aa8b6SKevin Wolf     int nb_sectors;
5117775aa8b6SKevin Wolf     int ret;
5118775aa8b6SKevin Wolf } DiscardCo;
51194265d620SPaolo Bonzini static void coroutine_fn bdrv_discard_co_entry(void *opaque)
51204265d620SPaolo Bonzini {
5121775aa8b6SKevin Wolf     DiscardCo *rwco = opaque;
51224265d620SPaolo Bonzini 
51234265d620SPaolo Bonzini     rwco->ret = bdrv_co_discard(rwco->bs, rwco->sector_num, rwco->nb_sectors);
51244265d620SPaolo Bonzini }
51254265d620SPaolo Bonzini 
51266f14da52SPeter Lieven /* if no limit is specified in the BlockLimits use a default
51276f14da52SPeter Lieven  * of 32768 512-byte sectors (16 MiB) per request.
51286f14da52SPeter Lieven  */
51296f14da52SPeter Lieven #define MAX_DISCARD_DEFAULT 32768
51306f14da52SPeter Lieven 
51314265d620SPaolo Bonzini int coroutine_fn bdrv_co_discard(BlockDriverState *bs, int64_t sector_num,
51324265d620SPaolo Bonzini                                  int nb_sectors)
51334265d620SPaolo Bonzini {
5134d51e9fe5SPaolo Bonzini     int max_discard;
5135d51e9fe5SPaolo Bonzini 
51364265d620SPaolo Bonzini     if (!bs->drv) {
51374265d620SPaolo Bonzini         return -ENOMEDIUM;
51384265d620SPaolo Bonzini     } else if (bdrv_check_request(bs, sector_num, nb_sectors)) {
51394265d620SPaolo Bonzini         return -EIO;
51404265d620SPaolo Bonzini     } else if (bs->read_only) {
51414265d620SPaolo Bonzini         return -EROFS;
5142df702c9bSPaolo Bonzini     }
5143df702c9bSPaolo Bonzini 
51448f0720ecSPaolo Bonzini     bdrv_reset_dirty(bs, sector_num, nb_sectors);
5145df702c9bSPaolo Bonzini 
51469e8f1835SPaolo Bonzini     /* Do nothing if disabled.  */
51479e8f1835SPaolo Bonzini     if (!(bs->open_flags & BDRV_O_UNMAP)) {
51489e8f1835SPaolo Bonzini         return 0;
51499e8f1835SPaolo Bonzini     }
51509e8f1835SPaolo Bonzini 
5151d51e9fe5SPaolo Bonzini     if (!bs->drv->bdrv_co_discard && !bs->drv->bdrv_aio_discard) {
5152d51e9fe5SPaolo Bonzini         return 0;
5153d51e9fe5SPaolo Bonzini     }
51546f14da52SPeter Lieven 
5155d51e9fe5SPaolo Bonzini     max_discard = bs->bl.max_discard ?  bs->bl.max_discard : MAX_DISCARD_DEFAULT;
51566f14da52SPeter Lieven     while (nb_sectors > 0) {
51576f14da52SPeter Lieven         int ret;
51586f14da52SPeter Lieven         int num = nb_sectors;
51596f14da52SPeter Lieven 
51606f14da52SPeter Lieven         /* align request */
51616f14da52SPeter Lieven         if (bs->bl.discard_alignment &&
51626f14da52SPeter Lieven             num >= bs->bl.discard_alignment &&
51636f14da52SPeter Lieven             sector_num % bs->bl.discard_alignment) {
51646f14da52SPeter Lieven             if (num > bs->bl.discard_alignment) {
51656f14da52SPeter Lieven                 num = bs->bl.discard_alignment;
51666f14da52SPeter Lieven             }
51676f14da52SPeter Lieven             num -= sector_num % bs->bl.discard_alignment;
51686f14da52SPeter Lieven         }
51696f14da52SPeter Lieven 
51706f14da52SPeter Lieven         /* limit request size */
51716f14da52SPeter Lieven         if (num > max_discard) {
51726f14da52SPeter Lieven             num = max_discard;
51736f14da52SPeter Lieven         }
51746f14da52SPeter Lieven 
5175d51e9fe5SPaolo Bonzini         if (bs->drv->bdrv_co_discard) {
51766f14da52SPeter Lieven             ret = bs->drv->bdrv_co_discard(bs, sector_num, num);
5177d51e9fe5SPaolo Bonzini         } else {
51784265d620SPaolo Bonzini             BlockDriverAIOCB *acb;
51794265d620SPaolo Bonzini             CoroutineIOCompletion co = {
51804265d620SPaolo Bonzini                 .coroutine = qemu_coroutine_self(),
51814265d620SPaolo Bonzini             };
51824265d620SPaolo Bonzini 
51834265d620SPaolo Bonzini             acb = bs->drv->bdrv_aio_discard(bs, sector_num, nb_sectors,
51844265d620SPaolo Bonzini                                             bdrv_co_io_em_complete, &co);
51854265d620SPaolo Bonzini             if (acb == NULL) {
51864265d620SPaolo Bonzini                 return -EIO;
51874265d620SPaolo Bonzini             } else {
51884265d620SPaolo Bonzini                 qemu_coroutine_yield();
5189d51e9fe5SPaolo Bonzini                 ret = co.ret;
51904265d620SPaolo Bonzini             }
5191d51e9fe5SPaolo Bonzini         }
51927ce21016SPaolo Bonzini         if (ret && ret != -ENOTSUP) {
5193d51e9fe5SPaolo Bonzini             return ret;
5194d51e9fe5SPaolo Bonzini         }
5195d51e9fe5SPaolo Bonzini 
5196d51e9fe5SPaolo Bonzini         sector_num += num;
5197d51e9fe5SPaolo Bonzini         nb_sectors -= num;
5198d51e9fe5SPaolo Bonzini     }
51994265d620SPaolo Bonzini     return 0;
52004265d620SPaolo Bonzini }
52014265d620SPaolo Bonzini 
52024265d620SPaolo Bonzini int bdrv_discard(BlockDriverState *bs, int64_t sector_num, int nb_sectors)
52034265d620SPaolo Bonzini {
52044265d620SPaolo Bonzini     Coroutine *co;
5205775aa8b6SKevin Wolf     DiscardCo rwco = {
52064265d620SPaolo Bonzini         .bs = bs,
52074265d620SPaolo Bonzini         .sector_num = sector_num,
52084265d620SPaolo Bonzini         .nb_sectors = nb_sectors,
52094265d620SPaolo Bonzini         .ret = NOT_DONE,
52104265d620SPaolo Bonzini     };
52114265d620SPaolo Bonzini 
52124265d620SPaolo Bonzini     if (qemu_in_coroutine()) {
52134265d620SPaolo Bonzini         /* Fast-path if already in coroutine context */
52144265d620SPaolo Bonzini         bdrv_discard_co_entry(&rwco);
52154265d620SPaolo Bonzini     } else {
52162572b37aSStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
52172572b37aSStefan Hajnoczi 
52184265d620SPaolo Bonzini         co = qemu_coroutine_create(bdrv_discard_co_entry);
52194265d620SPaolo Bonzini         qemu_coroutine_enter(co, &rwco);
52204265d620SPaolo Bonzini         while (rwco.ret == NOT_DONE) {
52212572b37aSStefan Hajnoczi             aio_poll(aio_context, true);
52224265d620SPaolo Bonzini         }
52234265d620SPaolo Bonzini     }
52244265d620SPaolo Bonzini 
52254265d620SPaolo Bonzini     return rwco.ret;
52264265d620SPaolo Bonzini }
52274265d620SPaolo Bonzini 
5228f9f05dc5SKevin Wolf /**************************************************************/
522919cb3738Sbellard /* removable device support */
523019cb3738Sbellard 
523119cb3738Sbellard /**
523219cb3738Sbellard  * Return TRUE if the media is present
523319cb3738Sbellard  */
523419cb3738Sbellard int bdrv_is_inserted(BlockDriverState *bs)
523519cb3738Sbellard {
523619cb3738Sbellard     BlockDriver *drv = bs->drv;
5237a1aff5bfSMarkus Armbruster 
523819cb3738Sbellard     if (!drv)
523919cb3738Sbellard         return 0;
524019cb3738Sbellard     if (!drv->bdrv_is_inserted)
5241a1aff5bfSMarkus Armbruster         return 1;
5242a1aff5bfSMarkus Armbruster     return drv->bdrv_is_inserted(bs);
524319cb3738Sbellard }
524419cb3738Sbellard 
524519cb3738Sbellard /**
52468e49ca46SMarkus Armbruster  * Return whether the media changed since the last call to this
52478e49ca46SMarkus Armbruster  * function, or -ENOTSUP if we don't know.  Most drivers don't know.
524819cb3738Sbellard  */
524919cb3738Sbellard int bdrv_media_changed(BlockDriverState *bs)
525019cb3738Sbellard {
525119cb3738Sbellard     BlockDriver *drv = bs->drv;
525219cb3738Sbellard 
52538e49ca46SMarkus Armbruster     if (drv && drv->bdrv_media_changed) {
52548e49ca46SMarkus Armbruster         return drv->bdrv_media_changed(bs);
52558e49ca46SMarkus Armbruster     }
52568e49ca46SMarkus Armbruster     return -ENOTSUP;
525719cb3738Sbellard }
525819cb3738Sbellard 
525919cb3738Sbellard /**
526019cb3738Sbellard  * If eject_flag is TRUE, eject the media. Otherwise, close the tray
526119cb3738Sbellard  */
5262f36f3949SLuiz Capitulino void bdrv_eject(BlockDriverState *bs, bool eject_flag)
526319cb3738Sbellard {
526419cb3738Sbellard     BlockDriver *drv = bs->drv;
526519cb3738Sbellard 
5266822e1cd1SMarkus Armbruster     if (drv && drv->bdrv_eject) {
5267822e1cd1SMarkus Armbruster         drv->bdrv_eject(bs, eject_flag);
526819cb3738Sbellard     }
52696f382ed2SLuiz Capitulino 
52706f382ed2SLuiz Capitulino     if (bs->device_name[0] != '\0') {
5271a5ee7bd4SWenchao Xia         qapi_event_send_device_tray_moved(bdrv_get_device_name(bs),
5272a5ee7bd4SWenchao Xia                                           eject_flag, &error_abort);
52736f382ed2SLuiz Capitulino     }
527419cb3738Sbellard }
527519cb3738Sbellard 
527619cb3738Sbellard /**
527719cb3738Sbellard  * Lock or unlock the media (if it is locked, the user won't be able
527819cb3738Sbellard  * to eject it manually).
527919cb3738Sbellard  */
5280025e849aSMarkus Armbruster void bdrv_lock_medium(BlockDriverState *bs, bool locked)
528119cb3738Sbellard {
528219cb3738Sbellard     BlockDriver *drv = bs->drv;
528319cb3738Sbellard 
5284025e849aSMarkus Armbruster     trace_bdrv_lock_medium(bs, locked);
5285b8c6d095SStefan Hajnoczi 
5286025e849aSMarkus Armbruster     if (drv && drv->bdrv_lock_medium) {
5287025e849aSMarkus Armbruster         drv->bdrv_lock_medium(bs, locked);
528819cb3738Sbellard     }
528919cb3738Sbellard }
5290985a03b0Sths 
5291985a03b0Sths /* needed for generic scsi interface */
5292985a03b0Sths 
5293985a03b0Sths int bdrv_ioctl(BlockDriverState *bs, unsigned long int req, void *buf)
5294985a03b0Sths {
5295985a03b0Sths     BlockDriver *drv = bs->drv;
5296985a03b0Sths 
5297985a03b0Sths     if (drv && drv->bdrv_ioctl)
5298985a03b0Sths         return drv->bdrv_ioctl(bs, req, buf);
5299985a03b0Sths     return -ENOTSUP;
5300985a03b0Sths }
53017d780669Saliguori 
5302221f715dSaliguori BlockDriverAIOCB *bdrv_aio_ioctl(BlockDriverState *bs,
5303221f715dSaliguori         unsigned long int req, void *buf,
53047d780669Saliguori         BlockDriverCompletionFunc *cb, void *opaque)
53057d780669Saliguori {
5306221f715dSaliguori     BlockDriver *drv = bs->drv;
53077d780669Saliguori 
5308221f715dSaliguori     if (drv && drv->bdrv_aio_ioctl)
5309221f715dSaliguori         return drv->bdrv_aio_ioctl(bs, req, buf, cb, opaque);
5310221f715dSaliguori     return NULL;
53117d780669Saliguori }
5312e268ca52Saliguori 
53131b7fd729SPaolo Bonzini void bdrv_set_guest_block_size(BlockDriverState *bs, int align)
53147b6f9300SMarkus Armbruster {
53151b7fd729SPaolo Bonzini     bs->guest_block_size = align;
53167b6f9300SMarkus Armbruster }
53177cd1e32aSlirans@il.ibm.com 
5318e268ca52Saliguori void *qemu_blockalign(BlockDriverState *bs, size_t size)
5319e268ca52Saliguori {
5320339064d5SKevin Wolf     return qemu_memalign(bdrv_opt_mem_align(bs), size);
5321e268ca52Saliguori }
53227cd1e32aSlirans@il.ibm.com 
53237d2a35ccSKevin Wolf void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
53247d2a35ccSKevin Wolf {
53257d2a35ccSKevin Wolf     size_t align = bdrv_opt_mem_align(bs);
53267d2a35ccSKevin Wolf 
53277d2a35ccSKevin Wolf     /* Ensure that NULL is never returned on success */
53287d2a35ccSKevin Wolf     assert(align > 0);
53297d2a35ccSKevin Wolf     if (size == 0) {
53307d2a35ccSKevin Wolf         size = align;
53317d2a35ccSKevin Wolf     }
53327d2a35ccSKevin Wolf 
53337d2a35ccSKevin Wolf     return qemu_try_memalign(align, size);
53347d2a35ccSKevin Wolf }
53357d2a35ccSKevin Wolf 
5336c53b1c51SStefan Hajnoczi /*
5337c53b1c51SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
5338c53b1c51SStefan Hajnoczi  */
5339c53b1c51SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
5340c53b1c51SStefan Hajnoczi {
5341c53b1c51SStefan Hajnoczi     int i;
5342339064d5SKevin Wolf     size_t alignment = bdrv_opt_mem_align(bs);
5343c53b1c51SStefan Hajnoczi 
5344c53b1c51SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
5345339064d5SKevin Wolf         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
5346c53b1c51SStefan Hajnoczi             return false;
5347c53b1c51SStefan Hajnoczi         }
5348339064d5SKevin Wolf         if (qiov->iov[i].iov_len % alignment) {
53491ff735bdSKevin Wolf             return false;
53501ff735bdSKevin Wolf         }
5351c53b1c51SStefan Hajnoczi     }
5352c53b1c51SStefan Hajnoczi 
5353c53b1c51SStefan Hajnoczi     return true;
5354c53b1c51SStefan Hajnoczi }
5355c53b1c51SStefan Hajnoczi 
5356b8afb520SFam Zheng BdrvDirtyBitmap *bdrv_create_dirty_bitmap(BlockDriverState *bs, int granularity,
5357b8afb520SFam Zheng                                           Error **errp)
53587cd1e32aSlirans@il.ibm.com {
53597cd1e32aSlirans@il.ibm.com     int64_t bitmap_size;
5360e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5361a55eb92cSJan Kiszka 
536250717e94SPaolo Bonzini     assert((granularity & (granularity - 1)) == 0);
536350717e94SPaolo Bonzini 
536450717e94SPaolo Bonzini     granularity >>= BDRV_SECTOR_BITS;
5365e4654d2dSFam Zheng     assert(granularity);
536657322b78SMarkus Armbruster     bitmap_size = bdrv_nb_sectors(bs);
5367b8afb520SFam Zheng     if (bitmap_size < 0) {
5368b8afb520SFam Zheng         error_setg_errno(errp, -bitmap_size, "could not get length of device");
5369b8afb520SFam Zheng         errno = -bitmap_size;
5370b8afb520SFam Zheng         return NULL;
5371b8afb520SFam Zheng     }
53725839e53bSMarkus Armbruster     bitmap = g_new0(BdrvDirtyBitmap, 1);
5373e4654d2dSFam Zheng     bitmap->bitmap = hbitmap_alloc(bitmap_size, ffs(granularity) - 1);
5374e4654d2dSFam Zheng     QLIST_INSERT_HEAD(&bs->dirty_bitmaps, bitmap, list);
5375e4654d2dSFam Zheng     return bitmap;
5376e4654d2dSFam Zheng }
5377e4654d2dSFam Zheng 
5378e4654d2dSFam Zheng void bdrv_release_dirty_bitmap(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5379e4654d2dSFam Zheng {
5380e4654d2dSFam Zheng     BdrvDirtyBitmap *bm, *next;
5381e4654d2dSFam Zheng     QLIST_FOREACH_SAFE(bm, &bs->dirty_bitmaps, list, next) {
5382e4654d2dSFam Zheng         if (bm == bitmap) {
5383e4654d2dSFam Zheng             QLIST_REMOVE(bitmap, list);
5384e4654d2dSFam Zheng             hbitmap_free(bitmap->bitmap);
5385e4654d2dSFam Zheng             g_free(bitmap);
5386e4654d2dSFam Zheng             return;
53877cd1e32aSlirans@il.ibm.com         }
53887cd1e32aSlirans@il.ibm.com     }
53897cd1e32aSlirans@il.ibm.com }
53907cd1e32aSlirans@il.ibm.com 
539121b56835SFam Zheng BlockDirtyInfoList *bdrv_query_dirty_bitmaps(BlockDriverState *bs)
539221b56835SFam Zheng {
539321b56835SFam Zheng     BdrvDirtyBitmap *bm;
539421b56835SFam Zheng     BlockDirtyInfoList *list = NULL;
539521b56835SFam Zheng     BlockDirtyInfoList **plist = &list;
539621b56835SFam Zheng 
539721b56835SFam Zheng     QLIST_FOREACH(bm, &bs->dirty_bitmaps, list) {
53985839e53bSMarkus Armbruster         BlockDirtyInfo *info = g_new0(BlockDirtyInfo, 1);
53995839e53bSMarkus Armbruster         BlockDirtyInfoList *entry = g_new0(BlockDirtyInfoList, 1);
540021b56835SFam Zheng         info->count = bdrv_get_dirty_count(bs, bm);
540121b56835SFam Zheng         info->granularity =
540221b56835SFam Zheng             ((int64_t) BDRV_SECTOR_SIZE << hbitmap_granularity(bm->bitmap));
540321b56835SFam Zheng         entry->value = info;
540421b56835SFam Zheng         *plist = entry;
540521b56835SFam Zheng         plist = &entry->next;
540621b56835SFam Zheng     }
540721b56835SFam Zheng 
540821b56835SFam Zheng     return list;
540921b56835SFam Zheng }
541021b56835SFam Zheng 
5411e4654d2dSFam Zheng int bdrv_get_dirty(BlockDriverState *bs, BdrvDirtyBitmap *bitmap, int64_t sector)
54127cd1e32aSlirans@il.ibm.com {
5413e4654d2dSFam Zheng     if (bitmap) {
5414e4654d2dSFam Zheng         return hbitmap_get(bitmap->bitmap, sector);
54157cd1e32aSlirans@il.ibm.com     } else {
54167cd1e32aSlirans@il.ibm.com         return 0;
54177cd1e32aSlirans@il.ibm.com     }
54187cd1e32aSlirans@il.ibm.com }
54197cd1e32aSlirans@il.ibm.com 
5420e4654d2dSFam Zheng void bdrv_dirty_iter_init(BlockDriverState *bs,
5421e4654d2dSFam Zheng                           BdrvDirtyBitmap *bitmap, HBitmapIter *hbi)
54221755da16SPaolo Bonzini {
5423e4654d2dSFam Zheng     hbitmap_iter_init(hbi, bitmap->bitmap, 0);
54241755da16SPaolo Bonzini }
54251755da16SPaolo Bonzini 
54261755da16SPaolo Bonzini void bdrv_set_dirty(BlockDriverState *bs, int64_t cur_sector,
54271755da16SPaolo Bonzini                     int nr_sectors)
54281755da16SPaolo Bonzini {
5429e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5430e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5431e4654d2dSFam Zheng         hbitmap_set(bitmap->bitmap, cur_sector, nr_sectors);
5432e4654d2dSFam Zheng     }
54331755da16SPaolo Bonzini }
54341755da16SPaolo Bonzini 
5435e4654d2dSFam Zheng void bdrv_reset_dirty(BlockDriverState *bs, int64_t cur_sector, int nr_sectors)
54367cd1e32aSlirans@il.ibm.com {
5437e4654d2dSFam Zheng     BdrvDirtyBitmap *bitmap;
5438e4654d2dSFam Zheng     QLIST_FOREACH(bitmap, &bs->dirty_bitmaps, list) {
5439e4654d2dSFam Zheng         hbitmap_reset(bitmap->bitmap, cur_sector, nr_sectors);
5440e4654d2dSFam Zheng     }
54417cd1e32aSlirans@il.ibm.com }
5442aaa0eb75SLiran Schour 
5443e4654d2dSFam Zheng int64_t bdrv_get_dirty_count(BlockDriverState *bs, BdrvDirtyBitmap *bitmap)
5444aaa0eb75SLiran Schour {
5445e4654d2dSFam Zheng     return hbitmap_count(bitmap->bitmap);
5446aaa0eb75SLiran Schour }
5447f88e1a42SJes Sorensen 
54489fcb0251SFam Zheng /* Get a reference to bs */
54499fcb0251SFam Zheng void bdrv_ref(BlockDriverState *bs)
54509fcb0251SFam Zheng {
54519fcb0251SFam Zheng     bs->refcnt++;
54529fcb0251SFam Zheng }
54539fcb0251SFam Zheng 
54549fcb0251SFam Zheng /* Release a previously grabbed reference to bs.
54559fcb0251SFam Zheng  * If after releasing, reference count is zero, the BlockDriverState is
54569fcb0251SFam Zheng  * deleted. */
54579fcb0251SFam Zheng void bdrv_unref(BlockDriverState *bs)
54589fcb0251SFam Zheng {
54599a4d5ca6SJeff Cody     if (!bs) {
54609a4d5ca6SJeff Cody         return;
54619a4d5ca6SJeff Cody     }
54629fcb0251SFam Zheng     assert(bs->refcnt > 0);
54639fcb0251SFam Zheng     if (--bs->refcnt == 0) {
54649fcb0251SFam Zheng         bdrv_delete(bs);
54659fcb0251SFam Zheng     }
54669fcb0251SFam Zheng }
54679fcb0251SFam Zheng 
5468fbe40ff7SFam Zheng struct BdrvOpBlocker {
5469fbe40ff7SFam Zheng     Error *reason;
5470fbe40ff7SFam Zheng     QLIST_ENTRY(BdrvOpBlocker) list;
5471fbe40ff7SFam Zheng };
5472fbe40ff7SFam Zheng 
5473fbe40ff7SFam Zheng bool bdrv_op_is_blocked(BlockDriverState *bs, BlockOpType op, Error **errp)
5474fbe40ff7SFam Zheng {
5475fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5476fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5477fbe40ff7SFam Zheng     if (!QLIST_EMPTY(&bs->op_blockers[op])) {
5478fbe40ff7SFam Zheng         blocker = QLIST_FIRST(&bs->op_blockers[op]);
5479fbe40ff7SFam Zheng         if (errp) {
5480fbe40ff7SFam Zheng             error_setg(errp, "Device '%s' is busy: %s",
5481fbe40ff7SFam Zheng                        bs->device_name, error_get_pretty(blocker->reason));
5482fbe40ff7SFam Zheng         }
5483fbe40ff7SFam Zheng         return true;
5484fbe40ff7SFam Zheng     }
5485fbe40ff7SFam Zheng     return false;
5486fbe40ff7SFam Zheng }
5487fbe40ff7SFam Zheng 
5488fbe40ff7SFam Zheng void bdrv_op_block(BlockDriverState *bs, BlockOpType op, Error *reason)
5489fbe40ff7SFam Zheng {
5490fbe40ff7SFam Zheng     BdrvOpBlocker *blocker;
5491fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5492fbe40ff7SFam Zheng 
54935839e53bSMarkus Armbruster     blocker = g_new0(BdrvOpBlocker, 1);
5494fbe40ff7SFam Zheng     blocker->reason = reason;
5495fbe40ff7SFam Zheng     QLIST_INSERT_HEAD(&bs->op_blockers[op], blocker, list);
5496fbe40ff7SFam Zheng }
5497fbe40ff7SFam Zheng 
5498fbe40ff7SFam Zheng void bdrv_op_unblock(BlockDriverState *bs, BlockOpType op, Error *reason)
5499fbe40ff7SFam Zheng {
5500fbe40ff7SFam Zheng     BdrvOpBlocker *blocker, *next;
5501fbe40ff7SFam Zheng     assert((int) op >= 0 && op < BLOCK_OP_TYPE_MAX);
5502fbe40ff7SFam Zheng     QLIST_FOREACH_SAFE(blocker, &bs->op_blockers[op], list, next) {
5503fbe40ff7SFam Zheng         if (blocker->reason == reason) {
5504fbe40ff7SFam Zheng             QLIST_REMOVE(blocker, list);
5505fbe40ff7SFam Zheng             g_free(blocker);
5506fbe40ff7SFam Zheng         }
5507fbe40ff7SFam Zheng     }
5508fbe40ff7SFam Zheng }
5509fbe40ff7SFam Zheng 
5510fbe40ff7SFam Zheng void bdrv_op_block_all(BlockDriverState *bs, Error *reason)
5511fbe40ff7SFam Zheng {
5512fbe40ff7SFam Zheng     int i;
5513fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5514fbe40ff7SFam Zheng         bdrv_op_block(bs, i, reason);
5515fbe40ff7SFam Zheng     }
5516fbe40ff7SFam Zheng }
5517fbe40ff7SFam Zheng 
5518fbe40ff7SFam Zheng void bdrv_op_unblock_all(BlockDriverState *bs, Error *reason)
5519fbe40ff7SFam Zheng {
5520fbe40ff7SFam Zheng     int i;
5521fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5522fbe40ff7SFam Zheng         bdrv_op_unblock(bs, i, reason);
5523fbe40ff7SFam Zheng     }
5524fbe40ff7SFam Zheng }
5525fbe40ff7SFam Zheng 
5526fbe40ff7SFam Zheng bool bdrv_op_blocker_is_empty(BlockDriverState *bs)
5527fbe40ff7SFam Zheng {
5528fbe40ff7SFam Zheng     int i;
5529fbe40ff7SFam Zheng 
5530fbe40ff7SFam Zheng     for (i = 0; i < BLOCK_OP_TYPE_MAX; i++) {
5531fbe40ff7SFam Zheng         if (!QLIST_EMPTY(&bs->op_blockers[i])) {
5532fbe40ff7SFam Zheng             return false;
5533fbe40ff7SFam Zheng         }
5534fbe40ff7SFam Zheng     }
5535fbe40ff7SFam Zheng     return true;
5536fbe40ff7SFam Zheng }
5537fbe40ff7SFam Zheng 
553828a7282aSLuiz Capitulino void bdrv_iostatus_enable(BlockDriverState *bs)
553928a7282aSLuiz Capitulino {
5540d6bf279eSLuiz Capitulino     bs->iostatus_enabled = true;
554158e21ef5SLuiz Capitulino     bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
554228a7282aSLuiz Capitulino }
554328a7282aSLuiz Capitulino 
554428a7282aSLuiz Capitulino /* The I/O status is only enabled if the drive explicitly
554528a7282aSLuiz Capitulino  * enables it _and_ the VM is configured to stop on errors */
554628a7282aSLuiz Capitulino bool bdrv_iostatus_is_enabled(const BlockDriverState *bs)
554728a7282aSLuiz Capitulino {
5548d6bf279eSLuiz Capitulino     return (bs->iostatus_enabled &&
554992aa5c6dSPaolo Bonzini            (bs->on_write_error == BLOCKDEV_ON_ERROR_ENOSPC ||
555092aa5c6dSPaolo Bonzini             bs->on_write_error == BLOCKDEV_ON_ERROR_STOP   ||
555192aa5c6dSPaolo Bonzini             bs->on_read_error == BLOCKDEV_ON_ERROR_STOP));
555228a7282aSLuiz Capitulino }
555328a7282aSLuiz Capitulino 
555428a7282aSLuiz Capitulino void bdrv_iostatus_disable(BlockDriverState *bs)
555528a7282aSLuiz Capitulino {
5556d6bf279eSLuiz Capitulino     bs->iostatus_enabled = false;
555728a7282aSLuiz Capitulino }
555828a7282aSLuiz Capitulino 
555928a7282aSLuiz Capitulino void bdrv_iostatus_reset(BlockDriverState *bs)
556028a7282aSLuiz Capitulino {
556128a7282aSLuiz Capitulino     if (bdrv_iostatus_is_enabled(bs)) {
556258e21ef5SLuiz Capitulino         bs->iostatus = BLOCK_DEVICE_IO_STATUS_OK;
55633bd293c3SPaolo Bonzini         if (bs->job) {
55643bd293c3SPaolo Bonzini             block_job_iostatus_reset(bs->job);
55653bd293c3SPaolo Bonzini         }
556628a7282aSLuiz Capitulino     }
556728a7282aSLuiz Capitulino }
556828a7282aSLuiz Capitulino 
556928a7282aSLuiz Capitulino void bdrv_iostatus_set_err(BlockDriverState *bs, int error)
557028a7282aSLuiz Capitulino {
55713e1caa5fSPaolo Bonzini     assert(bdrv_iostatus_is_enabled(bs));
55723e1caa5fSPaolo Bonzini     if (bs->iostatus == BLOCK_DEVICE_IO_STATUS_OK) {
557358e21ef5SLuiz Capitulino         bs->iostatus = error == ENOSPC ? BLOCK_DEVICE_IO_STATUS_NOSPACE :
557458e21ef5SLuiz Capitulino                                          BLOCK_DEVICE_IO_STATUS_FAILED;
557528a7282aSLuiz Capitulino     }
557628a7282aSLuiz Capitulino }
557728a7282aSLuiz Capitulino 
5578d92ada22SLuiz Capitulino void bdrv_img_create(const char *filename, const char *fmt,
5579f88e1a42SJes Sorensen                      const char *base_filename, const char *base_fmt,
5580f382d43aSMiroslav Rezanina                      char *options, uint64_t img_size, int flags,
5581f382d43aSMiroslav Rezanina                      Error **errp, bool quiet)
5582f88e1a42SJes Sorensen {
558383d0521aSChunyan Liu     QemuOptsList *create_opts = NULL;
558483d0521aSChunyan Liu     QemuOpts *opts = NULL;
558583d0521aSChunyan Liu     const char *backing_fmt, *backing_file;
558683d0521aSChunyan Liu     int64_t size;
5587f88e1a42SJes Sorensen     BlockDriver *drv, *proto_drv;
558896df67d1SStefan Hajnoczi     BlockDriver *backing_drv = NULL;
5589cc84d90fSMax Reitz     Error *local_err = NULL;
5590f88e1a42SJes Sorensen     int ret = 0;
5591f88e1a42SJes Sorensen 
5592f88e1a42SJes Sorensen     /* Find driver and parse its options */
5593f88e1a42SJes Sorensen     drv = bdrv_find_format(fmt);
5594f88e1a42SJes Sorensen     if (!drv) {
559571c79813SLuiz Capitulino         error_setg(errp, "Unknown file format '%s'", fmt);
5596d92ada22SLuiz Capitulino         return;
5597f88e1a42SJes Sorensen     }
5598f88e1a42SJes Sorensen 
559998289620SKevin Wolf     proto_drv = bdrv_find_protocol(filename, true);
5600f88e1a42SJes Sorensen     if (!proto_drv) {
560171c79813SLuiz Capitulino         error_setg(errp, "Unknown protocol '%s'", filename);
5602d92ada22SLuiz Capitulino         return;
5603f88e1a42SJes Sorensen     }
5604f88e1a42SJes Sorensen 
5605c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, drv->create_opts);
5606c282e1fdSChunyan Liu     create_opts = qemu_opts_append(create_opts, proto_drv->create_opts);
5607f88e1a42SJes Sorensen 
5608f88e1a42SJes Sorensen     /* Create parameter list with default values */
560983d0521aSChunyan Liu     opts = qemu_opts_create(create_opts, NULL, 0, &error_abort);
561083d0521aSChunyan Liu     qemu_opt_set_number(opts, BLOCK_OPT_SIZE, img_size);
5611f88e1a42SJes Sorensen 
5612f88e1a42SJes Sorensen     /* Parse -o options */
5613f88e1a42SJes Sorensen     if (options) {
561483d0521aSChunyan Liu         if (qemu_opts_do_parse(opts, options, NULL) != 0) {
561583d0521aSChunyan Liu             error_setg(errp, "Invalid options for file format '%s'", fmt);
5616f88e1a42SJes Sorensen             goto out;
5617f88e1a42SJes Sorensen         }
5618f88e1a42SJes Sorensen     }
5619f88e1a42SJes Sorensen 
5620f88e1a42SJes Sorensen     if (base_filename) {
562183d0521aSChunyan Liu         if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FILE, base_filename)) {
562271c79813SLuiz Capitulino             error_setg(errp, "Backing file not supported for file format '%s'",
562371c79813SLuiz Capitulino                        fmt);
5624f88e1a42SJes Sorensen             goto out;
5625f88e1a42SJes Sorensen         }
5626f88e1a42SJes Sorensen     }
5627f88e1a42SJes Sorensen 
5628f88e1a42SJes Sorensen     if (base_fmt) {
562983d0521aSChunyan Liu         if (qemu_opt_set(opts, BLOCK_OPT_BACKING_FMT, base_fmt)) {
563071c79813SLuiz Capitulino             error_setg(errp, "Backing file format not supported for file "
563171c79813SLuiz Capitulino                              "format '%s'", fmt);
5632f88e1a42SJes Sorensen             goto out;
5633f88e1a42SJes Sorensen         }
5634f88e1a42SJes Sorensen     }
5635f88e1a42SJes Sorensen 
563683d0521aSChunyan Liu     backing_file = qemu_opt_get(opts, BLOCK_OPT_BACKING_FILE);
563783d0521aSChunyan Liu     if (backing_file) {
563883d0521aSChunyan Liu         if (!strcmp(filename, backing_file)) {
563971c79813SLuiz Capitulino             error_setg(errp, "Error: Trying to create an image with the "
564071c79813SLuiz Capitulino                              "same filename as the backing file");
5641792da93aSJes Sorensen             goto out;
5642792da93aSJes Sorensen         }
5643792da93aSJes Sorensen     }
5644792da93aSJes Sorensen 
564583d0521aSChunyan Liu     backing_fmt = qemu_opt_get(opts, BLOCK_OPT_BACKING_FMT);
564683d0521aSChunyan Liu     if (backing_fmt) {
564783d0521aSChunyan Liu         backing_drv = bdrv_find_format(backing_fmt);
564896df67d1SStefan Hajnoczi         if (!backing_drv) {
564971c79813SLuiz Capitulino             error_setg(errp, "Unknown backing file format '%s'",
565083d0521aSChunyan Liu                        backing_fmt);
5651f88e1a42SJes Sorensen             goto out;
5652f88e1a42SJes Sorensen         }
5653f88e1a42SJes Sorensen     }
5654f88e1a42SJes Sorensen 
5655f88e1a42SJes Sorensen     // The size for the image must always be specified, with one exception:
5656f88e1a42SJes Sorensen     // If we are using a backing file, we can obtain the size from there
565783d0521aSChunyan Liu     size = qemu_opt_get_size(opts, BLOCK_OPT_SIZE, 0);
565883d0521aSChunyan Liu     if (size == -1) {
565983d0521aSChunyan Liu         if (backing_file) {
566066f6b814SMax Reitz             BlockDriverState *bs;
566152bf1e72SMarkus Armbruster             int64_t size;
566263090dacSPaolo Bonzini             int back_flags;
566363090dacSPaolo Bonzini 
566463090dacSPaolo Bonzini             /* backing files always opened read-only */
566563090dacSPaolo Bonzini             back_flags =
566663090dacSPaolo Bonzini                 flags & ~(BDRV_O_RDWR | BDRV_O_SNAPSHOT | BDRV_O_NO_BACKING);
5667f88e1a42SJes Sorensen 
5668f67503e5SMax Reitz             bs = NULL;
566983d0521aSChunyan Liu             ret = bdrv_open(&bs, backing_file, NULL, NULL, back_flags,
5670cc84d90fSMax Reitz                             backing_drv, &local_err);
5671f88e1a42SJes Sorensen             if (ret < 0) {
5672cc84d90fSMax Reitz                 error_setg_errno(errp, -ret, "Could not open '%s': %s",
567383d0521aSChunyan Liu                                  backing_file,
5674cc84d90fSMax Reitz                                  error_get_pretty(local_err));
5675cc84d90fSMax Reitz                 error_free(local_err);
5676cc84d90fSMax Reitz                 local_err = NULL;
5677f88e1a42SJes Sorensen                 goto out;
5678f88e1a42SJes Sorensen             }
567952bf1e72SMarkus Armbruster             size = bdrv_getlength(bs);
568052bf1e72SMarkus Armbruster             if (size < 0) {
568152bf1e72SMarkus Armbruster                 error_setg_errno(errp, -size, "Could not get size of '%s'",
568252bf1e72SMarkus Armbruster                                  backing_file);
568352bf1e72SMarkus Armbruster                 bdrv_unref(bs);
568452bf1e72SMarkus Armbruster                 goto out;
568552bf1e72SMarkus Armbruster             }
5686f88e1a42SJes Sorensen 
568783d0521aSChunyan Liu             qemu_opt_set_number(opts, BLOCK_OPT_SIZE, size);
568866f6b814SMax Reitz 
568966f6b814SMax Reitz             bdrv_unref(bs);
5690f88e1a42SJes Sorensen         } else {
569171c79813SLuiz Capitulino             error_setg(errp, "Image creation needs a size parameter");
5692f88e1a42SJes Sorensen             goto out;
5693f88e1a42SJes Sorensen         }
5694f88e1a42SJes Sorensen     }
5695f88e1a42SJes Sorensen 
5696f382d43aSMiroslav Rezanina     if (!quiet) {
5697f88e1a42SJes Sorensen         printf("Formatting '%s', fmt=%s ", filename, fmt);
569883d0521aSChunyan Liu         qemu_opts_print(opts);
5699f88e1a42SJes Sorensen         puts("");
5700f382d43aSMiroslav Rezanina     }
570183d0521aSChunyan Liu 
5702c282e1fdSChunyan Liu     ret = bdrv_create(drv, filename, opts, &local_err);
570383d0521aSChunyan Liu 
5704cc84d90fSMax Reitz     if (ret == -EFBIG) {
5705cc84d90fSMax Reitz         /* This is generally a better message than whatever the driver would
5706cc84d90fSMax Reitz          * deliver (especially because of the cluster_size_hint), since that
5707cc84d90fSMax Reitz          * is most probably not much different from "image too large". */
5708f3f4d2c0SKevin Wolf         const char *cluster_size_hint = "";
570983d0521aSChunyan Liu         if (qemu_opt_get_size(opts, BLOCK_OPT_CLUSTER_SIZE, 0)) {
5710f3f4d2c0SKevin Wolf             cluster_size_hint = " (try using a larger cluster size)";
5711f3f4d2c0SKevin Wolf         }
5712cc84d90fSMax Reitz         error_setg(errp, "The image size is too large for file format '%s'"
5713cc84d90fSMax Reitz                    "%s", fmt, cluster_size_hint);
5714cc84d90fSMax Reitz         error_free(local_err);
5715cc84d90fSMax Reitz         local_err = NULL;
5716f88e1a42SJes Sorensen     }
5717f88e1a42SJes Sorensen 
5718f88e1a42SJes Sorensen out:
571983d0521aSChunyan Liu     qemu_opts_del(opts);
572083d0521aSChunyan Liu     qemu_opts_free(create_opts);
572184d18f06SMarkus Armbruster     if (local_err) {
5722cc84d90fSMax Reitz         error_propagate(errp, local_err);
5723cc84d90fSMax Reitz     }
5724f88e1a42SJes Sorensen }
572585d126f3SStefan Hajnoczi 
572685d126f3SStefan Hajnoczi AioContext *bdrv_get_aio_context(BlockDriverState *bs)
572785d126f3SStefan Hajnoczi {
5728dcd04228SStefan Hajnoczi     return bs->aio_context;
5729dcd04228SStefan Hajnoczi }
5730dcd04228SStefan Hajnoczi 
5731dcd04228SStefan Hajnoczi void bdrv_detach_aio_context(BlockDriverState *bs)
5732dcd04228SStefan Hajnoczi {
573333384421SMax Reitz     BdrvAioNotifier *baf;
573433384421SMax Reitz 
5735dcd04228SStefan Hajnoczi     if (!bs->drv) {
5736dcd04228SStefan Hajnoczi         return;
5737dcd04228SStefan Hajnoczi     }
5738dcd04228SStefan Hajnoczi 
573933384421SMax Reitz     QLIST_FOREACH(baf, &bs->aio_notifiers, list) {
574033384421SMax Reitz         baf->detach_aio_context(baf->opaque);
574133384421SMax Reitz     }
574233384421SMax Reitz 
574313af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
574413af91ebSStefan Hajnoczi         throttle_detach_aio_context(&bs->throttle_state);
574513af91ebSStefan Hajnoczi     }
5746dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_detach_aio_context) {
5747dcd04228SStefan Hajnoczi         bs->drv->bdrv_detach_aio_context(bs);
5748dcd04228SStefan Hajnoczi     }
5749dcd04228SStefan Hajnoczi     if (bs->file) {
5750dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->file);
5751dcd04228SStefan Hajnoczi     }
5752dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
5753dcd04228SStefan Hajnoczi         bdrv_detach_aio_context(bs->backing_hd);
5754dcd04228SStefan Hajnoczi     }
5755dcd04228SStefan Hajnoczi 
5756dcd04228SStefan Hajnoczi     bs->aio_context = NULL;
5757dcd04228SStefan Hajnoczi }
5758dcd04228SStefan Hajnoczi 
5759dcd04228SStefan Hajnoczi void bdrv_attach_aio_context(BlockDriverState *bs,
5760dcd04228SStefan Hajnoczi                              AioContext *new_context)
5761dcd04228SStefan Hajnoczi {
576233384421SMax Reitz     BdrvAioNotifier *ban;
576333384421SMax Reitz 
5764dcd04228SStefan Hajnoczi     if (!bs->drv) {
5765dcd04228SStefan Hajnoczi         return;
5766dcd04228SStefan Hajnoczi     }
5767dcd04228SStefan Hajnoczi 
5768dcd04228SStefan Hajnoczi     bs->aio_context = new_context;
5769dcd04228SStefan Hajnoczi 
5770dcd04228SStefan Hajnoczi     if (bs->backing_hd) {
5771dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->backing_hd, new_context);
5772dcd04228SStefan Hajnoczi     }
5773dcd04228SStefan Hajnoczi     if (bs->file) {
5774dcd04228SStefan Hajnoczi         bdrv_attach_aio_context(bs->file, new_context);
5775dcd04228SStefan Hajnoczi     }
5776dcd04228SStefan Hajnoczi     if (bs->drv->bdrv_attach_aio_context) {
5777dcd04228SStefan Hajnoczi         bs->drv->bdrv_attach_aio_context(bs, new_context);
5778dcd04228SStefan Hajnoczi     }
577913af91ebSStefan Hajnoczi     if (bs->io_limits_enabled) {
578013af91ebSStefan Hajnoczi         throttle_attach_aio_context(&bs->throttle_state, new_context);
578113af91ebSStefan Hajnoczi     }
578233384421SMax Reitz 
578333384421SMax Reitz     QLIST_FOREACH(ban, &bs->aio_notifiers, list) {
578433384421SMax Reitz         ban->attached_aio_context(new_context, ban->opaque);
578533384421SMax Reitz     }
5786dcd04228SStefan Hajnoczi }
5787dcd04228SStefan Hajnoczi 
5788dcd04228SStefan Hajnoczi void bdrv_set_aio_context(BlockDriverState *bs, AioContext *new_context)
5789dcd04228SStefan Hajnoczi {
5790dcd04228SStefan Hajnoczi     bdrv_drain_all(); /* ensure there are no in-flight requests */
5791dcd04228SStefan Hajnoczi 
5792dcd04228SStefan Hajnoczi     bdrv_detach_aio_context(bs);
5793dcd04228SStefan Hajnoczi 
5794dcd04228SStefan Hajnoczi     /* This function executes in the old AioContext so acquire the new one in
5795dcd04228SStefan Hajnoczi      * case it runs in a different thread.
5796dcd04228SStefan Hajnoczi      */
5797dcd04228SStefan Hajnoczi     aio_context_acquire(new_context);
5798dcd04228SStefan Hajnoczi     bdrv_attach_aio_context(bs, new_context);
5799dcd04228SStefan Hajnoczi     aio_context_release(new_context);
580085d126f3SStefan Hajnoczi }
5801d616b224SStefan Hajnoczi 
580233384421SMax Reitz void bdrv_add_aio_context_notifier(BlockDriverState *bs,
580333384421SMax Reitz         void (*attached_aio_context)(AioContext *new_context, void *opaque),
580433384421SMax Reitz         void (*detach_aio_context)(void *opaque), void *opaque)
580533384421SMax Reitz {
580633384421SMax Reitz     BdrvAioNotifier *ban = g_new(BdrvAioNotifier, 1);
580733384421SMax Reitz     *ban = (BdrvAioNotifier){
580833384421SMax Reitz         .attached_aio_context = attached_aio_context,
580933384421SMax Reitz         .detach_aio_context   = detach_aio_context,
581033384421SMax Reitz         .opaque               = opaque
581133384421SMax Reitz     };
581233384421SMax Reitz 
581333384421SMax Reitz     QLIST_INSERT_HEAD(&bs->aio_notifiers, ban, list);
581433384421SMax Reitz }
581533384421SMax Reitz 
581633384421SMax Reitz void bdrv_remove_aio_context_notifier(BlockDriverState *bs,
581733384421SMax Reitz                                       void (*attached_aio_context)(AioContext *,
581833384421SMax Reitz                                                                    void *),
581933384421SMax Reitz                                       void (*detach_aio_context)(void *),
582033384421SMax Reitz                                       void *opaque)
582133384421SMax Reitz {
582233384421SMax Reitz     BdrvAioNotifier *ban, *ban_next;
582333384421SMax Reitz 
582433384421SMax Reitz     QLIST_FOREACH_SAFE(ban, &bs->aio_notifiers, list, ban_next) {
582533384421SMax Reitz         if (ban->attached_aio_context == attached_aio_context &&
582633384421SMax Reitz             ban->detach_aio_context   == detach_aio_context   &&
582733384421SMax Reitz             ban->opaque               == opaque)
582833384421SMax Reitz         {
582933384421SMax Reitz             QLIST_REMOVE(ban, list);
583033384421SMax Reitz             g_free(ban);
583133384421SMax Reitz 
583233384421SMax Reitz             return;
583333384421SMax Reitz         }
583433384421SMax Reitz     }
583533384421SMax Reitz 
583633384421SMax Reitz     abort();
583733384421SMax Reitz }
583833384421SMax Reitz 
5839d616b224SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
5840d616b224SStefan Hajnoczi                                     NotifierWithReturn *notifier)
5841d616b224SStefan Hajnoczi {
5842d616b224SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
5843d616b224SStefan Hajnoczi }
58446f176b48SMax Reitz 
5845c282e1fdSChunyan Liu int bdrv_amend_options(BlockDriverState *bs, QemuOpts *opts)
58466f176b48SMax Reitz {
5847c282e1fdSChunyan Liu     if (!bs->drv->bdrv_amend_options) {
58486f176b48SMax Reitz         return -ENOTSUP;
58496f176b48SMax Reitz     }
5850c282e1fdSChunyan Liu     return bs->drv->bdrv_amend_options(bs, opts);
58516f176b48SMax Reitz }
5852f6186f49SBenoît Canet 
5853b5042a36SBenoît Canet /* This function will be called by the bdrv_recurse_is_first_non_filter method
5854b5042a36SBenoît Canet  * of block filter and by bdrv_is_first_non_filter.
5855b5042a36SBenoît Canet  * It is used to test if the given bs is the candidate or recurse more in the
5856b5042a36SBenoît Canet  * node graph.
5857212a5a8fSBenoît Canet  */
5858212a5a8fSBenoît Canet bool bdrv_recurse_is_first_non_filter(BlockDriverState *bs,
5859212a5a8fSBenoît Canet                                       BlockDriverState *candidate)
5860f6186f49SBenoît Canet {
5861b5042a36SBenoît Canet     /* return false if basic checks fails */
5862b5042a36SBenoît Canet     if (!bs || !bs->drv) {
5863b5042a36SBenoît Canet         return false;
5864b5042a36SBenoît Canet     }
5865b5042a36SBenoît Canet 
5866b5042a36SBenoît Canet     /* the code reached a non block filter driver -> check if the bs is
5867b5042a36SBenoît Canet      * the same as the candidate. It's the recursion termination condition.
5868b5042a36SBenoît Canet      */
5869b5042a36SBenoît Canet     if (!bs->drv->is_filter) {
5870b5042a36SBenoît Canet         return bs == candidate;
5871b5042a36SBenoît Canet     }
5872b5042a36SBenoît Canet     /* Down this path the driver is a block filter driver */
5873b5042a36SBenoît Canet 
5874b5042a36SBenoît Canet     /* If the block filter recursion method is defined use it to recurse down
5875b5042a36SBenoît Canet      * the node graph.
5876b5042a36SBenoît Canet      */
5877b5042a36SBenoît Canet     if (bs->drv->bdrv_recurse_is_first_non_filter) {
5878212a5a8fSBenoît Canet         return bs->drv->bdrv_recurse_is_first_non_filter(bs, candidate);
5879212a5a8fSBenoît Canet     }
5880212a5a8fSBenoît Canet 
5881b5042a36SBenoît Canet     /* the driver is a block filter but don't allow to recurse -> return false
5882b5042a36SBenoît Canet      */
5883b5042a36SBenoît Canet     return false;
5884212a5a8fSBenoît Canet }
5885212a5a8fSBenoît Canet 
5886212a5a8fSBenoît Canet /* This function checks if the candidate is the first non filter bs down it's
5887212a5a8fSBenoît Canet  * bs chain. Since we don't have pointers to parents it explore all bs chains
5888212a5a8fSBenoît Canet  * from the top. Some filters can choose not to pass down the recursion.
5889212a5a8fSBenoît Canet  */
5890212a5a8fSBenoît Canet bool bdrv_is_first_non_filter(BlockDriverState *candidate)
5891212a5a8fSBenoît Canet {
5892212a5a8fSBenoît Canet     BlockDriverState *bs;
5893212a5a8fSBenoît Canet 
5894212a5a8fSBenoît Canet     /* walk down the bs forest recursively */
5895212a5a8fSBenoît Canet     QTAILQ_FOREACH(bs, &bdrv_states, device_list) {
5896212a5a8fSBenoît Canet         bool perm;
5897212a5a8fSBenoît Canet 
5898b5042a36SBenoît Canet         /* try to recurse in this top level bs */
5899e6dc8a1fSKevin Wolf         perm = bdrv_recurse_is_first_non_filter(bs, candidate);
5900212a5a8fSBenoît Canet 
5901212a5a8fSBenoît Canet         /* candidate is the first non filter */
5902212a5a8fSBenoît Canet         if (perm) {
5903212a5a8fSBenoît Canet             return true;
5904212a5a8fSBenoît Canet         }
5905212a5a8fSBenoît Canet     }
5906212a5a8fSBenoît Canet 
5907212a5a8fSBenoît Canet     return false;
5908f6186f49SBenoît Canet }
590909158f00SBenoît Canet 
591009158f00SBenoît Canet BlockDriverState *check_to_replace_node(const char *node_name, Error **errp)
591109158f00SBenoît Canet {
591209158f00SBenoît Canet     BlockDriverState *to_replace_bs = bdrv_find_node(node_name);
591309158f00SBenoît Canet     if (!to_replace_bs) {
591409158f00SBenoît Canet         error_setg(errp, "Node name '%s' not found", node_name);
591509158f00SBenoît Canet         return NULL;
591609158f00SBenoît Canet     }
591709158f00SBenoît Canet 
591809158f00SBenoît Canet     if (bdrv_op_is_blocked(to_replace_bs, BLOCK_OP_TYPE_REPLACE, errp)) {
591909158f00SBenoît Canet         return NULL;
592009158f00SBenoît Canet     }
592109158f00SBenoît Canet 
592209158f00SBenoît Canet     /* We don't want arbitrary node of the BDS chain to be replaced only the top
592309158f00SBenoît Canet      * most non filter in order to prevent data corruption.
592409158f00SBenoît Canet      * Another benefit is that this tests exclude backing files which are
592509158f00SBenoît Canet      * blocked by the backing blockers.
592609158f00SBenoît Canet      */
592709158f00SBenoît Canet     if (!bdrv_is_first_non_filter(to_replace_bs)) {
592809158f00SBenoît Canet         error_setg(errp, "Only top most non filter can be replaced");
592909158f00SBenoît Canet         return NULL;
593009158f00SBenoît Canet     }
593109158f00SBenoît Canet 
593209158f00SBenoît Canet     return to_replace_bs;
593309158f00SBenoît Canet }
5934448ad91dSMing Lei 
5935448ad91dSMing Lei void bdrv_io_plug(BlockDriverState *bs)
5936448ad91dSMing Lei {
5937448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5938448ad91dSMing Lei     if (drv && drv->bdrv_io_plug) {
5939448ad91dSMing Lei         drv->bdrv_io_plug(bs);
5940448ad91dSMing Lei     } else if (bs->file) {
5941448ad91dSMing Lei         bdrv_io_plug(bs->file);
5942448ad91dSMing Lei     }
5943448ad91dSMing Lei }
5944448ad91dSMing Lei 
5945448ad91dSMing Lei void bdrv_io_unplug(BlockDriverState *bs)
5946448ad91dSMing Lei {
5947448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5948448ad91dSMing Lei     if (drv && drv->bdrv_io_unplug) {
5949448ad91dSMing Lei         drv->bdrv_io_unplug(bs);
5950448ad91dSMing Lei     } else if (bs->file) {
5951448ad91dSMing Lei         bdrv_io_unplug(bs->file);
5952448ad91dSMing Lei     }
5953448ad91dSMing Lei }
5954448ad91dSMing Lei 
5955448ad91dSMing Lei void bdrv_flush_io_queue(BlockDriverState *bs)
5956448ad91dSMing Lei {
5957448ad91dSMing Lei     BlockDriver *drv = bs->drv;
5958448ad91dSMing Lei     if (drv && drv->bdrv_flush_io_queue) {
5959448ad91dSMing Lei         drv->bdrv_flush_io_queue(bs);
5960448ad91dSMing Lei     } else if (bs->file) {
5961448ad91dSMing Lei         bdrv_flush_io_queue(bs->file);
5962448ad91dSMing Lei     }
5963448ad91dSMing Lei }
596491af7014SMax Reitz 
596591af7014SMax Reitz static bool append_open_options(QDict *d, BlockDriverState *bs)
596691af7014SMax Reitz {
596791af7014SMax Reitz     const QDictEntry *entry;
596891af7014SMax Reitz     bool found_any = false;
596991af7014SMax Reitz 
597091af7014SMax Reitz     for (entry = qdict_first(bs->options); entry;
597191af7014SMax Reitz          entry = qdict_next(bs->options, entry))
597291af7014SMax Reitz     {
597391af7014SMax Reitz         /* Only take options for this level and exclude all non-driver-specific
597491af7014SMax Reitz          * options */
597591af7014SMax Reitz         if (!strchr(qdict_entry_key(entry), '.') &&
597691af7014SMax Reitz             strcmp(qdict_entry_key(entry), "node-name"))
597791af7014SMax Reitz         {
597891af7014SMax Reitz             qobject_incref(qdict_entry_value(entry));
597991af7014SMax Reitz             qdict_put_obj(d, qdict_entry_key(entry), qdict_entry_value(entry));
598091af7014SMax Reitz             found_any = true;
598191af7014SMax Reitz         }
598291af7014SMax Reitz     }
598391af7014SMax Reitz 
598491af7014SMax Reitz     return found_any;
598591af7014SMax Reitz }
598691af7014SMax Reitz 
598791af7014SMax Reitz /* Updates the following BDS fields:
598891af7014SMax Reitz  *  - exact_filename: A filename which may be used for opening a block device
598991af7014SMax Reitz  *                    which (mostly) equals the given BDS (even without any
599091af7014SMax Reitz  *                    other options; so reading and writing must return the same
599191af7014SMax Reitz  *                    results, but caching etc. may be different)
599291af7014SMax Reitz  *  - full_open_options: Options which, when given when opening a block device
599391af7014SMax Reitz  *                       (without a filename), result in a BDS (mostly)
599491af7014SMax Reitz  *                       equalling the given one
599591af7014SMax Reitz  *  - filename: If exact_filename is set, it is copied here. Otherwise,
599691af7014SMax Reitz  *              full_open_options is converted to a JSON object, prefixed with
599791af7014SMax Reitz  *              "json:" (for use through the JSON pseudo protocol) and put here.
599891af7014SMax Reitz  */
599991af7014SMax Reitz void bdrv_refresh_filename(BlockDriverState *bs)
600091af7014SMax Reitz {
600191af7014SMax Reitz     BlockDriver *drv = bs->drv;
600291af7014SMax Reitz     QDict *opts;
600391af7014SMax Reitz 
600491af7014SMax Reitz     if (!drv) {
600591af7014SMax Reitz         return;
600691af7014SMax Reitz     }
600791af7014SMax Reitz 
600891af7014SMax Reitz     /* This BDS's file name will most probably depend on its file's name, so
600991af7014SMax Reitz      * refresh that first */
601091af7014SMax Reitz     if (bs->file) {
601191af7014SMax Reitz         bdrv_refresh_filename(bs->file);
601291af7014SMax Reitz     }
601391af7014SMax Reitz 
601491af7014SMax Reitz     if (drv->bdrv_refresh_filename) {
601591af7014SMax Reitz         /* Obsolete information is of no use here, so drop the old file name
601691af7014SMax Reitz          * information before refreshing it */
601791af7014SMax Reitz         bs->exact_filename[0] = '\0';
601891af7014SMax Reitz         if (bs->full_open_options) {
601991af7014SMax Reitz             QDECREF(bs->full_open_options);
602091af7014SMax Reitz             bs->full_open_options = NULL;
602191af7014SMax Reitz         }
602291af7014SMax Reitz 
602391af7014SMax Reitz         drv->bdrv_refresh_filename(bs);
602491af7014SMax Reitz     } else if (bs->file) {
602591af7014SMax Reitz         /* Try to reconstruct valid information from the underlying file */
602691af7014SMax Reitz         bool has_open_options;
602791af7014SMax Reitz 
602891af7014SMax Reitz         bs->exact_filename[0] = '\0';
602991af7014SMax Reitz         if (bs->full_open_options) {
603091af7014SMax Reitz             QDECREF(bs->full_open_options);
603191af7014SMax Reitz             bs->full_open_options = NULL;
603291af7014SMax Reitz         }
603391af7014SMax Reitz 
603491af7014SMax Reitz         opts = qdict_new();
603591af7014SMax Reitz         has_open_options = append_open_options(opts, bs);
603691af7014SMax Reitz 
603791af7014SMax Reitz         /* If no specific options have been given for this BDS, the filename of
603891af7014SMax Reitz          * the underlying file should suffice for this one as well */
603991af7014SMax Reitz         if (bs->file->exact_filename[0] && !has_open_options) {
604091af7014SMax Reitz             strcpy(bs->exact_filename, bs->file->exact_filename);
604191af7014SMax Reitz         }
604291af7014SMax Reitz         /* Reconstructing the full options QDict is simple for most format block
604391af7014SMax Reitz          * drivers, as long as the full options are known for the underlying
604491af7014SMax Reitz          * file BDS. The full options QDict of that file BDS should somehow
604591af7014SMax Reitz          * contain a representation of the filename, therefore the following
604691af7014SMax Reitz          * suffices without querying the (exact_)filename of this BDS. */
604791af7014SMax Reitz         if (bs->file->full_open_options) {
604891af7014SMax Reitz             qdict_put_obj(opts, "driver",
604991af7014SMax Reitz                           QOBJECT(qstring_from_str(drv->format_name)));
605091af7014SMax Reitz             QINCREF(bs->file->full_open_options);
605191af7014SMax Reitz             qdict_put_obj(opts, "file", QOBJECT(bs->file->full_open_options));
605291af7014SMax Reitz 
605391af7014SMax Reitz             bs->full_open_options = opts;
605491af7014SMax Reitz         } else {
605591af7014SMax Reitz             QDECREF(opts);
605691af7014SMax Reitz         }
605791af7014SMax Reitz     } else if (!bs->full_open_options && qdict_size(bs->options)) {
605891af7014SMax Reitz         /* There is no underlying file BDS (at least referenced by BDS.file),
605991af7014SMax Reitz          * so the full options QDict should be equal to the options given
606091af7014SMax Reitz          * specifically for this block device when it was opened (plus the
606191af7014SMax Reitz          * driver specification).
606291af7014SMax Reitz          * Because those options don't change, there is no need to update
606391af7014SMax Reitz          * full_open_options when it's already set. */
606491af7014SMax Reitz 
606591af7014SMax Reitz         opts = qdict_new();
606691af7014SMax Reitz         append_open_options(opts, bs);
606791af7014SMax Reitz         qdict_put_obj(opts, "driver",
606891af7014SMax Reitz                       QOBJECT(qstring_from_str(drv->format_name)));
606991af7014SMax Reitz 
607091af7014SMax Reitz         if (bs->exact_filename[0]) {
607191af7014SMax Reitz             /* This may not work for all block protocol drivers (some may
607291af7014SMax Reitz              * require this filename to be parsed), but we have to find some
607391af7014SMax Reitz              * default solution here, so just include it. If some block driver
607491af7014SMax Reitz              * does not support pure options without any filename at all or
607591af7014SMax Reitz              * needs some special format of the options QDict, it needs to
607691af7014SMax Reitz              * implement the driver-specific bdrv_refresh_filename() function.
607791af7014SMax Reitz              */
607891af7014SMax Reitz             qdict_put_obj(opts, "filename",
607991af7014SMax Reitz                           QOBJECT(qstring_from_str(bs->exact_filename)));
608091af7014SMax Reitz         }
608191af7014SMax Reitz 
608291af7014SMax Reitz         bs->full_open_options = opts;
608391af7014SMax Reitz     }
608491af7014SMax Reitz 
608591af7014SMax Reitz     if (bs->exact_filename[0]) {
608691af7014SMax Reitz         pstrcpy(bs->filename, sizeof(bs->filename), bs->exact_filename);
608791af7014SMax Reitz     } else if (bs->full_open_options) {
608891af7014SMax Reitz         QString *json = qobject_to_json(QOBJECT(bs->full_open_options));
608991af7014SMax Reitz         snprintf(bs->filename, sizeof(bs->filename), "json:%s",
609091af7014SMax Reitz                  qstring_get_str(json));
609191af7014SMax Reitz         QDECREF(json);
609291af7014SMax Reitz     }
609391af7014SMax Reitz }
60945366d0c8SBenoît Canet 
60955366d0c8SBenoît Canet /* This accessor function purpose is to allow the device models to access the
60965366d0c8SBenoît Canet  * BlockAcctStats structure embedded inside a BlockDriverState without being
60975366d0c8SBenoît Canet  * aware of the BlockDriverState structure layout.
60985366d0c8SBenoît Canet  * It will go away when the BlockAcctStats structure will be moved inside
60995366d0c8SBenoît Canet  * the device models.
61005366d0c8SBenoît Canet  */
61015366d0c8SBenoît Canet BlockAcctStats *bdrv_get_stats(BlockDriverState *bs)
61025366d0c8SBenoît Canet {
61035366d0c8SBenoît Canet     return &bs->stats;
61045366d0c8SBenoît Canet }
6105