2 * Block layer I/O functions
4 * Copyright (c) 2003 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 #include "qemu/osdep.h"
27 #include "sysemu/block-backend.h"
28 #include "block/aio-wait.h"
29 #include "block/blockjob.h"
30 #include "block/blockjob_int.h"
31 #include "block/block_int.h"
32 #include "block/coroutines.h"
33 #include "block/write-threshold.h"
34 #include "qemu/cutils.h"
35 #include "qapi/error.h"
36 #include "qemu/error-report.h"
37 #include "qemu/main-loop.h"
38 #include "sysemu/replay.h"
40 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
41 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
43 static void bdrv_parent_cb_resize(BlockDriverState *bs);
44 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
45 int64_t offset, int64_t bytes, BdrvRequestFlags flags);
47 static void bdrv_parent_drained_begin(BlockDriverState *bs, BdrvChild *ignore,
48 bool ignore_bds_parents)
52 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
53 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
56 bdrv_parent_drained_begin_single(c, false);
60 static void bdrv_parent_drained_end_single_no_poll(BdrvChild *c,
61 int *drained_end_counter)
63 assert(c->parent_quiesce_counter > 0);
64 c->parent_quiesce_counter--;
65 if (c->klass->drained_end) {
66 c->klass->drained_end(c, drained_end_counter);
70 void bdrv_parent_drained_end_single(BdrvChild *c)
72 int drained_end_counter = 0;
74 bdrv_parent_drained_end_single_no_poll(c, &drained_end_counter);
75 BDRV_POLL_WHILE(c->bs, qatomic_read(&drained_end_counter) > 0);
78 static void bdrv_parent_drained_end(BlockDriverState *bs, BdrvChild *ignore,
79 bool ignore_bds_parents,
80 int *drained_end_counter)
84 QLIST_FOREACH(c, &bs->parents, next_parent) {
85 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
88 bdrv_parent_drained_end_single_no_poll(c, drained_end_counter);
92 static bool bdrv_parent_drained_poll_single(BdrvChild *c)
94 if (c->klass->drained_poll) {
95 return c->klass->drained_poll(c);
100 static bool bdrv_parent_drained_poll(BlockDriverState *bs, BdrvChild *ignore,
101 bool ignore_bds_parents)
106 QLIST_FOREACH_SAFE(c, &bs->parents, next_parent, next) {
107 if (c == ignore || (ignore_bds_parents && c->klass->parent_is_bds)) {
110 busy |= bdrv_parent_drained_poll_single(c);
116 void bdrv_parent_drained_begin_single(BdrvChild *c, bool poll)
119 c->parent_quiesce_counter++;
120 if (c->klass->drained_begin) {
121 c->klass->drained_begin(c);
124 BDRV_POLL_WHILE(c->bs, bdrv_parent_drained_poll_single(c));
128 static void bdrv_merge_limits(BlockLimits *dst, const BlockLimits *src)
130 dst->pdiscard_alignment = MAX(dst->pdiscard_alignment,
131 src->pdiscard_alignment);
132 dst->opt_transfer = MAX(dst->opt_transfer, src->opt_transfer);
133 dst->max_transfer = MIN_NON_ZERO(dst->max_transfer, src->max_transfer);
134 dst->max_hw_transfer = MIN_NON_ZERO(dst->max_hw_transfer,
135 src->max_hw_transfer);
136 dst->opt_mem_alignment = MAX(dst->opt_mem_alignment,
137 src->opt_mem_alignment);
138 dst->min_mem_alignment = MAX(dst->min_mem_alignment,
139 src->min_mem_alignment);
140 dst->max_iov = MIN_NON_ZERO(dst->max_iov, src->max_iov);
141 dst->max_hw_iov = MIN_NON_ZERO(dst->max_hw_iov, src->max_hw_iov);
144 typedef struct BdrvRefreshLimitsState {
145 BlockDriverState *bs;
147 } BdrvRefreshLimitsState;
149 static void bdrv_refresh_limits_abort(void *opaque)
151 BdrvRefreshLimitsState *s = opaque;
153 s->bs->bl = s->old_bl;
156 static TransactionActionDrv bdrv_refresh_limits_drv = {
157 .abort = bdrv_refresh_limits_abort,
161 /* @tran is allowed to be NULL, in this case no rollback is possible. */
162 void bdrv_refresh_limits(BlockDriverState *bs, Transaction *tran, Error **errp)
165 BlockDriver *drv = bs->drv;
172 BdrvRefreshLimitsState *s = g_new(BdrvRefreshLimitsState, 1);
173 *s = (BdrvRefreshLimitsState) {
177 tran_add(tran, &bdrv_refresh_limits_drv, s);
180 memset(&bs->bl, 0, sizeof(bs->bl));
186 /* Default alignment based on whether driver has byte interface */
187 bs->bl.request_alignment = (drv->bdrv_co_preadv ||
188 drv->bdrv_aio_preadv ||
189 drv->bdrv_co_preadv_part) ? 1 : 512;
191 /* Take some limits from the children as a default */
193 QLIST_FOREACH(c, &bs->children, next) {
194 if (c->role & (BDRV_CHILD_DATA | BDRV_CHILD_FILTERED | BDRV_CHILD_COW))
196 bdrv_merge_limits(&bs->bl, &c->bs->bl);
202 bs->bl.min_mem_alignment = 512;
203 bs->bl.opt_mem_alignment = qemu_real_host_page_size;
205 /* Safe default since most protocols use readv()/writev()/etc */
206 bs->bl.max_iov = IOV_MAX;
209 /* Then let the driver override it */
210 if (drv->bdrv_refresh_limits) {
211 drv->bdrv_refresh_limits(bs, errp);
217 if (bs->bl.request_alignment > BDRV_MAX_ALIGNMENT) {
218 error_setg(errp, "Driver requires too large request alignment");
223 * The copy-on-read flag is actually a reference count so multiple users may
224 * use the feature without worrying about clobbering its previous state.
225 * Copy-on-read stays enabled until all users have called to disable it.
227 void bdrv_enable_copy_on_read(BlockDriverState *bs)
230 qatomic_inc(&bs->copy_on_read);
233 void bdrv_disable_copy_on_read(BlockDriverState *bs)
235 int old = qatomic_fetch_dec(&bs->copy_on_read);
242 BlockDriverState *bs;
248 bool ignore_bds_parents;
249 int *drained_end_counter;
252 static void coroutine_fn bdrv_drain_invoke_entry(void *opaque)
254 BdrvCoDrainData *data = opaque;
255 BlockDriverState *bs = data->bs;
258 bs->drv->bdrv_co_drain_begin(bs);
260 bs->drv->bdrv_co_drain_end(bs);
263 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
264 qatomic_mb_set(&data->done, true);
266 qatomic_dec(data->drained_end_counter);
268 bdrv_dec_in_flight(bs);
273 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
274 static void bdrv_drain_invoke(BlockDriverState *bs, bool begin,
275 int *drained_end_counter)
277 BdrvCoDrainData *data;
279 if (!bs->drv || (begin && !bs->drv->bdrv_co_drain_begin) ||
280 (!begin && !bs->drv->bdrv_co_drain_end)) {
284 data = g_new(BdrvCoDrainData, 1);
285 *data = (BdrvCoDrainData) {
289 .drained_end_counter = drained_end_counter,
293 qatomic_inc(drained_end_counter);
296 /* Make sure the driver callback completes during the polling phase for
298 bdrv_inc_in_flight(bs);
299 data->co = qemu_coroutine_create(bdrv_drain_invoke_entry, data);
300 aio_co_schedule(bdrv_get_aio_context(bs), data->co);
303 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
304 bool bdrv_drain_poll(BlockDriverState *bs, bool recursive,
305 BdrvChild *ignore_parent, bool ignore_bds_parents)
307 BdrvChild *child, *next;
310 if (bdrv_parent_drained_poll(bs, ignore_parent, ignore_bds_parents)) {
314 if (qatomic_read(&bs->in_flight)) {
319 assert(!ignore_bds_parents);
320 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
321 if (bdrv_drain_poll(child->bs, recursive, child, false)) {
330 static bool bdrv_drain_poll_top_level(BlockDriverState *bs, bool recursive,
331 BdrvChild *ignore_parent)
333 return bdrv_drain_poll(bs, recursive, ignore_parent, false);
336 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
337 BdrvChild *parent, bool ignore_bds_parents,
339 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
340 BdrvChild *parent, bool ignore_bds_parents,
341 int *drained_end_counter);
343 static void bdrv_co_drain_bh_cb(void *opaque)
345 BdrvCoDrainData *data = opaque;
346 Coroutine *co = data->co;
347 BlockDriverState *bs = data->bs;
350 AioContext *ctx = bdrv_get_aio_context(bs);
351 aio_context_acquire(ctx);
352 bdrv_dec_in_flight(bs);
354 assert(!data->drained_end_counter);
355 bdrv_do_drained_begin(bs, data->recursive, data->parent,
356 data->ignore_bds_parents, data->poll);
359 bdrv_do_drained_end(bs, data->recursive, data->parent,
360 data->ignore_bds_parents,
361 data->drained_end_counter);
363 aio_context_release(ctx);
366 bdrv_drain_all_begin();
373 static void coroutine_fn bdrv_co_yield_to_drain(BlockDriverState *bs,
374 bool begin, bool recursive,
376 bool ignore_bds_parents,
378 int *drained_end_counter)
380 BdrvCoDrainData data;
381 Coroutine *self = qemu_coroutine_self();
382 AioContext *ctx = bdrv_get_aio_context(bs);
383 AioContext *co_ctx = qemu_coroutine_get_aio_context(self);
385 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
386 * other coroutines run if they were queued by aio_co_enter(). */
388 assert(qemu_in_coroutine());
389 data = (BdrvCoDrainData) {
394 .recursive = recursive,
396 .ignore_bds_parents = ignore_bds_parents,
398 .drained_end_counter = drained_end_counter,
402 bdrv_inc_in_flight(bs);
406 * Temporarily drop the lock across yield or we would get deadlocks.
407 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
409 * When we yield below, the lock for the current context will be
410 * released, so if this is actually the lock that protects bs, don't drop
414 aio_context_release(ctx);
416 replay_bh_schedule_oneshot_event(ctx, bdrv_co_drain_bh_cb, &data);
418 qemu_coroutine_yield();
419 /* If we are resumed from some other event (such as an aio completion or a
420 * timer callback), it is a bug in the caller that should be fixed. */
423 /* Reaquire the AioContext of bs if we dropped it */
425 aio_context_acquire(ctx);
429 void bdrv_do_drained_begin_quiesce(BlockDriverState *bs,
430 BdrvChild *parent, bool ignore_bds_parents)
433 assert(!qemu_in_coroutine());
435 /* Stop things in parent-to-child order */
436 if (qatomic_fetch_inc(&bs->quiesce_counter) == 0) {
437 aio_disable_external(bdrv_get_aio_context(bs));
440 bdrv_parent_drained_begin(bs, parent, ignore_bds_parents);
441 bdrv_drain_invoke(bs, true, NULL);
444 static void bdrv_do_drained_begin(BlockDriverState *bs, bool recursive,
445 BdrvChild *parent, bool ignore_bds_parents,
448 BdrvChild *child, *next;
450 if (qemu_in_coroutine()) {
451 bdrv_co_yield_to_drain(bs, true, recursive, parent, ignore_bds_parents,
456 bdrv_do_drained_begin_quiesce(bs, parent, ignore_bds_parents);
459 assert(!ignore_bds_parents);
460 bs->recursive_quiesce_counter++;
461 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
462 bdrv_do_drained_begin(child->bs, true, child, ignore_bds_parents,
468 * Wait for drained requests to finish.
470 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
471 * call is needed so things in this AioContext can make progress even
472 * though we don't return to the main AioContext loop - this automatically
473 * includes other nodes in the same AioContext and therefore all child
477 assert(!ignore_bds_parents);
478 BDRV_POLL_WHILE(bs, bdrv_drain_poll_top_level(bs, recursive, parent));
482 void bdrv_drained_begin(BlockDriverState *bs)
485 bdrv_do_drained_begin(bs, false, NULL, false, true);
488 void bdrv_subtree_drained_begin(BlockDriverState *bs)
491 bdrv_do_drained_begin(bs, true, NULL, false, true);
495 * This function does not poll, nor must any of its recursively called
496 * functions. The *drained_end_counter pointee will be incremented
497 * once for every background operation scheduled, and decremented once
498 * the operation settles. Therefore, the pointer must remain valid
499 * until the pointee reaches 0. That implies that whoever sets up the
500 * pointee has to poll until it is 0.
502 * We use atomic operations to access *drained_end_counter, because
503 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
504 * @bs may contain nodes in different AioContexts,
505 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
506 * regardless of which AioContext they are in.
508 static void bdrv_do_drained_end(BlockDriverState *bs, bool recursive,
509 BdrvChild *parent, bool ignore_bds_parents,
510 int *drained_end_counter)
513 int old_quiesce_counter;
515 assert(drained_end_counter != NULL);
517 if (qemu_in_coroutine()) {
518 bdrv_co_yield_to_drain(bs, false, recursive, parent, ignore_bds_parents,
519 false, drained_end_counter);
522 assert(bs->quiesce_counter > 0);
524 /* Re-enable things in child-to-parent order */
525 bdrv_drain_invoke(bs, false, drained_end_counter);
526 bdrv_parent_drained_end(bs, parent, ignore_bds_parents,
527 drained_end_counter);
529 old_quiesce_counter = qatomic_fetch_dec(&bs->quiesce_counter);
530 if (old_quiesce_counter == 1) {
531 aio_enable_external(bdrv_get_aio_context(bs));
535 assert(!ignore_bds_parents);
536 bs->recursive_quiesce_counter--;
537 QLIST_FOREACH(child, &bs->children, next) {
538 bdrv_do_drained_end(child->bs, true, child, ignore_bds_parents,
539 drained_end_counter);
544 void bdrv_drained_end(BlockDriverState *bs)
546 int drained_end_counter = 0;
548 bdrv_do_drained_end(bs, false, NULL, false, &drained_end_counter);
549 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
552 void bdrv_drained_end_no_poll(BlockDriverState *bs, int *drained_end_counter)
555 bdrv_do_drained_end(bs, false, NULL, false, drained_end_counter);
558 void bdrv_subtree_drained_end(BlockDriverState *bs)
560 int drained_end_counter = 0;
562 bdrv_do_drained_end(bs, true, NULL, false, &drained_end_counter);
563 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
566 void bdrv_apply_subtree_drain(BdrvChild *child, BlockDriverState *new_parent)
571 for (i = 0; i < new_parent->recursive_quiesce_counter; i++) {
572 bdrv_do_drained_begin(child->bs, true, child, false, true);
576 void bdrv_unapply_subtree_drain(BdrvChild *child, BlockDriverState *old_parent)
578 int drained_end_counter = 0;
582 for (i = 0; i < old_parent->recursive_quiesce_counter; i++) {
583 bdrv_do_drained_end(child->bs, true, child, false,
584 &drained_end_counter);
587 BDRV_POLL_WHILE(child->bs, qatomic_read(&drained_end_counter) > 0);
591 * Wait for pending requests to complete on a single BlockDriverState subtree,
592 * and suspend block driver's internal I/O until next request arrives.
594 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
597 void coroutine_fn bdrv_co_drain(BlockDriverState *bs)
600 assert(qemu_in_coroutine());
601 bdrv_drained_begin(bs);
602 bdrv_drained_end(bs);
605 void bdrv_drain(BlockDriverState *bs)
608 bdrv_drained_begin(bs);
609 bdrv_drained_end(bs);
612 static void bdrv_drain_assert_idle(BlockDriverState *bs)
614 BdrvChild *child, *next;
616 assert(qatomic_read(&bs->in_flight) == 0);
617 QLIST_FOREACH_SAFE(child, &bs->children, next, next) {
618 bdrv_drain_assert_idle(child->bs);
622 unsigned int bdrv_drain_all_count = 0;
624 static bool bdrv_drain_all_poll(void)
626 BlockDriverState *bs = NULL;
630 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
631 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
632 while ((bs = bdrv_next_all_states(bs))) {
633 AioContext *aio_context = bdrv_get_aio_context(bs);
634 aio_context_acquire(aio_context);
635 result |= bdrv_drain_poll(bs, false, NULL, true);
636 aio_context_release(aio_context);
643 * Wait for pending requests to complete across all BlockDriverStates
645 * This function does not flush data to disk, use bdrv_flush_all() for that
646 * after calling this function.
648 * This pauses all block jobs and disables external clients. It must
649 * be paired with bdrv_drain_all_end().
651 * NOTE: no new block jobs or BlockDriverStates can be created between
652 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
654 void bdrv_drain_all_begin(void)
656 BlockDriverState *bs = NULL;
659 if (qemu_in_coroutine()) {
660 bdrv_co_yield_to_drain(NULL, true, false, NULL, true, true, NULL);
665 * bdrv queue is managed by record/replay,
666 * waiting for finishing the I/O requests may
669 if (replay_events_enabled()) {
673 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
674 * loop AioContext, so make sure we're in the main context. */
675 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
676 assert(bdrv_drain_all_count < INT_MAX);
677 bdrv_drain_all_count++;
679 /* Quiesce all nodes, without polling in-flight requests yet. The graph
680 * cannot change during this loop. */
681 while ((bs = bdrv_next_all_states(bs))) {
682 AioContext *aio_context = bdrv_get_aio_context(bs);
684 aio_context_acquire(aio_context);
685 bdrv_do_drained_begin(bs, false, NULL, true, false);
686 aio_context_release(aio_context);
689 /* Now poll the in-flight requests */
690 AIO_WAIT_WHILE(NULL, bdrv_drain_all_poll());
692 while ((bs = bdrv_next_all_states(bs))) {
693 bdrv_drain_assert_idle(bs);
697 void bdrv_drain_all_end_quiesce(BlockDriverState *bs)
699 int drained_end_counter = 0;
702 g_assert(bs->quiesce_counter > 0);
703 g_assert(!bs->refcnt);
705 while (bs->quiesce_counter) {
706 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
708 BDRV_POLL_WHILE(bs, qatomic_read(&drained_end_counter) > 0);
711 void bdrv_drain_all_end(void)
713 BlockDriverState *bs = NULL;
714 int drained_end_counter = 0;
718 * bdrv queue is managed by record/replay,
719 * waiting for finishing the I/O requests may
722 if (replay_events_enabled()) {
726 while ((bs = bdrv_next_all_states(bs))) {
727 AioContext *aio_context = bdrv_get_aio_context(bs);
729 aio_context_acquire(aio_context);
730 bdrv_do_drained_end(bs, false, NULL, true, &drained_end_counter);
731 aio_context_release(aio_context);
734 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
735 AIO_WAIT_WHILE(NULL, qatomic_read(&drained_end_counter) > 0);
737 assert(bdrv_drain_all_count > 0);
738 bdrv_drain_all_count--;
741 void bdrv_drain_all(void)
744 bdrv_drain_all_begin();
745 bdrv_drain_all_end();
749 * Remove an active request from the tracked requests list
751 * This function should be called when a tracked request is completing.
753 static void tracked_request_end(BdrvTrackedRequest *req)
755 if (req->serialising) {
756 qatomic_dec(&req->bs->serialising_in_flight);
759 qemu_co_mutex_lock(&req->bs->reqs_lock);
760 QLIST_REMOVE(req, list);
761 qemu_co_queue_restart_all(&req->wait_queue);
762 qemu_co_mutex_unlock(&req->bs->reqs_lock);
766 * Add an active request to the tracked requests list
768 static void tracked_request_begin(BdrvTrackedRequest *req,
769 BlockDriverState *bs,
772 enum BdrvTrackedRequestType type)
774 bdrv_check_request(offset, bytes, &error_abort);
776 *req = (BdrvTrackedRequest){
781 .co = qemu_coroutine_self(),
782 .serialising = false,
783 .overlap_offset = offset,
784 .overlap_bytes = bytes,
787 qemu_co_queue_init(&req->wait_queue);
789 qemu_co_mutex_lock(&bs->reqs_lock);
790 QLIST_INSERT_HEAD(&bs->tracked_requests, req, list);
791 qemu_co_mutex_unlock(&bs->reqs_lock);
794 static bool tracked_request_overlaps(BdrvTrackedRequest *req,
795 int64_t offset, int64_t bytes)
797 bdrv_check_request(offset, bytes, &error_abort);
800 if (offset >= req->overlap_offset + req->overlap_bytes) {
804 if (req->overlap_offset >= offset + bytes) {
810 /* Called with self->bs->reqs_lock held */
811 static BdrvTrackedRequest *
812 bdrv_find_conflicting_request(BdrvTrackedRequest *self)
814 BdrvTrackedRequest *req;
816 QLIST_FOREACH(req, &self->bs->tracked_requests, list) {
817 if (req == self || (!req->serialising && !self->serialising)) {
820 if (tracked_request_overlaps(req, self->overlap_offset,
821 self->overlap_bytes))
824 * Hitting this means there was a reentrant request, for
825 * example, a block driver issuing nested requests. This must
826 * never happen since it means deadlock.
828 assert(qemu_coroutine_self() != req->co);
831 * If the request is already (indirectly) waiting for us, or
832 * will wait for us as soon as it wakes up, then just go on
833 * (instead of producing a deadlock in the former case).
835 if (!req->waiting_for) {
844 /* Called with self->bs->reqs_lock held */
845 static bool coroutine_fn
846 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest *self)
848 BdrvTrackedRequest *req;
851 while ((req = bdrv_find_conflicting_request(self))) {
852 self->waiting_for = req;
853 qemu_co_queue_wait(&req->wait_queue, &self->bs->reqs_lock);
854 self->waiting_for = NULL;
861 /* Called with req->bs->reqs_lock held */
862 static void tracked_request_set_serialising(BdrvTrackedRequest *req,
865 int64_t overlap_offset = req->offset & ~(align - 1);
866 int64_t overlap_bytes =
867 ROUND_UP(req->offset + req->bytes, align) - overlap_offset;
869 bdrv_check_request(req->offset, req->bytes, &error_abort);
871 if (!req->serialising) {
872 qatomic_inc(&req->bs->serialising_in_flight);
873 req->serialising = true;
876 req->overlap_offset = MIN(req->overlap_offset, overlap_offset);
877 req->overlap_bytes = MAX(req->overlap_bytes, overlap_bytes);
881 * Return the tracked request on @bs for the current coroutine, or
882 * NULL if there is none.
884 BdrvTrackedRequest *coroutine_fn bdrv_co_get_self_request(BlockDriverState *bs)
886 BdrvTrackedRequest *req;
887 Coroutine *self = qemu_coroutine_self();
890 QLIST_FOREACH(req, &bs->tracked_requests, list) {
891 if (req->co == self) {
900 * Round a region to cluster boundaries
902 void bdrv_round_to_clusters(BlockDriverState *bs,
903 int64_t offset, int64_t bytes,
904 int64_t *cluster_offset,
905 int64_t *cluster_bytes)
909 if (bdrv_get_info(bs, &bdi) < 0 || bdi.cluster_size == 0) {
910 *cluster_offset = offset;
911 *cluster_bytes = bytes;
913 int64_t c = bdi.cluster_size;
914 *cluster_offset = QEMU_ALIGN_DOWN(offset, c);
915 *cluster_bytes = QEMU_ALIGN_UP(offset - *cluster_offset + bytes, c);
919 static int bdrv_get_cluster_size(BlockDriverState *bs)
924 ret = bdrv_get_info(bs, &bdi);
925 if (ret < 0 || bdi.cluster_size == 0) {
926 return bs->bl.request_alignment;
928 return bdi.cluster_size;
932 void bdrv_inc_in_flight(BlockDriverState *bs)
935 qatomic_inc(&bs->in_flight);
938 void bdrv_wakeup(BlockDriverState *bs)
944 void bdrv_dec_in_flight(BlockDriverState *bs)
947 qatomic_dec(&bs->in_flight);
951 static bool coroutine_fn bdrv_wait_serialising_requests(BdrvTrackedRequest *self)
953 BlockDriverState *bs = self->bs;
956 if (!qatomic_read(&bs->serialising_in_flight)) {
960 qemu_co_mutex_lock(&bs->reqs_lock);
961 waited = bdrv_wait_serialising_requests_locked(self);
962 qemu_co_mutex_unlock(&bs->reqs_lock);
967 bool coroutine_fn bdrv_make_request_serialising(BdrvTrackedRequest *req,
973 qemu_co_mutex_lock(&req->bs->reqs_lock);
975 tracked_request_set_serialising(req, align);
976 waited = bdrv_wait_serialising_requests_locked(req);
978 qemu_co_mutex_unlock(&req->bs->reqs_lock);
983 int bdrv_check_qiov_request(int64_t offset, int64_t bytes,
984 QEMUIOVector *qiov, size_t qiov_offset,
988 * Check generic offset/bytes correctness
992 error_setg(errp, "offset is negative: %" PRIi64, offset);
997 error_setg(errp, "bytes is negative: %" PRIi64, bytes);
1001 if (bytes > BDRV_MAX_LENGTH) {
1002 error_setg(errp, "bytes(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
1003 bytes, BDRV_MAX_LENGTH);
1007 if (offset > BDRV_MAX_LENGTH) {
1008 error_setg(errp, "offset(%" PRIi64 ") exceeds maximum(%" PRIi64 ")",
1009 offset, BDRV_MAX_LENGTH);
1013 if (offset > BDRV_MAX_LENGTH - bytes) {
1014 error_setg(errp, "sum of offset(%" PRIi64 ") and bytes(%" PRIi64 ") "
1015 "exceeds maximum(%" PRIi64 ")", offset, bytes,
1025 * Check qiov and qiov_offset
1028 if (qiov_offset > qiov->size) {
1029 error_setg(errp, "qiov_offset(%zu) overflow io vector size(%zu)",
1030 qiov_offset, qiov->size);
1034 if (bytes > qiov->size - qiov_offset) {
1035 error_setg(errp, "bytes(%" PRIi64 ") + qiov_offset(%zu) overflow io "
1036 "vector size(%zu)", bytes, qiov_offset, qiov->size);
1043 int bdrv_check_request(int64_t offset, int64_t bytes, Error **errp)
1045 return bdrv_check_qiov_request(offset, bytes, NULL, 0, errp);
1048 static int bdrv_check_request32(int64_t offset, int64_t bytes,
1049 QEMUIOVector *qiov, size_t qiov_offset)
1051 int ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
1056 if (bytes > BDRV_REQUEST_MAX_BYTES) {
1063 int bdrv_pwrite_zeroes(BdrvChild *child, int64_t offset,
1064 int64_t bytes, BdrvRequestFlags flags)
1067 return bdrv_pwritev(child, offset, bytes, NULL,
1068 BDRV_REQ_ZERO_WRITE | flags);
1072 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
1073 * The operation is sped up by checking the block status and only writing
1074 * zeroes to the device if they currently do not return zeroes. Optional
1075 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
1078 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
1080 int bdrv_make_zero(BdrvChild *child, BdrvRequestFlags flags)
1083 int64_t target_size, bytes, offset = 0;
1084 BlockDriverState *bs = child->bs;
1087 target_size = bdrv_getlength(bs);
1088 if (target_size < 0) {
1093 bytes = MIN(target_size - offset, BDRV_REQUEST_MAX_BYTES);
1097 ret = bdrv_block_status(bs, offset, bytes, &bytes, NULL, NULL);
1101 if (ret & BDRV_BLOCK_ZERO) {
1105 ret = bdrv_pwrite_zeroes(child, offset, bytes, flags);
1113 /* See bdrv_pwrite() for the return codes */
1114 int bdrv_pread(BdrvChild *child, int64_t offset, void *buf, int64_t bytes)
1117 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1124 ret = bdrv_preadv(child, offset, bytes, &qiov, 0);
1126 return ret < 0 ? ret : bytes;
1129 /* Return no. of bytes on success or < 0 on error. Important errors are:
1130 -EIO generic I/O error (may happen for all errors)
1131 -ENOMEDIUM No media inserted.
1132 -EINVAL Invalid offset or number of bytes
1133 -EACCES Trying to write a read-only device
1135 int bdrv_pwrite(BdrvChild *child, int64_t offset, const void *buf,
1139 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, bytes);
1146 ret = bdrv_pwritev(child, offset, bytes, &qiov, 0);
1148 return ret < 0 ? ret : bytes;
1152 * Writes to the file and ensures that no writes are reordered across this
1153 * request (acts as a barrier)
1155 * Returns 0 on success, -errno in error cases.
1157 int bdrv_pwrite_sync(BdrvChild *child, int64_t offset,
1158 const void *buf, int64_t count)
1163 ret = bdrv_pwrite(child, offset, buf, count);
1168 ret = bdrv_flush(child->bs);
1176 typedef struct CoroutineIOCompletion {
1177 Coroutine *coroutine;
1179 } CoroutineIOCompletion;
1181 static void bdrv_co_io_em_complete(void *opaque, int ret)
1183 CoroutineIOCompletion *co = opaque;
1186 aio_co_wake(co->coroutine);
1189 static int coroutine_fn bdrv_driver_preadv(BlockDriverState *bs,
1190 int64_t offset, int64_t bytes,
1192 size_t qiov_offset, int flags)
1194 BlockDriver *drv = bs->drv;
1196 unsigned int nb_sectors;
1197 QEMUIOVector local_qiov;
1200 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1201 assert(!(flags & ~BDRV_REQ_MASK));
1202 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1208 if (drv->bdrv_co_preadv_part) {
1209 return drv->bdrv_co_preadv_part(bs, offset, bytes, qiov, qiov_offset,
1213 if (qiov_offset > 0 || bytes != qiov->size) {
1214 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1218 if (drv->bdrv_co_preadv) {
1219 ret = drv->bdrv_co_preadv(bs, offset, bytes, qiov, flags);
1223 if (drv->bdrv_aio_preadv) {
1225 CoroutineIOCompletion co = {
1226 .coroutine = qemu_coroutine_self(),
1229 acb = drv->bdrv_aio_preadv(bs, offset, bytes, qiov, flags,
1230 bdrv_co_io_em_complete, &co);
1235 qemu_coroutine_yield();
1241 sector_num = offset >> BDRV_SECTOR_BITS;
1242 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1244 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1245 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1246 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1247 assert(drv->bdrv_co_readv);
1249 ret = drv->bdrv_co_readv(bs, sector_num, nb_sectors, qiov);
1252 if (qiov == &local_qiov) {
1253 qemu_iovec_destroy(&local_qiov);
1259 static int coroutine_fn bdrv_driver_pwritev(BlockDriverState *bs,
1260 int64_t offset, int64_t bytes,
1263 BdrvRequestFlags flags)
1265 BlockDriver *drv = bs->drv;
1267 unsigned int nb_sectors;
1268 QEMUIOVector local_qiov;
1271 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1272 assert(!(flags & ~BDRV_REQ_MASK));
1273 assert(!(flags & BDRV_REQ_NO_FALLBACK));
1279 if (drv->bdrv_co_pwritev_part) {
1280 ret = drv->bdrv_co_pwritev_part(bs, offset, bytes, qiov, qiov_offset,
1281 flags & bs->supported_write_flags);
1282 flags &= ~bs->supported_write_flags;
1286 if (qiov_offset > 0 || bytes != qiov->size) {
1287 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1291 if (drv->bdrv_co_pwritev) {
1292 ret = drv->bdrv_co_pwritev(bs, offset, bytes, qiov,
1293 flags & bs->supported_write_flags);
1294 flags &= ~bs->supported_write_flags;
1298 if (drv->bdrv_aio_pwritev) {
1300 CoroutineIOCompletion co = {
1301 .coroutine = qemu_coroutine_self(),
1304 acb = drv->bdrv_aio_pwritev(bs, offset, bytes, qiov,
1305 flags & bs->supported_write_flags,
1306 bdrv_co_io_em_complete, &co);
1307 flags &= ~bs->supported_write_flags;
1311 qemu_coroutine_yield();
1317 sector_num = offset >> BDRV_SECTOR_BITS;
1318 nb_sectors = bytes >> BDRV_SECTOR_BITS;
1320 assert(QEMU_IS_ALIGNED(offset, BDRV_SECTOR_SIZE));
1321 assert(QEMU_IS_ALIGNED(bytes, BDRV_SECTOR_SIZE));
1322 assert(bytes <= BDRV_REQUEST_MAX_BYTES);
1324 assert(drv->bdrv_co_writev);
1325 ret = drv->bdrv_co_writev(bs, sector_num, nb_sectors, qiov,
1326 flags & bs->supported_write_flags);
1327 flags &= ~bs->supported_write_flags;
1330 if (ret == 0 && (flags & BDRV_REQ_FUA)) {
1331 ret = bdrv_co_flush(bs);
1334 if (qiov == &local_qiov) {
1335 qemu_iovec_destroy(&local_qiov);
1341 static int coroutine_fn
1342 bdrv_driver_pwritev_compressed(BlockDriverState *bs, int64_t offset,
1343 int64_t bytes, QEMUIOVector *qiov,
1346 BlockDriver *drv = bs->drv;
1347 QEMUIOVector local_qiov;
1350 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1356 if (!block_driver_can_compress(drv)) {
1360 if (drv->bdrv_co_pwritev_compressed_part) {
1361 return drv->bdrv_co_pwritev_compressed_part(bs, offset, bytes,
1365 if (qiov_offset == 0) {
1366 return drv->bdrv_co_pwritev_compressed(bs, offset, bytes, qiov);
1369 qemu_iovec_init_slice(&local_qiov, qiov, qiov_offset, bytes);
1370 ret = drv->bdrv_co_pwritev_compressed(bs, offset, bytes, &local_qiov);
1371 qemu_iovec_destroy(&local_qiov);
1376 static int coroutine_fn bdrv_co_do_copy_on_readv(BdrvChild *child,
1377 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1378 size_t qiov_offset, int flags)
1380 BlockDriverState *bs = child->bs;
1382 /* Perform I/O through a temporary buffer so that users who scribble over
1383 * their read buffer while the operation is in progress do not end up
1384 * modifying the image file. This is critical for zero-copy guest I/O
1385 * where anything might happen inside guest memory.
1387 void *bounce_buffer = NULL;
1389 BlockDriver *drv = bs->drv;
1390 int64_t cluster_offset;
1391 int64_t cluster_bytes;
1394 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer,
1395 BDRV_REQUEST_MAX_BYTES);
1396 int64_t progress = 0;
1399 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1406 * Do not write anything when the BDS is inactive. That is not
1407 * allowed, and it would not help.
1409 skip_write = (bs->open_flags & BDRV_O_INACTIVE);
1411 /* FIXME We cannot require callers to have write permissions when all they
1412 * are doing is a read request. If we did things right, write permissions
1413 * would be obtained anyway, but internally by the copy-on-read code. As
1414 * long as it is implemented here rather than in a separate filter driver,
1415 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1416 * it could request permissions. Therefore we have to bypass the permission
1417 * system for the moment. */
1418 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1420 /* Cover entire cluster so no additional backing file I/O is required when
1421 * allocating cluster in the image file. Note that this value may exceed
1422 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1423 * is one reason we loop rather than doing it all at once.
1425 bdrv_round_to_clusters(bs, offset, bytes, &cluster_offset, &cluster_bytes);
1426 skip_bytes = offset - cluster_offset;
1428 trace_bdrv_co_do_copy_on_readv(bs, offset, bytes,
1429 cluster_offset, cluster_bytes);
1431 while (cluster_bytes) {
1435 ret = 1; /* "already allocated", so nothing will be copied */
1436 pnum = MIN(cluster_bytes, max_transfer);
1438 ret = bdrv_is_allocated(bs, cluster_offset,
1439 MIN(cluster_bytes, max_transfer), &pnum);
1442 * Safe to treat errors in querying allocation as if
1443 * unallocated; we'll probably fail again soon on the
1444 * read, but at least that will set a decent errno.
1446 pnum = MIN(cluster_bytes, max_transfer);
1449 /* Stop at EOF if the image ends in the middle of the cluster */
1450 if (ret == 0 && pnum == 0) {
1451 assert(progress >= bytes);
1455 assert(skip_bytes < pnum);
1459 QEMUIOVector local_qiov;
1461 /* Must copy-on-read; use the bounce buffer */
1462 pnum = MIN(pnum, MAX_BOUNCE_BUFFER);
1463 if (!bounce_buffer) {
1464 int64_t max_we_need = MAX(pnum, cluster_bytes - pnum);
1465 int64_t max_allowed = MIN(max_transfer, MAX_BOUNCE_BUFFER);
1466 int64_t bounce_buffer_len = MIN(max_we_need, max_allowed);
1468 bounce_buffer = qemu_try_blockalign(bs, bounce_buffer_len);
1469 if (!bounce_buffer) {
1474 qemu_iovec_init_buf(&local_qiov, bounce_buffer, pnum);
1476 ret = bdrv_driver_preadv(bs, cluster_offset, pnum,
1482 bdrv_debug_event(bs, BLKDBG_COR_WRITE);
1483 if (drv->bdrv_co_pwrite_zeroes &&
1484 buffer_is_zero(bounce_buffer, pnum)) {
1485 /* FIXME: Should we (perhaps conditionally) be setting
1486 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1487 * that still correctly reads as zero? */
1488 ret = bdrv_co_do_pwrite_zeroes(bs, cluster_offset, pnum,
1489 BDRV_REQ_WRITE_UNCHANGED);
1491 /* This does not change the data on the disk, it is not
1492 * necessary to flush even in cache=writethrough mode.
1494 ret = bdrv_driver_pwritev(bs, cluster_offset, pnum,
1496 BDRV_REQ_WRITE_UNCHANGED);
1500 /* It might be okay to ignore write errors for guest
1501 * requests. If this is a deliberate copy-on-read
1502 * then we don't want to ignore the error. Simply
1503 * report it in all cases.
1508 if (!(flags & BDRV_REQ_PREFETCH)) {
1509 qemu_iovec_from_buf(qiov, qiov_offset + progress,
1510 bounce_buffer + skip_bytes,
1511 MIN(pnum - skip_bytes, bytes - progress));
1513 } else if (!(flags & BDRV_REQ_PREFETCH)) {
1514 /* Read directly into the destination */
1515 ret = bdrv_driver_preadv(bs, offset + progress,
1516 MIN(pnum - skip_bytes, bytes - progress),
1517 qiov, qiov_offset + progress, 0);
1523 cluster_offset += pnum;
1524 cluster_bytes -= pnum;
1525 progress += pnum - skip_bytes;
1531 qemu_vfree(bounce_buffer);
1536 * Forwards an already correctly aligned request to the BlockDriver. This
1537 * handles copy on read, zeroing after EOF, and fragmentation of large
1538 * reads; any other features must be implemented by the caller.
1540 static int coroutine_fn bdrv_aligned_preadv(BdrvChild *child,
1541 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
1542 int64_t align, QEMUIOVector *qiov, size_t qiov_offset, int flags)
1544 BlockDriverState *bs = child->bs;
1545 int64_t total_bytes, max_bytes;
1547 int64_t bytes_remaining = bytes;
1550 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
1551 assert(is_power_of_2(align));
1552 assert((offset & (align - 1)) == 0);
1553 assert((bytes & (align - 1)) == 0);
1554 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
1555 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
1558 /* TODO: We would need a per-BDS .supported_read_flags and
1559 * potential fallback support, if we ever implement any read flags
1560 * to pass through to drivers. For now, there aren't any
1561 * passthrough flags. */
1562 assert(!(flags & ~(BDRV_REQ_COPY_ON_READ | BDRV_REQ_PREFETCH)));
1564 /* Handle Copy on Read and associated serialisation */
1565 if (flags & BDRV_REQ_COPY_ON_READ) {
1566 /* If we touch the same cluster it counts as an overlap. This
1567 * guarantees that allocating writes will be serialized and not race
1568 * with each other for the same cluster. For example, in copy-on-read
1569 * it ensures that the CoR read and write operations are atomic and
1570 * guest writes cannot interleave between them. */
1571 bdrv_make_request_serialising(req, bdrv_get_cluster_size(bs));
1573 bdrv_wait_serialising_requests(req);
1576 if (flags & BDRV_REQ_COPY_ON_READ) {
1579 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1580 flags &= ~BDRV_REQ_COPY_ON_READ;
1582 ret = bdrv_is_allocated(bs, offset, bytes, &pnum);
1587 if (!ret || pnum != bytes) {
1588 ret = bdrv_co_do_copy_on_readv(child, offset, bytes,
1589 qiov, qiov_offset, flags);
1591 } else if (flags & BDRV_REQ_PREFETCH) {
1596 /* Forward the request to the BlockDriver, possibly fragmenting it */
1597 total_bytes = bdrv_getlength(bs);
1598 if (total_bytes < 0) {
1603 assert(!(flags & ~bs->supported_read_flags));
1605 max_bytes = ROUND_UP(MAX(0, total_bytes - offset), align);
1606 if (bytes <= max_bytes && bytes <= max_transfer) {
1607 ret = bdrv_driver_preadv(bs, offset, bytes, qiov, qiov_offset, flags);
1611 while (bytes_remaining) {
1615 num = MIN(bytes_remaining, MIN(max_bytes, max_transfer));
1618 ret = bdrv_driver_preadv(bs, offset + bytes - bytes_remaining,
1620 qiov_offset + bytes - bytes_remaining,
1624 num = bytes_remaining;
1625 ret = qemu_iovec_memset(qiov, qiov_offset + bytes - bytes_remaining,
1626 0, bytes_remaining);
1631 bytes_remaining -= num;
1635 return ret < 0 ? ret : 0;
1641 * |<---- align ----->| |<----- align ---->|
1642 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1644 * -*----------$-------*-------- ... --------*-----$------------*---
1646 * | offset | | end |
1647 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1648 * [buf ... ) [tail_buf )
1650 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1651 * is placed at the beginning of @buf and @tail at the @end.
1653 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1654 * around tail, if tail exists.
1656 * @merge_reads is true for small requests,
1657 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1658 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1660 typedef struct BdrvRequestPadding {
1667 QEMUIOVector local_qiov;
1668 } BdrvRequestPadding;
1670 static bool bdrv_init_padding(BlockDriverState *bs,
1671 int64_t offset, int64_t bytes,
1672 BdrvRequestPadding *pad)
1674 int64_t align = bs->bl.request_alignment;
1677 bdrv_check_request(offset, bytes, &error_abort);
1678 assert(align <= INT_MAX); /* documented in block/block_int.h */
1679 assert(align <= SIZE_MAX / 2); /* so we can allocate the buffer */
1681 memset(pad, 0, sizeof(*pad));
1683 pad->head = offset & (align - 1);
1684 pad->tail = ((offset + bytes) & (align - 1));
1686 pad->tail = align - pad->tail;
1689 if (!pad->head && !pad->tail) {
1693 assert(bytes); /* Nothing good in aligning zero-length requests */
1695 sum = pad->head + bytes + pad->tail;
1696 pad->buf_len = (sum > align && pad->head && pad->tail) ? 2 * align : align;
1697 pad->buf = qemu_blockalign(bs, pad->buf_len);
1698 pad->merge_reads = sum == pad->buf_len;
1700 pad->tail_buf = pad->buf + pad->buf_len - align;
1706 static int bdrv_padding_rmw_read(BdrvChild *child,
1707 BdrvTrackedRequest *req,
1708 BdrvRequestPadding *pad,
1711 QEMUIOVector local_qiov;
1712 BlockDriverState *bs = child->bs;
1713 uint64_t align = bs->bl.request_alignment;
1716 assert(req->serialising && pad->buf);
1718 if (pad->head || pad->merge_reads) {
1719 int64_t bytes = pad->merge_reads ? pad->buf_len : align;
1721 qemu_iovec_init_buf(&local_qiov, pad->buf, bytes);
1724 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_HEAD);
1726 if (pad->merge_reads && pad->tail) {
1727 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1729 ret = bdrv_aligned_preadv(child, req, req->overlap_offset, bytes,
1730 align, &local_qiov, 0, 0);
1735 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_HEAD);
1737 if (pad->merge_reads && pad->tail) {
1738 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1741 if (pad->merge_reads) {
1747 qemu_iovec_init_buf(&local_qiov, pad->tail_buf, align);
1749 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_TAIL);
1750 ret = bdrv_aligned_preadv(
1752 req->overlap_offset + req->overlap_bytes - align,
1753 align, align, &local_qiov, 0, 0);
1757 bdrv_debug_event(bs, BLKDBG_PWRITEV_RMW_AFTER_TAIL);
1762 memset(pad->buf + pad->head, 0, pad->buf_len - pad->head - pad->tail);
1768 static void bdrv_padding_destroy(BdrvRequestPadding *pad)
1771 qemu_vfree(pad->buf);
1772 qemu_iovec_destroy(&pad->local_qiov);
1774 memset(pad, 0, sizeof(*pad));
1780 * Exchange request parameters with padded request if needed. Don't include RMW
1781 * read of padding, bdrv_padding_rmw_read() should be called separately if
1784 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1785 * - on function start they represent original request
1786 * - on failure or when padding is not needed they are unchanged
1787 * - on success when padding is needed they represent padded request
1789 static int bdrv_pad_request(BlockDriverState *bs,
1790 QEMUIOVector **qiov, size_t *qiov_offset,
1791 int64_t *offset, int64_t *bytes,
1792 BdrvRequestPadding *pad, bool *padded)
1796 bdrv_check_qiov_request(*offset, *bytes, *qiov, *qiov_offset, &error_abort);
1798 if (!bdrv_init_padding(bs, *offset, *bytes, pad)) {
1805 ret = qemu_iovec_init_extended(&pad->local_qiov, pad->buf, pad->head,
1806 *qiov, *qiov_offset, *bytes,
1807 pad->buf + pad->buf_len - pad->tail,
1810 bdrv_padding_destroy(pad);
1813 *bytes += pad->head + pad->tail;
1814 *offset -= pad->head;
1815 *qiov = &pad->local_qiov;
1824 int coroutine_fn bdrv_co_preadv(BdrvChild *child,
1825 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
1826 BdrvRequestFlags flags)
1829 return bdrv_co_preadv_part(child, offset, bytes, qiov, 0, flags);
1832 int coroutine_fn bdrv_co_preadv_part(BdrvChild *child,
1833 int64_t offset, int64_t bytes,
1834 QEMUIOVector *qiov, size_t qiov_offset,
1835 BdrvRequestFlags flags)
1837 BlockDriverState *bs = child->bs;
1838 BdrvTrackedRequest req;
1839 BdrvRequestPadding pad;
1843 trace_bdrv_co_preadv_part(bs, offset, bytes, flags);
1845 if (!bdrv_is_inserted(bs)) {
1849 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
1854 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
1856 * Aligning zero request is nonsense. Even if driver has special meaning
1857 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1858 * it to driver due to request_alignment.
1860 * Still, no reason to return an error if someone do unaligned
1861 * zero-length read occasionally.
1866 bdrv_inc_in_flight(bs);
1868 /* Don't do copy-on-read if we read data before write operation */
1869 if (qatomic_read(&bs->copy_on_read)) {
1870 flags |= BDRV_REQ_COPY_ON_READ;
1873 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
1879 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_READ);
1880 ret = bdrv_aligned_preadv(child, &req, offset, bytes,
1881 bs->bl.request_alignment,
1882 qiov, qiov_offset, flags);
1883 tracked_request_end(&req);
1884 bdrv_padding_destroy(&pad);
1887 bdrv_dec_in_flight(bs);
1892 static int coroutine_fn bdrv_co_do_pwrite_zeroes(BlockDriverState *bs,
1893 int64_t offset, int64_t bytes, BdrvRequestFlags flags)
1895 BlockDriver *drv = bs->drv;
1899 bool need_flush = false;
1903 int64_t max_write_zeroes = MIN_NON_ZERO(bs->bl.max_pwrite_zeroes,
1905 int alignment = MAX(bs->bl.pwrite_zeroes_alignment,
1906 bs->bl.request_alignment);
1907 int max_transfer = MIN_NON_ZERO(bs->bl.max_transfer, MAX_BOUNCE_BUFFER);
1909 bdrv_check_request(offset, bytes, &error_abort);
1915 if ((flags & ~bs->supported_zero_flags) & BDRV_REQ_NO_FALLBACK) {
1919 /* Invalidate the cached block-status data range if this write overlaps */
1920 bdrv_bsc_invalidate_range(bs, offset, bytes);
1922 assert(alignment % bs->bl.request_alignment == 0);
1923 head = offset % alignment;
1924 tail = (offset + bytes) % alignment;
1925 max_write_zeroes = QEMU_ALIGN_DOWN(max_write_zeroes, alignment);
1926 assert(max_write_zeroes >= bs->bl.request_alignment);
1928 while (bytes > 0 && !ret) {
1929 int64_t num = bytes;
1931 /* Align request. Block drivers can expect the "bulk" of the request
1932 * to be aligned, and that unaligned requests do not cross cluster
1936 /* Make a small request up to the first aligned sector. For
1937 * convenience, limit this request to max_transfer even if
1938 * we don't need to fall back to writes. */
1939 num = MIN(MIN(bytes, max_transfer), alignment - head);
1940 head = (head + num) % alignment;
1941 assert(num < max_write_zeroes);
1942 } else if (tail && num > alignment) {
1943 /* Shorten the request to the last aligned sector. */
1947 /* limit request size */
1948 if (num > max_write_zeroes) {
1949 num = max_write_zeroes;
1953 /* First try the efficient write zeroes operation */
1954 if (drv->bdrv_co_pwrite_zeroes) {
1955 ret = drv->bdrv_co_pwrite_zeroes(bs, offset, num,
1956 flags & bs->supported_zero_flags);
1957 if (ret != -ENOTSUP && (flags & BDRV_REQ_FUA) &&
1958 !(bs->supported_zero_flags & BDRV_REQ_FUA)) {
1962 assert(!bs->supported_zero_flags);
1965 if (ret == -ENOTSUP && !(flags & BDRV_REQ_NO_FALLBACK)) {
1966 /* Fall back to bounce buffer if write zeroes is unsupported */
1967 BdrvRequestFlags write_flags = flags & ~BDRV_REQ_ZERO_WRITE;
1969 if ((flags & BDRV_REQ_FUA) &&
1970 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
1971 /* No need for bdrv_driver_pwrite() to do a fallback
1972 * flush on each chunk; use just one at the end */
1973 write_flags &= ~BDRV_REQ_FUA;
1976 num = MIN(num, max_transfer);
1978 buf = qemu_try_blockalign0(bs, num);
1984 qemu_iovec_init_buf(&qiov, buf, num);
1986 ret = bdrv_driver_pwritev(bs, offset, num, &qiov, 0, write_flags);
1988 /* Keep bounce buffer around if it is big enough for all
1989 * all future requests.
1991 if (num < max_transfer) {
2002 if (ret == 0 && need_flush) {
2003 ret = bdrv_co_flush(bs);
2009 static inline int coroutine_fn
2010 bdrv_co_write_req_prepare(BdrvChild *child, int64_t offset, int64_t bytes,
2011 BdrvTrackedRequest *req, int flags)
2013 BlockDriverState *bs = child->bs;
2015 bdrv_check_request(offset, bytes, &error_abort);
2017 if (bdrv_is_read_only(bs)) {
2021 assert(!(bs->open_flags & BDRV_O_INACTIVE));
2022 assert((bs->open_flags & BDRV_O_NO_IO) == 0);
2023 assert(!(flags & ~BDRV_REQ_MASK));
2024 assert(!((flags & BDRV_REQ_NO_WAIT) && !(flags & BDRV_REQ_SERIALISING)));
2026 if (flags & BDRV_REQ_SERIALISING) {
2027 QEMU_LOCK_GUARD(&bs->reqs_lock);
2029 tracked_request_set_serialising(req, bdrv_get_cluster_size(bs));
2031 if ((flags & BDRV_REQ_NO_WAIT) && bdrv_find_conflicting_request(req)) {
2035 bdrv_wait_serialising_requests_locked(req);
2037 bdrv_wait_serialising_requests(req);
2040 assert(req->overlap_offset <= offset);
2041 assert(offset + bytes <= req->overlap_offset + req->overlap_bytes);
2042 assert(offset + bytes <= bs->total_sectors * BDRV_SECTOR_SIZE ||
2043 child->perm & BLK_PERM_RESIZE);
2045 switch (req->type) {
2046 case BDRV_TRACKED_WRITE:
2047 case BDRV_TRACKED_DISCARD:
2048 if (flags & BDRV_REQ_WRITE_UNCHANGED) {
2049 assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
2051 assert(child->perm & BLK_PERM_WRITE);
2053 bdrv_write_threshold_check_write(bs, offset, bytes);
2055 case BDRV_TRACKED_TRUNCATE:
2056 assert(child->perm & BLK_PERM_RESIZE);
2063 static inline void coroutine_fn
2064 bdrv_co_write_req_finish(BdrvChild *child, int64_t offset, int64_t bytes,
2065 BdrvTrackedRequest *req, int ret)
2067 int64_t end_sector = DIV_ROUND_UP(offset + bytes, BDRV_SECTOR_SIZE);
2068 BlockDriverState *bs = child->bs;
2070 bdrv_check_request(offset, bytes, &error_abort);
2072 qatomic_inc(&bs->write_gen);
2075 * Discard cannot extend the image, but in error handling cases, such as
2076 * when reverting a qcow2 cluster allocation, the discarded range can pass
2077 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
2078 * here. Instead, just skip it, since semantically a discard request
2079 * beyond EOF cannot expand the image anyway.
2082 (req->type == BDRV_TRACKED_TRUNCATE ||
2083 end_sector > bs->total_sectors) &&
2084 req->type != BDRV_TRACKED_DISCARD) {
2085 bs->total_sectors = end_sector;
2086 bdrv_parent_cb_resize(bs);
2087 bdrv_dirty_bitmap_truncate(bs, end_sector << BDRV_SECTOR_BITS);
2090 switch (req->type) {
2091 case BDRV_TRACKED_WRITE:
2092 stat64_max(&bs->wr_highest_offset, offset + bytes);
2093 /* fall through, to set dirty bits */
2094 case BDRV_TRACKED_DISCARD:
2095 bdrv_set_dirty(bs, offset, bytes);
2104 * Forwards an already correctly aligned write request to the BlockDriver,
2105 * after possibly fragmenting it.
2107 static int coroutine_fn bdrv_aligned_pwritev(BdrvChild *child,
2108 BdrvTrackedRequest *req, int64_t offset, int64_t bytes,
2109 int64_t align, QEMUIOVector *qiov, size_t qiov_offset,
2110 BdrvRequestFlags flags)
2112 BlockDriverState *bs = child->bs;
2113 BlockDriver *drv = bs->drv;
2116 int64_t bytes_remaining = bytes;
2119 bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, &error_abort);
2125 if (bdrv_has_readonly_bitmaps(bs)) {
2129 assert(is_power_of_2(align));
2130 assert((offset & (align - 1)) == 0);
2131 assert((bytes & (align - 1)) == 0);
2132 max_transfer = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_transfer, INT_MAX),
2135 ret = bdrv_co_write_req_prepare(child, offset, bytes, req, flags);
2137 if (!ret && bs->detect_zeroes != BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF &&
2138 !(flags & BDRV_REQ_ZERO_WRITE) && drv->bdrv_co_pwrite_zeroes &&
2139 qemu_iovec_is_zero(qiov, qiov_offset, bytes)) {
2140 flags |= BDRV_REQ_ZERO_WRITE;
2141 if (bs->detect_zeroes == BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP) {
2142 flags |= BDRV_REQ_MAY_UNMAP;
2147 /* Do nothing, write notifier decided to fail this request */
2148 } else if (flags & BDRV_REQ_ZERO_WRITE) {
2149 bdrv_debug_event(bs, BLKDBG_PWRITEV_ZERO);
2150 ret = bdrv_co_do_pwrite_zeroes(bs, offset, bytes, flags);
2151 } else if (flags & BDRV_REQ_WRITE_COMPRESSED) {
2152 ret = bdrv_driver_pwritev_compressed(bs, offset, bytes,
2154 } else if (bytes <= max_transfer) {
2155 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2156 ret = bdrv_driver_pwritev(bs, offset, bytes, qiov, qiov_offset, flags);
2158 bdrv_debug_event(bs, BLKDBG_PWRITEV);
2159 while (bytes_remaining) {
2160 int num = MIN(bytes_remaining, max_transfer);
2161 int local_flags = flags;
2164 if (num < bytes_remaining && (flags & BDRV_REQ_FUA) &&
2165 !(bs->supported_write_flags & BDRV_REQ_FUA)) {
2166 /* If FUA is going to be emulated by flush, we only
2167 * need to flush on the last iteration */
2168 local_flags &= ~BDRV_REQ_FUA;
2171 ret = bdrv_driver_pwritev(bs, offset + bytes - bytes_remaining,
2173 qiov_offset + bytes - bytes_remaining,
2178 bytes_remaining -= num;
2181 bdrv_debug_event(bs, BLKDBG_PWRITEV_DONE);
2186 bdrv_co_write_req_finish(child, offset, bytes, req, ret);
2191 static int coroutine_fn bdrv_co_do_zero_pwritev(BdrvChild *child,
2194 BdrvRequestFlags flags,
2195 BdrvTrackedRequest *req)
2197 BlockDriverState *bs = child->bs;
2198 QEMUIOVector local_qiov;
2199 uint64_t align = bs->bl.request_alignment;
2202 BdrvRequestPadding pad;
2204 padding = bdrv_init_padding(bs, offset, bytes, &pad);
2206 assert(!(flags & BDRV_REQ_NO_WAIT));
2207 bdrv_make_request_serialising(req, align);
2209 bdrv_padding_rmw_read(child, req, &pad, true);
2211 if (pad.head || pad.merge_reads) {
2212 int64_t aligned_offset = offset & ~(align - 1);
2213 int64_t write_bytes = pad.merge_reads ? pad.buf_len : align;
2215 qemu_iovec_init_buf(&local_qiov, pad.buf, write_bytes);
2216 ret = bdrv_aligned_pwritev(child, req, aligned_offset, write_bytes,
2217 align, &local_qiov, 0,
2218 flags & ~BDRV_REQ_ZERO_WRITE);
2219 if (ret < 0 || pad.merge_reads) {
2220 /* Error or all work is done */
2223 offset += write_bytes - pad.head;
2224 bytes -= write_bytes - pad.head;
2228 assert(!bytes || (offset & (align - 1)) == 0);
2229 if (bytes >= align) {
2230 /* Write the aligned part in the middle. */
2231 int64_t aligned_bytes = bytes & ~(align - 1);
2232 ret = bdrv_aligned_pwritev(child, req, offset, aligned_bytes, align,
2237 bytes -= aligned_bytes;
2238 offset += aligned_bytes;
2241 assert(!bytes || (offset & (align - 1)) == 0);
2243 assert(align == pad.tail + bytes);
2245 qemu_iovec_init_buf(&local_qiov, pad.tail_buf, align);
2246 ret = bdrv_aligned_pwritev(child, req, offset, align, align,
2248 flags & ~BDRV_REQ_ZERO_WRITE);
2252 bdrv_padding_destroy(&pad);
2258 * Handle a write request in coroutine context
2260 int coroutine_fn bdrv_co_pwritev(BdrvChild *child,
2261 int64_t offset, int64_t bytes, QEMUIOVector *qiov,
2262 BdrvRequestFlags flags)
2265 return bdrv_co_pwritev_part(child, offset, bytes, qiov, 0, flags);
2268 int coroutine_fn bdrv_co_pwritev_part(BdrvChild *child,
2269 int64_t offset, int64_t bytes, QEMUIOVector *qiov, size_t qiov_offset,
2270 BdrvRequestFlags flags)
2272 BlockDriverState *bs = child->bs;
2273 BdrvTrackedRequest req;
2274 uint64_t align = bs->bl.request_alignment;
2275 BdrvRequestPadding pad;
2277 bool padded = false;
2280 trace_bdrv_co_pwritev_part(child->bs, offset, bytes, flags);
2282 if (!bdrv_is_inserted(bs)) {
2286 if (flags & BDRV_REQ_ZERO_WRITE) {
2287 ret = bdrv_check_qiov_request(offset, bytes, qiov, qiov_offset, NULL);
2289 ret = bdrv_check_request32(offset, bytes, qiov, qiov_offset);
2295 /* If the request is misaligned then we can't make it efficient */
2296 if ((flags & BDRV_REQ_NO_FALLBACK) &&
2297 !QEMU_IS_ALIGNED(offset | bytes, align))
2302 if (bytes == 0 && !QEMU_IS_ALIGNED(offset, bs->bl.request_alignment)) {
2304 * Aligning zero request is nonsense. Even if driver has special meaning
2305 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2306 * it to driver due to request_alignment.
2308 * Still, no reason to return an error if someone do unaligned
2309 * zero-length write occasionally.
2314 if (!(flags & BDRV_REQ_ZERO_WRITE)) {
2316 * Pad request for following read-modify-write cycle.
2317 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2318 * alignment only if there is no ZERO flag.
2320 ret = bdrv_pad_request(bs, &qiov, &qiov_offset, &offset, &bytes, &pad,
2327 bdrv_inc_in_flight(bs);
2328 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_WRITE);
2330 if (flags & BDRV_REQ_ZERO_WRITE) {
2332 ret = bdrv_co_do_zero_pwritev(child, offset, bytes, flags, &req);
2338 * Request was unaligned to request_alignment and therefore
2339 * padded. We are going to do read-modify-write, and must
2340 * serialize the request to prevent interactions of the
2341 * widened region with other transactions.
2343 assert(!(flags & BDRV_REQ_NO_WAIT));
2344 bdrv_make_request_serialising(&req, align);
2345 bdrv_padding_rmw_read(child, &req, &pad, false);
2348 ret = bdrv_aligned_pwritev(child, &req, offset, bytes, align,
2349 qiov, qiov_offset, flags);
2351 bdrv_padding_destroy(&pad);
2354 tracked_request_end(&req);
2355 bdrv_dec_in_flight(bs);
2360 int coroutine_fn bdrv_co_pwrite_zeroes(BdrvChild *child, int64_t offset,
2361 int64_t bytes, BdrvRequestFlags flags)
2364 trace_bdrv_co_pwrite_zeroes(child->bs, offset, bytes, flags);
2366 if (!(child->bs->open_flags & BDRV_O_UNMAP)) {
2367 flags &= ~BDRV_REQ_MAY_UNMAP;
2370 return bdrv_co_pwritev(child, offset, bytes, NULL,
2371 BDRV_REQ_ZERO_WRITE | flags);
2375 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2377 int bdrv_flush_all(void)
2379 BdrvNextIterator it;
2380 BlockDriverState *bs = NULL;
2383 GLOBAL_STATE_CODE();
2386 * bdrv queue is managed by record/replay,
2387 * creating new flush request for stopping
2388 * the VM may break the determinism
2390 if (replay_events_enabled()) {
2394 for (bs = bdrv_first(&it); bs; bs = bdrv_next(&it)) {
2395 AioContext *aio_context = bdrv_get_aio_context(bs);
2398 aio_context_acquire(aio_context);
2399 ret = bdrv_flush(bs);
2400 if (ret < 0 && !result) {
2403 aio_context_release(aio_context);
2410 * Returns the allocation status of the specified sectors.
2411 * Drivers not implementing the functionality are assumed to not support
2412 * backing files, hence all their sectors are reported as allocated.
2414 * If 'want_zero' is true, the caller is querying for mapping
2415 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2416 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2417 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2419 * If 'offset' is beyond the end of the disk image the return value is
2420 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2422 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2423 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2424 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2426 * 'pnum' is set to the number of bytes (including and immediately
2427 * following the specified offset) that are easily known to be in the
2428 * same allocated/unallocated state. Note that a second call starting
2429 * at the original offset plus returned pnum may have the same status.
2430 * The returned value is non-zero on success except at end-of-file.
2432 * Returns negative errno on failure. Otherwise, if the
2433 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2434 * set to the host mapping and BDS corresponding to the guest offset.
2436 static int coroutine_fn bdrv_co_block_status(BlockDriverState *bs,
2438 int64_t offset, int64_t bytes,
2439 int64_t *pnum, int64_t *map,
2440 BlockDriverState **file)
2443 int64_t n; /* bytes */
2445 int64_t local_map = 0;
2446 BlockDriverState *local_file = NULL;
2447 int64_t aligned_offset, aligned_bytes;
2449 bool has_filtered_child;
2453 total_size = bdrv_getlength(bs);
2454 if (total_size < 0) {
2459 if (offset >= total_size) {
2460 ret = BDRV_BLOCK_EOF;
2468 n = total_size - offset;
2473 /* Must be non-NULL or bdrv_getlength() would have failed */
2475 has_filtered_child = bdrv_filter_child(bs);
2476 if (!bs->drv->bdrv_co_block_status && !has_filtered_child) {
2478 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_ALLOCATED;
2479 if (offset + bytes == total_size) {
2480 ret |= BDRV_BLOCK_EOF;
2482 if (bs->drv->protocol_name) {
2483 ret |= BDRV_BLOCK_OFFSET_VALID;
2490 bdrv_inc_in_flight(bs);
2492 /* Round out to request_alignment boundaries */
2493 align = bs->bl.request_alignment;
2494 aligned_offset = QEMU_ALIGN_DOWN(offset, align);
2495 aligned_bytes = ROUND_UP(offset + bytes, align) - aligned_offset;
2497 if (bs->drv->bdrv_co_block_status) {
2499 * Use the block-status cache only for protocol nodes: Format
2500 * drivers are generally quick to inquire the status, but protocol
2501 * drivers often need to get information from outside of qemu, so
2502 * we do not have control over the actual implementation. There
2503 * have been cases where inquiring the status took an unreasonably
2504 * long time, and we can do nothing in qemu to fix it.
2505 * This is especially problematic for images with large data areas,
2506 * because finding the few holes in them and giving them special
2507 * treatment does not gain much performance. Therefore, we try to
2508 * cache the last-identified data region.
2510 * Second, limiting ourselves to protocol nodes allows us to assume
2511 * the block status for data regions to be DATA | OFFSET_VALID, and
2512 * that the host offset is the same as the guest offset.
2514 * Note that it is possible that external writers zero parts of
2515 * the cached regions without the cache being invalidated, and so
2516 * we may report zeroes as data. This is not catastrophic,
2517 * however, because reporting zeroes as data is fine.
2519 if (QLIST_EMPTY(&bs->children) &&
2520 bdrv_bsc_is_data(bs, aligned_offset, pnum))
2522 ret = BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID;
2524 local_map = aligned_offset;
2526 ret = bs->drv->bdrv_co_block_status(bs, want_zero, aligned_offset,
2527 aligned_bytes, pnum, &local_map,
2531 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2532 * the cache is queried above. Technically, we do not need to check
2533 * it here; the worst that can happen is that we fill the cache for
2534 * non-protocol nodes, and then it is never used. However, filling
2535 * the cache requires an RCU update, so double check here to avoid
2536 * such an update if possible.
2538 * Check want_zero, because we only want to update the cache when we
2539 * have accurate information about what is zero and what is data.
2542 ret == (BDRV_BLOCK_DATA | BDRV_BLOCK_OFFSET_VALID) &&
2543 QLIST_EMPTY(&bs->children))
2546 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2547 * returned local_map value must be the same as the offset we
2548 * have passed (aligned_offset), and local_bs must be the node
2550 * Assert this, because we follow this rule when reading from
2551 * the cache (see the `local_file = bs` and
2552 * `local_map = aligned_offset` assignments above), and the
2553 * result the cache delivers must be the same as the driver
2556 assert(local_file == bs);
2557 assert(local_map == aligned_offset);
2558 bdrv_bsc_fill(bs, aligned_offset, *pnum);
2562 /* Default code for filters */
2564 local_file = bdrv_filter_bs(bs);
2567 *pnum = aligned_bytes;
2568 local_map = aligned_offset;
2569 ret = BDRV_BLOCK_RAW | BDRV_BLOCK_OFFSET_VALID;
2577 * The driver's result must be a non-zero multiple of request_alignment.
2578 * Clamp pnum and adjust map to original request.
2580 assert(*pnum && QEMU_IS_ALIGNED(*pnum, align) &&
2581 align > offset - aligned_offset);
2582 if (ret & BDRV_BLOCK_RECURSE) {
2583 assert(ret & BDRV_BLOCK_DATA);
2584 assert(ret & BDRV_BLOCK_OFFSET_VALID);
2585 assert(!(ret & BDRV_BLOCK_ZERO));
2588 *pnum -= offset - aligned_offset;
2589 if (*pnum > bytes) {
2592 if (ret & BDRV_BLOCK_OFFSET_VALID) {
2593 local_map += offset - aligned_offset;
2596 if (ret & BDRV_BLOCK_RAW) {
2597 assert(ret & BDRV_BLOCK_OFFSET_VALID && local_file);
2598 ret = bdrv_co_block_status(local_file, want_zero, local_map,
2599 *pnum, pnum, &local_map, &local_file);
2603 if (ret & (BDRV_BLOCK_DATA | BDRV_BLOCK_ZERO)) {
2604 ret |= BDRV_BLOCK_ALLOCATED;
2605 } else if (bs->drv->supports_backing) {
2606 BlockDriverState *cow_bs = bdrv_cow_bs(bs);
2609 ret |= BDRV_BLOCK_ZERO;
2610 } else if (want_zero) {
2611 int64_t size2 = bdrv_getlength(cow_bs);
2613 if (size2 >= 0 && offset >= size2) {
2614 ret |= BDRV_BLOCK_ZERO;
2619 if (want_zero && ret & BDRV_BLOCK_RECURSE &&
2620 local_file && local_file != bs &&
2621 (ret & BDRV_BLOCK_DATA) && !(ret & BDRV_BLOCK_ZERO) &&
2622 (ret & BDRV_BLOCK_OFFSET_VALID)) {
2626 ret2 = bdrv_co_block_status(local_file, want_zero, local_map,
2627 *pnum, &file_pnum, NULL, NULL);
2629 /* Ignore errors. This is just providing extra information, it
2630 * is useful but not necessary.
2632 if (ret2 & BDRV_BLOCK_EOF &&
2633 (!file_pnum || ret2 & BDRV_BLOCK_ZERO)) {
2635 * It is valid for the format block driver to read
2636 * beyond the end of the underlying file's current
2637 * size; such areas read as zero.
2639 ret |= BDRV_BLOCK_ZERO;
2641 /* Limit request to the range reported by the protocol driver */
2643 ret |= (ret2 & BDRV_BLOCK_ZERO);
2649 bdrv_dec_in_flight(bs);
2650 if (ret >= 0 && offset + *pnum == total_size) {
2651 ret |= BDRV_BLOCK_EOF;
2664 bdrv_co_common_block_status_above(BlockDriverState *bs,
2665 BlockDriverState *base,
2672 BlockDriverState **file,
2676 BlockDriverState *p;
2681 assert(!include_base || base); /* Can't include NULL base */
2688 if (!include_base && bs == base) {
2693 ret = bdrv_co_block_status(bs, want_zero, offset, bytes, pnum, map, file);
2695 if (ret < 0 || *pnum == 0 || ret & BDRV_BLOCK_ALLOCATED || bs == base) {
2699 if (ret & BDRV_BLOCK_EOF) {
2700 eof = offset + *pnum;
2703 assert(*pnum <= bytes);
2706 for (p = bdrv_filter_or_cow_bs(bs); include_base || p != base;
2707 p = bdrv_filter_or_cow_bs(p))
2709 ret = bdrv_co_block_status(p, want_zero, offset, bytes, pnum, map,
2717 * The top layer deferred to this layer, and because this layer is
2718 * short, any zeroes that we synthesize beyond EOF behave as if they
2719 * were allocated at this layer.
2721 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2722 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2725 assert(ret & BDRV_BLOCK_EOF);
2730 ret = BDRV_BLOCK_ZERO | BDRV_BLOCK_ALLOCATED;
2733 if (ret & BDRV_BLOCK_ALLOCATED) {
2735 * We've found the node and the status, we must break.
2737 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2738 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2741 ret &= ~BDRV_BLOCK_EOF;
2746 assert(include_base);
2751 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2752 * let's continue the diving.
2754 assert(*pnum <= bytes);
2758 if (offset + *pnum == eof) {
2759 ret |= BDRV_BLOCK_EOF;
2765 int bdrv_block_status_above(BlockDriverState *bs, BlockDriverState *base,
2766 int64_t offset, int64_t bytes, int64_t *pnum,
2767 int64_t *map, BlockDriverState **file)
2770 return bdrv_common_block_status_above(bs, base, false, true, offset, bytes,
2771 pnum, map, file, NULL);
2774 int bdrv_block_status(BlockDriverState *bs, int64_t offset, int64_t bytes,
2775 int64_t *pnum, int64_t *map, BlockDriverState **file)
2778 return bdrv_block_status_above(bs, bdrv_filter_or_cow_bs(bs),
2779 offset, bytes, pnum, map, file);
2783 * Check @bs (and its backing chain) to see if the range defined
2784 * by @offset and @bytes is known to read as zeroes.
2785 * Return 1 if that is the case, 0 otherwise and -errno on error.
2786 * This test is meant to be fast rather than accurate so returning 0
2787 * does not guarantee non-zero data.
2789 int coroutine_fn bdrv_co_is_zero_fast(BlockDriverState *bs, int64_t offset,
2793 int64_t pnum = bytes;
2800 ret = bdrv_common_block_status_above(bs, NULL, false, false, offset,
2801 bytes, &pnum, NULL, NULL, NULL);
2807 return (pnum == bytes) && (ret & BDRV_BLOCK_ZERO);
2810 int coroutine_fn bdrv_is_allocated(BlockDriverState *bs, int64_t offset,
2811 int64_t bytes, int64_t *pnum)
2817 ret = bdrv_common_block_status_above(bs, bs, true, false, offset,
2818 bytes, pnum ? pnum : &dummy, NULL,
2823 return !!(ret & BDRV_BLOCK_ALLOCATED);
2827 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2829 * Return a positive depth if (a prefix of) the given range is allocated
2830 * in any image between BASE and TOP (BASE is only included if include_base
2831 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2832 * BASE can be NULL to check if the given offset is allocated in any
2833 * image of the chain. Return 0 otherwise, or negative errno on
2836 * 'pnum' is set to the number of bytes (including and immediately
2837 * following the specified offset) that are known to be in the same
2838 * allocated/unallocated state. Note that a subsequent call starting
2839 * at 'offset + *pnum' may return the same allocation status (in other
2840 * words, the result is not necessarily the maximum possible range);
2841 * but 'pnum' will only be 0 when end of file is reached.
2843 int bdrv_is_allocated_above(BlockDriverState *top,
2844 BlockDriverState *base,
2845 bool include_base, int64_t offset,
2846 int64_t bytes, int64_t *pnum)
2849 int ret = bdrv_common_block_status_above(top, base, include_base, false,
2850 offset, bytes, pnum, NULL, NULL,
2857 if (ret & BDRV_BLOCK_ALLOCATED) {
2864 bdrv_co_readv_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2866 BlockDriver *drv = bs->drv;
2867 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2871 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2880 bdrv_inc_in_flight(bs);
2882 if (drv->bdrv_load_vmstate) {
2883 ret = drv->bdrv_load_vmstate(bs, qiov, pos);
2884 } else if (child_bs) {
2885 ret = bdrv_co_readv_vmstate(child_bs, qiov, pos);
2890 bdrv_dec_in_flight(bs);
2896 bdrv_co_writev_vmstate(BlockDriverState *bs, QEMUIOVector *qiov, int64_t pos)
2898 BlockDriver *drv = bs->drv;
2899 BlockDriverState *child_bs = bdrv_primary_bs(bs);
2903 ret = bdrv_check_qiov_request(pos, qiov->size, qiov, 0, NULL);
2912 bdrv_inc_in_flight(bs);
2914 if (drv->bdrv_save_vmstate) {
2915 ret = drv->bdrv_save_vmstate(bs, qiov, pos);
2916 } else if (child_bs) {
2917 ret = bdrv_co_writev_vmstate(child_bs, qiov, pos);
2922 bdrv_dec_in_flight(bs);
2927 int bdrv_save_vmstate(BlockDriverState *bs, const uint8_t *buf,
2928 int64_t pos, int size)
2930 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2931 int ret = bdrv_writev_vmstate(bs, &qiov, pos);
2934 return ret < 0 ? ret : size;
2937 int bdrv_load_vmstate(BlockDriverState *bs, uint8_t *buf,
2938 int64_t pos, int size)
2940 QEMUIOVector qiov = QEMU_IOVEC_INIT_BUF(qiov, buf, size);
2941 int ret = bdrv_readv_vmstate(bs, &qiov, pos);
2944 return ret < 0 ? ret : size;
2947 /**************************************************************/
2950 void bdrv_aio_cancel(BlockAIOCB *acb)
2954 bdrv_aio_cancel_async(acb);
2955 while (acb->refcnt > 1) {
2956 if (acb->aiocb_info->get_aio_context) {
2957 aio_poll(acb->aiocb_info->get_aio_context(acb), true);
2958 } else if (acb->bs) {
2959 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2960 * assert that we're not using an I/O thread. Thread-safe
2961 * code should use bdrv_aio_cancel_async exclusively.
2963 assert(bdrv_get_aio_context(acb->bs) == qemu_get_aio_context());
2964 aio_poll(bdrv_get_aio_context(acb->bs), true);
2969 qemu_aio_unref(acb);
2972 /* Async version of aio cancel. The caller is not blocked if the acb implements
2973 * cancel_async, otherwise we do nothing and let the request normally complete.
2974 * In either case the completion callback must be called. */
2975 void bdrv_aio_cancel_async(BlockAIOCB *acb)
2978 if (acb->aiocb_info->cancel_async) {
2979 acb->aiocb_info->cancel_async(acb);
2983 /**************************************************************/
2984 /* Coroutine block device emulation */
2986 int coroutine_fn bdrv_co_flush(BlockDriverState *bs)
2988 BdrvChild *primary_child = bdrv_primary_child(bs);
2994 bdrv_inc_in_flight(bs);
2996 if (!bdrv_is_inserted(bs) || bdrv_is_read_only(bs) ||
3001 qemu_co_mutex_lock(&bs->reqs_lock);
3002 current_gen = qatomic_read(&bs->write_gen);
3004 /* Wait until any previous flushes are completed */
3005 while (bs->active_flush_req) {
3006 qemu_co_queue_wait(&bs->flush_queue, &bs->reqs_lock);
3009 /* Flushes reach this point in nondecreasing current_gen order. */
3010 bs->active_flush_req = true;
3011 qemu_co_mutex_unlock(&bs->reqs_lock);
3013 /* Write back all layers by calling one driver function */
3014 if (bs->drv->bdrv_co_flush) {
3015 ret = bs->drv->bdrv_co_flush(bs);
3019 /* Write back cached data to the OS even with cache=unsafe */
3020 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_OS);
3021 if (bs->drv->bdrv_co_flush_to_os) {
3022 ret = bs->drv->bdrv_co_flush_to_os(bs);
3028 /* But don't actually force it to the disk with cache=unsafe */
3029 if (bs->open_flags & BDRV_O_NO_FLUSH) {
3030 goto flush_children;
3033 /* Check if we really need to flush anything */
3034 if (bs->flushed_gen == current_gen) {
3035 goto flush_children;
3038 BLKDBG_EVENT(primary_child, BLKDBG_FLUSH_TO_DISK);
3040 /* bs->drv->bdrv_co_flush() might have ejected the BDS
3041 * (even in case of apparent success) */
3045 if (bs->drv->bdrv_co_flush_to_disk) {
3046 ret = bs->drv->bdrv_co_flush_to_disk(bs);
3047 } else if (bs->drv->bdrv_aio_flush) {
3049 CoroutineIOCompletion co = {
3050 .coroutine = qemu_coroutine_self(),
3053 acb = bs->drv->bdrv_aio_flush(bs, bdrv_co_io_em_complete, &co);
3057 qemu_coroutine_yield();
3062 * Some block drivers always operate in either writethrough or unsafe
3063 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
3064 * know how the server works (because the behaviour is hardcoded or
3065 * depends on server-side configuration), so we can't ensure that
3066 * everything is safe on disk. Returning an error doesn't work because
3067 * that would break guests even if the server operates in writethrough
3070 * Let's hope the user knows what he's doing.
3079 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
3080 * in the case of cache=unsafe, so there are no useless flushes.
3084 QLIST_FOREACH(child, &bs->children, next) {
3085 if (child->perm & (BLK_PERM_WRITE | BLK_PERM_WRITE_UNCHANGED)) {
3086 int this_child_ret = bdrv_co_flush(child->bs);
3088 ret = this_child_ret;
3094 /* Notify any pending flushes that we have completed */
3096 bs->flushed_gen = current_gen;
3099 qemu_co_mutex_lock(&bs->reqs_lock);
3100 bs->active_flush_req = false;
3101 /* Return value is ignored - it's ok if wait queue is empty */
3102 qemu_co_queue_next(&bs->flush_queue);
3103 qemu_co_mutex_unlock(&bs->reqs_lock);
3106 bdrv_dec_in_flight(bs);
3110 int coroutine_fn bdrv_co_pdiscard(BdrvChild *child, int64_t offset,
3113 BdrvTrackedRequest req;
3115 int64_t max_pdiscard;
3116 int head, tail, align;
3117 BlockDriverState *bs = child->bs;
3120 if (!bs || !bs->drv || !bdrv_is_inserted(bs)) {
3124 if (bdrv_has_readonly_bitmaps(bs)) {
3128 ret = bdrv_check_request(offset, bytes, NULL);
3133 /* Do nothing if disabled. */
3134 if (!(bs->open_flags & BDRV_O_UNMAP)) {
3138 if (!bs->drv->bdrv_co_pdiscard && !bs->drv->bdrv_aio_pdiscard) {
3142 /* Invalidate the cached block-status data range if this discard overlaps */
3143 bdrv_bsc_invalidate_range(bs, offset, bytes);
3145 /* Discard is advisory, but some devices track and coalesce
3146 * unaligned requests, so we must pass everything down rather than
3147 * round here. Still, most devices will just silently ignore
3148 * unaligned requests (by returning -ENOTSUP), so we must fragment
3149 * the request accordingly. */
3150 align = MAX(bs->bl.pdiscard_alignment, bs->bl.request_alignment);
3151 assert(align % bs->bl.request_alignment == 0);
3152 head = offset % align;
3153 tail = (offset + bytes) % align;
3155 bdrv_inc_in_flight(bs);
3156 tracked_request_begin(&req, bs, offset, bytes, BDRV_TRACKED_DISCARD);
3158 ret = bdrv_co_write_req_prepare(child, offset, bytes, &req, 0);
3163 max_pdiscard = QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs->bl.max_pdiscard, INT64_MAX),
3165 assert(max_pdiscard >= bs->bl.request_alignment);
3168 int64_t num = bytes;
3171 /* Make small requests to get to alignment boundaries. */
3172 num = MIN(bytes, align - head);
3173 if (!QEMU_IS_ALIGNED(num, bs->bl.request_alignment)) {
3174 num %= bs->bl.request_alignment;
3176 head = (head + num) % align;
3177 assert(num < max_pdiscard);
3180 /* Shorten the request to the last aligned cluster. */
3182 } else if (!QEMU_IS_ALIGNED(tail, bs->bl.request_alignment) &&
3183 tail > bs->bl.request_alignment) {
3184 tail %= bs->bl.request_alignment;
3188 /* limit request size */
3189 if (num > max_pdiscard) {
3197 if (bs->drv->bdrv_co_pdiscard) {
3198 ret = bs->drv->bdrv_co_pdiscard(bs, offset, num);
3201 CoroutineIOCompletion co = {
3202 .coroutine = qemu_coroutine_self(),
3205 acb = bs->drv->bdrv_aio_pdiscard(bs, offset, num,
3206 bdrv_co_io_em_complete, &co);
3211 qemu_coroutine_yield();
3215 if (ret && ret != -ENOTSUP) {
3224 bdrv_co_write_req_finish(child, req.offset, req.bytes, &req, ret);
3225 tracked_request_end(&req);
3226 bdrv_dec_in_flight(bs);
3230 int bdrv_co_ioctl(BlockDriverState *bs, int req, void *buf)
3232 BlockDriver *drv = bs->drv;
3233 CoroutineIOCompletion co = {
3234 .coroutine = qemu_coroutine_self(),
3239 bdrv_inc_in_flight(bs);
3240 if (!drv || (!drv->bdrv_aio_ioctl && !drv->bdrv_co_ioctl)) {
3245 if (drv->bdrv_co_ioctl) {
3246 co.ret = drv->bdrv_co_ioctl(bs, req, buf);
3248 acb = drv->bdrv_aio_ioctl(bs, req, buf, bdrv_co_io_em_complete, &co);
3253 qemu_coroutine_yield();
3256 bdrv_dec_in_flight(bs);
3260 void *qemu_blockalign(BlockDriverState *bs, size_t size)
3263 return qemu_memalign(bdrv_opt_mem_align(bs), size);
3266 void *qemu_blockalign0(BlockDriverState *bs, size_t size)
3269 return memset(qemu_blockalign(bs, size), 0, size);
3272 void *qemu_try_blockalign(BlockDriverState *bs, size_t size)
3274 size_t align = bdrv_opt_mem_align(bs);
3277 /* Ensure that NULL is never returned on success */
3283 return qemu_try_memalign(align, size);
3286 void *qemu_try_blockalign0(BlockDriverState *bs, size_t size)
3288 void *mem = qemu_try_blockalign(bs, size);
3292 memset(mem, 0, size);
3299 * Check if all memory in this vector is sector aligned.
3301 bool bdrv_qiov_is_aligned(BlockDriverState *bs, QEMUIOVector *qiov)
3304 size_t alignment = bdrv_min_mem_align(bs);
3307 for (i = 0; i < qiov->niov; i++) {
3308 if ((uintptr_t) qiov->iov[i].iov_base % alignment) {
3311 if (qiov->iov[i].iov_len % alignment) {
3319 void bdrv_io_plug(BlockDriverState *bs)
3324 QLIST_FOREACH(child, &bs->children, next) {
3325 bdrv_io_plug(child->bs);
3328 if (qatomic_fetch_inc(&bs->io_plugged) == 0) {
3329 BlockDriver *drv = bs->drv;
3330 if (drv && drv->bdrv_io_plug) {
3331 drv->bdrv_io_plug(bs);
3336 void bdrv_io_unplug(BlockDriverState *bs)
3341 assert(bs->io_plugged);
3342 if (qatomic_fetch_dec(&bs->io_plugged) == 1) {
3343 BlockDriver *drv = bs->drv;
3344 if (drv && drv->bdrv_io_unplug) {
3345 drv->bdrv_io_unplug(bs);
3349 QLIST_FOREACH(child, &bs->children, next) {
3350 bdrv_io_unplug(child->bs);
3354 void bdrv_register_buf(BlockDriverState *bs, void *host, size_t size)
3358 GLOBAL_STATE_CODE();
3359 if (bs->drv && bs->drv->bdrv_register_buf) {
3360 bs->drv->bdrv_register_buf(bs, host, size);
3362 QLIST_FOREACH(child, &bs->children, next) {
3363 bdrv_register_buf(child->bs, host, size);
3367 void bdrv_unregister_buf(BlockDriverState *bs, void *host)
3371 GLOBAL_STATE_CODE();
3372 if (bs->drv && bs->drv->bdrv_unregister_buf) {
3373 bs->drv->bdrv_unregister_buf(bs, host);
3375 QLIST_FOREACH(child, &bs->children, next) {
3376 bdrv_unregister_buf(child->bs, host);
3380 static int coroutine_fn bdrv_co_copy_range_internal(
3381 BdrvChild *src, int64_t src_offset, BdrvChild *dst,
3382 int64_t dst_offset, int64_t bytes,
3383 BdrvRequestFlags read_flags, BdrvRequestFlags write_flags,
3386 BdrvTrackedRequest req;
3389 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3390 assert(!(read_flags & BDRV_REQ_NO_FALLBACK));
3391 assert(!(write_flags & BDRV_REQ_NO_FALLBACK));
3392 assert(!(read_flags & BDRV_REQ_NO_WAIT));
3393 assert(!(write_flags & BDRV_REQ_NO_WAIT));
3395 if (!dst || !dst->bs || !bdrv_is_inserted(dst->bs)) {
3398 ret = bdrv_check_request32(dst_offset, bytes, NULL, 0);
3402 if (write_flags & BDRV_REQ_ZERO_WRITE) {
3403 return bdrv_co_pwrite_zeroes(dst, dst_offset, bytes, write_flags);
3406 if (!src || !src->bs || !bdrv_is_inserted(src->bs)) {
3409 ret = bdrv_check_request32(src_offset, bytes, NULL, 0);
3414 if (!src->bs->drv->bdrv_co_copy_range_from
3415 || !dst->bs->drv->bdrv_co_copy_range_to
3416 || src->bs->encrypted || dst->bs->encrypted) {
3421 bdrv_inc_in_flight(src->bs);
3422 tracked_request_begin(&req, src->bs, src_offset, bytes,
3425 /* BDRV_REQ_SERIALISING is only for write operation */
3426 assert(!(read_flags & BDRV_REQ_SERIALISING));
3427 bdrv_wait_serialising_requests(&req);
3429 ret = src->bs->drv->bdrv_co_copy_range_from(src->bs,
3433 read_flags, write_flags);
3435 tracked_request_end(&req);
3436 bdrv_dec_in_flight(src->bs);
3438 bdrv_inc_in_flight(dst->bs);
3439 tracked_request_begin(&req, dst->bs, dst_offset, bytes,
3440 BDRV_TRACKED_WRITE);
3441 ret = bdrv_co_write_req_prepare(dst, dst_offset, bytes, &req,
3444 ret = dst->bs->drv->bdrv_co_copy_range_to(dst->bs,
3448 read_flags, write_flags);
3450 bdrv_co_write_req_finish(dst, dst_offset, bytes, &req, ret);
3451 tracked_request_end(&req);
3452 bdrv_dec_in_flight(dst->bs);
3458 /* Copy range from @src to @dst.
3460 * See the comment of bdrv_co_copy_range for the parameter and return value
3462 int coroutine_fn bdrv_co_copy_range_from(BdrvChild *src, int64_t src_offset,
3463 BdrvChild *dst, int64_t dst_offset,
3465 BdrvRequestFlags read_flags,
3466 BdrvRequestFlags write_flags)
3469 trace_bdrv_co_copy_range_from(src, src_offset, dst, dst_offset, bytes,
3470 read_flags, write_flags);
3471 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3472 bytes, read_flags, write_flags, true);
3475 /* Copy range from @src to @dst.
3477 * See the comment of bdrv_co_copy_range for the parameter and return value
3479 int coroutine_fn bdrv_co_copy_range_to(BdrvChild *src, int64_t src_offset,
3480 BdrvChild *dst, int64_t dst_offset,
3482 BdrvRequestFlags read_flags,
3483 BdrvRequestFlags write_flags)
3486 trace_bdrv_co_copy_range_to(src, src_offset, dst, dst_offset, bytes,
3487 read_flags, write_flags);
3488 return bdrv_co_copy_range_internal(src, src_offset, dst, dst_offset,
3489 bytes, read_flags, write_flags, false);
3492 int coroutine_fn bdrv_co_copy_range(BdrvChild *src, int64_t src_offset,
3493 BdrvChild *dst, int64_t dst_offset,
3494 int64_t bytes, BdrvRequestFlags read_flags,
3495 BdrvRequestFlags write_flags)
3498 return bdrv_co_copy_range_from(src, src_offset,
3500 bytes, read_flags, write_flags);
3503 static void bdrv_parent_cb_resize(BlockDriverState *bs)
3506 QLIST_FOREACH(c, &bs->parents, next_parent) {
3507 if (c->klass->resize) {
3508 c->klass->resize(c);
3514 * Truncate file to 'offset' bytes (needed only for file protocols)
3516 * If 'exact' is true, the file must be resized to exactly the given
3517 * 'offset'. Otherwise, it is sufficient for the node to be at least
3518 * 'offset' bytes in length.
3520 int coroutine_fn bdrv_co_truncate(BdrvChild *child, int64_t offset, bool exact,
3521 PreallocMode prealloc, BdrvRequestFlags flags,
3524 BlockDriverState *bs = child->bs;
3525 BdrvChild *filtered, *backing;
3526 BlockDriver *drv = bs->drv;
3527 BdrvTrackedRequest req;
3528 int64_t old_size, new_bytes;
3532 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3534 error_setg(errp, "No medium inserted");
3538 error_setg(errp, "Image size cannot be negative");
3542 ret = bdrv_check_request(offset, 0, errp);
3547 old_size = bdrv_getlength(bs);
3549 error_setg_errno(errp, -old_size, "Failed to get old image size");
3553 if (bdrv_is_read_only(bs)) {
3554 error_setg(errp, "Image is read-only");
3558 if (offset > old_size) {
3559 new_bytes = offset - old_size;
3564 bdrv_inc_in_flight(bs);
3565 tracked_request_begin(&req, bs, offset - new_bytes, new_bytes,
3566 BDRV_TRACKED_TRUNCATE);
3568 /* If we are growing the image and potentially using preallocation for the
3569 * new area, we need to make sure that no write requests are made to it
3570 * concurrently or they might be overwritten by preallocation. */
3572 bdrv_make_request_serialising(&req, 1);
3574 ret = bdrv_co_write_req_prepare(child, offset - new_bytes, new_bytes, &req,
3577 error_setg_errno(errp, -ret,
3578 "Failed to prepare request for truncation");
3582 filtered = bdrv_filter_child(bs);
3583 backing = bdrv_cow_child(bs);
3586 * If the image has a backing file that is large enough that it would
3587 * provide data for the new area, we cannot leave it unallocated because
3588 * then the backing file content would become visible. Instead, zero-fill
3591 * Note that if the image has a backing file, but was opened without the
3592 * backing file, taking care of keeping things consistent with that backing
3593 * file is the user's responsibility.
3595 if (new_bytes && backing) {
3596 int64_t backing_len;
3598 backing_len = bdrv_getlength(backing->bs);
3599 if (backing_len < 0) {
3601 error_setg_errno(errp, -ret, "Could not get backing file size");
3605 if (backing_len > old_size) {
3606 flags |= BDRV_REQ_ZERO_WRITE;
3610 if (drv->bdrv_co_truncate) {
3611 if (flags & ~bs->supported_truncate_flags) {
3612 error_setg(errp, "Block driver does not support requested flags");
3616 ret = drv->bdrv_co_truncate(bs, offset, exact, prealloc, flags, errp);
3617 } else if (filtered) {
3618 ret = bdrv_co_truncate(filtered, offset, exact, prealloc, flags, errp);
3620 error_setg(errp, "Image format driver does not support resize");
3628 ret = refresh_total_sectors(bs, offset >> BDRV_SECTOR_BITS);
3630 error_setg_errno(errp, -ret, "Could not refresh total sector count");
3632 offset = bs->total_sectors * BDRV_SECTOR_SIZE;
3634 /* It's possible that truncation succeeded but refresh_total_sectors
3635 * failed, but the latter doesn't affect how we should finish the request.
3636 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3637 bdrv_co_write_req_finish(child, offset - new_bytes, new_bytes, &req, 0);
3640 tracked_request_end(&req);
3641 bdrv_dec_in_flight(bs);
3646 void bdrv_cancel_in_flight(BlockDriverState *bs)
3648 GLOBAL_STATE_CODE();
3649 if (!bs || !bs->drv) {
3653 if (bs->drv->bdrv_cancel_in_flight) {
3654 bs->drv->bdrv_cancel_in_flight(bs);
3659 bdrv_co_preadv_snapshot(BdrvChild *child, int64_t offset, int64_t bytes,
3660 QEMUIOVector *qiov, size_t qiov_offset)
3662 BlockDriverState *bs = child->bs;
3663 BlockDriver *drv = bs->drv;
3671 if (!drv->bdrv_co_preadv_snapshot) {
3675 bdrv_inc_in_flight(bs);
3676 ret = drv->bdrv_co_preadv_snapshot(bs, offset, bytes, qiov, qiov_offset);
3677 bdrv_dec_in_flight(bs);
3683 bdrv_co_snapshot_block_status(BlockDriverState *bs,
3684 bool want_zero, int64_t offset, int64_t bytes,
3685 int64_t *pnum, int64_t *map,
3686 BlockDriverState **file)
3688 BlockDriver *drv = bs->drv;
3696 if (!drv->bdrv_co_snapshot_block_status) {
3700 bdrv_inc_in_flight(bs);
3701 ret = drv->bdrv_co_snapshot_block_status(bs, want_zero, offset, bytes,
3703 bdrv_dec_in_flight(bs);
3709 bdrv_co_pdiscard_snapshot(BlockDriverState *bs, int64_t offset, int64_t bytes)
3711 BlockDriver *drv = bs->drv;
3719 if (!drv->bdrv_co_pdiscard_snapshot) {
3723 bdrv_inc_in_flight(bs);
3724 ret = drv->bdrv_co_pdiscard_snapshot(bs, offset, bytes);
3725 bdrv_dec_in_flight(bs);