xref: /qemu/block/io.c (revision e2a6ae7fe57c17199624e4d47826ec46ca57d546)
161007b31SStefan Hajnoczi /*
261007b31SStefan Hajnoczi  * Block layer I/O functions
361007b31SStefan Hajnoczi  *
461007b31SStefan Hajnoczi  * Copyright (c) 2003 Fabrice Bellard
561007b31SStefan Hajnoczi  *
661007b31SStefan Hajnoczi  * Permission is hereby granted, free of charge, to any person obtaining a copy
761007b31SStefan Hajnoczi  * of this software and associated documentation files (the "Software"), to deal
861007b31SStefan Hajnoczi  * in the Software without restriction, including without limitation the rights
961007b31SStefan Hajnoczi  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
1061007b31SStefan Hajnoczi  * copies of the Software, and to permit persons to whom the Software is
1161007b31SStefan Hajnoczi  * furnished to do so, subject to the following conditions:
1261007b31SStefan Hajnoczi  *
1361007b31SStefan Hajnoczi  * The above copyright notice and this permission notice shall be included in
1461007b31SStefan Hajnoczi  * all copies or substantial portions of the Software.
1561007b31SStefan Hajnoczi  *
1661007b31SStefan Hajnoczi  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
1761007b31SStefan Hajnoczi  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
1861007b31SStefan Hajnoczi  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
1961007b31SStefan Hajnoczi  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
2061007b31SStefan Hajnoczi  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
2161007b31SStefan Hajnoczi  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
2261007b31SStefan Hajnoczi  * THE SOFTWARE.
2361007b31SStefan Hajnoczi  */
2461007b31SStefan Hajnoczi 
2580c71a24SPeter Maydell #include "qemu/osdep.h"
2661007b31SStefan Hajnoczi #include "trace.h"
277f0e9da6SMax Reitz #include "sysemu/block-backend.h"
2861007b31SStefan Hajnoczi #include "block/blockjob.h"
29f321dcb5SPaolo Bonzini #include "block/blockjob_int.h"
3061007b31SStefan Hajnoczi #include "block/block_int.h"
31f348b6d1SVeronia Bahaa #include "qemu/cutils.h"
32da34e65cSMarkus Armbruster #include "qapi/error.h"
33d49b6836SMarkus Armbruster #include "qemu/error-report.h"
3461007b31SStefan Hajnoczi 
3561007b31SStefan Hajnoczi #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
3661007b31SStefan Hajnoczi 
37b15404e0SEric Blake static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child,
38b15404e0SEric Blake                                           int64_t offset,
3961007b31SStefan Hajnoczi                                           QEMUIOVector *qiov,
4061007b31SStefan Hajnoczi                                           BdrvRequestFlags flags,
4161007b31SStefan Hajnoczi                                           BlockCompletionFunc *cb,
4261007b31SStefan Hajnoczi                                           void *opaque,
4361007b31SStefan Hajnoczi                                           bool is_write);
4461007b31SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque);
45d05aa8bbSEric Blake static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
46d05aa8bbSEric Blake     int64_t offset, int count, BdrvRequestFlags flags);
4761007b31SStefan Hajnoczi 
4814e9559fSFam Zheng void bdrv_parent_drained_begin(BlockDriverState *bs)
4961007b31SStefan Hajnoczi {
50c2066af0SKevin Wolf     BdrvChild *c;
5127ccdd52SKevin Wolf 
52c2066af0SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
53c2066af0SKevin Wolf         if (c->role->drained_begin) {
54c2066af0SKevin Wolf             c->role->drained_begin(c);
55c2066af0SKevin Wolf         }
56ce0f1412SPaolo Bonzini     }
57ce0f1412SPaolo Bonzini }
58ce0f1412SPaolo Bonzini 
5914e9559fSFam Zheng void bdrv_parent_drained_end(BlockDriverState *bs)
60ce0f1412SPaolo Bonzini {
61c2066af0SKevin Wolf     BdrvChild *c;
6227ccdd52SKevin Wolf 
63c2066af0SKevin Wolf     QLIST_FOREACH(c, &bs->parents, next_parent) {
64c2066af0SKevin Wolf         if (c->role->drained_end) {
65c2066af0SKevin Wolf             c->role->drained_end(c);
6627ccdd52SKevin Wolf         }
67c2066af0SKevin Wolf     }
6861007b31SStefan Hajnoczi }
6961007b31SStefan Hajnoczi 
70d9e0dfa2SEric Blake static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
71d9e0dfa2SEric Blake {
72d9e0dfa2SEric Blake     dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
73d9e0dfa2SEric Blake     dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
74d9e0dfa2SEric Blake     dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
75d9e0dfa2SEric Blake                                  src->opt_mem_alignment);
76d9e0dfa2SEric Blake     dst->min_mem_alignment = MAX(dst->min_mem_alignment,
77d9e0dfa2SEric Blake                                  src->min_mem_alignment);
78d9e0dfa2SEric Blake     dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
79d9e0dfa2SEric Blake }
80d9e0dfa2SEric Blake 
8161007b31SStefan Hajnoczi void bdrv_refresh_limits(BlockDriverState *bs, Error **errp)
8261007b31SStefan Hajnoczi {
8361007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
8461007b31SStefan Hajnoczi     Error *local_err = NULL;
8561007b31SStefan Hajnoczi 
8661007b31SStefan Hajnoczi     memset(&bs->bl, 0, sizeof(bs->bl));
8761007b31SStefan Hajnoczi 
8861007b31SStefan Hajnoczi     if (!drv) {
8961007b31SStefan Hajnoczi         return;
9061007b31SStefan Hajnoczi     }
9161007b31SStefan Hajnoczi 
9279ba8c98SEric Blake     /* Default alignment based on whether driver has byte interface */
93a5b8dd2cSEric Blake     bs->bl.request_alignment = drv->bdrv_co_preadv ? 1 : 512;
9479ba8c98SEric Blake 
9561007b31SStefan Hajnoczi     /* Take some limits from the children as a default */
9661007b31SStefan Hajnoczi     if (bs->file) {
979a4f4c31SKevin Wolf         bdrv_refresh_limits(bs->file->bs, &local_err);
9861007b31SStefan Hajnoczi         if (local_err) {
9961007b31SStefan Hajnoczi             error_propagate(errp, local_err);
10061007b31SStefan Hajnoczi             return;
10161007b31SStefan Hajnoczi         }
102d9e0dfa2SEric Blake         bdrv_merge_limits(&bs->bl, &bs->file->bs->bl);
10361007b31SStefan Hajnoczi     } else {
1044196d2f0SDenis V. Lunev         bs->bl.min_mem_alignment = 512;
105459b4e66SDenis V. Lunev         bs->bl.opt_mem_alignment = getpagesize();
106bd44feb7SStefan Hajnoczi 
107bd44feb7SStefan Hajnoczi         /* Safe default since most protocols use readv()/writev()/etc */
108bd44feb7SStefan Hajnoczi         bs->bl.max_iov = IOV_MAX;
10961007b31SStefan Hajnoczi     }
11061007b31SStefan Hajnoczi 
111760e0063SKevin Wolf     if (bs->backing) {
112760e0063SKevin Wolf         bdrv_refresh_limits(bs->backing->bs, &local_err);
11361007b31SStefan Hajnoczi         if (local_err) {
11461007b31SStefan Hajnoczi             error_propagate(errp, local_err);
11561007b31SStefan Hajnoczi             return;
11661007b31SStefan Hajnoczi         }
117d9e0dfa2SEric Blake         bdrv_merge_limits(&bs->bl, &bs->backing->bs->bl);
11861007b31SStefan Hajnoczi     }
11961007b31SStefan Hajnoczi 
12061007b31SStefan Hajnoczi     /* Then let the driver override it */
12161007b31SStefan Hajnoczi     if (drv->bdrv_refresh_limits) {
12261007b31SStefan Hajnoczi         drv->bdrv_refresh_limits(bs, errp);
12361007b31SStefan Hajnoczi     }
12461007b31SStefan Hajnoczi }
12561007b31SStefan Hajnoczi 
12661007b31SStefan Hajnoczi /**
12761007b31SStefan Hajnoczi  * The copy-on-read flag is actually a reference count so multiple users may
12861007b31SStefan Hajnoczi  * use the feature without worrying about clobbering its previous state.
12961007b31SStefan Hajnoczi  * Copy-on-read stays enabled until all users have called to disable it.
13061007b31SStefan Hajnoczi  */
13161007b31SStefan Hajnoczi void bdrv_enable_copy_on_read(BlockDriverState *bs)
13261007b31SStefan Hajnoczi {
133d3faa13eSPaolo Bonzini     atomic_inc(&bs->copy_on_read);
13461007b31SStefan Hajnoczi }
13561007b31SStefan Hajnoczi 
13661007b31SStefan Hajnoczi void bdrv_disable_copy_on_read(BlockDriverState *bs)
13761007b31SStefan Hajnoczi {
138d3faa13eSPaolo Bonzini     int old = atomic_fetch_dec(&bs->copy_on_read);
139d3faa13eSPaolo Bonzini     assert(old >= 1);
14061007b31SStefan Hajnoczi }
14161007b31SStefan Hajnoczi 
14261007b31SStefan Hajnoczi /* Check if any requests are in-flight (including throttled requests) */
143439db28cSKevin Wolf bool bdrv_requests_pending(BlockDriverState *bs)
14461007b31SStefan Hajnoczi {
14537a639a7SKevin Wolf     BdrvChild *child;
14637a639a7SKevin Wolf 
14799723548SPaolo Bonzini     if (atomic_read(&bs->in_flight)) {
14861007b31SStefan Hajnoczi         return true;
14961007b31SStefan Hajnoczi     }
15037a639a7SKevin Wolf 
15137a639a7SKevin Wolf     QLIST_FOREACH(child, &bs->children, next) {
15237a639a7SKevin Wolf         if (bdrv_requests_pending(child->bs)) {
15361007b31SStefan Hajnoczi             return true;
15461007b31SStefan Hajnoczi         }
15561007b31SStefan Hajnoczi     }
15637a639a7SKevin Wolf 
15761007b31SStefan Hajnoczi     return false;
15861007b31SStefan Hajnoczi }
15961007b31SStefan Hajnoczi 
160d42cf288SPaolo Bonzini static bool bdrv_drain_recurse(BlockDriverState *bs)
16167da1dc5SFam Zheng {
162178bd438SFam Zheng     BdrvChild *child, *tmp;
163d42cf288SPaolo Bonzini     bool waited;
164d42cf288SPaolo Bonzini 
16588b062c2SPaolo Bonzini     waited = BDRV_POLL_WHILE(bs, atomic_read(&bs->in_flight) > 0);
16667da1dc5SFam Zheng 
16767da1dc5SFam Zheng     if (bs->drv && bs->drv->bdrv_drain) {
16867da1dc5SFam Zheng         bs->drv->bdrv_drain(bs);
16967da1dc5SFam Zheng     }
170d42cf288SPaolo Bonzini 
171178bd438SFam Zheng     QLIST_FOREACH_SAFE(child, &bs->children, next, tmp) {
172178bd438SFam Zheng         BlockDriverState *bs = child->bs;
173178bd438SFam Zheng         bool in_main_loop =
174178bd438SFam Zheng             qemu_get_current_aio_context() == qemu_get_aio_context();
175178bd438SFam Zheng         assert(bs->refcnt > 0);
176178bd438SFam Zheng         if (in_main_loop) {
177178bd438SFam Zheng             /* In case the recursive bdrv_drain_recurse processes a
178178bd438SFam Zheng              * block_job_defer_to_main_loop BH and modifies the graph,
179178bd438SFam Zheng              * let's hold a reference to bs until we are done.
180178bd438SFam Zheng              *
181178bd438SFam Zheng              * IOThread doesn't have such a BH, and it is not safe to call
182178bd438SFam Zheng              * bdrv_unref without BQL, so skip doing it there.
183178bd438SFam Zheng              */
184178bd438SFam Zheng             bdrv_ref(bs);
185178bd438SFam Zheng         }
186178bd438SFam Zheng         waited |= bdrv_drain_recurse(bs);
187178bd438SFam Zheng         if (in_main_loop) {
188178bd438SFam Zheng             bdrv_unref(bs);
189178bd438SFam Zheng         }
19067da1dc5SFam Zheng     }
191d42cf288SPaolo Bonzini 
192d42cf288SPaolo Bonzini     return waited;
19367da1dc5SFam Zheng }
19467da1dc5SFam Zheng 
195a77fd4bbSFam Zheng typedef struct {
196a77fd4bbSFam Zheng     Coroutine *co;
197a77fd4bbSFam Zheng     BlockDriverState *bs;
198a77fd4bbSFam Zheng     bool done;
199a77fd4bbSFam Zheng } BdrvCoDrainData;
200a77fd4bbSFam Zheng 
201a77fd4bbSFam Zheng static void bdrv_co_drain_bh_cb(void *opaque)
202a77fd4bbSFam Zheng {
203a77fd4bbSFam Zheng     BdrvCoDrainData *data = opaque;
204a77fd4bbSFam Zheng     Coroutine *co = data->co;
20599723548SPaolo Bonzini     BlockDriverState *bs = data->bs;
206a77fd4bbSFam Zheng 
20799723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
208d42cf288SPaolo Bonzini     bdrv_drained_begin(bs);
209a77fd4bbSFam Zheng     data->done = true;
2101919631eSPaolo Bonzini     aio_co_wake(co);
211a77fd4bbSFam Zheng }
212a77fd4bbSFam Zheng 
213b6e84c97SPaolo Bonzini static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs)
214a77fd4bbSFam Zheng {
215a77fd4bbSFam Zheng     BdrvCoDrainData data;
216a77fd4bbSFam Zheng 
217a77fd4bbSFam Zheng     /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
218a77fd4bbSFam Zheng      * other coroutines run if they were queued from
219a77fd4bbSFam Zheng      * qemu_co_queue_run_restart(). */
220a77fd4bbSFam Zheng 
221a77fd4bbSFam Zheng     assert(qemu_in_coroutine());
222a77fd4bbSFam Zheng     data = (BdrvCoDrainData) {
223a77fd4bbSFam Zheng         .co = qemu_coroutine_self(),
224a77fd4bbSFam Zheng         .bs = bs,
225a77fd4bbSFam Zheng         .done = false,
226a77fd4bbSFam Zheng     };
22799723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
228fffb6e12SPaolo Bonzini     aio_bh_schedule_oneshot(bdrv_get_aio_context(bs),
229fffb6e12SPaolo Bonzini                             bdrv_co_drain_bh_cb, &data);
230a77fd4bbSFam Zheng 
231a77fd4bbSFam Zheng     qemu_coroutine_yield();
232a77fd4bbSFam Zheng     /* If we are resumed from some other event (such as an aio completion or a
233a77fd4bbSFam Zheng      * timer callback), it is a bug in the caller that should be fixed. */
234a77fd4bbSFam Zheng     assert(data.done);
235a77fd4bbSFam Zheng }
236a77fd4bbSFam Zheng 
2376820643fSKevin Wolf void bdrv_drained_begin(BlockDriverState *bs)
2386820643fSKevin Wolf {
239d42cf288SPaolo Bonzini     if (qemu_in_coroutine()) {
240d42cf288SPaolo Bonzini         bdrv_co_yield_to_drain(bs);
241d42cf288SPaolo Bonzini         return;
242d42cf288SPaolo Bonzini     }
243d42cf288SPaolo Bonzini 
244414c2ec3SPaolo Bonzini     if (atomic_fetch_inc(&bs->quiesce_counter) == 0) {
2456820643fSKevin Wolf         aio_disable_external(bdrv_get_aio_context(bs));
2466820643fSKevin Wolf         bdrv_parent_drained_begin(bs);
2476820643fSKevin Wolf     }
2486820643fSKevin Wolf 
2496820643fSKevin Wolf     bdrv_drain_recurse(bs);
2506820643fSKevin Wolf }
2516820643fSKevin Wolf 
2526820643fSKevin Wolf void bdrv_drained_end(BlockDriverState *bs)
2536820643fSKevin Wolf {
2546820643fSKevin Wolf     assert(bs->quiesce_counter > 0);
255414c2ec3SPaolo Bonzini     if (atomic_fetch_dec(&bs->quiesce_counter) > 1) {
2566820643fSKevin Wolf         return;
2576820643fSKevin Wolf     }
2586820643fSKevin Wolf 
2596820643fSKevin Wolf     bdrv_parent_drained_end(bs);
2606820643fSKevin Wolf     aio_enable_external(bdrv_get_aio_context(bs));
2616820643fSKevin Wolf }
2626820643fSKevin Wolf 
26361007b31SStefan Hajnoczi /*
26467da1dc5SFam Zheng  * Wait for pending requests to complete on a single BlockDriverState subtree,
26567da1dc5SFam Zheng  * and suspend block driver's internal I/O until next request arrives.
26661007b31SStefan Hajnoczi  *
26761007b31SStefan Hajnoczi  * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
26861007b31SStefan Hajnoczi  * AioContext.
2697a63f3cdSStefan Hajnoczi  *
2707a63f3cdSStefan Hajnoczi  * Only this BlockDriverState's AioContext is run, so in-flight requests must
2717a63f3cdSStefan Hajnoczi  * not depend on events in other AioContexts.  In that case, use
2727a63f3cdSStefan Hajnoczi  * bdrv_drain_all() instead.
27361007b31SStefan Hajnoczi  */
274b6e84c97SPaolo Bonzini void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
275b6e84c97SPaolo Bonzini {
2766820643fSKevin Wolf     assert(qemu_in_coroutine());
2776820643fSKevin Wolf     bdrv_drained_begin(bs);
2786820643fSKevin Wolf     bdrv_drained_end(bs);
279b6e84c97SPaolo Bonzini }
280b6e84c97SPaolo Bonzini 
28161007b31SStefan Hajnoczi void bdrv_drain(BlockDriverState *bs)
28261007b31SStefan Hajnoczi {
2836820643fSKevin Wolf     bdrv_drained_begin(bs);
2846820643fSKevin Wolf     bdrv_drained_end(bs);
28561007b31SStefan Hajnoczi }
28661007b31SStefan Hajnoczi 
28761007b31SStefan Hajnoczi /*
28861007b31SStefan Hajnoczi  * Wait for pending requests to complete across all BlockDriverStates
28961007b31SStefan Hajnoczi  *
29061007b31SStefan Hajnoczi  * This function does not flush data to disk, use bdrv_flush_all() for that
29161007b31SStefan Hajnoczi  * after calling this function.
292c0778f66SAlberto Garcia  *
293c0778f66SAlberto Garcia  * This pauses all block jobs and disables external clients. It must
294c0778f66SAlberto Garcia  * be paired with bdrv_drain_all_end().
295c0778f66SAlberto Garcia  *
296c0778f66SAlberto Garcia  * NOTE: no new block jobs or BlockDriverStates can be created between
297c0778f66SAlberto Garcia  * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
29861007b31SStefan Hajnoczi  */
299c0778f66SAlberto Garcia void bdrv_drain_all_begin(void)
30061007b31SStefan Hajnoczi {
30161007b31SStefan Hajnoczi     /* Always run first iteration so any pending completion BHs run */
30299723548SPaolo Bonzini     bool waited = true;
3037c8eece4SKevin Wolf     BlockDriverState *bs;
30488be7b4bSKevin Wolf     BdrvNextIterator it;
305f406c03cSAlexander Yarygin     GSList *aio_ctxs = NULL, *ctx;
30661007b31SStefan Hajnoczi 
307f321dcb5SPaolo Bonzini     block_job_pause_all();
308eb1364ceSAlberto Garcia 
30988be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
31061007b31SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
31161007b31SStefan Hajnoczi 
31261007b31SStefan Hajnoczi         aio_context_acquire(aio_context);
313c2066af0SKevin Wolf         bdrv_parent_drained_begin(bs);
314c0778f66SAlberto Garcia         aio_disable_external(aio_context);
31561007b31SStefan Hajnoczi         aio_context_release(aio_context);
316f406c03cSAlexander Yarygin 
317764ba3aeSAlberto Garcia         if (!g_slist_find(aio_ctxs, aio_context)) {
318f406c03cSAlexander Yarygin             aio_ctxs = g_slist_prepend(aio_ctxs, aio_context);
319f406c03cSAlexander Yarygin         }
32061007b31SStefan Hajnoczi     }
32161007b31SStefan Hajnoczi 
3227a63f3cdSStefan Hajnoczi     /* Note that completion of an asynchronous I/O operation can trigger any
3237a63f3cdSStefan Hajnoczi      * number of other I/O operations on other devices---for example a
3247a63f3cdSStefan Hajnoczi      * coroutine can submit an I/O request to another device in response to
3257a63f3cdSStefan Hajnoczi      * request completion.  Therefore we must keep looping until there was no
3267a63f3cdSStefan Hajnoczi      * more activity rather than simply draining each device independently.
3277a63f3cdSStefan Hajnoczi      */
32899723548SPaolo Bonzini     while (waited) {
32999723548SPaolo Bonzini         waited = false;
330f406c03cSAlexander Yarygin 
331f406c03cSAlexander Yarygin         for (ctx = aio_ctxs; ctx != NULL; ctx = ctx->next) {
332f406c03cSAlexander Yarygin             AioContext *aio_context = ctx->data;
33361007b31SStefan Hajnoczi 
33461007b31SStefan Hajnoczi             aio_context_acquire(aio_context);
33588be7b4bSKevin Wolf             for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
336f406c03cSAlexander Yarygin                 if (aio_context == bdrv_get_aio_context(bs)) {
337d42cf288SPaolo Bonzini                     waited |= bdrv_drain_recurse(bs);
338f406c03cSAlexander Yarygin                 }
339f406c03cSAlexander Yarygin             }
34061007b31SStefan Hajnoczi             aio_context_release(aio_context);
34161007b31SStefan Hajnoczi         }
34261007b31SStefan Hajnoczi     }
34361007b31SStefan Hajnoczi 
344c0778f66SAlberto Garcia     g_slist_free(aio_ctxs);
345c0778f66SAlberto Garcia }
346c0778f66SAlberto Garcia 
347c0778f66SAlberto Garcia void bdrv_drain_all_end(void)
348c0778f66SAlberto Garcia {
349c0778f66SAlberto Garcia     BlockDriverState *bs;
350c0778f66SAlberto Garcia     BdrvNextIterator it;
351c0778f66SAlberto Garcia 
35288be7b4bSKevin Wolf     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
35361007b31SStefan Hajnoczi         AioContext *aio_context = bdrv_get_aio_context(bs);
35461007b31SStefan Hajnoczi 
35561007b31SStefan Hajnoczi         aio_context_acquire(aio_context);
356c0778f66SAlberto Garcia         aio_enable_external(aio_context);
357c2066af0SKevin Wolf         bdrv_parent_drained_end(bs);
35861007b31SStefan Hajnoczi         aio_context_release(aio_context);
35961007b31SStefan Hajnoczi     }
360eb1364ceSAlberto Garcia 
361f321dcb5SPaolo Bonzini     block_job_resume_all();
36261007b31SStefan Hajnoczi }
36361007b31SStefan Hajnoczi 
364c0778f66SAlberto Garcia void bdrv_drain_all(void)
365c0778f66SAlberto Garcia {
366c0778f66SAlberto Garcia     bdrv_drain_all_begin();
367c0778f66SAlberto Garcia     bdrv_drain_all_end();
368c0778f66SAlberto Garcia }
369c0778f66SAlberto Garcia 
37061007b31SStefan Hajnoczi /**
37161007b31SStefan Hajnoczi  * Remove an active request from the tracked requests list
37261007b31SStefan Hajnoczi  *
37361007b31SStefan Hajnoczi  * This function should be called when a tracked request is completing.
37461007b31SStefan Hajnoczi  */
37561007b31SStefan Hajnoczi static void tracked_request_end(BdrvTrackedRequest *req)
37661007b31SStefan Hajnoczi {
37761007b31SStefan Hajnoczi     if (req->serialising) {
37820fc71b2SPaolo Bonzini         atomic_dec(&req->bs->serialising_in_flight);
37961007b31SStefan Hajnoczi     }
38061007b31SStefan Hajnoczi 
38161007b31SStefan Hajnoczi     QLIST_REMOVE(req, list);
38261007b31SStefan Hajnoczi     qemu_co_queue_restart_all(&req->wait_queue);
38361007b31SStefan Hajnoczi }
38461007b31SStefan Hajnoczi 
38561007b31SStefan Hajnoczi /**
38661007b31SStefan Hajnoczi  * Add an active request to the tracked requests list
38761007b31SStefan Hajnoczi  */
38861007b31SStefan Hajnoczi static void tracked_request_begin(BdrvTrackedRequest *req,
38961007b31SStefan Hajnoczi                                   BlockDriverState *bs,
39061007b31SStefan Hajnoczi                                   int64_t offset,
391ebde595cSFam Zheng                                   unsigned int bytes,
392ebde595cSFam Zheng                                   enum BdrvTrackedRequestType type)
39361007b31SStefan Hajnoczi {
39461007b31SStefan Hajnoczi     *req = (BdrvTrackedRequest){
39561007b31SStefan Hajnoczi         .bs = bs,
39661007b31SStefan Hajnoczi         .offset         = offset,
39761007b31SStefan Hajnoczi         .bytes          = bytes,
398ebde595cSFam Zheng         .type           = type,
39961007b31SStefan Hajnoczi         .co             = qemu_coroutine_self(),
40061007b31SStefan Hajnoczi         .serialising    = false,
40161007b31SStefan Hajnoczi         .overlap_offset = offset,
40261007b31SStefan Hajnoczi         .overlap_bytes  = bytes,
40361007b31SStefan Hajnoczi     };
40461007b31SStefan Hajnoczi 
40561007b31SStefan Hajnoczi     qemu_co_queue_init(&req->wait_queue);
40661007b31SStefan Hajnoczi 
40761007b31SStefan Hajnoczi     QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
40861007b31SStefan Hajnoczi }
40961007b31SStefan Hajnoczi 
41061007b31SStefan Hajnoczi static void mark_request_serialising(BdrvTrackedRequest *req, uint64_t align)
41161007b31SStefan Hajnoczi {
41261007b31SStefan Hajnoczi     int64_t overlap_offset = req->offset & ~(align - 1);
41361007b31SStefan Hajnoczi     unsigned int overlap_bytes = ROUND_UP(req->offset + req->bytes, align)
41461007b31SStefan Hajnoczi                                - overlap_offset;
41561007b31SStefan Hajnoczi 
41661007b31SStefan Hajnoczi     if (!req->serialising) {
41720fc71b2SPaolo Bonzini         atomic_inc(&req->bs->serialising_in_flight);
41861007b31SStefan Hajnoczi         req->serialising = true;
41961007b31SStefan Hajnoczi     }
42061007b31SStefan Hajnoczi 
42161007b31SStefan Hajnoczi     req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
42261007b31SStefan Hajnoczi     req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
42361007b31SStefan Hajnoczi }
42461007b31SStefan Hajnoczi 
42561007b31SStefan Hajnoczi /**
426244483e6SKevin Wolf  * Round a region to cluster boundaries (sector-based)
42761007b31SStefan Hajnoczi  */
428244483e6SKevin Wolf void bdrv_round_sectors_to_clusters(BlockDriverState *bs,
42961007b31SStefan Hajnoczi                                     int64_t sector_num, int nb_sectors,
43061007b31SStefan Hajnoczi                                     int64_t *cluster_sector_num,
43161007b31SStefan Hajnoczi                                     int *cluster_nb_sectors)
43261007b31SStefan Hajnoczi {
43361007b31SStefan Hajnoczi     BlockDriverInfo bdi;
43461007b31SStefan Hajnoczi 
43561007b31SStefan Hajnoczi     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
43661007b31SStefan Hajnoczi         *cluster_sector_num = sector_num;
43761007b31SStefan Hajnoczi         *cluster_nb_sectors = nb_sectors;
43861007b31SStefan Hajnoczi     } else {
43961007b31SStefan Hajnoczi         int64_t c = bdi.cluster_size / BDRV_SECTOR_SIZE;
44061007b31SStefan Hajnoczi         *cluster_sector_num = QEMU_ALIGN_DOWN(sector_num, c);
44161007b31SStefan Hajnoczi         *cluster_nb_sectors = QEMU_ALIGN_UP(sector_num - *cluster_sector_num +
44261007b31SStefan Hajnoczi                                             nb_sectors, c);
44361007b31SStefan Hajnoczi     }
44461007b31SStefan Hajnoczi }
44561007b31SStefan Hajnoczi 
446244483e6SKevin Wolf /**
447244483e6SKevin Wolf  * Round a region to cluster boundaries
448244483e6SKevin Wolf  */
449244483e6SKevin Wolf void bdrv_round_to_clusters(BlockDriverState *bs,
450244483e6SKevin Wolf                             int64_t offset, unsigned int bytes,
451244483e6SKevin Wolf                             int64_t *cluster_offset,
452244483e6SKevin Wolf                             unsigned int *cluster_bytes)
453244483e6SKevin Wolf {
454244483e6SKevin Wolf     BlockDriverInfo bdi;
455244483e6SKevin Wolf 
456244483e6SKevin Wolf     if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
457244483e6SKevin Wolf         *cluster_offset = offset;
458244483e6SKevin Wolf         *cluster_bytes = bytes;
459244483e6SKevin Wolf     } else {
460244483e6SKevin Wolf         int64_t c = bdi.cluster_size;
461244483e6SKevin Wolf         *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
462244483e6SKevin Wolf         *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
463244483e6SKevin Wolf     }
464244483e6SKevin Wolf }
465244483e6SKevin Wolf 
46661007b31SStefan Hajnoczi static int bdrv_get_cluster_size(BlockDriverState *bs)
46761007b31SStefan Hajnoczi {
46861007b31SStefan Hajnoczi     BlockDriverInfo bdi;
46961007b31SStefan Hajnoczi     int ret;
47061007b31SStefan Hajnoczi 
47161007b31SStefan Hajnoczi     ret = bdrv_get_info(bs, &bdi);
47261007b31SStefan Hajnoczi     if (ret < 0 || bdi.cluster_size == 0) {
473a5b8dd2cSEric Blake         return bs->bl.request_alignment;
47461007b31SStefan Hajnoczi     } else {
47561007b31SStefan Hajnoczi         return bdi.cluster_size;
47661007b31SStefan Hajnoczi     }
47761007b31SStefan Hajnoczi }
47861007b31SStefan Hajnoczi 
47961007b31SStefan Hajnoczi static bool tracked_request_overlaps(BdrvTrackedRequest *req,
48061007b31SStefan Hajnoczi                                      int64_t offset, unsigned int bytes)
48161007b31SStefan Hajnoczi {
48261007b31SStefan Hajnoczi     /*        aaaa   bbbb */
48361007b31SStefan Hajnoczi     if (offset >= req->overlap_offset + req->overlap_bytes) {
48461007b31SStefan Hajnoczi         return false;
48561007b31SStefan Hajnoczi     }
48661007b31SStefan Hajnoczi     /* bbbb   aaaa        */
48761007b31SStefan Hajnoczi     if (req->overlap_offset >= offset + bytes) {
48861007b31SStefan Hajnoczi         return false;
48961007b31SStefan Hajnoczi     }
49061007b31SStefan Hajnoczi     return true;
49161007b31SStefan Hajnoczi }
49261007b31SStefan Hajnoczi 
49399723548SPaolo Bonzini void bdrv_inc_in_flight(BlockDriverState *bs)
49499723548SPaolo Bonzini {
49599723548SPaolo Bonzini     atomic_inc(&bs->in_flight);
49699723548SPaolo Bonzini }
49799723548SPaolo Bonzini 
498c9d1a561SPaolo Bonzini static void dummy_bh_cb(void *opaque)
499c9d1a561SPaolo Bonzini {
500c9d1a561SPaolo Bonzini }
501c9d1a561SPaolo Bonzini 
502c9d1a561SPaolo Bonzini void bdrv_wakeup(BlockDriverState *bs)
503c9d1a561SPaolo Bonzini {
504*e2a6ae7fSPaolo Bonzini     /* The barrier (or an atomic op) is in the caller.  */
505*e2a6ae7fSPaolo Bonzini     if (atomic_read(&bs->wakeup)) {
506c9d1a561SPaolo Bonzini         aio_bh_schedule_oneshot(qemu_get_aio_context(), dummy_bh_cb, NULL);
507c9d1a561SPaolo Bonzini     }
508c9d1a561SPaolo Bonzini }
509c9d1a561SPaolo Bonzini 
51099723548SPaolo Bonzini void bdrv_dec_in_flight(BlockDriverState *bs)
51199723548SPaolo Bonzini {
51299723548SPaolo Bonzini     atomic_dec(&bs->in_flight);
513c9d1a561SPaolo Bonzini     bdrv_wakeup(bs);
51499723548SPaolo Bonzini }
51599723548SPaolo Bonzini 
51661007b31SStefan Hajnoczi static bool coroutine_fn wait_serialising_requests(BdrvTrackedRequest *self)
51761007b31SStefan Hajnoczi {
51861007b31SStefan Hajnoczi     BlockDriverState *bs = self->bs;
51961007b31SStefan Hajnoczi     BdrvTrackedRequest *req;
52061007b31SStefan Hajnoczi     bool retry;
52161007b31SStefan Hajnoczi     bool waited = false;
52261007b31SStefan Hajnoczi 
52320fc71b2SPaolo Bonzini     if (!atomic_read(&bs->serialising_in_flight)) {
52461007b31SStefan Hajnoczi         return false;
52561007b31SStefan Hajnoczi     }
52661007b31SStefan Hajnoczi 
52761007b31SStefan Hajnoczi     do {
52861007b31SStefan Hajnoczi         retry = false;
52961007b31SStefan Hajnoczi         QLIST_FOREACH(req, &bs->tracked_requests, list) {
53061007b31SStefan Hajnoczi             if (req == self || (!req->serialising && !self->serialising)) {
53161007b31SStefan Hajnoczi                 continue;
53261007b31SStefan Hajnoczi             }
53361007b31SStefan Hajnoczi             if (tracked_request_overlaps(req, self->overlap_offset,
53461007b31SStefan Hajnoczi                                          self->overlap_bytes))
53561007b31SStefan Hajnoczi             {
53661007b31SStefan Hajnoczi                 /* Hitting this means there was a reentrant request, for
53761007b31SStefan Hajnoczi                  * example, a block driver issuing nested requests.  This must
53861007b31SStefan Hajnoczi                  * never happen since it means deadlock.
53961007b31SStefan Hajnoczi                  */
54061007b31SStefan Hajnoczi                 assert(qemu_coroutine_self() != req->co);
54161007b31SStefan Hajnoczi 
54261007b31SStefan Hajnoczi                 /* If the request is already (indirectly) waiting for us, or
54361007b31SStefan Hajnoczi                  * will wait for us as soon as it wakes up, then just go on
54461007b31SStefan Hajnoczi                  * (instead of producing a deadlock in the former case). */
54561007b31SStefan Hajnoczi                 if (!req->waiting_for) {
54661007b31SStefan Hajnoczi                     self->waiting_for = req;
5471ace7ceaSPaolo Bonzini                     qemu_co_queue_wait(&req->wait_queue, NULL);
54861007b31SStefan Hajnoczi                     self->waiting_for = NULL;
54961007b31SStefan Hajnoczi                     retry = true;
55061007b31SStefan Hajnoczi                     waited = true;
55161007b31SStefan Hajnoczi                     break;
55261007b31SStefan Hajnoczi                 }
55361007b31SStefan Hajnoczi             }
55461007b31SStefan Hajnoczi         }
55561007b31SStefan Hajnoczi     } while (retry);
55661007b31SStefan Hajnoczi 
55761007b31SStefan Hajnoczi     return waited;
55861007b31SStefan Hajnoczi }
55961007b31SStefan Hajnoczi 
56061007b31SStefan Hajnoczi static int bdrv_check_byte_request(BlockDriverState *bs, int64_t offset,
56161007b31SStefan Hajnoczi                                    size_t size)
56261007b31SStefan Hajnoczi {
56361007b31SStefan Hajnoczi     if (size > BDRV_REQUEST_MAX_SECTORS << BDRV_SECTOR_BITS) {
56461007b31SStefan Hajnoczi         return -EIO;
56561007b31SStefan Hajnoczi     }
56661007b31SStefan Hajnoczi 
56761007b31SStefan Hajnoczi     if (!bdrv_is_inserted(bs)) {
56861007b31SStefan Hajnoczi         return -ENOMEDIUM;
56961007b31SStefan Hajnoczi     }
57061007b31SStefan Hajnoczi 
57161007b31SStefan Hajnoczi     if (offset < 0) {
57261007b31SStefan Hajnoczi         return -EIO;
57361007b31SStefan Hajnoczi     }
57461007b31SStefan Hajnoczi 
57561007b31SStefan Hajnoczi     return 0;
57661007b31SStefan Hajnoczi }
57761007b31SStefan Hajnoczi 
57861007b31SStefan Hajnoczi typedef struct RwCo {
579e293b7a3SKevin Wolf     BdrvChild *child;
58061007b31SStefan Hajnoczi     int64_t offset;
58161007b31SStefan Hajnoczi     QEMUIOVector *qiov;
58261007b31SStefan Hajnoczi     bool is_write;
58361007b31SStefan Hajnoczi     int ret;
58461007b31SStefan Hajnoczi     BdrvRequestFlags flags;
58561007b31SStefan Hajnoczi } RwCo;
58661007b31SStefan Hajnoczi 
58761007b31SStefan Hajnoczi static void coroutine_fn bdrv_rw_co_entry(void *opaque)
58861007b31SStefan Hajnoczi {
58961007b31SStefan Hajnoczi     RwCo *rwco = opaque;
59061007b31SStefan Hajnoczi 
59161007b31SStefan Hajnoczi     if (!rwco->is_write) {
592a03ef88fSKevin Wolf         rwco->ret = bdrv_co_preadv(rwco->child, rwco->offset,
59361007b31SStefan Hajnoczi                                    rwco->qiov->size, rwco->qiov,
59461007b31SStefan Hajnoczi                                    rwco->flags);
59561007b31SStefan Hajnoczi     } else {
596a03ef88fSKevin Wolf         rwco->ret = bdrv_co_pwritev(rwco->child, rwco->offset,
59761007b31SStefan Hajnoczi                                     rwco->qiov->size, rwco->qiov,
59861007b31SStefan Hajnoczi                                     rwco->flags);
59961007b31SStefan Hajnoczi     }
60061007b31SStefan Hajnoczi }
60161007b31SStefan Hajnoczi 
60261007b31SStefan Hajnoczi /*
60361007b31SStefan Hajnoczi  * Process a vectored synchronous request using coroutines
60461007b31SStefan Hajnoczi  */
605e293b7a3SKevin Wolf static int bdrv_prwv_co(BdrvChild *child, int64_t offset,
60661007b31SStefan Hajnoczi                         QEMUIOVector *qiov, bool is_write,
60761007b31SStefan Hajnoczi                         BdrvRequestFlags flags)
60861007b31SStefan Hajnoczi {
60961007b31SStefan Hajnoczi     Coroutine *co;
61061007b31SStefan Hajnoczi     RwCo rwco = {
611e293b7a3SKevin Wolf         .child = child,
61261007b31SStefan Hajnoczi         .offset = offset,
61361007b31SStefan Hajnoczi         .qiov = qiov,
61461007b31SStefan Hajnoczi         .is_write = is_write,
61561007b31SStefan Hajnoczi         .ret = NOT_DONE,
61661007b31SStefan Hajnoczi         .flags = flags,
61761007b31SStefan Hajnoczi     };
61861007b31SStefan Hajnoczi 
61961007b31SStefan Hajnoczi     if (qemu_in_coroutine()) {
62061007b31SStefan Hajnoczi         /* Fast-path if already in coroutine context */
62161007b31SStefan Hajnoczi         bdrv_rw_co_entry(&rwco);
62261007b31SStefan Hajnoczi     } else {
6230b8b8753SPaolo Bonzini         co = qemu_coroutine_create(bdrv_rw_co_entry, &rwco);
624e92f0e19SFam Zheng         bdrv_coroutine_enter(child->bs, co);
62588b062c2SPaolo Bonzini         BDRV_POLL_WHILE(child->bs, rwco.ret == NOT_DONE);
62661007b31SStefan Hajnoczi     }
62761007b31SStefan Hajnoczi     return rwco.ret;
62861007b31SStefan Hajnoczi }
62961007b31SStefan Hajnoczi 
63061007b31SStefan Hajnoczi /*
63161007b31SStefan Hajnoczi  * Process a synchronous request using coroutines
63261007b31SStefan Hajnoczi  */
633e293b7a3SKevin Wolf static int bdrv_rw_co(BdrvChild *child, int64_t sector_num, uint8_t *buf,
63461007b31SStefan Hajnoczi                       int nb_sectors, bool is_write, BdrvRequestFlags flags)
63561007b31SStefan Hajnoczi {
63661007b31SStefan Hajnoczi     QEMUIOVector qiov;
63761007b31SStefan Hajnoczi     struct iovec iov = {
63861007b31SStefan Hajnoczi         .iov_base = (void *)buf,
63961007b31SStefan Hajnoczi         .iov_len = nb_sectors * BDRV_SECTOR_SIZE,
64061007b31SStefan Hajnoczi     };
64161007b31SStefan Hajnoczi 
64261007b31SStefan Hajnoczi     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
64361007b31SStefan Hajnoczi         return -EINVAL;
64461007b31SStefan Hajnoczi     }
64561007b31SStefan Hajnoczi 
64661007b31SStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
647e293b7a3SKevin Wolf     return bdrv_prwv_co(child, sector_num << BDRV_SECTOR_BITS,
64861007b31SStefan Hajnoczi                         &qiov, is_write, flags);
64961007b31SStefan Hajnoczi }
65061007b31SStefan Hajnoczi 
65161007b31SStefan Hajnoczi /* return < 0 if error. See bdrv_write() for the return codes */
652fbcbbf4eSKevin Wolf int bdrv_read(BdrvChild *child, int64_t sector_num,
65361007b31SStefan Hajnoczi               uint8_t *buf, int nb_sectors)
65461007b31SStefan Hajnoczi {
655e293b7a3SKevin Wolf     return bdrv_rw_co(child, sector_num, buf, nb_sectors, false, 0);
65661007b31SStefan Hajnoczi }
65761007b31SStefan Hajnoczi 
65861007b31SStefan Hajnoczi /* Return < 0 if error. Important errors are:
65961007b31SStefan Hajnoczi   -EIO         generic I/O error (may happen for all errors)
66061007b31SStefan Hajnoczi   -ENOMEDIUM   No media inserted.
66161007b31SStefan Hajnoczi   -EINVAL      Invalid sector number or nb_sectors
66261007b31SStefan Hajnoczi   -EACCES      Trying to write a read-only device
66361007b31SStefan Hajnoczi */
66418d51c4bSKevin Wolf int bdrv_write(BdrvChild *child, int64_t sector_num,
66561007b31SStefan Hajnoczi                const uint8_t *buf, int nb_sectors)
66661007b31SStefan Hajnoczi {
667e293b7a3SKevin Wolf     return bdrv_rw_co(child, sector_num, (uint8_t *)buf, nb_sectors, true, 0);
66861007b31SStefan Hajnoczi }
66961007b31SStefan Hajnoczi 
670720ff280SKevin Wolf int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
67174021bc4SEric Blake                        int count, BdrvRequestFlags flags)
67261007b31SStefan Hajnoczi {
67374021bc4SEric Blake     QEMUIOVector qiov;
67474021bc4SEric Blake     struct iovec iov = {
67574021bc4SEric Blake         .iov_base = NULL,
67674021bc4SEric Blake         .iov_len = count,
67774021bc4SEric Blake     };
67874021bc4SEric Blake 
67974021bc4SEric Blake     qemu_iovec_init_external(&qiov, &iov, 1);
680e293b7a3SKevin Wolf     return bdrv_prwv_co(child, offset, &qiov, true,
68161007b31SStefan Hajnoczi                         BDRV_REQ_ZERO_WRITE | flags);
68261007b31SStefan Hajnoczi }
68361007b31SStefan Hajnoczi 
68461007b31SStefan Hajnoczi /*
68574021bc4SEric Blake  * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
68661007b31SStefan Hajnoczi  * The operation is sped up by checking the block status and only writing
68761007b31SStefan Hajnoczi  * zeroes to the device if they currently do not return zeroes. Optional
68874021bc4SEric Blake  * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
689465fe887SEric Blake  * BDRV_REQ_FUA).
69061007b31SStefan Hajnoczi  *
69161007b31SStefan Hajnoczi  * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
69261007b31SStefan Hajnoczi  */
693720ff280SKevin Wolf int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
69461007b31SStefan Hajnoczi {
69561007b31SStefan Hajnoczi     int64_t target_sectors, ret, nb_sectors, sector_num = 0;
696720ff280SKevin Wolf     BlockDriverState *bs = child->bs;
69767a0fd2aSFam Zheng     BlockDriverState *file;
69861007b31SStefan Hajnoczi     int n;
69961007b31SStefan Hajnoczi 
70061007b31SStefan Hajnoczi     target_sectors = bdrv_nb_sectors(bs);
70161007b31SStefan Hajnoczi     if (target_sectors < 0) {
70261007b31SStefan Hajnoczi         return target_sectors;
70361007b31SStefan Hajnoczi     }
70461007b31SStefan Hajnoczi 
70561007b31SStefan Hajnoczi     for (;;) {
70661007b31SStefan Hajnoczi         nb_sectors = MIN(target_sectors - sector_num, BDRV_REQUEST_MAX_SECTORS);
70761007b31SStefan Hajnoczi         if (nb_sectors <= 0) {
70861007b31SStefan Hajnoczi             return 0;
70961007b31SStefan Hajnoczi         }
71067a0fd2aSFam Zheng         ret = bdrv_get_block_status(bs, sector_num, nb_sectors, &n, &file);
71161007b31SStefan Hajnoczi         if (ret < 0) {
71261007b31SStefan Hajnoczi             error_report("error getting block status at sector %" PRId64 ": %s",
71361007b31SStefan Hajnoczi                          sector_num, strerror(-ret));
71461007b31SStefan Hajnoczi             return ret;
71561007b31SStefan Hajnoczi         }
71661007b31SStefan Hajnoczi         if (ret & BDRV_BLOCK_ZERO) {
71761007b31SStefan Hajnoczi             sector_num += n;
71861007b31SStefan Hajnoczi             continue;
71961007b31SStefan Hajnoczi         }
720720ff280SKevin Wolf         ret = bdrv_pwrite_zeroes(child, sector_num << BDRV_SECTOR_BITS,
72174021bc4SEric Blake                                  n << BDRV_SECTOR_BITS, flags);
72261007b31SStefan Hajnoczi         if (ret < 0) {
72361007b31SStefan Hajnoczi             error_report("error writing zeroes at sector %" PRId64 ": %s",
72461007b31SStefan Hajnoczi                          sector_num, strerror(-ret));
72561007b31SStefan Hajnoczi             return ret;
72661007b31SStefan Hajnoczi         }
72761007b31SStefan Hajnoczi         sector_num += n;
72861007b31SStefan Hajnoczi     }
72961007b31SStefan Hajnoczi }
73061007b31SStefan Hajnoczi 
731cf2ab8fcSKevin Wolf int bdrv_preadv(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
732f1e84741SKevin Wolf {
733f1e84741SKevin Wolf     int ret;
734f1e84741SKevin Wolf 
735e293b7a3SKevin Wolf     ret = bdrv_prwv_co(child, offset, qiov, false, 0);
736f1e84741SKevin Wolf     if (ret < 0) {
737f1e84741SKevin Wolf         return ret;
738f1e84741SKevin Wolf     }
739f1e84741SKevin Wolf 
740f1e84741SKevin Wolf     return qiov->size;
741f1e84741SKevin Wolf }
742f1e84741SKevin Wolf 
743cf2ab8fcSKevin Wolf int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int bytes)
74461007b31SStefan Hajnoczi {
74561007b31SStefan Hajnoczi     QEMUIOVector qiov;
74661007b31SStefan Hajnoczi     struct iovec iov = {
74761007b31SStefan Hajnoczi         .iov_base = (void *)buf,
74861007b31SStefan Hajnoczi         .iov_len = bytes,
74961007b31SStefan Hajnoczi     };
75061007b31SStefan Hajnoczi 
75161007b31SStefan Hajnoczi     if (bytes < 0) {
75261007b31SStefan Hajnoczi         return -EINVAL;
75361007b31SStefan Hajnoczi     }
75461007b31SStefan Hajnoczi 
75561007b31SStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
756cf2ab8fcSKevin Wolf     return bdrv_preadv(child, offset, &qiov);
75761007b31SStefan Hajnoczi }
75861007b31SStefan Hajnoczi 
759d9ca2ea2SKevin Wolf int bdrv_pwritev(BdrvChild *child, int64_t offset, QEMUIOVector *qiov)
76061007b31SStefan Hajnoczi {
76161007b31SStefan Hajnoczi     int ret;
76261007b31SStefan Hajnoczi 
763e293b7a3SKevin Wolf     ret = bdrv_prwv_co(child, offset, qiov, true, 0);
76461007b31SStefan Hajnoczi     if (ret < 0) {
76561007b31SStefan Hajnoczi         return ret;
76661007b31SStefan Hajnoczi     }
76761007b31SStefan Hajnoczi 
76861007b31SStefan Hajnoczi     return qiov->size;
76961007b31SStefan Hajnoczi }
77061007b31SStefan Hajnoczi 
771d9ca2ea2SKevin Wolf int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf, int bytes)
77261007b31SStefan Hajnoczi {
77361007b31SStefan Hajnoczi     QEMUIOVector qiov;
77461007b31SStefan Hajnoczi     struct iovec iov = {
77561007b31SStefan Hajnoczi         .iov_base   = (void *) buf,
77661007b31SStefan Hajnoczi         .iov_len    = bytes,
77761007b31SStefan Hajnoczi     };
77861007b31SStefan Hajnoczi 
77961007b31SStefan Hajnoczi     if (bytes < 0) {
78061007b31SStefan Hajnoczi         return -EINVAL;
78161007b31SStefan Hajnoczi     }
78261007b31SStefan Hajnoczi 
78361007b31SStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
784d9ca2ea2SKevin Wolf     return bdrv_pwritev(child, offset, &qiov);
78561007b31SStefan Hajnoczi }
78661007b31SStefan Hajnoczi 
78761007b31SStefan Hajnoczi /*
78861007b31SStefan Hajnoczi  * Writes to the file and ensures that no writes are reordered across this
78961007b31SStefan Hajnoczi  * request (acts as a barrier)
79061007b31SStefan Hajnoczi  *
79161007b31SStefan Hajnoczi  * Returns 0 on success, -errno in error cases.
79261007b31SStefan Hajnoczi  */
793d9ca2ea2SKevin Wolf int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
79461007b31SStefan Hajnoczi                      const void *buf, int count)
79561007b31SStefan Hajnoczi {
79661007b31SStefan Hajnoczi     int ret;
79761007b31SStefan Hajnoczi 
798d9ca2ea2SKevin Wolf     ret = bdrv_pwrite(child, offset, buf, count);
79961007b31SStefan Hajnoczi     if (ret < 0) {
80061007b31SStefan Hajnoczi         return ret;
80161007b31SStefan Hajnoczi     }
80261007b31SStefan Hajnoczi 
803d9ca2ea2SKevin Wolf     ret = bdrv_flush(child->bs);
804855a6a93SKevin Wolf     if (ret < 0) {
805855a6a93SKevin Wolf         return ret;
80661007b31SStefan Hajnoczi     }
80761007b31SStefan Hajnoczi 
80861007b31SStefan Hajnoczi     return 0;
80961007b31SStefan Hajnoczi }
81061007b31SStefan Hajnoczi 
81108844473SKevin Wolf typedef struct CoroutineIOCompletion {
81208844473SKevin Wolf     Coroutine *coroutine;
81308844473SKevin Wolf     int ret;
81408844473SKevin Wolf } CoroutineIOCompletion;
81508844473SKevin Wolf 
81608844473SKevin Wolf static void bdrv_co_io_em_complete(void *opaque, int ret)
81708844473SKevin Wolf {
81808844473SKevin Wolf     CoroutineIOCompletion *co = opaque;
81908844473SKevin Wolf 
82008844473SKevin Wolf     co->ret = ret;
821b9e413ddSPaolo Bonzini     aio_co_wake(co->coroutine);
82208844473SKevin Wolf }
82308844473SKevin Wolf 
824166fe960SKevin Wolf static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
825166fe960SKevin Wolf                                            uint64_t offset, uint64_t bytes,
826166fe960SKevin Wolf                                            QEMUIOVector *qiov, int flags)
827166fe960SKevin Wolf {
828166fe960SKevin Wolf     BlockDriver *drv = bs->drv;
8293fb06697SKevin Wolf     int64_t sector_num;
8303fb06697SKevin Wolf     unsigned int nb_sectors;
8313fb06697SKevin Wolf 
832fa166538SEric Blake     assert(!(flags & ~BDRV_REQ_MASK));
833fa166538SEric Blake 
8343fb06697SKevin Wolf     if (drv->bdrv_co_preadv) {
8353fb06697SKevin Wolf         return drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
8363fb06697SKevin Wolf     }
8373fb06697SKevin Wolf 
8383fb06697SKevin Wolf     sector_num = offset >> BDRV_SECTOR_BITS;
8393fb06697SKevin Wolf     nb_sectors = bytes >> BDRV_SECTOR_BITS;
840166fe960SKevin Wolf 
841166fe960SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
842166fe960SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
843166fe960SKevin Wolf     assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
844166fe960SKevin Wolf 
84508844473SKevin Wolf     if (drv->bdrv_co_readv) {
846166fe960SKevin Wolf         return drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
84708844473SKevin Wolf     } else {
84808844473SKevin Wolf         BlockAIOCB *acb;
84908844473SKevin Wolf         CoroutineIOCompletion co = {
85008844473SKevin Wolf             .coroutine = qemu_coroutine_self(),
85108844473SKevin Wolf         };
85208844473SKevin Wolf 
85308844473SKevin Wolf         acb = bs->drv->bdrv_aio_readv(bs, sector_num, qiov, nb_sectors,
85408844473SKevin Wolf                                       bdrv_co_io_em_complete, &co);
85508844473SKevin Wolf         if (acb == NULL) {
85608844473SKevin Wolf             return -EIO;
85708844473SKevin Wolf         } else {
85808844473SKevin Wolf             qemu_coroutine_yield();
85908844473SKevin Wolf             return co.ret;
86008844473SKevin Wolf         }
86108844473SKevin Wolf     }
862166fe960SKevin Wolf }
863166fe960SKevin Wolf 
86478a07294SKevin Wolf static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
86578a07294SKevin Wolf                                             uint64_t offset, uint64_t bytes,
86678a07294SKevin Wolf                                             QEMUIOVector *qiov, int flags)
86778a07294SKevin Wolf {
86878a07294SKevin Wolf     BlockDriver *drv = bs->drv;
8693fb06697SKevin Wolf     int64_t sector_num;
8703fb06697SKevin Wolf     unsigned int nb_sectors;
87178a07294SKevin Wolf     int ret;
87278a07294SKevin Wolf 
873fa166538SEric Blake     assert(!(flags & ~BDRV_REQ_MASK));
874fa166538SEric Blake 
8753fb06697SKevin Wolf     if (drv->bdrv_co_pwritev) {
876515c2f43SKevin Wolf         ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
877515c2f43SKevin Wolf                                    flags & bs->supported_write_flags);
878515c2f43SKevin Wolf         flags &= ~bs->supported_write_flags;
8793fb06697SKevin Wolf         goto emulate_flags;
8803fb06697SKevin Wolf     }
8813fb06697SKevin Wolf 
8823fb06697SKevin Wolf     sector_num = offset >> BDRV_SECTOR_BITS;
8833fb06697SKevin Wolf     nb_sectors = bytes >> BDRV_SECTOR_BITS;
8843fb06697SKevin Wolf 
88578a07294SKevin Wolf     assert((offset & (BDRV_SECTOR_SIZE - 1)) == 0);
88678a07294SKevin Wolf     assert((bytes & (BDRV_SECTOR_SIZE - 1)) == 0);
88778a07294SKevin Wolf     assert((bytes >> BDRV_SECTOR_BITS) <= BDRV_REQUEST_MAX_SECTORS);
88878a07294SKevin Wolf 
88978a07294SKevin Wolf     if (drv->bdrv_co_writev_flags) {
89078a07294SKevin Wolf         ret = drv->bdrv_co_writev_flags(bs, sector_num, nb_sectors, qiov,
8914df863f3SEric Blake                                         flags & bs->supported_write_flags);
8924df863f3SEric Blake         flags &= ~bs->supported_write_flags;
89308844473SKevin Wolf     } else if (drv->bdrv_co_writev) {
8944df863f3SEric Blake         assert(!bs->supported_write_flags);
89578a07294SKevin Wolf         ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov);
89608844473SKevin Wolf     } else {
89708844473SKevin Wolf         BlockAIOCB *acb;
89808844473SKevin Wolf         CoroutineIOCompletion co = {
89908844473SKevin Wolf             .coroutine = qemu_coroutine_self(),
90008844473SKevin Wolf         };
90108844473SKevin Wolf 
90208844473SKevin Wolf         acb = bs->drv->bdrv_aio_writev(bs, sector_num, qiov, nb_sectors,
90308844473SKevin Wolf                                        bdrv_co_io_em_complete, &co);
90408844473SKevin Wolf         if (acb == NULL) {
9053fb06697SKevin Wolf             ret = -EIO;
90608844473SKevin Wolf         } else {
90708844473SKevin Wolf             qemu_coroutine_yield();
9083fb06697SKevin Wolf             ret = co.ret;
90908844473SKevin Wolf         }
91078a07294SKevin Wolf     }
91178a07294SKevin Wolf 
9123fb06697SKevin Wolf emulate_flags:
9134df863f3SEric Blake     if (ret == 0 && (flags & BDRV_REQ_FUA)) {
91478a07294SKevin Wolf         ret = bdrv_co_flush(bs);
91578a07294SKevin Wolf     }
91678a07294SKevin Wolf 
91778a07294SKevin Wolf     return ret;
91878a07294SKevin Wolf }
91978a07294SKevin Wolf 
92029a298afSPavel Butsykin static int coroutine_fn
92129a298afSPavel Butsykin bdrv_driver_pwritev_compressed(BlockDriverState *bs, uint64_t offset,
92229a298afSPavel Butsykin                                uint64_t bytes, QEMUIOVector *qiov)
92329a298afSPavel Butsykin {
92429a298afSPavel Butsykin     BlockDriver *drv = bs->drv;
92529a298afSPavel Butsykin 
92629a298afSPavel Butsykin     if (!drv->bdrv_co_pwritev_compressed) {
92729a298afSPavel Butsykin         return -ENOTSUP;
92829a298afSPavel Butsykin     }
92929a298afSPavel Butsykin 
93029a298afSPavel Butsykin     return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
93129a298afSPavel Butsykin }
93229a298afSPavel Butsykin 
93385c97ca7SKevin Wolf static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
934244483e6SKevin Wolf         int64_t offset, unsigned int bytes, QEMUIOVector *qiov)
93561007b31SStefan Hajnoczi {
93685c97ca7SKevin Wolf     BlockDriverState *bs = child->bs;
93785c97ca7SKevin Wolf 
93861007b31SStefan Hajnoczi     /* Perform I/O through a temporary buffer so that users who scribble over
93961007b31SStefan Hajnoczi      * their read buffer while the operation is in progress do not end up
94061007b31SStefan Hajnoczi      * modifying the image file.  This is critical for zero-copy guest I/O
94161007b31SStefan Hajnoczi      * where anything might happen inside guest memory.
94261007b31SStefan Hajnoczi      */
94361007b31SStefan Hajnoczi     void *bounce_buffer;
94461007b31SStefan Hajnoczi 
94561007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
94661007b31SStefan Hajnoczi     struct iovec iov;
94761007b31SStefan Hajnoczi     QEMUIOVector bounce_qiov;
948244483e6SKevin Wolf     int64_t cluster_offset;
949244483e6SKevin Wolf     unsigned int cluster_bytes;
95061007b31SStefan Hajnoczi     size_t skip_bytes;
95161007b31SStefan Hajnoczi     int ret;
95261007b31SStefan Hajnoczi 
9531bf03e66SKevin Wolf     /* FIXME We cannot require callers to have write permissions when all they
9541bf03e66SKevin Wolf      * are doing is a read request. If we did things right, write permissions
9551bf03e66SKevin Wolf      * would be obtained anyway, but internally by the copy-on-read code. As
9561bf03e66SKevin Wolf      * long as it is implemented here rather than in a separat filter driver,
9571bf03e66SKevin Wolf      * the copy-on-read code doesn't have its own BdrvChild, however, for which
9581bf03e66SKevin Wolf      * it could request permissions. Therefore we have to bypass the permission
9591bf03e66SKevin Wolf      * system for the moment. */
9601bf03e66SKevin Wolf     // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
961afa4b293SKevin Wolf 
96261007b31SStefan Hajnoczi     /* Cover entire cluster so no additional backing file I/O is required when
96361007b31SStefan Hajnoczi      * allocating cluster in the image file.
96461007b31SStefan Hajnoczi      */
965244483e6SKevin Wolf     bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
96661007b31SStefan Hajnoczi 
967244483e6SKevin Wolf     trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
968244483e6SKevin Wolf                                    cluster_offset, cluster_bytes);
96961007b31SStefan Hajnoczi 
970244483e6SKevin Wolf     iov.iov_len = cluster_bytes;
97161007b31SStefan Hajnoczi     iov.iov_base = bounce_buffer = qemu_try_blockalign(bs, iov.iov_len);
97261007b31SStefan Hajnoczi     if (bounce_buffer == NULL) {
97361007b31SStefan Hajnoczi         ret = -ENOMEM;
97461007b31SStefan Hajnoczi         goto err;
97561007b31SStefan Hajnoczi     }
97661007b31SStefan Hajnoczi 
97761007b31SStefan Hajnoczi     qemu_iovec_init_external(&bounce_qiov, &iov, 1);
97861007b31SStefan Hajnoczi 
979244483e6SKevin Wolf     ret = bdrv_driver_preadv(bs, cluster_offset, cluster_bytes,
980166fe960SKevin Wolf                              &bounce_qiov, 0);
98161007b31SStefan Hajnoczi     if (ret < 0) {
98261007b31SStefan Hajnoczi         goto err;
98361007b31SStefan Hajnoczi     }
98461007b31SStefan Hajnoczi 
985c1499a5eSEric Blake     if (drv->bdrv_co_pwrite_zeroes &&
98661007b31SStefan Hajnoczi         buffer_is_zero(bounce_buffer, iov.iov_len)) {
987a604fa2bSEric Blake         /* FIXME: Should we (perhaps conditionally) be setting
988a604fa2bSEric Blake          * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
989a604fa2bSEric Blake          * that still correctly reads as zero? */
990244483e6SKevin Wolf         ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, cluster_bytes, 0);
99161007b31SStefan Hajnoczi     } else {
99261007b31SStefan Hajnoczi         /* This does not change the data on the disk, it is not necessary
99361007b31SStefan Hajnoczi          * to flush even in cache=writethrough mode.
99461007b31SStefan Hajnoczi          */
995244483e6SKevin Wolf         ret = bdrv_driver_pwritev(bs, cluster_offset, cluster_bytes,
99678a07294SKevin Wolf                                   &bounce_qiov, 0);
99761007b31SStefan Hajnoczi     }
99861007b31SStefan Hajnoczi 
99961007b31SStefan Hajnoczi     if (ret < 0) {
100061007b31SStefan Hajnoczi         /* It might be okay to ignore write errors for guest requests.  If this
100161007b31SStefan Hajnoczi          * is a deliberate copy-on-read then we don't want to ignore the error.
100261007b31SStefan Hajnoczi          * Simply report it in all cases.
100361007b31SStefan Hajnoczi          */
100461007b31SStefan Hajnoczi         goto err;
100561007b31SStefan Hajnoczi     }
100661007b31SStefan Hajnoczi 
1007244483e6SKevin Wolf     skip_bytes = offset - cluster_offset;
1008244483e6SKevin Wolf     qemu_iovec_from_buf(qiov, 0, bounce_buffer + skip_bytes, bytes);
100961007b31SStefan Hajnoczi 
101061007b31SStefan Hajnoczi err:
101161007b31SStefan Hajnoczi     qemu_vfree(bounce_buffer);
101261007b31SStefan Hajnoczi     return ret;
101361007b31SStefan Hajnoczi }
101461007b31SStefan Hajnoczi 
101561007b31SStefan Hajnoczi /*
101661007b31SStefan Hajnoczi  * Forwards an already correctly aligned request to the BlockDriver. This
10171a62d0acSEric Blake  * handles copy on read, zeroing after EOF, and fragmentation of large
10181a62d0acSEric Blake  * reads; any other features must be implemented by the caller.
101961007b31SStefan Hajnoczi  */
102085c97ca7SKevin Wolf static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
102161007b31SStefan Hajnoczi     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
102261007b31SStefan Hajnoczi     int64_t align, QEMUIOVector *qiov, int flags)
102361007b31SStefan Hajnoczi {
102485c97ca7SKevin Wolf     BlockDriverState *bs = child->bs;
1025c9d20029SKevin Wolf     int64_t total_bytes, max_bytes;
10261a62d0acSEric Blake     int ret = 0;
10271a62d0acSEric Blake     uint64_t bytes_remaining = bytes;
10281a62d0acSEric Blake     int max_transfer;
102961007b31SStefan Hajnoczi 
103049c07526SKevin Wolf     assert(is_power_of_2(align));
103149c07526SKevin Wolf     assert((offset & (align - 1)) == 0);
103249c07526SKevin Wolf     assert((bytes & (align - 1)) == 0);
103361007b31SStefan Hajnoczi     assert(!qiov || bytes == qiov->size);
1034abb06c5aSDaniel P. Berrange     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
10351a62d0acSEric Blake     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
10361a62d0acSEric Blake                                    align);
1037a604fa2bSEric Blake 
1038a604fa2bSEric Blake     /* TODO: We would need a per-BDS .supported_read_flags and
1039a604fa2bSEric Blake      * potential fallback support, if we ever implement any read flags
1040a604fa2bSEric Blake      * to pass through to drivers.  For now, there aren't any
1041a604fa2bSEric Blake      * passthrough flags.  */
1042a604fa2bSEric Blake     assert(!(flags & ~(BDRV_REQ_NO_SERIALISING | BDRV_REQ_COPY_ON_READ)));
104361007b31SStefan Hajnoczi 
104461007b31SStefan Hajnoczi     /* Handle Copy on Read and associated serialisation */
104561007b31SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
104661007b31SStefan Hajnoczi         /* If we touch the same cluster it counts as an overlap.  This
104761007b31SStefan Hajnoczi          * guarantees that allocating writes will be serialized and not race
104861007b31SStefan Hajnoczi          * with each other for the same cluster.  For example, in copy-on-read
104961007b31SStefan Hajnoczi          * it ensures that the CoR read and write operations are atomic and
105061007b31SStefan Hajnoczi          * guest writes cannot interleave between them. */
105161007b31SStefan Hajnoczi         mark_request_serialising(req, bdrv_get_cluster_size(bs));
105261007b31SStefan Hajnoczi     }
105361007b31SStefan Hajnoczi 
105461408b25SFam Zheng     if (!(flags & BDRV_REQ_NO_SERIALISING)) {
105561007b31SStefan Hajnoczi         wait_serialising_requests(req);
105661408b25SFam Zheng     }
105761007b31SStefan Hajnoczi 
105861007b31SStefan Hajnoczi     if (flags & BDRV_REQ_COPY_ON_READ) {
105949c07526SKevin Wolf         int64_t start_sector = offset >> BDRV_SECTOR_BITS;
106049c07526SKevin Wolf         int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
106149c07526SKevin Wolf         unsigned int nb_sectors = end_sector - start_sector;
106261007b31SStefan Hajnoczi         int pnum;
106361007b31SStefan Hajnoczi 
106449c07526SKevin Wolf         ret = bdrv_is_allocated(bs, start_sector, nb_sectors, &pnum);
106561007b31SStefan Hajnoczi         if (ret < 0) {
106661007b31SStefan Hajnoczi             goto out;
106761007b31SStefan Hajnoczi         }
106861007b31SStefan Hajnoczi 
106961007b31SStefan Hajnoczi         if (!ret || pnum != nb_sectors) {
107085c97ca7SKevin Wolf             ret = bdrv_co_do_copy_on_readv(child, offset, bytes, qiov);
107161007b31SStefan Hajnoczi             goto out;
107261007b31SStefan Hajnoczi         }
107361007b31SStefan Hajnoczi     }
107461007b31SStefan Hajnoczi 
10751a62d0acSEric Blake     /* Forward the request to the BlockDriver, possibly fragmenting it */
107649c07526SKevin Wolf     total_bytes = bdrv_getlength(bs);
107749c07526SKevin Wolf     if (total_bytes < 0) {
107849c07526SKevin Wolf         ret = total_bytes;
107961007b31SStefan Hajnoczi         goto out;
108061007b31SStefan Hajnoczi     }
108161007b31SStefan Hajnoczi 
108249c07526SKevin Wolf     max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
10831a62d0acSEric Blake     if (bytes <= max_bytes && bytes <= max_transfer) {
1084166fe960SKevin Wolf         ret = bdrv_driver_preadv(bs, offset, bytes, qiov, 0);
10851a62d0acSEric Blake         goto out;
108661007b31SStefan Hajnoczi     }
108761007b31SStefan Hajnoczi 
10881a62d0acSEric Blake     while (bytes_remaining) {
10891a62d0acSEric Blake         int num;
10901a62d0acSEric Blake 
10911a62d0acSEric Blake         if (max_bytes) {
10921a62d0acSEric Blake             QEMUIOVector local_qiov;
10931a62d0acSEric Blake 
10941a62d0acSEric Blake             num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
10951a62d0acSEric Blake             assert(num);
10961a62d0acSEric Blake             qemu_iovec_init(&local_qiov, qiov->niov);
10971a62d0acSEric Blake             qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
10981a62d0acSEric Blake 
10991a62d0acSEric Blake             ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
11001a62d0acSEric Blake                                      num, &local_qiov, 0);
11011a62d0acSEric Blake             max_bytes -= num;
11021a62d0acSEric Blake             qemu_iovec_destroy(&local_qiov);
11031a62d0acSEric Blake         } else {
11041a62d0acSEric Blake             num = bytes_remaining;
11051a62d0acSEric Blake             ret = qemu_iovec_memset(qiov, bytes - bytes_remaining, 0,
11061a62d0acSEric Blake                                     bytes_remaining);
11071a62d0acSEric Blake         }
11081a62d0acSEric Blake         if (ret < 0) {
11091a62d0acSEric Blake             goto out;
11101a62d0acSEric Blake         }
11111a62d0acSEric Blake         bytes_remaining -= num;
111261007b31SStefan Hajnoczi     }
111361007b31SStefan Hajnoczi 
111461007b31SStefan Hajnoczi out:
11151a62d0acSEric Blake     return ret < 0 ? ret : 0;
111661007b31SStefan Hajnoczi }
111761007b31SStefan Hajnoczi 
111861007b31SStefan Hajnoczi /*
111961007b31SStefan Hajnoczi  * Handle a read request in coroutine context
112061007b31SStefan Hajnoczi  */
1121a03ef88fSKevin Wolf int coroutine_fn bdrv_co_preadv(BdrvChild *child,
112261007b31SStefan Hajnoczi     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
112361007b31SStefan Hajnoczi     BdrvRequestFlags flags)
112461007b31SStefan Hajnoczi {
1125a03ef88fSKevin Wolf     BlockDriverState *bs = child->bs;
112661007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
112761007b31SStefan Hajnoczi     BdrvTrackedRequest req;
112861007b31SStefan Hajnoczi 
1129a5b8dd2cSEric Blake     uint64_t align = bs->bl.request_alignment;
113061007b31SStefan Hajnoczi     uint8_t *head_buf = NULL;
113161007b31SStefan Hajnoczi     uint8_t *tail_buf = NULL;
113261007b31SStefan Hajnoczi     QEMUIOVector local_qiov;
113361007b31SStefan Hajnoczi     bool use_local_qiov = false;
113461007b31SStefan Hajnoczi     int ret;
113561007b31SStefan Hajnoczi 
113661007b31SStefan Hajnoczi     if (!drv) {
113761007b31SStefan Hajnoczi         return -ENOMEDIUM;
113861007b31SStefan Hajnoczi     }
113961007b31SStefan Hajnoczi 
114061007b31SStefan Hajnoczi     ret = bdrv_check_byte_request(bs, offset, bytes);
114161007b31SStefan Hajnoczi     if (ret < 0) {
114261007b31SStefan Hajnoczi         return ret;
114361007b31SStefan Hajnoczi     }
114461007b31SStefan Hajnoczi 
114599723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
114699723548SPaolo Bonzini 
11479568b511SWen Congyang     /* Don't do copy-on-read if we read data before write operation */
1148d3faa13eSPaolo Bonzini     if (atomic_read(&bs->copy_on_read) && !(flags & BDRV_REQ_NO_SERIALISING)) {
114961007b31SStefan Hajnoczi         flags |= BDRV_REQ_COPY_ON_READ;
115061007b31SStefan Hajnoczi     }
115161007b31SStefan Hajnoczi 
115261007b31SStefan Hajnoczi     /* Align read if necessary by padding qiov */
115361007b31SStefan Hajnoczi     if (offset & (align - 1)) {
115461007b31SStefan Hajnoczi         head_buf = qemu_blockalign(bs, align);
115561007b31SStefan Hajnoczi         qemu_iovec_init(&local_qiov, qiov->niov + 2);
115661007b31SStefan Hajnoczi         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
115761007b31SStefan Hajnoczi         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
115861007b31SStefan Hajnoczi         use_local_qiov = true;
115961007b31SStefan Hajnoczi 
116061007b31SStefan Hajnoczi         bytes += offset & (align - 1);
116161007b31SStefan Hajnoczi         offset = offset & ~(align - 1);
116261007b31SStefan Hajnoczi     }
116361007b31SStefan Hajnoczi 
116461007b31SStefan Hajnoczi     if ((offset + bytes) & (align - 1)) {
116561007b31SStefan Hajnoczi         if (!use_local_qiov) {
116661007b31SStefan Hajnoczi             qemu_iovec_init(&local_qiov, qiov->niov + 1);
116761007b31SStefan Hajnoczi             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
116861007b31SStefan Hajnoczi             use_local_qiov = true;
116961007b31SStefan Hajnoczi         }
117061007b31SStefan Hajnoczi         tail_buf = qemu_blockalign(bs, align);
117161007b31SStefan Hajnoczi         qemu_iovec_add(&local_qiov, tail_buf,
117261007b31SStefan Hajnoczi                        align - ((offset + bytes) & (align - 1)));
117361007b31SStefan Hajnoczi 
117461007b31SStefan Hajnoczi         bytes = ROUND_UP(bytes, align);
117561007b31SStefan Hajnoczi     }
117661007b31SStefan Hajnoczi 
1177ebde595cSFam Zheng     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
117885c97ca7SKevin Wolf     ret = bdrv_aligned_preadv(child, &req, offset, bytes, align,
117961007b31SStefan Hajnoczi                               use_local_qiov ? &local_qiov : qiov,
118061007b31SStefan Hajnoczi                               flags);
118161007b31SStefan Hajnoczi     tracked_request_end(&req);
118299723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
118361007b31SStefan Hajnoczi 
118461007b31SStefan Hajnoczi     if (use_local_qiov) {
118561007b31SStefan Hajnoczi         qemu_iovec_destroy(&local_qiov);
118661007b31SStefan Hajnoczi         qemu_vfree(head_buf);
118761007b31SStefan Hajnoczi         qemu_vfree(tail_buf);
118861007b31SStefan Hajnoczi     }
118961007b31SStefan Hajnoczi 
119061007b31SStefan Hajnoczi     return ret;
119161007b31SStefan Hajnoczi }
119261007b31SStefan Hajnoczi 
1193adad6496SKevin Wolf static int coroutine_fn bdrv_co_do_readv(BdrvChild *child,
119461007b31SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
119561007b31SStefan Hajnoczi     BdrvRequestFlags flags)
119661007b31SStefan Hajnoczi {
119761007b31SStefan Hajnoczi     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
119861007b31SStefan Hajnoczi         return -EINVAL;
119961007b31SStefan Hajnoczi     }
120061007b31SStefan Hajnoczi 
1201a03ef88fSKevin Wolf     return bdrv_co_preadv(child, sector_num << BDRV_SECTOR_BITS,
120261007b31SStefan Hajnoczi                           nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
120361007b31SStefan Hajnoczi }
120461007b31SStefan Hajnoczi 
120528b04a8fSKevin Wolf int coroutine_fn bdrv_co_readv(BdrvChild *child, int64_t sector_num,
120661007b31SStefan Hajnoczi                                int nb_sectors, QEMUIOVector *qiov)
120761007b31SStefan Hajnoczi {
120828b04a8fSKevin Wolf     trace_bdrv_co_readv(child->bs, sector_num, nb_sectors);
120961007b31SStefan Hajnoczi 
1210adad6496SKevin Wolf     return bdrv_co_do_readv(child, sector_num, nb_sectors, qiov, 0);
121161007b31SStefan Hajnoczi }
121261007b31SStefan Hajnoczi 
12135def6b80SEric Blake /* Maximum buffer for write zeroes fallback, in bytes */
12145def6b80SEric Blake #define MAX_WRITE_ZEROES_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
121561007b31SStefan Hajnoczi 
1216d05aa8bbSEric Blake static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1217d05aa8bbSEric Blake     int64_t offset, int count, BdrvRequestFlags flags)
121861007b31SStefan Hajnoczi {
121961007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
122061007b31SStefan Hajnoczi     QEMUIOVector qiov;
122161007b31SStefan Hajnoczi     struct iovec iov = {0};
122261007b31SStefan Hajnoczi     int ret = 0;
1223465fe887SEric Blake     bool need_flush = false;
1224443668caSDenis V. Lunev     int head = 0;
1225443668caSDenis V. Lunev     int tail = 0;
122661007b31SStefan Hajnoczi 
1227cf081fcaSEric Blake     int max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes, INT_MAX);
1228a5b8dd2cSEric Blake     int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1229a5b8dd2cSEric Blake                         bs->bl.request_alignment);
1230b2f95feeSEric Blake     int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1231b2f95feeSEric Blake                                     MAX_WRITE_ZEROES_BOUNCE_BUFFER);
1232cf081fcaSEric Blake 
1233b8d0a980SEric Blake     assert(alignment % bs->bl.request_alignment == 0);
1234b8d0a980SEric Blake     head = offset % alignment;
1235b8d0a980SEric Blake     tail = (offset + count) % alignment;
1236b8d0a980SEric Blake     max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1237b8d0a980SEric Blake     assert(max_write_zeroes >= bs->bl.request_alignment);
123861007b31SStefan Hajnoczi 
1239d05aa8bbSEric Blake     while (count > 0 && !ret) {
1240d05aa8bbSEric Blake         int num = count;
124161007b31SStefan Hajnoczi 
124261007b31SStefan Hajnoczi         /* Align request.  Block drivers can expect the "bulk" of the request
1243443668caSDenis V. Lunev          * to be aligned, and that unaligned requests do not cross cluster
1244443668caSDenis V. Lunev          * boundaries.
124561007b31SStefan Hajnoczi          */
1246443668caSDenis V. Lunev         if (head) {
1247b2f95feeSEric Blake             /* Make a small request up to the first aligned sector. For
1248b2f95feeSEric Blake              * convenience, limit this request to max_transfer even if
1249b2f95feeSEric Blake              * we don't need to fall back to writes.  */
1250b2f95feeSEric Blake             num = MIN(MIN(count, max_transfer), alignment - head);
1251b2f95feeSEric Blake             head = (head + num) % alignment;
1252b2f95feeSEric Blake             assert(num < max_write_zeroes);
1253d05aa8bbSEric Blake         } else if (tail && num > alignment) {
1254443668caSDenis V. Lunev             /* Shorten the request to the last aligned sector.  */
1255443668caSDenis V. Lunev             num -= tail;
125661007b31SStefan Hajnoczi         }
125761007b31SStefan Hajnoczi 
125861007b31SStefan Hajnoczi         /* limit request size */
125961007b31SStefan Hajnoczi         if (num > max_write_zeroes) {
126061007b31SStefan Hajnoczi             num = max_write_zeroes;
126161007b31SStefan Hajnoczi         }
126261007b31SStefan Hajnoczi 
126361007b31SStefan Hajnoczi         ret = -ENOTSUP;
126461007b31SStefan Hajnoczi         /* First try the efficient write zeroes operation */
1265d05aa8bbSEric Blake         if (drv->bdrv_co_pwrite_zeroes) {
1266d05aa8bbSEric Blake             ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1267d05aa8bbSEric Blake                                              flags & bs->supported_zero_flags);
1268d05aa8bbSEric Blake             if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1269d05aa8bbSEric Blake                 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1270d05aa8bbSEric Blake                 need_flush = true;
1271d05aa8bbSEric Blake             }
1272465fe887SEric Blake         } else {
1273465fe887SEric Blake             assert(!bs->supported_zero_flags);
127461007b31SStefan Hajnoczi         }
127561007b31SStefan Hajnoczi 
127661007b31SStefan Hajnoczi         if (ret == -ENOTSUP) {
127761007b31SStefan Hajnoczi             /* Fall back to bounce buffer if write zeroes is unsupported */
1278465fe887SEric Blake             BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1279465fe887SEric Blake 
1280465fe887SEric Blake             if ((flags & BDRV_REQ_FUA) &&
1281465fe887SEric Blake                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1282465fe887SEric Blake                 /* No need for bdrv_driver_pwrite() to do a fallback
1283465fe887SEric Blake                  * flush on each chunk; use just one at the end */
1284465fe887SEric Blake                 write_flags &= ~BDRV_REQ_FUA;
1285465fe887SEric Blake                 need_flush = true;
1286465fe887SEric Blake             }
12875def6b80SEric Blake             num = MIN(num, max_transfer);
1288d05aa8bbSEric Blake             iov.iov_len = num;
128961007b31SStefan Hajnoczi             if (iov.iov_base == NULL) {
1290d05aa8bbSEric Blake                 iov.iov_base = qemu_try_blockalign(bs, num);
129161007b31SStefan Hajnoczi                 if (iov.iov_base == NULL) {
129261007b31SStefan Hajnoczi                     ret = -ENOMEM;
129361007b31SStefan Hajnoczi                     goto fail;
129461007b31SStefan Hajnoczi                 }
1295d05aa8bbSEric Blake                 memset(iov.iov_base, 0, num);
129661007b31SStefan Hajnoczi             }
129761007b31SStefan Hajnoczi             qemu_iovec_init_external(&qiov, &iov, 1);
129861007b31SStefan Hajnoczi 
1299d05aa8bbSEric Blake             ret = bdrv_driver_pwritev(bs, offset, num, &qiov, write_flags);
130061007b31SStefan Hajnoczi 
130161007b31SStefan Hajnoczi             /* Keep bounce buffer around if it is big enough for all
130261007b31SStefan Hajnoczi              * all future requests.
130361007b31SStefan Hajnoczi              */
13045def6b80SEric Blake             if (num < max_transfer) {
130561007b31SStefan Hajnoczi                 qemu_vfree(iov.iov_base);
130661007b31SStefan Hajnoczi                 iov.iov_base = NULL;
130761007b31SStefan Hajnoczi             }
130861007b31SStefan Hajnoczi         }
130961007b31SStefan Hajnoczi 
1310d05aa8bbSEric Blake         offset += num;
1311d05aa8bbSEric Blake         count -= num;
131261007b31SStefan Hajnoczi     }
131361007b31SStefan Hajnoczi 
131461007b31SStefan Hajnoczi fail:
1315465fe887SEric Blake     if (ret == 0 && need_flush) {
1316465fe887SEric Blake         ret = bdrv_co_flush(bs);
1317465fe887SEric Blake     }
131861007b31SStefan Hajnoczi     qemu_vfree(iov.iov_base);
131961007b31SStefan Hajnoczi     return ret;
132061007b31SStefan Hajnoczi }
132161007b31SStefan Hajnoczi 
132261007b31SStefan Hajnoczi /*
132304ed95f4SEric Blake  * Forwards an already correctly aligned write request to the BlockDriver,
132404ed95f4SEric Blake  * after possibly fragmenting it.
132561007b31SStefan Hajnoczi  */
132685c97ca7SKevin Wolf static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
132761007b31SStefan Hajnoczi     BdrvTrackedRequest *req, int64_t offset, unsigned int bytes,
1328cff86b38SEric Blake     int64_t align, QEMUIOVector *qiov, int flags)
132961007b31SStefan Hajnoczi {
133085c97ca7SKevin Wolf     BlockDriverState *bs = child->bs;
133161007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
133261007b31SStefan Hajnoczi     bool waited;
133361007b31SStefan Hajnoczi     int ret;
133461007b31SStefan Hajnoczi 
13359896c876SKevin Wolf     int64_t start_sector = offset >> BDRV_SECTOR_BITS;
13369896c876SKevin Wolf     int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
133704ed95f4SEric Blake     uint64_t bytes_remaining = bytes;
133804ed95f4SEric Blake     int max_transfer;
133961007b31SStefan Hajnoczi 
1340cff86b38SEric Blake     assert(is_power_of_2(align));
1341cff86b38SEric Blake     assert((offset & (align - 1)) == 0);
1342cff86b38SEric Blake     assert((bytes & (align - 1)) == 0);
134361007b31SStefan Hajnoczi     assert(!qiov || bytes == qiov->size);
1344abb06c5aSDaniel P. Berrange     assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1345fa166538SEric Blake     assert(!(flags & ~BDRV_REQ_MASK));
134604ed95f4SEric Blake     max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
134704ed95f4SEric Blake                                    align);
134861007b31SStefan Hajnoczi 
134961007b31SStefan Hajnoczi     waited = wait_serialising_requests(req);
135061007b31SStefan Hajnoczi     assert(!waited || !req->serialising);
135161007b31SStefan Hajnoczi     assert(req->overlap_offset <= offset);
135261007b31SStefan Hajnoczi     assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
1353362b3786SMax Reitz     assert(child->perm & BLK_PERM_WRITE);
1354362b3786SMax Reitz     assert(end_sector <= bs->total_sectors || child->perm & BLK_PERM_RESIZE);
135561007b31SStefan Hajnoczi 
135661007b31SStefan Hajnoczi     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, req);
135761007b31SStefan Hajnoczi 
135861007b31SStefan Hajnoczi     if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
1359c1499a5eSEric Blake         !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
136061007b31SStefan Hajnoczi         qemu_iovec_is_zero(qiov)) {
136161007b31SStefan Hajnoczi         flags |= BDRV_REQ_ZERO_WRITE;
136261007b31SStefan Hajnoczi         if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
136361007b31SStefan Hajnoczi             flags |= BDRV_REQ_MAY_UNMAP;
136461007b31SStefan Hajnoczi         }
136561007b31SStefan Hajnoczi     }
136661007b31SStefan Hajnoczi 
136761007b31SStefan Hajnoczi     if (ret < 0) {
136861007b31SStefan Hajnoczi         /* Do nothing, write notifier decided to fail this request */
136961007b31SStefan Hajnoczi     } else if (flags & BDRV_REQ_ZERO_WRITE) {
13709a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
13719896c876SKevin Wolf         ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
13723ea1a091SPavel Butsykin     } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
13733ea1a091SPavel Butsykin         ret = bdrv_driver_pwritev_compressed(bs, offset, bytes, qiov);
137404ed95f4SEric Blake     } else if (bytes <= max_transfer) {
13759a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV);
137678a07294SKevin Wolf         ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, flags);
137704ed95f4SEric Blake     } else {
137804ed95f4SEric Blake         bdrv_debug_event(bs, BLKDBG_PWRITEV);
137904ed95f4SEric Blake         while (bytes_remaining) {
138004ed95f4SEric Blake             int num = MIN(bytes_remaining, max_transfer);
138104ed95f4SEric Blake             QEMUIOVector local_qiov;
138204ed95f4SEric Blake             int local_flags = flags;
138304ed95f4SEric Blake 
138404ed95f4SEric Blake             assert(num);
138504ed95f4SEric Blake             if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
138604ed95f4SEric Blake                 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
138704ed95f4SEric Blake                 /* If FUA is going to be emulated by flush, we only
138804ed95f4SEric Blake                  * need to flush on the last iteration */
138904ed95f4SEric Blake                 local_flags &= ~BDRV_REQ_FUA;
139004ed95f4SEric Blake             }
139104ed95f4SEric Blake             qemu_iovec_init(&local_qiov, qiov->niov);
139204ed95f4SEric Blake             qemu_iovec_concat(&local_qiov, qiov, bytes - bytes_remaining, num);
139304ed95f4SEric Blake 
139404ed95f4SEric Blake             ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
139504ed95f4SEric Blake                                       num, &local_qiov, local_flags);
139604ed95f4SEric Blake             qemu_iovec_destroy(&local_qiov);
139704ed95f4SEric Blake             if (ret < 0) {
139804ed95f4SEric Blake                 break;
139904ed95f4SEric Blake             }
140004ed95f4SEric Blake             bytes_remaining -= num;
140104ed95f4SEric Blake         }
140261007b31SStefan Hajnoczi     }
14039a4f4c31SKevin Wolf     bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
140461007b31SStefan Hajnoczi 
14053ff2f67aSEvgeny Yakovlev     ++bs->write_gen;
14069896c876SKevin Wolf     bdrv_set_dirty(bs, start_sector, end_sector - start_sector);
140761007b31SStefan Hajnoczi 
140853d8f9d8SMax Reitz     if (bs->wr_highest_offset < offset + bytes) {
140953d8f9d8SMax Reitz         bs->wr_highest_offset = offset + bytes;
141053d8f9d8SMax Reitz     }
141161007b31SStefan Hajnoczi 
141261007b31SStefan Hajnoczi     if (ret >= 0) {
14139896c876SKevin Wolf         bs->total_sectors = MAX(bs->total_sectors, end_sector);
141404ed95f4SEric Blake         ret = 0;
141561007b31SStefan Hajnoczi     }
141661007b31SStefan Hajnoczi 
141761007b31SStefan Hajnoczi     return ret;
141861007b31SStefan Hajnoczi }
141961007b31SStefan Hajnoczi 
142085c97ca7SKevin Wolf static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
14219eeb6dd1SFam Zheng                                                 int64_t offset,
14229eeb6dd1SFam Zheng                                                 unsigned int bytes,
14239eeb6dd1SFam Zheng                                                 BdrvRequestFlags flags,
14249eeb6dd1SFam Zheng                                                 BdrvTrackedRequest *req)
14259eeb6dd1SFam Zheng {
142685c97ca7SKevin Wolf     BlockDriverState *bs = child->bs;
14279eeb6dd1SFam Zheng     uint8_t *buf = NULL;
14289eeb6dd1SFam Zheng     QEMUIOVector local_qiov;
14299eeb6dd1SFam Zheng     struct iovec iov;
1430a5b8dd2cSEric Blake     uint64_t align = bs->bl.request_alignment;
14319eeb6dd1SFam Zheng     unsigned int head_padding_bytes, tail_padding_bytes;
14329eeb6dd1SFam Zheng     int ret = 0;
14339eeb6dd1SFam Zheng 
14349eeb6dd1SFam Zheng     head_padding_bytes = offset & (align - 1);
1435f13ce1beSDenis V. Lunev     tail_padding_bytes = (align - (offset + bytes)) & (align - 1);
14369eeb6dd1SFam Zheng 
14379eeb6dd1SFam Zheng 
14389eeb6dd1SFam Zheng     assert(flags & BDRV_REQ_ZERO_WRITE);
14399eeb6dd1SFam Zheng     if (head_padding_bytes || tail_padding_bytes) {
14409eeb6dd1SFam Zheng         buf = qemu_blockalign(bs, align);
14419eeb6dd1SFam Zheng         iov = (struct iovec) {
14429eeb6dd1SFam Zheng             .iov_base   = buf,
14439eeb6dd1SFam Zheng             .iov_len    = align,
14449eeb6dd1SFam Zheng         };
14459eeb6dd1SFam Zheng         qemu_iovec_init_external(&local_qiov, &iov, 1);
14469eeb6dd1SFam Zheng     }
14479eeb6dd1SFam Zheng     if (head_padding_bytes) {
14489eeb6dd1SFam Zheng         uint64_t zero_bytes = MIN(bytes, align - head_padding_bytes);
14499eeb6dd1SFam Zheng 
14509eeb6dd1SFam Zheng         /* RMW the unaligned part before head. */
14519eeb6dd1SFam Zheng         mark_request_serialising(req, align);
14529eeb6dd1SFam Zheng         wait_serialising_requests(req);
14539a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
145485c97ca7SKevin Wolf         ret = bdrv_aligned_preadv(child, req, offset & ~(align - 1), align,
14559eeb6dd1SFam Zheng                                   align, &local_qiov, 0);
14569eeb6dd1SFam Zheng         if (ret < 0) {
14579eeb6dd1SFam Zheng             goto fail;
14589eeb6dd1SFam Zheng         }
14599a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
14609eeb6dd1SFam Zheng 
14619eeb6dd1SFam Zheng         memset(buf + head_padding_bytes, 0, zero_bytes);
146285c97ca7SKevin Wolf         ret = bdrv_aligned_pwritev(child, req, offset & ~(align - 1), align,
1463cff86b38SEric Blake                                    align, &local_qiov,
14649eeb6dd1SFam Zheng                                    flags & ~BDRV_REQ_ZERO_WRITE);
14659eeb6dd1SFam Zheng         if (ret < 0) {
14669eeb6dd1SFam Zheng             goto fail;
14679eeb6dd1SFam Zheng         }
14689eeb6dd1SFam Zheng         offset += zero_bytes;
14699eeb6dd1SFam Zheng         bytes -= zero_bytes;
14709eeb6dd1SFam Zheng     }
14719eeb6dd1SFam Zheng 
14729eeb6dd1SFam Zheng     assert(!bytes || (offset & (align - 1)) == 0);
14739eeb6dd1SFam Zheng     if (bytes >= align) {
14749eeb6dd1SFam Zheng         /* Write the aligned part in the middle. */
14759eeb6dd1SFam Zheng         uint64_t aligned_bytes = bytes & ~(align - 1);
147685c97ca7SKevin Wolf         ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
14779eeb6dd1SFam Zheng                                    NULL, flags);
14789eeb6dd1SFam Zheng         if (ret < 0) {
14799eeb6dd1SFam Zheng             goto fail;
14809eeb6dd1SFam Zheng         }
14819eeb6dd1SFam Zheng         bytes -= aligned_bytes;
14829eeb6dd1SFam Zheng         offset += aligned_bytes;
14839eeb6dd1SFam Zheng     }
14849eeb6dd1SFam Zheng 
14859eeb6dd1SFam Zheng     assert(!bytes || (offset & (align - 1)) == 0);
14869eeb6dd1SFam Zheng     if (bytes) {
14879eeb6dd1SFam Zheng         assert(align == tail_padding_bytes + bytes);
14889eeb6dd1SFam Zheng         /* RMW the unaligned part after tail. */
14899eeb6dd1SFam Zheng         mark_request_serialising(req, align);
14909eeb6dd1SFam Zheng         wait_serialising_requests(req);
14919a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
149285c97ca7SKevin Wolf         ret = bdrv_aligned_preadv(child, req, offset, align,
14939eeb6dd1SFam Zheng                                   align, &local_qiov, 0);
14949eeb6dd1SFam Zheng         if (ret < 0) {
14959eeb6dd1SFam Zheng             goto fail;
14969eeb6dd1SFam Zheng         }
14979a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
14989eeb6dd1SFam Zheng 
14999eeb6dd1SFam Zheng         memset(buf, 0, bytes);
150085c97ca7SKevin Wolf         ret = bdrv_aligned_pwritev(child, req, offset, align, align,
15019eeb6dd1SFam Zheng                                    &local_qiov, flags & ~BDRV_REQ_ZERO_WRITE);
15029eeb6dd1SFam Zheng     }
15039eeb6dd1SFam Zheng fail:
15049eeb6dd1SFam Zheng     qemu_vfree(buf);
15059eeb6dd1SFam Zheng     return ret;
15069eeb6dd1SFam Zheng 
15079eeb6dd1SFam Zheng }
15089eeb6dd1SFam Zheng 
150961007b31SStefan Hajnoczi /*
151061007b31SStefan Hajnoczi  * Handle a write request in coroutine context
151161007b31SStefan Hajnoczi  */
1512a03ef88fSKevin Wolf int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
151361007b31SStefan Hajnoczi     int64_t offset, unsigned int bytes, QEMUIOVector *qiov,
151461007b31SStefan Hajnoczi     BdrvRequestFlags flags)
151561007b31SStefan Hajnoczi {
1516a03ef88fSKevin Wolf     BlockDriverState *bs = child->bs;
151761007b31SStefan Hajnoczi     BdrvTrackedRequest req;
1518a5b8dd2cSEric Blake     uint64_t align = bs->bl.request_alignment;
151961007b31SStefan Hajnoczi     uint8_t *head_buf = NULL;
152061007b31SStefan Hajnoczi     uint8_t *tail_buf = NULL;
152161007b31SStefan Hajnoczi     QEMUIOVector local_qiov;
152261007b31SStefan Hajnoczi     bool use_local_qiov = false;
152361007b31SStefan Hajnoczi     int ret;
152461007b31SStefan Hajnoczi 
152561007b31SStefan Hajnoczi     if (!bs->drv) {
152661007b31SStefan Hajnoczi         return -ENOMEDIUM;
152761007b31SStefan Hajnoczi     }
152861007b31SStefan Hajnoczi     if (bs->read_only) {
1529eaf5fe2dSPaolo Bonzini         return -EPERM;
153061007b31SStefan Hajnoczi     }
153104c01a5cSKevin Wolf     assert(!(bs->open_flags & BDRV_O_INACTIVE));
153261007b31SStefan Hajnoczi 
153361007b31SStefan Hajnoczi     ret = bdrv_check_byte_request(bs, offset, bytes);
153461007b31SStefan Hajnoczi     if (ret < 0) {
153561007b31SStefan Hajnoczi         return ret;
153661007b31SStefan Hajnoczi     }
153761007b31SStefan Hajnoczi 
153899723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
153961007b31SStefan Hajnoczi     /*
154061007b31SStefan Hajnoczi      * Align write if necessary by performing a read-modify-write cycle.
154161007b31SStefan Hajnoczi      * Pad qiov with the read parts and be sure to have a tracked request not
154261007b31SStefan Hajnoczi      * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
154361007b31SStefan Hajnoczi      */
1544ebde595cSFam Zheng     tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
154561007b31SStefan Hajnoczi 
15469eeb6dd1SFam Zheng     if (!qiov) {
154785c97ca7SKevin Wolf         ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
15489eeb6dd1SFam Zheng         goto out;
15499eeb6dd1SFam Zheng     }
15509eeb6dd1SFam Zheng 
155161007b31SStefan Hajnoczi     if (offset & (align - 1)) {
155261007b31SStefan Hajnoczi         QEMUIOVector head_qiov;
155361007b31SStefan Hajnoczi         struct iovec head_iov;
155461007b31SStefan Hajnoczi 
155561007b31SStefan Hajnoczi         mark_request_serialising(&req, align);
155661007b31SStefan Hajnoczi         wait_serialising_requests(&req);
155761007b31SStefan Hajnoczi 
155861007b31SStefan Hajnoczi         head_buf = qemu_blockalign(bs, align);
155961007b31SStefan Hajnoczi         head_iov = (struct iovec) {
156061007b31SStefan Hajnoczi             .iov_base   = head_buf,
156161007b31SStefan Hajnoczi             .iov_len    = align,
156261007b31SStefan Hajnoczi         };
156361007b31SStefan Hajnoczi         qemu_iovec_init_external(&head_qiov, &head_iov, 1);
156461007b31SStefan Hajnoczi 
15659a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
156685c97ca7SKevin Wolf         ret = bdrv_aligned_preadv(child, &req, offset & ~(align - 1), align,
156761007b31SStefan Hajnoczi                                   align, &head_qiov, 0);
156861007b31SStefan Hajnoczi         if (ret < 0) {
156961007b31SStefan Hajnoczi             goto fail;
157061007b31SStefan Hajnoczi         }
15719a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
157261007b31SStefan Hajnoczi 
157361007b31SStefan Hajnoczi         qemu_iovec_init(&local_qiov, qiov->niov + 2);
157461007b31SStefan Hajnoczi         qemu_iovec_add(&local_qiov, head_buf, offset & (align - 1));
157561007b31SStefan Hajnoczi         qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
157661007b31SStefan Hajnoczi         use_local_qiov = true;
157761007b31SStefan Hajnoczi 
157861007b31SStefan Hajnoczi         bytes += offset & (align - 1);
157961007b31SStefan Hajnoczi         offset = offset & ~(align - 1);
1580117bc3faSPeter Lieven 
1581117bc3faSPeter Lieven         /* We have read the tail already if the request is smaller
1582117bc3faSPeter Lieven          * than one aligned block.
1583117bc3faSPeter Lieven          */
1584117bc3faSPeter Lieven         if (bytes < align) {
1585117bc3faSPeter Lieven             qemu_iovec_add(&local_qiov, head_buf + bytes, align - bytes);
1586117bc3faSPeter Lieven             bytes = align;
1587117bc3faSPeter Lieven         }
158861007b31SStefan Hajnoczi     }
158961007b31SStefan Hajnoczi 
159061007b31SStefan Hajnoczi     if ((offset + bytes) & (align - 1)) {
159161007b31SStefan Hajnoczi         QEMUIOVector tail_qiov;
159261007b31SStefan Hajnoczi         struct iovec tail_iov;
159361007b31SStefan Hajnoczi         size_t tail_bytes;
159461007b31SStefan Hajnoczi         bool waited;
159561007b31SStefan Hajnoczi 
159661007b31SStefan Hajnoczi         mark_request_serialising(&req, align);
159761007b31SStefan Hajnoczi         waited = wait_serialising_requests(&req);
159861007b31SStefan Hajnoczi         assert(!waited || !use_local_qiov);
159961007b31SStefan Hajnoczi 
160061007b31SStefan Hajnoczi         tail_buf = qemu_blockalign(bs, align);
160161007b31SStefan Hajnoczi         tail_iov = (struct iovec) {
160261007b31SStefan Hajnoczi             .iov_base   = tail_buf,
160361007b31SStefan Hajnoczi             .iov_len    = align,
160461007b31SStefan Hajnoczi         };
160561007b31SStefan Hajnoczi         qemu_iovec_init_external(&tail_qiov, &tail_iov, 1);
160661007b31SStefan Hajnoczi 
16079a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
160885c97ca7SKevin Wolf         ret = bdrv_aligned_preadv(child, &req, (offset + bytes) & ~(align - 1),
160985c97ca7SKevin Wolf                                   align, align, &tail_qiov, 0);
161061007b31SStefan Hajnoczi         if (ret < 0) {
161161007b31SStefan Hajnoczi             goto fail;
161261007b31SStefan Hajnoczi         }
16139a4f4c31SKevin Wolf         bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
161461007b31SStefan Hajnoczi 
161561007b31SStefan Hajnoczi         if (!use_local_qiov) {
161661007b31SStefan Hajnoczi             qemu_iovec_init(&local_qiov, qiov->niov + 1);
161761007b31SStefan Hajnoczi             qemu_iovec_concat(&local_qiov, qiov, 0, qiov->size);
161861007b31SStefan Hajnoczi             use_local_qiov = true;
161961007b31SStefan Hajnoczi         }
162061007b31SStefan Hajnoczi 
162161007b31SStefan Hajnoczi         tail_bytes = (offset + bytes) & (align - 1);
162261007b31SStefan Hajnoczi         qemu_iovec_add(&local_qiov, tail_buf + tail_bytes, align - tail_bytes);
162361007b31SStefan Hajnoczi 
162461007b31SStefan Hajnoczi         bytes = ROUND_UP(bytes, align);
162561007b31SStefan Hajnoczi     }
162661007b31SStefan Hajnoczi 
162785c97ca7SKevin Wolf     ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
162861007b31SStefan Hajnoczi                                use_local_qiov ? &local_qiov : qiov,
162961007b31SStefan Hajnoczi                                flags);
163061007b31SStefan Hajnoczi 
163161007b31SStefan Hajnoczi fail:
163261007b31SStefan Hajnoczi 
163361007b31SStefan Hajnoczi     if (use_local_qiov) {
163461007b31SStefan Hajnoczi         qemu_iovec_destroy(&local_qiov);
163561007b31SStefan Hajnoczi     }
163661007b31SStefan Hajnoczi     qemu_vfree(head_buf);
163761007b31SStefan Hajnoczi     qemu_vfree(tail_buf);
16389eeb6dd1SFam Zheng out:
16399eeb6dd1SFam Zheng     tracked_request_end(&req);
164099723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
164161007b31SStefan Hajnoczi     return ret;
164261007b31SStefan Hajnoczi }
164361007b31SStefan Hajnoczi 
1644adad6496SKevin Wolf static int coroutine_fn bdrv_co_do_writev(BdrvChild *child,
164561007b31SStefan Hajnoczi     int64_t sector_num, int nb_sectors, QEMUIOVector *qiov,
164661007b31SStefan Hajnoczi     BdrvRequestFlags flags)
164761007b31SStefan Hajnoczi {
164861007b31SStefan Hajnoczi     if (nb_sectors < 0 || nb_sectors > BDRV_REQUEST_MAX_SECTORS) {
164961007b31SStefan Hajnoczi         return -EINVAL;
165061007b31SStefan Hajnoczi     }
165161007b31SStefan Hajnoczi 
1652a03ef88fSKevin Wolf     return bdrv_co_pwritev(child, sector_num << BDRV_SECTOR_BITS,
165361007b31SStefan Hajnoczi                            nb_sectors << BDRV_SECTOR_BITS, qiov, flags);
165461007b31SStefan Hajnoczi }
165561007b31SStefan Hajnoczi 
165625ec177dSKevin Wolf int coroutine_fn bdrv_co_writev(BdrvChild *child, int64_t sector_num,
165761007b31SStefan Hajnoczi     int nb_sectors, QEMUIOVector *qiov)
165861007b31SStefan Hajnoczi {
165925ec177dSKevin Wolf     trace_bdrv_co_writev(child->bs, sector_num, nb_sectors);
166061007b31SStefan Hajnoczi 
1661adad6496SKevin Wolf     return bdrv_co_do_writev(child, sector_num, nb_sectors, qiov, 0);
166261007b31SStefan Hajnoczi }
166361007b31SStefan Hajnoczi 
1664a03ef88fSKevin Wolf int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
1665a03ef88fSKevin Wolf                                        int count, BdrvRequestFlags flags)
166661007b31SStefan Hajnoczi {
1667a03ef88fSKevin Wolf     trace_bdrv_co_pwrite_zeroes(child->bs, offset, count, flags);
166861007b31SStefan Hajnoczi 
1669a03ef88fSKevin Wolf     if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
167061007b31SStefan Hajnoczi         flags &= ~BDRV_REQ_MAY_UNMAP;
167161007b31SStefan Hajnoczi     }
167261007b31SStefan Hajnoczi 
1673a03ef88fSKevin Wolf     return bdrv_co_pwritev(child, offset, count, NULL,
167461007b31SStefan Hajnoczi                            BDRV_REQ_ZERO_WRITE | flags);
167561007b31SStefan Hajnoczi }
167661007b31SStefan Hajnoczi 
16774085f5c7SJohn Snow /*
16784085f5c7SJohn Snow  * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
16794085f5c7SJohn Snow  */
16804085f5c7SJohn Snow int bdrv_flush_all(void)
16814085f5c7SJohn Snow {
16824085f5c7SJohn Snow     BdrvNextIterator it;
16834085f5c7SJohn Snow     BlockDriverState *bs = NULL;
16844085f5c7SJohn Snow     int result = 0;
16854085f5c7SJohn Snow 
16864085f5c7SJohn Snow     for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
16874085f5c7SJohn Snow         AioContext *aio_context = bdrv_get_aio_context(bs);
16884085f5c7SJohn Snow         int ret;
16894085f5c7SJohn Snow 
16904085f5c7SJohn Snow         aio_context_acquire(aio_context);
16914085f5c7SJohn Snow         ret = bdrv_flush(bs);
16924085f5c7SJohn Snow         if (ret < 0 && !result) {
16934085f5c7SJohn Snow             result = ret;
16944085f5c7SJohn Snow         }
16954085f5c7SJohn Snow         aio_context_release(aio_context);
16964085f5c7SJohn Snow     }
16974085f5c7SJohn Snow 
16984085f5c7SJohn Snow     return result;
16994085f5c7SJohn Snow }
17004085f5c7SJohn Snow 
17014085f5c7SJohn Snow 
170261007b31SStefan Hajnoczi typedef struct BdrvCoGetBlockStatusData {
170361007b31SStefan Hajnoczi     BlockDriverState *bs;
170461007b31SStefan Hajnoczi     BlockDriverState *base;
170567a0fd2aSFam Zheng     BlockDriverState **file;
170661007b31SStefan Hajnoczi     int64_t sector_num;
170761007b31SStefan Hajnoczi     int nb_sectors;
170861007b31SStefan Hajnoczi     int *pnum;
170961007b31SStefan Hajnoczi     int64_t ret;
171061007b31SStefan Hajnoczi     bool done;
171161007b31SStefan Hajnoczi } BdrvCoGetBlockStatusData;
171261007b31SStefan Hajnoczi 
171361007b31SStefan Hajnoczi /*
171461007b31SStefan Hajnoczi  * Returns the allocation status of the specified sectors.
171561007b31SStefan Hajnoczi  * Drivers not implementing the functionality are assumed to not support
171661007b31SStefan Hajnoczi  * backing files, hence all their sectors are reported as allocated.
171761007b31SStefan Hajnoczi  *
171861007b31SStefan Hajnoczi  * If 'sector_num' is beyond the end of the disk image the return value is 0
171961007b31SStefan Hajnoczi  * and 'pnum' is set to 0.
172061007b31SStefan Hajnoczi  *
172161007b31SStefan Hajnoczi  * 'pnum' is set to the number of sectors (including and immediately following
172261007b31SStefan Hajnoczi  * the specified sector) that are known to be in the same
172361007b31SStefan Hajnoczi  * allocated/unallocated state.
172461007b31SStefan Hajnoczi  *
172561007b31SStefan Hajnoczi  * 'nb_sectors' is the max value 'pnum' should be set to.  If nb_sectors goes
172661007b31SStefan Hajnoczi  * beyond the end of the disk image it will be clamped.
172767a0fd2aSFam Zheng  *
172867a0fd2aSFam Zheng  * If returned value is positive and BDRV_BLOCK_OFFSET_VALID bit is set, 'file'
172967a0fd2aSFam Zheng  * points to the BDS which the sector range is allocated in.
173061007b31SStefan Hajnoczi  */
173161007b31SStefan Hajnoczi static int64_t coroutine_fn bdrv_co_get_block_status(BlockDriverState *bs,
173261007b31SStefan Hajnoczi                                                      int64_t sector_num,
173367a0fd2aSFam Zheng                                                      int nb_sectors, int *pnum,
173467a0fd2aSFam Zheng                                                      BlockDriverState **file)
173561007b31SStefan Hajnoczi {
173661007b31SStefan Hajnoczi     int64_t total_sectors;
173761007b31SStefan Hajnoczi     int64_t n;
173861007b31SStefan Hajnoczi     int64_t ret, ret2;
173961007b31SStefan Hajnoczi 
174061007b31SStefan Hajnoczi     total_sectors = bdrv_nb_sectors(bs);
174161007b31SStefan Hajnoczi     if (total_sectors < 0) {
174261007b31SStefan Hajnoczi         return total_sectors;
174361007b31SStefan Hajnoczi     }
174461007b31SStefan Hajnoczi 
174561007b31SStefan Hajnoczi     if (sector_num >= total_sectors) {
174661007b31SStefan Hajnoczi         *pnum = 0;
174761007b31SStefan Hajnoczi         return 0;
174861007b31SStefan Hajnoczi     }
174961007b31SStefan Hajnoczi 
175061007b31SStefan Hajnoczi     n = total_sectors - sector_num;
175161007b31SStefan Hajnoczi     if (n < nb_sectors) {
175261007b31SStefan Hajnoczi         nb_sectors = n;
175361007b31SStefan Hajnoczi     }
175461007b31SStefan Hajnoczi 
175561007b31SStefan Hajnoczi     if (!bs->drv->bdrv_co_get_block_status) {
175661007b31SStefan Hajnoczi         *pnum = nb_sectors;
175761007b31SStefan Hajnoczi         ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
175861007b31SStefan Hajnoczi         if (bs->drv->protocol_name) {
175961007b31SStefan Hajnoczi             ret |= BDRV_BLOCK_OFFSET_VALID | (sector_num * BDRV_SECTOR_SIZE);
176061007b31SStefan Hajnoczi         }
176161007b31SStefan Hajnoczi         return ret;
176261007b31SStefan Hajnoczi     }
176361007b31SStefan Hajnoczi 
176467a0fd2aSFam Zheng     *file = NULL;
176599723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
176667a0fd2aSFam Zheng     ret = bs->drv->bdrv_co_get_block_status(bs, sector_num, nb_sectors, pnum,
176767a0fd2aSFam Zheng                                             file);
176861007b31SStefan Hajnoczi     if (ret < 0) {
176961007b31SStefan Hajnoczi         *pnum = 0;
177099723548SPaolo Bonzini         goto out;
177161007b31SStefan Hajnoczi     }
177261007b31SStefan Hajnoczi 
177361007b31SStefan Hajnoczi     if (ret & BDRV_BLOCK_RAW) {
177461007b31SStefan Hajnoczi         assert(ret & BDRV_BLOCK_OFFSET_VALID);
1775ee29d6adSEric Blake         ret = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
177667a0fd2aSFam Zheng                                        *pnum, pnum, file);
177799723548SPaolo Bonzini         goto out;
177861007b31SStefan Hajnoczi     }
177961007b31SStefan Hajnoczi 
178061007b31SStefan Hajnoczi     if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
178161007b31SStefan Hajnoczi         ret |= BDRV_BLOCK_ALLOCATED;
1782a53f1a95SPaolo Bonzini     } else {
178361007b31SStefan Hajnoczi         if (bdrv_unallocated_blocks_are_zero(bs)) {
178461007b31SStefan Hajnoczi             ret |= BDRV_BLOCK_ZERO;
1785760e0063SKevin Wolf         } else if (bs->backing) {
1786760e0063SKevin Wolf             BlockDriverState *bs2 = bs->backing->bs;
178761007b31SStefan Hajnoczi             int64_t nb_sectors2 = bdrv_nb_sectors(bs2);
178861007b31SStefan Hajnoczi             if (nb_sectors2 >= 0 && sector_num >= nb_sectors2) {
178961007b31SStefan Hajnoczi                 ret |= BDRV_BLOCK_ZERO;
179061007b31SStefan Hajnoczi             }
179161007b31SStefan Hajnoczi         }
179261007b31SStefan Hajnoczi     }
179361007b31SStefan Hajnoczi 
1794ac987b30SFam Zheng     if (*file && *file != bs &&
179561007b31SStefan Hajnoczi         (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
179661007b31SStefan Hajnoczi         (ret & BDRV_BLOCK_OFFSET_VALID)) {
179767a0fd2aSFam Zheng         BlockDriverState *file2;
179861007b31SStefan Hajnoczi         int file_pnum;
179961007b31SStefan Hajnoczi 
1800ac987b30SFam Zheng         ret2 = bdrv_co_get_block_status(*file, ret >> BDRV_SECTOR_BITS,
180167a0fd2aSFam Zheng                                         *pnum, &file_pnum, &file2);
180261007b31SStefan Hajnoczi         if (ret2 >= 0) {
180361007b31SStefan Hajnoczi             /* Ignore errors.  This is just providing extra information, it
180461007b31SStefan Hajnoczi              * is useful but not necessary.
180561007b31SStefan Hajnoczi              */
180661007b31SStefan Hajnoczi             if (!file_pnum) {
180761007b31SStefan Hajnoczi                 /* !file_pnum indicates an offset at or beyond the EOF; it is
180861007b31SStefan Hajnoczi                  * perfectly valid for the format block driver to point to such
180961007b31SStefan Hajnoczi                  * offsets, so catch it and mark everything as zero */
181061007b31SStefan Hajnoczi                 ret |= BDRV_BLOCK_ZERO;
181161007b31SStefan Hajnoczi             } else {
181261007b31SStefan Hajnoczi                 /* Limit request to the range reported by the protocol driver */
181361007b31SStefan Hajnoczi                 *pnum = file_pnum;
181461007b31SStefan Hajnoczi                 ret |= (ret2 & BDRV_BLOCK_ZERO);
181561007b31SStefan Hajnoczi             }
181661007b31SStefan Hajnoczi         }
181761007b31SStefan Hajnoczi     }
181861007b31SStefan Hajnoczi 
181999723548SPaolo Bonzini out:
182099723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
182161007b31SStefan Hajnoczi     return ret;
182261007b31SStefan Hajnoczi }
182361007b31SStefan Hajnoczi 
1824ba3f0e25SFam Zheng static int64_t coroutine_fn bdrv_co_get_block_status_above(BlockDriverState *bs,
1825ba3f0e25SFam Zheng         BlockDriverState *base,
1826ba3f0e25SFam Zheng         int64_t sector_num,
1827ba3f0e25SFam Zheng         int nb_sectors,
182867a0fd2aSFam Zheng         int *pnum,
182967a0fd2aSFam Zheng         BlockDriverState **file)
1830ba3f0e25SFam Zheng {
1831ba3f0e25SFam Zheng     BlockDriverState *p;
1832ba3f0e25SFam Zheng     int64_t ret = 0;
1833ba3f0e25SFam Zheng 
1834ba3f0e25SFam Zheng     assert(bs != base);
1835760e0063SKevin Wolf     for (p = bs; p != base; p = backing_bs(p)) {
183667a0fd2aSFam Zheng         ret = bdrv_co_get_block_status(p, sector_num, nb_sectors, pnum, file);
1837ba3f0e25SFam Zheng         if (ret < 0 || ret & BDRV_BLOCK_ALLOCATED) {
1838ba3f0e25SFam Zheng             break;
1839ba3f0e25SFam Zheng         }
1840ba3f0e25SFam Zheng         /* [sector_num, pnum] unallocated on this layer, which could be only
1841ba3f0e25SFam Zheng          * the first part of [sector_num, nb_sectors].  */
1842ba3f0e25SFam Zheng         nb_sectors = MIN(nb_sectors, *pnum);
1843ba3f0e25SFam Zheng     }
1844ba3f0e25SFam Zheng     return ret;
1845ba3f0e25SFam Zheng }
1846ba3f0e25SFam Zheng 
1847ba3f0e25SFam Zheng /* Coroutine wrapper for bdrv_get_block_status_above() */
1848ba3f0e25SFam Zheng static void coroutine_fn bdrv_get_block_status_above_co_entry(void *opaque)
184961007b31SStefan Hajnoczi {
185061007b31SStefan Hajnoczi     BdrvCoGetBlockStatusData *data = opaque;
185161007b31SStefan Hajnoczi 
1852ba3f0e25SFam Zheng     data->ret = bdrv_co_get_block_status_above(data->bs, data->base,
1853ba3f0e25SFam Zheng                                                data->sector_num,
1854ba3f0e25SFam Zheng                                                data->nb_sectors,
185567a0fd2aSFam Zheng                                                data->pnum,
185667a0fd2aSFam Zheng                                                data->file);
185761007b31SStefan Hajnoczi     data->done = true;
185861007b31SStefan Hajnoczi }
185961007b31SStefan Hajnoczi 
186061007b31SStefan Hajnoczi /*
1861ba3f0e25SFam Zheng  * Synchronous wrapper around bdrv_co_get_block_status_above().
186261007b31SStefan Hajnoczi  *
1863ba3f0e25SFam Zheng  * See bdrv_co_get_block_status_above() for details.
186461007b31SStefan Hajnoczi  */
1865ba3f0e25SFam Zheng int64_t bdrv_get_block_status_above(BlockDriverState *bs,
1866ba3f0e25SFam Zheng                                     BlockDriverState *base,
1867ba3f0e25SFam Zheng                                     int64_t sector_num,
186867a0fd2aSFam Zheng                                     int nb_sectors, int *pnum,
186967a0fd2aSFam Zheng                                     BlockDriverState **file)
187061007b31SStefan Hajnoczi {
187161007b31SStefan Hajnoczi     Coroutine *co;
187261007b31SStefan Hajnoczi     BdrvCoGetBlockStatusData data = {
187361007b31SStefan Hajnoczi         .bs = bs,
1874ba3f0e25SFam Zheng         .base = base,
187567a0fd2aSFam Zheng         .file = file,
187661007b31SStefan Hajnoczi         .sector_num = sector_num,
187761007b31SStefan Hajnoczi         .nb_sectors = nb_sectors,
187861007b31SStefan Hajnoczi         .pnum = pnum,
187961007b31SStefan Hajnoczi         .done = false,
188061007b31SStefan Hajnoczi     };
188161007b31SStefan Hajnoczi 
188261007b31SStefan Hajnoczi     if (qemu_in_coroutine()) {
188361007b31SStefan Hajnoczi         /* Fast-path if already in coroutine context */
1884ba3f0e25SFam Zheng         bdrv_get_block_status_above_co_entry(&data);
188561007b31SStefan Hajnoczi     } else {
18860b8b8753SPaolo Bonzini         co = qemu_coroutine_create(bdrv_get_block_status_above_co_entry,
18870b8b8753SPaolo Bonzini                                    &data);
1888e92f0e19SFam Zheng         bdrv_coroutine_enter(bs, co);
188988b062c2SPaolo Bonzini         BDRV_POLL_WHILE(bs, !data.done);
189061007b31SStefan Hajnoczi     }
189161007b31SStefan Hajnoczi     return data.ret;
189261007b31SStefan Hajnoczi }
189361007b31SStefan Hajnoczi 
1894ba3f0e25SFam Zheng int64_t bdrv_get_block_status(BlockDriverState *bs,
1895ba3f0e25SFam Zheng                               int64_t sector_num,
189667a0fd2aSFam Zheng                               int nb_sectors, int *pnum,
189767a0fd2aSFam Zheng                               BlockDriverState **file)
1898ba3f0e25SFam Zheng {
1899760e0063SKevin Wolf     return bdrv_get_block_status_above(bs, backing_bs(bs),
190067a0fd2aSFam Zheng                                        sector_num, nb_sectors, pnum, file);
1901ba3f0e25SFam Zheng }
1902ba3f0e25SFam Zheng 
190361007b31SStefan Hajnoczi int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t sector_num,
190461007b31SStefan Hajnoczi                                    int nb_sectors, int *pnum)
190561007b31SStefan Hajnoczi {
190667a0fd2aSFam Zheng     BlockDriverState *file;
190767a0fd2aSFam Zheng     int64_t ret = bdrv_get_block_status(bs, sector_num, nb_sectors, pnum,
190867a0fd2aSFam Zheng                                         &file);
190961007b31SStefan Hajnoczi     if (ret < 0) {
191061007b31SStefan Hajnoczi         return ret;
191161007b31SStefan Hajnoczi     }
191261007b31SStefan Hajnoczi     return !!(ret & BDRV_BLOCK_ALLOCATED);
191361007b31SStefan Hajnoczi }
191461007b31SStefan Hajnoczi 
191561007b31SStefan Hajnoczi /*
191661007b31SStefan Hajnoczi  * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
191761007b31SStefan Hajnoczi  *
191861007b31SStefan Hajnoczi  * Return true if the given sector is allocated in any image between
191961007b31SStefan Hajnoczi  * BASE and TOP (inclusive).  BASE can be NULL to check if the given
192061007b31SStefan Hajnoczi  * sector is allocated in any image of the chain.  Return false otherwise.
192161007b31SStefan Hajnoczi  *
192261007b31SStefan Hajnoczi  * 'pnum' is set to the number of sectors (including and immediately following
192361007b31SStefan Hajnoczi  *  the specified sector) that are known to be in the same
192461007b31SStefan Hajnoczi  *  allocated/unallocated state.
192561007b31SStefan Hajnoczi  *
192661007b31SStefan Hajnoczi  */
192761007b31SStefan Hajnoczi int bdrv_is_allocated_above(BlockDriverState *top,
192861007b31SStefan Hajnoczi                             BlockDriverState *base,
192961007b31SStefan Hajnoczi                             int64_t sector_num,
193061007b31SStefan Hajnoczi                             int nb_sectors, int *pnum)
193161007b31SStefan Hajnoczi {
193261007b31SStefan Hajnoczi     BlockDriverState *intermediate;
193361007b31SStefan Hajnoczi     int ret, n = nb_sectors;
193461007b31SStefan Hajnoczi 
193561007b31SStefan Hajnoczi     intermediate = top;
193661007b31SStefan Hajnoczi     while (intermediate && intermediate != base) {
193761007b31SStefan Hajnoczi         int pnum_inter;
193861007b31SStefan Hajnoczi         ret = bdrv_is_allocated(intermediate, sector_num, nb_sectors,
193961007b31SStefan Hajnoczi                                 &pnum_inter);
194061007b31SStefan Hajnoczi         if (ret < 0) {
194161007b31SStefan Hajnoczi             return ret;
194261007b31SStefan Hajnoczi         } else if (ret) {
194361007b31SStefan Hajnoczi             *pnum = pnum_inter;
194461007b31SStefan Hajnoczi             return 1;
194561007b31SStefan Hajnoczi         }
194661007b31SStefan Hajnoczi 
194761007b31SStefan Hajnoczi         /*
194861007b31SStefan Hajnoczi          * [sector_num, nb_sectors] is unallocated on top but intermediate
194961007b31SStefan Hajnoczi          * might have
195061007b31SStefan Hajnoczi          *
195161007b31SStefan Hajnoczi          * [sector_num+x, nr_sectors] allocated.
195261007b31SStefan Hajnoczi          */
195361007b31SStefan Hajnoczi         if (n > pnum_inter &&
195461007b31SStefan Hajnoczi             (intermediate == top ||
195561007b31SStefan Hajnoczi              sector_num + pnum_inter < intermediate->total_sectors)) {
195661007b31SStefan Hajnoczi             n = pnum_inter;
195761007b31SStefan Hajnoczi         }
195861007b31SStefan Hajnoczi 
1959760e0063SKevin Wolf         intermediate = backing_bs(intermediate);
196061007b31SStefan Hajnoczi     }
196161007b31SStefan Hajnoczi 
196261007b31SStefan Hajnoczi     *pnum = n;
196361007b31SStefan Hajnoczi     return 0;
196461007b31SStefan Hajnoczi }
196561007b31SStefan Hajnoczi 
19661a8ae822SKevin Wolf typedef struct BdrvVmstateCo {
19671a8ae822SKevin Wolf     BlockDriverState    *bs;
19681a8ae822SKevin Wolf     QEMUIOVector        *qiov;
19691a8ae822SKevin Wolf     int64_t             pos;
19701a8ae822SKevin Wolf     bool                is_read;
19711a8ae822SKevin Wolf     int                 ret;
19721a8ae822SKevin Wolf } BdrvVmstateCo;
19731a8ae822SKevin Wolf 
19741a8ae822SKevin Wolf static int coroutine_fn
19751a8ae822SKevin Wolf bdrv_co_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
19761a8ae822SKevin Wolf                    bool is_read)
19771a8ae822SKevin Wolf {
19781a8ae822SKevin Wolf     BlockDriver *drv = bs->drv;
19791a8ae822SKevin Wolf 
19801a8ae822SKevin Wolf     if (!drv) {
19811a8ae822SKevin Wolf         return -ENOMEDIUM;
19821a8ae822SKevin Wolf     } else if (drv->bdrv_load_vmstate) {
19831a8ae822SKevin Wolf         return is_read ? drv->bdrv_load_vmstate(bs, qiov, pos)
19841a8ae822SKevin Wolf                        : drv->bdrv_save_vmstate(bs, qiov, pos);
19851a8ae822SKevin Wolf     } else if (bs->file) {
19861a8ae822SKevin Wolf         return bdrv_co_rw_vmstate(bs->file->bs, qiov, pos, is_read);
19871a8ae822SKevin Wolf     }
19881a8ae822SKevin Wolf 
19891a8ae822SKevin Wolf     return -ENOTSUP;
19901a8ae822SKevin Wolf }
19911a8ae822SKevin Wolf 
19921a8ae822SKevin Wolf static void coroutine_fn bdrv_co_rw_vmstate_entry(void *opaque)
19931a8ae822SKevin Wolf {
19941a8ae822SKevin Wolf     BdrvVmstateCo *co = opaque;
19951a8ae822SKevin Wolf     co->ret = bdrv_co_rw_vmstate(co->bs, co->qiov, co->pos, co->is_read);
19961a8ae822SKevin Wolf }
19971a8ae822SKevin Wolf 
19981a8ae822SKevin Wolf static inline int
19991a8ae822SKevin Wolf bdrv_rw_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos,
20001a8ae822SKevin Wolf                 bool is_read)
20011a8ae822SKevin Wolf {
20021a8ae822SKevin Wolf     if (qemu_in_coroutine()) {
20031a8ae822SKevin Wolf         return bdrv_co_rw_vmstate(bs, qiov, pos, is_read);
20041a8ae822SKevin Wolf     } else {
20051a8ae822SKevin Wolf         BdrvVmstateCo data = {
20061a8ae822SKevin Wolf             .bs         = bs,
20071a8ae822SKevin Wolf             .qiov       = qiov,
20081a8ae822SKevin Wolf             .pos        = pos,
20091a8ae822SKevin Wolf             .is_read    = is_read,
20101a8ae822SKevin Wolf             .ret        = -EINPROGRESS,
20111a8ae822SKevin Wolf         };
20120b8b8753SPaolo Bonzini         Coroutine *co = qemu_coroutine_create(bdrv_co_rw_vmstate_entry, &data);
20131a8ae822SKevin Wolf 
2014e92f0e19SFam Zheng         bdrv_coroutine_enter(bs, co);
20151a8ae822SKevin Wolf         while (data.ret == -EINPROGRESS) {
20161a8ae822SKevin Wolf             aio_poll(bdrv_get_aio_context(bs), true);
20171a8ae822SKevin Wolf         }
20181a8ae822SKevin Wolf         return data.ret;
20191a8ae822SKevin Wolf     }
20201a8ae822SKevin Wolf }
20211a8ae822SKevin Wolf 
202261007b31SStefan Hajnoczi int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
202361007b31SStefan Hajnoczi                       int64_t pos, int size)
202461007b31SStefan Hajnoczi {
202561007b31SStefan Hajnoczi     QEMUIOVector qiov;
202661007b31SStefan Hajnoczi     struct iovec iov = {
202761007b31SStefan Hajnoczi         .iov_base   = (void *) buf,
202861007b31SStefan Hajnoczi         .iov_len    = size,
202961007b31SStefan Hajnoczi     };
2030b433d942SKevin Wolf     int ret;
203161007b31SStefan Hajnoczi 
203261007b31SStefan Hajnoczi     qemu_iovec_init_external(&qiov, &iov, 1);
2033b433d942SKevin Wolf 
2034b433d942SKevin Wolf     ret = bdrv_writev_vmstate(bs, &qiov, pos);
2035b433d942SKevin Wolf     if (ret < 0) {
2036b433d942SKevin Wolf         return ret;
2037b433d942SKevin Wolf     }
2038b433d942SKevin Wolf 
2039b433d942SKevin Wolf     return size;
204061007b31SStefan Hajnoczi }
204161007b31SStefan Hajnoczi 
204261007b31SStefan Hajnoczi int bdrv_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
204361007b31SStefan Hajnoczi {
20441a8ae822SKevin Wolf     return bdrv_rw_vmstate(bs, qiov, pos, false);
204561007b31SStefan Hajnoczi }
204661007b31SStefan Hajnoczi 
204761007b31SStefan Hajnoczi int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
204861007b31SStefan Hajnoczi                       int64_t pos, int size)
204961007b31SStefan Hajnoczi {
20505ddda0b8SKevin Wolf     QEMUIOVector qiov;
20515ddda0b8SKevin Wolf     struct iovec iov = {
20525ddda0b8SKevin Wolf         .iov_base   = buf,
20535ddda0b8SKevin Wolf         .iov_len    = size,
20545ddda0b8SKevin Wolf     };
2055b433d942SKevin Wolf     int ret;
20565ddda0b8SKevin Wolf 
20575ddda0b8SKevin Wolf     qemu_iovec_init_external(&qiov, &iov, 1);
2058b433d942SKevin Wolf     ret = bdrv_readv_vmstate(bs, &qiov, pos);
2059b433d942SKevin Wolf     if (ret < 0) {
2060b433d942SKevin Wolf         return ret;
2061b433d942SKevin Wolf     }
2062b433d942SKevin Wolf 
2063b433d942SKevin Wolf     return size;
20645ddda0b8SKevin Wolf }
20655ddda0b8SKevin Wolf 
20665ddda0b8SKevin Wolf int bdrv_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
20675ddda0b8SKevin Wolf {
20681a8ae822SKevin Wolf     return bdrv_rw_vmstate(bs, qiov, pos, true);
206961007b31SStefan Hajnoczi }
207061007b31SStefan Hajnoczi 
207161007b31SStefan Hajnoczi /**************************************************************/
207261007b31SStefan Hajnoczi /* async I/Os */
207361007b31SStefan Hajnoczi 
2074ebb7af21SKevin Wolf BlockAIOCB *bdrv_aio_readv(BdrvChild *child, int64_t sector_num,
207561007b31SStefan Hajnoczi                            QEMUIOVector *qiov, int nb_sectors,
207661007b31SStefan Hajnoczi                            BlockCompletionFunc *cb, void *opaque)
207761007b31SStefan Hajnoczi {
2078ebb7af21SKevin Wolf     trace_bdrv_aio_readv(child->bs, sector_num, nb_sectors, opaque);
207961007b31SStefan Hajnoczi 
2080b15404e0SEric Blake     assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2081b15404e0SEric Blake     return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2082b15404e0SEric Blake                                   0, cb, opaque, false);
208361007b31SStefan Hajnoczi }
208461007b31SStefan Hajnoczi 
20850d1049c7SKevin Wolf BlockAIOCB *bdrv_aio_writev(BdrvChild *child, int64_t sector_num,
208661007b31SStefan Hajnoczi                             QEMUIOVector *qiov, int nb_sectors,
208761007b31SStefan Hajnoczi                             BlockCompletionFunc *cb, void *opaque)
208861007b31SStefan Hajnoczi {
20890d1049c7SKevin Wolf     trace_bdrv_aio_writev(child->bs, sector_num, nb_sectors, opaque);
209061007b31SStefan Hajnoczi 
2091b15404e0SEric Blake     assert(nb_sectors << BDRV_SECTOR_BITS == qiov->size);
2092b15404e0SEric Blake     return bdrv_co_aio_prw_vector(child, sector_num << BDRV_SECTOR_BITS, qiov,
2093b15404e0SEric Blake                                   0, cb, opaque, true);
209461007b31SStefan Hajnoczi }
209561007b31SStefan Hajnoczi 
209661007b31SStefan Hajnoczi void bdrv_aio_cancel(BlockAIOCB *acb)
209761007b31SStefan Hajnoczi {
209861007b31SStefan Hajnoczi     qemu_aio_ref(acb);
209961007b31SStefan Hajnoczi     bdrv_aio_cancel_async(acb);
210061007b31SStefan Hajnoczi     while (acb->refcnt > 1) {
210161007b31SStefan Hajnoczi         if (acb->aiocb_info->get_aio_context) {
210261007b31SStefan Hajnoczi             aio_poll(acb->aiocb_info->get_aio_context(acb), true);
210361007b31SStefan Hajnoczi         } else if (acb->bs) {
21042f47da5fSPaolo Bonzini             /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
21052f47da5fSPaolo Bonzini              * assert that we're not using an I/O thread.  Thread-safe
21062f47da5fSPaolo Bonzini              * code should use bdrv_aio_cancel_async exclusively.
21072f47da5fSPaolo Bonzini              */
21082f47da5fSPaolo Bonzini             assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
210961007b31SStefan Hajnoczi             aio_poll(bdrv_get_aio_context(acb->bs), true);
211061007b31SStefan Hajnoczi         } else {
211161007b31SStefan Hajnoczi             abort();
211261007b31SStefan Hajnoczi         }
211361007b31SStefan Hajnoczi     }
211461007b31SStefan Hajnoczi     qemu_aio_unref(acb);
211561007b31SStefan Hajnoczi }
211661007b31SStefan Hajnoczi 
211761007b31SStefan Hajnoczi /* Async version of aio cancel. The caller is not blocked if the acb implements
211861007b31SStefan Hajnoczi  * cancel_async, otherwise we do nothing and let the request normally complete.
211961007b31SStefan Hajnoczi  * In either case the completion callback must be called. */
212061007b31SStefan Hajnoczi void bdrv_aio_cancel_async(BlockAIOCB *acb)
212161007b31SStefan Hajnoczi {
212261007b31SStefan Hajnoczi     if (acb->aiocb_info->cancel_async) {
212361007b31SStefan Hajnoczi         acb->aiocb_info->cancel_async(acb);
212461007b31SStefan Hajnoczi     }
212561007b31SStefan Hajnoczi }
212661007b31SStefan Hajnoczi 
212761007b31SStefan Hajnoczi /**************************************************************/
212861007b31SStefan Hajnoczi /* async block device emulation */
212961007b31SStefan Hajnoczi 
213041574268SEric Blake typedef struct BlockRequest {
213141574268SEric Blake     union {
213241574268SEric Blake         /* Used during read, write, trim */
213341574268SEric Blake         struct {
2134b15404e0SEric Blake             int64_t offset;
2135b15404e0SEric Blake             int bytes;
213641574268SEric Blake             int flags;
213741574268SEric Blake             QEMUIOVector *qiov;
213841574268SEric Blake         };
213941574268SEric Blake         /* Used during ioctl */
214041574268SEric Blake         struct {
214141574268SEric Blake             int req;
214241574268SEric Blake             void *buf;
214341574268SEric Blake         };
214441574268SEric Blake     };
214541574268SEric Blake     BlockCompletionFunc *cb;
214641574268SEric Blake     void *opaque;
214741574268SEric Blake 
214841574268SEric Blake     int error;
214941574268SEric Blake } BlockRequest;
215041574268SEric Blake 
215161007b31SStefan Hajnoczi typedef struct BlockAIOCBCoroutine {
215261007b31SStefan Hajnoczi     BlockAIOCB common;
2153adad6496SKevin Wolf     BdrvChild *child;
215461007b31SStefan Hajnoczi     BlockRequest req;
215561007b31SStefan Hajnoczi     bool is_write;
215661007b31SStefan Hajnoczi     bool need_bh;
215761007b31SStefan Hajnoczi     bool *done;
215861007b31SStefan Hajnoczi } BlockAIOCBCoroutine;
215961007b31SStefan Hajnoczi 
216061007b31SStefan Hajnoczi static const AIOCBInfo bdrv_em_co_aiocb_info = {
216161007b31SStefan Hajnoczi     .aiocb_size         = sizeof(BlockAIOCBCoroutine),
216261007b31SStefan Hajnoczi };
216361007b31SStefan Hajnoczi 
216461007b31SStefan Hajnoczi static void bdrv_co_complete(BlockAIOCBCoroutine *acb)
216561007b31SStefan Hajnoczi {
216661007b31SStefan Hajnoczi     if (!acb->need_bh) {
216799723548SPaolo Bonzini         bdrv_dec_in_flight(acb->common.bs);
216861007b31SStefan Hajnoczi         acb->common.cb(acb->common.opaque, acb->req.error);
216961007b31SStefan Hajnoczi         qemu_aio_unref(acb);
217061007b31SStefan Hajnoczi     }
217161007b31SStefan Hajnoczi }
217261007b31SStefan Hajnoczi 
217361007b31SStefan Hajnoczi static void bdrv_co_em_bh(void *opaque)
217461007b31SStefan Hajnoczi {
217561007b31SStefan Hajnoczi     BlockAIOCBCoroutine *acb = opaque;
217661007b31SStefan Hajnoczi 
217761007b31SStefan Hajnoczi     assert(!acb->need_bh);
217861007b31SStefan Hajnoczi     bdrv_co_complete(acb);
217961007b31SStefan Hajnoczi }
218061007b31SStefan Hajnoczi 
218161007b31SStefan Hajnoczi static void bdrv_co_maybe_schedule_bh(BlockAIOCBCoroutine *acb)
218261007b31SStefan Hajnoczi {
218361007b31SStefan Hajnoczi     acb->need_bh = false;
218461007b31SStefan Hajnoczi     if (acb->req.error != -EINPROGRESS) {
218561007b31SStefan Hajnoczi         BlockDriverState *bs = acb->common.bs;
218661007b31SStefan Hajnoczi 
2187fffb6e12SPaolo Bonzini         aio_bh_schedule_oneshot(bdrv_get_aio_context(bs), bdrv_co_em_bh, acb);
218861007b31SStefan Hajnoczi     }
218961007b31SStefan Hajnoczi }
219061007b31SStefan Hajnoczi 
219161007b31SStefan Hajnoczi /* Invoke bdrv_co_do_readv/bdrv_co_do_writev */
219261007b31SStefan Hajnoczi static void coroutine_fn bdrv_co_do_rw(void *opaque)
219361007b31SStefan Hajnoczi {
219461007b31SStefan Hajnoczi     BlockAIOCBCoroutine *acb = opaque;
219561007b31SStefan Hajnoczi 
219661007b31SStefan Hajnoczi     if (!acb->is_write) {
2197b15404e0SEric Blake         acb->req.error = bdrv_co_preadv(acb->child, acb->req.offset,
2198b15404e0SEric Blake             acb->req.qiov->size, acb->req.qiov, acb->req.flags);
219961007b31SStefan Hajnoczi     } else {
2200b15404e0SEric Blake         acb->req.error = bdrv_co_pwritev(acb->child, acb->req.offset,
2201b15404e0SEric Blake             acb->req.qiov->size, acb->req.qiov, acb->req.flags);
220261007b31SStefan Hajnoczi     }
220361007b31SStefan Hajnoczi 
220461007b31SStefan Hajnoczi     bdrv_co_complete(acb);
220561007b31SStefan Hajnoczi }
220661007b31SStefan Hajnoczi 
2207b15404e0SEric Blake static BlockAIOCB *bdrv_co_aio_prw_vector(BdrvChild *child,
2208b15404e0SEric Blake                                           int64_t offset,
220961007b31SStefan Hajnoczi                                           QEMUIOVector *qiov,
221061007b31SStefan Hajnoczi                                           BdrvRequestFlags flags,
221161007b31SStefan Hajnoczi                                           BlockCompletionFunc *cb,
221261007b31SStefan Hajnoczi                                           void *opaque,
221361007b31SStefan Hajnoczi                                           bool is_write)
221461007b31SStefan Hajnoczi {
221561007b31SStefan Hajnoczi     Coroutine *co;
221661007b31SStefan Hajnoczi     BlockAIOCBCoroutine *acb;
221761007b31SStefan Hajnoczi 
221899723548SPaolo Bonzini     /* Matched by bdrv_co_complete's bdrv_dec_in_flight.  */
221999723548SPaolo Bonzini     bdrv_inc_in_flight(child->bs);
222099723548SPaolo Bonzini 
2221adad6496SKevin Wolf     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, child->bs, cb, opaque);
2222adad6496SKevin Wolf     acb->child = child;
222361007b31SStefan Hajnoczi     acb->need_bh = true;
222461007b31SStefan Hajnoczi     acb->req.error = -EINPROGRESS;
2225b15404e0SEric Blake     acb->req.offset = offset;
222661007b31SStefan Hajnoczi     acb->req.qiov = qiov;
222761007b31SStefan Hajnoczi     acb->req.flags = flags;
222861007b31SStefan Hajnoczi     acb->is_write = is_write;
222961007b31SStefan Hajnoczi 
22300b8b8753SPaolo Bonzini     co = qemu_coroutine_create(bdrv_co_do_rw, acb);
2231e92f0e19SFam Zheng     bdrv_coroutine_enter(child->bs, co);
223261007b31SStefan Hajnoczi 
223361007b31SStefan Hajnoczi     bdrv_co_maybe_schedule_bh(acb);
223461007b31SStefan Hajnoczi     return &acb->common;
223561007b31SStefan Hajnoczi }
223661007b31SStefan Hajnoczi 
223761007b31SStefan Hajnoczi static void coroutine_fn bdrv_aio_flush_co_entry(void *opaque)
223861007b31SStefan Hajnoczi {
223961007b31SStefan Hajnoczi     BlockAIOCBCoroutine *acb = opaque;
224061007b31SStefan Hajnoczi     BlockDriverState *bs = acb->common.bs;
224161007b31SStefan Hajnoczi 
224261007b31SStefan Hajnoczi     acb->req.error = bdrv_co_flush(bs);
224361007b31SStefan Hajnoczi     bdrv_co_complete(acb);
224461007b31SStefan Hajnoczi }
224561007b31SStefan Hajnoczi 
224661007b31SStefan Hajnoczi BlockAIOCB *bdrv_aio_flush(BlockDriverState *bs,
224761007b31SStefan Hajnoczi         BlockCompletionFunc *cb, void *opaque)
224861007b31SStefan Hajnoczi {
224961007b31SStefan Hajnoczi     trace_bdrv_aio_flush(bs, opaque);
225061007b31SStefan Hajnoczi 
225161007b31SStefan Hajnoczi     Coroutine *co;
225261007b31SStefan Hajnoczi     BlockAIOCBCoroutine *acb;
225361007b31SStefan Hajnoczi 
225499723548SPaolo Bonzini     /* Matched by bdrv_co_complete's bdrv_dec_in_flight.  */
225599723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
225699723548SPaolo Bonzini 
225761007b31SStefan Hajnoczi     acb = qemu_aio_get(&bdrv_em_co_aiocb_info, bs, cb, opaque);
225861007b31SStefan Hajnoczi     acb->need_bh = true;
225961007b31SStefan Hajnoczi     acb->req.error = -EINPROGRESS;
226061007b31SStefan Hajnoczi 
22610b8b8753SPaolo Bonzini     co = qemu_coroutine_create(bdrv_aio_flush_co_entry, acb);
2262e92f0e19SFam Zheng     bdrv_coroutine_enter(bs, co);
226361007b31SStefan Hajnoczi 
226461007b31SStefan Hajnoczi     bdrv_co_maybe_schedule_bh(acb);
226561007b31SStefan Hajnoczi     return &acb->common;
226661007b31SStefan Hajnoczi }
226761007b31SStefan Hajnoczi 
226861007b31SStefan Hajnoczi /**************************************************************/
226961007b31SStefan Hajnoczi /* Coroutine block device emulation */
227061007b31SStefan Hajnoczi 
2271e293b7a3SKevin Wolf typedef struct FlushCo {
2272e293b7a3SKevin Wolf     BlockDriverState *bs;
2273e293b7a3SKevin Wolf     int ret;
2274e293b7a3SKevin Wolf } FlushCo;
2275e293b7a3SKevin Wolf 
2276e293b7a3SKevin Wolf 
227761007b31SStefan Hajnoczi static void coroutine_fn bdrv_flush_co_entry(void *opaque)
227861007b31SStefan Hajnoczi {
2279e293b7a3SKevin Wolf     FlushCo *rwco = opaque;
228061007b31SStefan Hajnoczi 
228161007b31SStefan Hajnoczi     rwco->ret = bdrv_co_flush(rwco->bs);
228261007b31SStefan Hajnoczi }
228361007b31SStefan Hajnoczi 
228461007b31SStefan Hajnoczi int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
228561007b31SStefan Hajnoczi {
228649ca6259SFam Zheng     int current_gen;
228749ca6259SFam Zheng     int ret = 0;
228861007b31SStefan Hajnoczi 
228999723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
2290c32b82afSPavel Dovgalyuk 
2291e914404eSFam Zheng     if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
229249ca6259SFam Zheng         bdrv_is_sg(bs)) {
229349ca6259SFam Zheng         goto early_exit;
229449ca6259SFam Zheng     }
229549ca6259SFam Zheng 
229649ca6259SFam Zheng     current_gen = bs->write_gen;
22973ff2f67aSEvgeny Yakovlev 
22983ff2f67aSEvgeny Yakovlev     /* Wait until any previous flushes are completed */
229999723548SPaolo Bonzini     while (bs->active_flush_req) {
23001ace7ceaSPaolo Bonzini         qemu_co_queue_wait(&bs->flush_queue, NULL);
23013ff2f67aSEvgeny Yakovlev     }
23023ff2f67aSEvgeny Yakovlev 
230399723548SPaolo Bonzini     bs->active_flush_req = true;
23043ff2f67aSEvgeny Yakovlev 
2305c32b82afSPavel Dovgalyuk     /* Write back all layers by calling one driver function */
2306c32b82afSPavel Dovgalyuk     if (bs->drv->bdrv_co_flush) {
2307c32b82afSPavel Dovgalyuk         ret = bs->drv->bdrv_co_flush(bs);
2308c32b82afSPavel Dovgalyuk         goto out;
2309c32b82afSPavel Dovgalyuk     }
2310c32b82afSPavel Dovgalyuk 
231161007b31SStefan Hajnoczi     /* Write back cached data to the OS even with cache=unsafe */
231261007b31SStefan Hajnoczi     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_OS);
231361007b31SStefan Hajnoczi     if (bs->drv->bdrv_co_flush_to_os) {
231461007b31SStefan Hajnoczi         ret = bs->drv->bdrv_co_flush_to_os(bs);
231561007b31SStefan Hajnoczi         if (ret < 0) {
2316cdb5e315SFam Zheng             goto out;
231761007b31SStefan Hajnoczi         }
231861007b31SStefan Hajnoczi     }
231961007b31SStefan Hajnoczi 
232061007b31SStefan Hajnoczi     /* But don't actually force it to the disk with cache=unsafe */
232161007b31SStefan Hajnoczi     if (bs->open_flags & BDRV_O_NO_FLUSH) {
232261007b31SStefan Hajnoczi         goto flush_parent;
232361007b31SStefan Hajnoczi     }
232461007b31SStefan Hajnoczi 
23253ff2f67aSEvgeny Yakovlev     /* Check if we really need to flush anything */
23263ff2f67aSEvgeny Yakovlev     if (bs->flushed_gen == current_gen) {
23273ff2f67aSEvgeny Yakovlev         goto flush_parent;
23283ff2f67aSEvgeny Yakovlev     }
23293ff2f67aSEvgeny Yakovlev 
233061007b31SStefan Hajnoczi     BLKDBG_EVENT(bs->file, BLKDBG_FLUSH_TO_DISK);
233161007b31SStefan Hajnoczi     if (bs->drv->bdrv_co_flush_to_disk) {
233261007b31SStefan Hajnoczi         ret = bs->drv->bdrv_co_flush_to_disk(bs);
233361007b31SStefan Hajnoczi     } else if (bs->drv->bdrv_aio_flush) {
233461007b31SStefan Hajnoczi         BlockAIOCB *acb;
233561007b31SStefan Hajnoczi         CoroutineIOCompletion co = {
233661007b31SStefan Hajnoczi             .coroutine = qemu_coroutine_self(),
233761007b31SStefan Hajnoczi         };
233861007b31SStefan Hajnoczi 
233961007b31SStefan Hajnoczi         acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
234061007b31SStefan Hajnoczi         if (acb == NULL) {
234161007b31SStefan Hajnoczi             ret = -EIO;
234261007b31SStefan Hajnoczi         } else {
234361007b31SStefan Hajnoczi             qemu_coroutine_yield();
234461007b31SStefan Hajnoczi             ret = co.ret;
234561007b31SStefan Hajnoczi         }
234661007b31SStefan Hajnoczi     } else {
234761007b31SStefan Hajnoczi         /*
234861007b31SStefan Hajnoczi          * Some block drivers always operate in either writethrough or unsafe
234961007b31SStefan Hajnoczi          * mode and don't support bdrv_flush therefore. Usually qemu doesn't
235061007b31SStefan Hajnoczi          * know how the server works (because the behaviour is hardcoded or
235161007b31SStefan Hajnoczi          * depends on server-side configuration), so we can't ensure that
235261007b31SStefan Hajnoczi          * everything is safe on disk. Returning an error doesn't work because
235361007b31SStefan Hajnoczi          * that would break guests even if the server operates in writethrough
235461007b31SStefan Hajnoczi          * mode.
235561007b31SStefan Hajnoczi          *
235661007b31SStefan Hajnoczi          * Let's hope the user knows what he's doing.
235761007b31SStefan Hajnoczi          */
235861007b31SStefan Hajnoczi         ret = 0;
235961007b31SStefan Hajnoczi     }
23603ff2f67aSEvgeny Yakovlev 
236161007b31SStefan Hajnoczi     if (ret < 0) {
2362cdb5e315SFam Zheng         goto out;
236361007b31SStefan Hajnoczi     }
236461007b31SStefan Hajnoczi 
236561007b31SStefan Hajnoczi     /* Now flush the underlying protocol.  It will also have BDRV_O_NO_FLUSH
236661007b31SStefan Hajnoczi      * in the case of cache=unsafe, so there are no useless flushes.
236761007b31SStefan Hajnoczi      */
236861007b31SStefan Hajnoczi flush_parent:
2369cdb5e315SFam Zheng     ret = bs->file ? bdrv_co_flush(bs->file->bs) : 0;
2370cdb5e315SFam Zheng out:
23713ff2f67aSEvgeny Yakovlev     /* Notify any pending flushes that we have completed */
2372e6af1e08SKevin Wolf     if (ret == 0) {
23733ff2f67aSEvgeny Yakovlev         bs->flushed_gen = current_gen;
2374e6af1e08SKevin Wolf     }
237599723548SPaolo Bonzini     bs->active_flush_req = false;
2376156af3acSDenis V. Lunev     /* Return value is ignored - it's ok if wait queue is empty */
2377156af3acSDenis V. Lunev     qemu_co_queue_next(&bs->flush_queue);
23783ff2f67aSEvgeny Yakovlev 
237949ca6259SFam Zheng early_exit:
238099723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
2381cdb5e315SFam Zheng     return ret;
238261007b31SStefan Hajnoczi }
238361007b31SStefan Hajnoczi 
238461007b31SStefan Hajnoczi int bdrv_flush(BlockDriverState *bs)
238561007b31SStefan Hajnoczi {
238661007b31SStefan Hajnoczi     Coroutine *co;
2387e293b7a3SKevin Wolf     FlushCo flush_co = {
238861007b31SStefan Hajnoczi         .bs = bs,
238961007b31SStefan Hajnoczi         .ret = NOT_DONE,
239061007b31SStefan Hajnoczi     };
239161007b31SStefan Hajnoczi 
239261007b31SStefan Hajnoczi     if (qemu_in_coroutine()) {
239361007b31SStefan Hajnoczi         /* Fast-path if already in coroutine context */
2394e293b7a3SKevin Wolf         bdrv_flush_co_entry(&flush_co);
239561007b31SStefan Hajnoczi     } else {
23960b8b8753SPaolo Bonzini         co = qemu_coroutine_create(bdrv_flush_co_entry, &flush_co);
2397e92f0e19SFam Zheng         bdrv_coroutine_enter(bs, co);
239888b062c2SPaolo Bonzini         BDRV_POLL_WHILE(bs, flush_co.ret == NOT_DONE);
239961007b31SStefan Hajnoczi     }
240061007b31SStefan Hajnoczi 
2401e293b7a3SKevin Wolf     return flush_co.ret;
240261007b31SStefan Hajnoczi }
240361007b31SStefan Hajnoczi 
240461007b31SStefan Hajnoczi typedef struct DiscardCo {
240561007b31SStefan Hajnoczi     BlockDriverState *bs;
24060c51a893SEric Blake     int64_t offset;
24070c51a893SEric Blake     int count;
240861007b31SStefan Hajnoczi     int ret;
240961007b31SStefan Hajnoczi } DiscardCo;
24100c51a893SEric Blake static void coroutine_fn bdrv_pdiscard_co_entry(void *opaque)
241161007b31SStefan Hajnoczi {
241261007b31SStefan Hajnoczi     DiscardCo *rwco = opaque;
241361007b31SStefan Hajnoczi 
24140c51a893SEric Blake     rwco->ret = bdrv_co_pdiscard(rwco->bs, rwco->offset, rwco->count);
241561007b31SStefan Hajnoczi }
241661007b31SStefan Hajnoczi 
24179f1963b3SEric Blake int coroutine_fn bdrv_co_pdiscard(BlockDriverState *bs, int64_t offset,
24189f1963b3SEric Blake                                   int count)
241961007b31SStefan Hajnoczi {
2420b1066c87SFam Zheng     BdrvTrackedRequest req;
24219f1963b3SEric Blake     int max_pdiscard, ret;
24223482b9bcSEric Blake     int head, tail, align;
242361007b31SStefan Hajnoczi 
242461007b31SStefan Hajnoczi     if (!bs->drv) {
242561007b31SStefan Hajnoczi         return -ENOMEDIUM;
242661007b31SStefan Hajnoczi     }
242761007b31SStefan Hajnoczi 
24289f1963b3SEric Blake     ret = bdrv_check_byte_request(bs, offset, count);
242961007b31SStefan Hajnoczi     if (ret < 0) {
243061007b31SStefan Hajnoczi         return ret;
243161007b31SStefan Hajnoczi     } else if (bs->read_only) {
2432eaf5fe2dSPaolo Bonzini         return -EPERM;
243361007b31SStefan Hajnoczi     }
243404c01a5cSKevin Wolf     assert(!(bs->open_flags & BDRV_O_INACTIVE));
243561007b31SStefan Hajnoczi 
243661007b31SStefan Hajnoczi     /* Do nothing if disabled.  */
243761007b31SStefan Hajnoczi     if (!(bs->open_flags & BDRV_O_UNMAP)) {
243861007b31SStefan Hajnoczi         return 0;
243961007b31SStefan Hajnoczi     }
244061007b31SStefan Hajnoczi 
244102aefe43SEric Blake     if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
244261007b31SStefan Hajnoczi         return 0;
244361007b31SStefan Hajnoczi     }
244461007b31SStefan Hajnoczi 
24453482b9bcSEric Blake     /* Discard is advisory, but some devices track and coalesce
24463482b9bcSEric Blake      * unaligned requests, so we must pass everything down rather than
24473482b9bcSEric Blake      * round here.  Still, most devices will just silently ignore
24483482b9bcSEric Blake      * unaligned requests (by returning -ENOTSUP), so we must fragment
24493482b9bcSEric Blake      * the request accordingly.  */
245002aefe43SEric Blake     align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
2451b8d0a980SEric Blake     assert(align % bs->bl.request_alignment == 0);
2452b8d0a980SEric Blake     head = offset % align;
24533482b9bcSEric Blake     tail = (offset + count) % align;
24549f1963b3SEric Blake 
245599723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
24569f1963b3SEric Blake     tracked_request_begin(&req, bs, offset, count, BDRV_TRACKED_DISCARD);
245750824995SFam Zheng 
2458ec050f77SDenis V. Lunev     ret = notifier_with_return_list_notify(&bs->before_write_notifiers, &req);
2459ec050f77SDenis V. Lunev     if (ret < 0) {
2460ec050f77SDenis V. Lunev         goto out;
2461ec050f77SDenis V. Lunev     }
2462ec050f77SDenis V. Lunev 
24639f1963b3SEric Blake     max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT_MAX),
24649f1963b3SEric Blake                                    align);
24653482b9bcSEric Blake     assert(max_pdiscard >= bs->bl.request_alignment);
24669f1963b3SEric Blake 
24679f1963b3SEric Blake     while (count > 0) {
246861007b31SStefan Hajnoczi         int ret;
24693482b9bcSEric Blake         int num = count;
24703482b9bcSEric Blake 
24713482b9bcSEric Blake         if (head) {
24723482b9bcSEric Blake             /* Make small requests to get to alignment boundaries. */
24733482b9bcSEric Blake             num = MIN(count, align - head);
24743482b9bcSEric Blake             if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
24753482b9bcSEric Blake                 num %= bs->bl.request_alignment;
24763482b9bcSEric Blake             }
24773482b9bcSEric Blake             head = (head + num) % align;
24783482b9bcSEric Blake             assert(num < max_pdiscard);
24793482b9bcSEric Blake         } else if (tail) {
24803482b9bcSEric Blake             if (num > align) {
24813482b9bcSEric Blake                 /* Shorten the request to the last aligned cluster.  */
24823482b9bcSEric Blake                 num -= tail;
24833482b9bcSEric Blake             } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
24843482b9bcSEric Blake                        tail > bs->bl.request_alignment) {
24853482b9bcSEric Blake                 tail %= bs->bl.request_alignment;
24863482b9bcSEric Blake                 num -= tail;
24873482b9bcSEric Blake             }
24883482b9bcSEric Blake         }
24893482b9bcSEric Blake         /* limit request size */
24903482b9bcSEric Blake         if (num > max_pdiscard) {
24913482b9bcSEric Blake             num = max_pdiscard;
24923482b9bcSEric Blake         }
249361007b31SStefan Hajnoczi 
249447a5486dSEric Blake         if (bs->drv->bdrv_co_pdiscard) {
249547a5486dSEric Blake             ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
249661007b31SStefan Hajnoczi         } else {
249761007b31SStefan Hajnoczi             BlockAIOCB *acb;
249861007b31SStefan Hajnoczi             CoroutineIOCompletion co = {
249961007b31SStefan Hajnoczi                 .coroutine = qemu_coroutine_self(),
250061007b31SStefan Hajnoczi             };
250161007b31SStefan Hajnoczi 
25024da444a0SEric Blake             acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
250361007b31SStefan Hajnoczi                                              bdrv_co_io_em_complete, &co);
250461007b31SStefan Hajnoczi             if (acb == NULL) {
2505b1066c87SFam Zheng                 ret = -EIO;
2506b1066c87SFam Zheng                 goto out;
250761007b31SStefan Hajnoczi             } else {
250861007b31SStefan Hajnoczi                 qemu_coroutine_yield();
250961007b31SStefan Hajnoczi                 ret = co.ret;
251061007b31SStefan Hajnoczi             }
251161007b31SStefan Hajnoczi         }
251261007b31SStefan Hajnoczi         if (ret && ret != -ENOTSUP) {
2513b1066c87SFam Zheng             goto out;
251461007b31SStefan Hajnoczi         }
251561007b31SStefan Hajnoczi 
25169f1963b3SEric Blake         offset += num;
25179f1963b3SEric Blake         count -= num;
251861007b31SStefan Hajnoczi     }
2519b1066c87SFam Zheng     ret = 0;
2520b1066c87SFam Zheng out:
25213ff2f67aSEvgeny Yakovlev     ++bs->write_gen;
2522968d8b06SDenis V. Lunev     bdrv_set_dirty(bs, req.offset >> BDRV_SECTOR_BITS,
2523968d8b06SDenis V. Lunev                    req.bytes >> BDRV_SECTOR_BITS);
2524b1066c87SFam Zheng     tracked_request_end(&req);
252599723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
2526b1066c87SFam Zheng     return ret;
252761007b31SStefan Hajnoczi }
252861007b31SStefan Hajnoczi 
25290c51a893SEric Blake int bdrv_pdiscard(BlockDriverState *bs, int64_t offset, int count)
253061007b31SStefan Hajnoczi {
253161007b31SStefan Hajnoczi     Coroutine *co;
253261007b31SStefan Hajnoczi     DiscardCo rwco = {
253361007b31SStefan Hajnoczi         .bs = bs,
25340c51a893SEric Blake         .offset = offset,
25350c51a893SEric Blake         .count = count,
253661007b31SStefan Hajnoczi         .ret = NOT_DONE,
253761007b31SStefan Hajnoczi     };
253861007b31SStefan Hajnoczi 
253961007b31SStefan Hajnoczi     if (qemu_in_coroutine()) {
254061007b31SStefan Hajnoczi         /* Fast-path if already in coroutine context */
25410c51a893SEric Blake         bdrv_pdiscard_co_entry(&rwco);
254261007b31SStefan Hajnoczi     } else {
25430c51a893SEric Blake         co = qemu_coroutine_create(bdrv_pdiscard_co_entry, &rwco);
2544e92f0e19SFam Zheng         bdrv_coroutine_enter(bs, co);
254588b062c2SPaolo Bonzini         BDRV_POLL_WHILE(bs, rwco.ret == NOT_DONE);
254661007b31SStefan Hajnoczi     }
254761007b31SStefan Hajnoczi 
254861007b31SStefan Hajnoczi     return rwco.ret;
254961007b31SStefan Hajnoczi }
255061007b31SStefan Hajnoczi 
255148af776aSKevin Wolf int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
255261007b31SStefan Hajnoczi {
255361007b31SStefan Hajnoczi     BlockDriver *drv = bs->drv;
25545c5ae76aSFam Zheng     CoroutineIOCompletion co = {
25555c5ae76aSFam Zheng         .coroutine = qemu_coroutine_self(),
25565c5ae76aSFam Zheng     };
25575c5ae76aSFam Zheng     BlockAIOCB *acb;
255861007b31SStefan Hajnoczi 
255999723548SPaolo Bonzini     bdrv_inc_in_flight(bs);
256016a389dcSKevin Wolf     if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
25615c5ae76aSFam Zheng         co.ret = -ENOTSUP;
25625c5ae76aSFam Zheng         goto out;
25635c5ae76aSFam Zheng     }
25645c5ae76aSFam Zheng 
256516a389dcSKevin Wolf     if (drv->bdrv_co_ioctl) {
256616a389dcSKevin Wolf         co.ret = drv->bdrv_co_ioctl(bs, req, buf);
256716a389dcSKevin Wolf     } else {
25685c5ae76aSFam Zheng         acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
25695c5ae76aSFam Zheng         if (!acb) {
2570c8a9fd80SFam Zheng             co.ret = -ENOTSUP;
2571c8a9fd80SFam Zheng             goto out;
25725c5ae76aSFam Zheng         }
25735c5ae76aSFam Zheng         qemu_coroutine_yield();
257416a389dcSKevin Wolf     }
25755c5ae76aSFam Zheng out:
257699723548SPaolo Bonzini     bdrv_dec_in_flight(bs);
25775c5ae76aSFam Zheng     return co.ret;
25785c5ae76aSFam Zheng }
25795c5ae76aSFam Zheng 
258061007b31SStefan Hajnoczi void *qemu_blockalign(BlockDriverState *bs, size_t size)
258161007b31SStefan Hajnoczi {
258261007b31SStefan Hajnoczi     return qemu_memalign(bdrv_opt_mem_align(bs), size);
258361007b31SStefan Hajnoczi }
258461007b31SStefan Hajnoczi 
258561007b31SStefan Hajnoczi void *qemu_blockalign0(BlockDriverState *bs, size_t size)
258661007b31SStefan Hajnoczi {
258761007b31SStefan Hajnoczi     return memset(qemu_blockalign(bs, size), 0, size);
258861007b31SStefan Hajnoczi }
258961007b31SStefan Hajnoczi 
259061007b31SStefan Hajnoczi void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
259161007b31SStefan Hajnoczi {
259261007b31SStefan Hajnoczi     size_t align = bdrv_opt_mem_align(bs);
259361007b31SStefan Hajnoczi 
259461007b31SStefan Hajnoczi     /* Ensure that NULL is never returned on success */
259561007b31SStefan Hajnoczi     assert(align > 0);
259661007b31SStefan Hajnoczi     if (size == 0) {
259761007b31SStefan Hajnoczi         size = align;
259861007b31SStefan Hajnoczi     }
259961007b31SStefan Hajnoczi 
260061007b31SStefan Hajnoczi     return qemu_try_memalign(align, size);
260161007b31SStefan Hajnoczi }
260261007b31SStefan Hajnoczi 
260361007b31SStefan Hajnoczi void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
260461007b31SStefan Hajnoczi {
260561007b31SStefan Hajnoczi     void *mem = qemu_try_blockalign(bs, size);
260661007b31SStefan Hajnoczi 
260761007b31SStefan Hajnoczi     if (mem) {
260861007b31SStefan Hajnoczi         memset(mem, 0, size);
260961007b31SStefan Hajnoczi     }
261061007b31SStefan Hajnoczi 
261161007b31SStefan Hajnoczi     return mem;
261261007b31SStefan Hajnoczi }
261361007b31SStefan Hajnoczi 
261461007b31SStefan Hajnoczi /*
261561007b31SStefan Hajnoczi  * Check if all memory in this vector is sector aligned.
261661007b31SStefan Hajnoczi  */
261761007b31SStefan Hajnoczi bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
261861007b31SStefan Hajnoczi {
261961007b31SStefan Hajnoczi     int i;
26204196d2f0SDenis V. Lunev     size_t alignment = bdrv_min_mem_align(bs);
262161007b31SStefan Hajnoczi 
262261007b31SStefan Hajnoczi     for (i = 0; i < qiov->niov; i++) {
262361007b31SStefan Hajnoczi         if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
262461007b31SStefan Hajnoczi             return false;
262561007b31SStefan Hajnoczi         }
262661007b31SStefan Hajnoczi         if (qiov->iov[i].iov_len % alignment) {
262761007b31SStefan Hajnoczi             return false;
262861007b31SStefan Hajnoczi         }
262961007b31SStefan Hajnoczi     }
263061007b31SStefan Hajnoczi 
263161007b31SStefan Hajnoczi     return true;
263261007b31SStefan Hajnoczi }
263361007b31SStefan Hajnoczi 
263461007b31SStefan Hajnoczi void bdrv_add_before_write_notifier(BlockDriverState *bs,
263561007b31SStefan Hajnoczi                                     NotifierWithReturn *notifier)
263661007b31SStefan Hajnoczi {
263761007b31SStefan Hajnoczi     notifier_with_return_list_add(&bs->before_write_notifiers, notifier);
263861007b31SStefan Hajnoczi }
263961007b31SStefan Hajnoczi 
264061007b31SStefan Hajnoczi void bdrv_io_plug(BlockDriverState *bs)
264161007b31SStefan Hajnoczi {
26426b98bd64SPaolo Bonzini     BdrvChild *child;
26436b98bd64SPaolo Bonzini 
26446b98bd64SPaolo Bonzini     QLIST_FOREACH(child, &bs->children, next) {
26456b98bd64SPaolo Bonzini         bdrv_io_plug(child->bs);
26466b98bd64SPaolo Bonzini     }
26476b98bd64SPaolo Bonzini 
26488f90b5e9SPaolo Bonzini     if (bs->io_plugged++ == 0) {
264961007b31SStefan Hajnoczi         BlockDriver *drv = bs->drv;
265061007b31SStefan Hajnoczi         if (drv && drv->bdrv_io_plug) {
265161007b31SStefan Hajnoczi             drv->bdrv_io_plug(bs);
26526b98bd64SPaolo Bonzini         }
265361007b31SStefan Hajnoczi     }
265461007b31SStefan Hajnoczi }
265561007b31SStefan Hajnoczi 
265661007b31SStefan Hajnoczi void bdrv_io_unplug(BlockDriverState *bs)
265761007b31SStefan Hajnoczi {
26586b98bd64SPaolo Bonzini     BdrvChild *child;
26596b98bd64SPaolo Bonzini 
26606b98bd64SPaolo Bonzini     assert(bs->io_plugged);
26618f90b5e9SPaolo Bonzini     if (--bs->io_plugged == 0) {
266261007b31SStefan Hajnoczi         BlockDriver *drv = bs->drv;
266361007b31SStefan Hajnoczi         if (drv && drv->bdrv_io_unplug) {
266461007b31SStefan Hajnoczi             drv->bdrv_io_unplug(bs);
266561007b31SStefan Hajnoczi         }
266661007b31SStefan Hajnoczi     }
266761007b31SStefan Hajnoczi 
26686b98bd64SPaolo Bonzini     QLIST_FOREACH(child, &bs->children, next) {
26696b98bd64SPaolo Bonzini         bdrv_io_unplug(child->bs);
26706b98bd64SPaolo Bonzini     }
26716b98bd64SPaolo Bonzini }
2672