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 "qemu/memalign.h"
36 #include "qapi/error.h"
37 #include "qemu/error-report.h"
38 #include "qemu/main-loop.h"
39 #include "sysemu/replay.h"
41 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
42 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
44 static void bdrv_parent_cb_resize(BlockDriverState
*bs
);
45 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
46 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
);
48 static void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
)
52 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
56 bdrv_parent_drained_begin_single(c
, false);
60 void bdrv_parent_drained_end_single(BdrvChild
*c
)
64 assert(c
->quiesced_parent
);
65 c
->quiesced_parent
= false;
67 if (c
->klass
->drained_end
) {
68 c
->klass
->drained_end(c
);
72 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
)
76 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
80 bdrv_parent_drained_end_single(c
);
84 bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
86 if (c
->klass
->drained_poll
) {
87 return c
->klass
->drained_poll(c
);
92 static bool bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
93 bool ignore_bds_parents
)
98 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
99 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
102 busy
|= bdrv_parent_drained_poll_single(c
);
108 void bdrv_parent_drained_begin_single(BdrvChild
*c
, bool poll
)
110 AioContext
*ctx
= bdrv_child_get_parent_aio_context(c
);
113 assert(!c
->quiesced_parent
);
114 c
->quiesced_parent
= true;
116 if (c
->klass
->drained_begin
) {
117 c
->klass
->drained_begin(c
);
120 AIO_WAIT_WHILE(ctx
, bdrv_parent_drained_poll_single(c
));
124 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
126 dst
->pdiscard_alignment
= MAX(dst
->pdiscard_alignment
,
127 src
->pdiscard_alignment
);
128 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
129 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
130 dst
->max_hw_transfer
= MIN_NON_ZERO(dst
->max_hw_transfer
,
131 src
->max_hw_transfer
);
132 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
133 src
->opt_mem_alignment
);
134 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
135 src
->min_mem_alignment
);
136 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
137 dst
->max_hw_iov
= MIN_NON_ZERO(dst
->max_hw_iov
, src
->max_hw_iov
);
140 typedef struct BdrvRefreshLimitsState
{
141 BlockDriverState
*bs
;
143 } BdrvRefreshLimitsState
;
145 static void bdrv_refresh_limits_abort(void *opaque
)
147 BdrvRefreshLimitsState
*s
= opaque
;
149 s
->bs
->bl
= s
->old_bl
;
152 static TransactionActionDrv bdrv_refresh_limits_drv
= {
153 .abort
= bdrv_refresh_limits_abort
,
157 /* @tran is allowed to be NULL, in this case no rollback is possible. */
158 void bdrv_refresh_limits(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
161 BlockDriver
*drv
= bs
->drv
;
168 BdrvRefreshLimitsState
*s
= g_new(BdrvRefreshLimitsState
, 1);
169 *s
= (BdrvRefreshLimitsState
) {
173 tran_add(tran
, &bdrv_refresh_limits_drv
, s
);
176 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
182 /* Default alignment based on whether driver has byte interface */
183 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
184 drv
->bdrv_aio_preadv
||
185 drv
->bdrv_co_preadv_part
) ? 1 : 512;
187 /* Take some limits from the children as a default */
189 QLIST_FOREACH(c
, &bs
->children
, next
) {
190 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
192 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
198 bs
->bl
.min_mem_alignment
= 512;
199 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size();
201 /* Safe default since most protocols use readv()/writev()/etc */
202 bs
->bl
.max_iov
= IOV_MAX
;
205 /* Then let the driver override it */
206 if (drv
->bdrv_refresh_limits
) {
207 drv
->bdrv_refresh_limits(bs
, errp
);
213 if (bs
->bl
.request_alignment
> BDRV_MAX_ALIGNMENT
) {
214 error_setg(errp
, "Driver requires too large request alignment");
219 * The copy-on-read flag is actually a reference count so multiple users may
220 * use the feature without worrying about clobbering its previous state.
221 * Copy-on-read stays enabled until all users have called to disable it.
223 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
226 qatomic_inc(&bs
->copy_on_read
);
229 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
231 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
238 BlockDriverState
*bs
;
245 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
246 bool bdrv_drain_poll(BlockDriverState
*bs
, BdrvChild
*ignore_parent
,
247 bool ignore_bds_parents
)
251 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
255 if (qatomic_read(&bs
->in_flight
)) {
262 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
,
263 BdrvChild
*ignore_parent
)
265 return bdrv_drain_poll(bs
, ignore_parent
, false);
268 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
270 static void bdrv_do_drained_end(BlockDriverState
*bs
, BdrvChild
*parent
);
272 static void bdrv_co_drain_bh_cb(void *opaque
)
274 BdrvCoDrainData
*data
= opaque
;
275 Coroutine
*co
= data
->co
;
276 BlockDriverState
*bs
= data
->bs
;
279 AioContext
*ctx
= bdrv_get_aio_context(bs
);
280 aio_context_acquire(ctx
);
281 bdrv_dec_in_flight(bs
);
283 bdrv_do_drained_begin(bs
, data
->parent
, data
->poll
);
286 bdrv_do_drained_end(bs
, data
->parent
);
288 aio_context_release(ctx
);
291 bdrv_drain_all_begin();
298 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
303 BdrvCoDrainData data
;
304 Coroutine
*self
= qemu_coroutine_self();
305 AioContext
*ctx
= bdrv_get_aio_context(bs
);
306 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(self
);
308 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
309 * other coroutines run if they were queued by aio_co_enter(). */
311 assert(qemu_in_coroutine());
312 data
= (BdrvCoDrainData
) {
322 bdrv_inc_in_flight(bs
);
326 * Temporarily drop the lock across yield or we would get deadlocks.
327 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
329 * When we yield below, the lock for the current context will be
330 * released, so if this is actually the lock that protects bs, don't drop
334 aio_context_release(ctx
);
336 replay_bh_schedule_oneshot_event(ctx
, bdrv_co_drain_bh_cb
, &data
);
338 qemu_coroutine_yield();
339 /* If we are resumed from some other event (such as an aio completion or a
340 * timer callback), it is a bug in the caller that should be fixed. */
343 /* Reaquire the AioContext of bs if we dropped it */
345 aio_context_acquire(ctx
);
349 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
354 if (qemu_in_coroutine()) {
355 bdrv_co_yield_to_drain(bs
, true, parent
, poll
);
359 /* Stop things in parent-to-child order */
360 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
361 aio_disable_external(bdrv_get_aio_context(bs
));
362 bdrv_parent_drained_begin(bs
, parent
);
363 if (bs
->drv
&& bs
->drv
->bdrv_drain_begin
) {
364 bs
->drv
->bdrv_drain_begin(bs
);
369 * Wait for drained requests to finish.
371 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
372 * call is needed so things in this AioContext can make progress even
373 * though we don't return to the main AioContext loop - this automatically
374 * includes other nodes in the same AioContext and therefore all child
378 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, parent
));
382 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
, BdrvChild
*parent
)
384 bdrv_do_drained_begin(bs
, parent
, false);
387 void bdrv_drained_begin(BlockDriverState
*bs
)
390 bdrv_do_drained_begin(bs
, NULL
, true);
394 * This function does not poll, nor must any of its recursively called
397 static void bdrv_do_drained_end(BlockDriverState
*bs
, BdrvChild
*parent
)
399 int old_quiesce_counter
;
401 if (qemu_in_coroutine()) {
402 bdrv_co_yield_to_drain(bs
, false, parent
, false);
405 assert(bs
->quiesce_counter
> 0);
407 /* Re-enable things in child-to-parent order */
408 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
409 if (old_quiesce_counter
== 1) {
410 if (bs
->drv
&& bs
->drv
->bdrv_drain_end
) {
411 bs
->drv
->bdrv_drain_end(bs
);
413 bdrv_parent_drained_end(bs
, parent
);
414 aio_enable_external(bdrv_get_aio_context(bs
));
418 void bdrv_drained_end(BlockDriverState
*bs
)
421 bdrv_do_drained_end(bs
, NULL
);
424 void bdrv_drain(BlockDriverState
*bs
)
427 bdrv_drained_begin(bs
);
428 bdrv_drained_end(bs
);
431 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
433 BdrvChild
*child
, *next
;
435 assert(qatomic_read(&bs
->in_flight
) == 0);
436 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
437 bdrv_drain_assert_idle(child
->bs
);
441 unsigned int bdrv_drain_all_count
= 0;
443 static bool bdrv_drain_all_poll(void)
445 BlockDriverState
*bs
= NULL
;
449 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
450 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
451 while ((bs
= bdrv_next_all_states(bs
))) {
452 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
453 aio_context_acquire(aio_context
);
454 result
|= bdrv_drain_poll(bs
, NULL
, true);
455 aio_context_release(aio_context
);
462 * Wait for pending requests to complete across all BlockDriverStates
464 * This function does not flush data to disk, use bdrv_flush_all() for that
465 * after calling this function.
467 * This pauses all block jobs and disables external clients. It must
468 * be paired with bdrv_drain_all_end().
470 * NOTE: no new block jobs or BlockDriverStates can be created between
471 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
473 void bdrv_drain_all_begin(void)
475 BlockDriverState
*bs
= NULL
;
478 if (qemu_in_coroutine()) {
479 bdrv_co_yield_to_drain(NULL
, true, NULL
, true);
484 * bdrv queue is managed by record/replay,
485 * waiting for finishing the I/O requests may
488 if (replay_events_enabled()) {
492 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
493 * loop AioContext, so make sure we're in the main context. */
494 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
495 assert(bdrv_drain_all_count
< INT_MAX
);
496 bdrv_drain_all_count
++;
498 /* Quiesce all nodes, without polling in-flight requests yet. The graph
499 * cannot change during this loop. */
500 while ((bs
= bdrv_next_all_states(bs
))) {
501 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
503 aio_context_acquire(aio_context
);
504 bdrv_do_drained_begin(bs
, NULL
, false);
505 aio_context_release(aio_context
);
508 /* Now poll the in-flight requests */
509 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
511 while ((bs
= bdrv_next_all_states(bs
))) {
512 bdrv_drain_assert_idle(bs
);
516 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
520 g_assert(bs
->quiesce_counter
> 0);
521 g_assert(!bs
->refcnt
);
523 while (bs
->quiesce_counter
) {
524 bdrv_do_drained_end(bs
, NULL
);
528 void bdrv_drain_all_end(void)
530 BlockDriverState
*bs
= NULL
;
534 * bdrv queue is managed by record/replay,
535 * waiting for finishing the I/O requests may
538 if (replay_events_enabled()) {
542 while ((bs
= bdrv_next_all_states(bs
))) {
543 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
545 aio_context_acquire(aio_context
);
546 bdrv_do_drained_end(bs
, NULL
);
547 aio_context_release(aio_context
);
550 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
551 assert(bdrv_drain_all_count
> 0);
552 bdrv_drain_all_count
--;
555 void bdrv_drain_all(void)
558 bdrv_drain_all_begin();
559 bdrv_drain_all_end();
563 * Remove an active request from the tracked requests list
565 * This function should be called when a tracked request is completing.
567 static void coroutine_fn
tracked_request_end(BdrvTrackedRequest
*req
)
569 if (req
->serialising
) {
570 qatomic_dec(&req
->bs
->serialising_in_flight
);
573 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
574 QLIST_REMOVE(req
, list
);
575 qemu_co_queue_restart_all(&req
->wait_queue
);
576 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
580 * Add an active request to the tracked requests list
582 static void coroutine_fn
tracked_request_begin(BdrvTrackedRequest
*req
,
583 BlockDriverState
*bs
,
586 enum BdrvTrackedRequestType type
)
588 bdrv_check_request(offset
, bytes
, &error_abort
);
590 *req
= (BdrvTrackedRequest
){
595 .co
= qemu_coroutine_self(),
596 .serialising
= false,
597 .overlap_offset
= offset
,
598 .overlap_bytes
= bytes
,
601 qemu_co_queue_init(&req
->wait_queue
);
603 qemu_co_mutex_lock(&bs
->reqs_lock
);
604 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
605 qemu_co_mutex_unlock(&bs
->reqs_lock
);
608 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
609 int64_t offset
, int64_t bytes
)
611 bdrv_check_request(offset
, bytes
, &error_abort
);
614 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
618 if (req
->overlap_offset
>= offset
+ bytes
) {
624 /* Called with self->bs->reqs_lock held */
625 static coroutine_fn BdrvTrackedRequest
*
626 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
628 BdrvTrackedRequest
*req
;
630 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
631 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
634 if (tracked_request_overlaps(req
, self
->overlap_offset
,
635 self
->overlap_bytes
))
638 * Hitting this means there was a reentrant request, for
639 * example, a block driver issuing nested requests. This must
640 * never happen since it means deadlock.
642 assert(qemu_coroutine_self() != req
->co
);
645 * If the request is already (indirectly) waiting for us, or
646 * will wait for us as soon as it wakes up, then just go on
647 * (instead of producing a deadlock in the former case).
649 if (!req
->waiting_for
) {
658 /* Called with self->bs->reqs_lock held */
659 static void coroutine_fn
660 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
662 BdrvTrackedRequest
*req
;
664 while ((req
= bdrv_find_conflicting_request(self
))) {
665 self
->waiting_for
= req
;
666 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
667 self
->waiting_for
= NULL
;
671 /* Called with req->bs->reqs_lock held */
672 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
675 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
676 int64_t overlap_bytes
=
677 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
679 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
681 if (!req
->serialising
) {
682 qatomic_inc(&req
->bs
->serialising_in_flight
);
683 req
->serialising
= true;
686 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
687 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
691 * Return the tracked request on @bs for the current coroutine, or
692 * NULL if there is none.
694 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
696 BdrvTrackedRequest
*req
;
697 Coroutine
*self
= qemu_coroutine_self();
700 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
701 if (req
->co
== self
) {
710 * Round a region to cluster boundaries
712 void bdrv_round_to_clusters(BlockDriverState
*bs
,
713 int64_t offset
, int64_t bytes
,
714 int64_t *cluster_offset
,
715 int64_t *cluster_bytes
)
719 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
720 *cluster_offset
= offset
;
721 *cluster_bytes
= bytes
;
723 int64_t c
= bdi
.cluster_size
;
724 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
725 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
729 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
734 ret
= bdrv_get_info(bs
, &bdi
);
735 if (ret
< 0 || bdi
.cluster_size
== 0) {
736 return bs
->bl
.request_alignment
;
738 return bdi
.cluster_size
;
742 void bdrv_inc_in_flight(BlockDriverState
*bs
)
745 qatomic_inc(&bs
->in_flight
);
748 void bdrv_wakeup(BlockDriverState
*bs
)
754 void bdrv_dec_in_flight(BlockDriverState
*bs
)
757 qatomic_dec(&bs
->in_flight
);
761 static void coroutine_fn
762 bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
764 BlockDriverState
*bs
= self
->bs
;
766 if (!qatomic_read(&bs
->serialising_in_flight
)) {
770 qemu_co_mutex_lock(&bs
->reqs_lock
);
771 bdrv_wait_serialising_requests_locked(self
);
772 qemu_co_mutex_unlock(&bs
->reqs_lock
);
775 void coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
780 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
782 tracked_request_set_serialising(req
, align
);
783 bdrv_wait_serialising_requests_locked(req
);
785 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
788 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
789 QEMUIOVector
*qiov
, size_t qiov_offset
,
793 * Check generic offset/bytes correctness
797 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
802 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
806 if (bytes
> BDRV_MAX_LENGTH
) {
807 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
808 bytes
, BDRV_MAX_LENGTH
);
812 if (offset
> BDRV_MAX_LENGTH
) {
813 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
814 offset
, BDRV_MAX_LENGTH
);
818 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
819 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
820 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
830 * Check qiov and qiov_offset
833 if (qiov_offset
> qiov
->size
) {
834 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
835 qiov_offset
, qiov
->size
);
839 if (bytes
> qiov
->size
- qiov_offset
) {
840 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
841 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
848 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
850 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
853 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
854 QEMUIOVector
*qiov
, size_t qiov_offset
)
856 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
861 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
869 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
870 * The operation is sped up by checking the block status and only writing
871 * zeroes to the device if they currently do not return zeroes. Optional
872 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
875 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
877 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
880 int64_t target_size
, bytes
, offset
= 0;
881 BlockDriverState
*bs
= child
->bs
;
884 target_size
= bdrv_getlength(bs
);
885 if (target_size
< 0) {
890 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
894 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
898 if (ret
& BDRV_BLOCK_ZERO
) {
902 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
911 * Writes to the file and ensures that no writes are reordered across this
912 * request (acts as a barrier)
914 * Returns 0 on success, -errno in error cases.
916 int coroutine_fn
bdrv_co_pwrite_sync(BdrvChild
*child
, int64_t offset
,
917 int64_t bytes
, const void *buf
,
918 BdrvRequestFlags flags
)
923 ret
= bdrv_co_pwrite(child
, offset
, bytes
, buf
, flags
);
928 ret
= bdrv_co_flush(child
->bs
);
936 typedef struct CoroutineIOCompletion
{
937 Coroutine
*coroutine
;
939 } CoroutineIOCompletion
;
941 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
943 CoroutineIOCompletion
*co
= opaque
;
946 aio_co_wake(co
->coroutine
);
949 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
950 int64_t offset
, int64_t bytes
,
952 size_t qiov_offset
, int flags
)
954 BlockDriver
*drv
= bs
->drv
;
956 unsigned int nb_sectors
;
957 QEMUIOVector local_qiov
;
960 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
961 assert(!(flags
& ~bs
->supported_read_flags
));
967 if (drv
->bdrv_co_preadv_part
) {
968 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
972 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
973 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
977 if (drv
->bdrv_co_preadv
) {
978 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
982 if (drv
->bdrv_aio_preadv
) {
984 CoroutineIOCompletion co
= {
985 .coroutine
= qemu_coroutine_self(),
988 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
989 bdrv_co_io_em_complete
, &co
);
994 qemu_coroutine_yield();
1000 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1001 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1003 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1004 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1005 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1006 assert(drv
->bdrv_co_readv
);
1008 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1011 if (qiov
== &local_qiov
) {
1012 qemu_iovec_destroy(&local_qiov
);
1018 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1019 int64_t offset
, int64_t bytes
,
1022 BdrvRequestFlags flags
)
1024 BlockDriver
*drv
= bs
->drv
;
1025 bool emulate_fua
= false;
1027 unsigned int nb_sectors
;
1028 QEMUIOVector local_qiov
;
1031 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1037 if ((flags
& BDRV_REQ_FUA
) &&
1038 (~bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1039 flags
&= ~BDRV_REQ_FUA
;
1043 flags
&= bs
->supported_write_flags
;
1045 if (drv
->bdrv_co_pwritev_part
) {
1046 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1051 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1052 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1056 if (drv
->bdrv_co_pwritev
) {
1057 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1061 if (drv
->bdrv_aio_pwritev
) {
1063 CoroutineIOCompletion co
= {
1064 .coroutine
= qemu_coroutine_self(),
1067 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
, flags
,
1068 bdrv_co_io_em_complete
, &co
);
1072 qemu_coroutine_yield();
1078 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1079 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1081 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1082 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1083 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1085 assert(drv
->bdrv_co_writev
);
1086 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
, flags
);
1089 if (ret
== 0 && emulate_fua
) {
1090 ret
= bdrv_co_flush(bs
);
1093 if (qiov
== &local_qiov
) {
1094 qemu_iovec_destroy(&local_qiov
);
1100 static int coroutine_fn
1101 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1102 int64_t bytes
, QEMUIOVector
*qiov
,
1105 BlockDriver
*drv
= bs
->drv
;
1106 QEMUIOVector local_qiov
;
1109 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1115 if (!block_driver_can_compress(drv
)) {
1119 if (drv
->bdrv_co_pwritev_compressed_part
) {
1120 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1124 if (qiov_offset
== 0) {
1125 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1128 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1129 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1130 qemu_iovec_destroy(&local_qiov
);
1135 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1136 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1137 size_t qiov_offset
, int flags
)
1139 BlockDriverState
*bs
= child
->bs
;
1141 /* Perform I/O through a temporary buffer so that users who scribble over
1142 * their read buffer while the operation is in progress do not end up
1143 * modifying the image file. This is critical for zero-copy guest I/O
1144 * where anything might happen inside guest memory.
1146 void *bounce_buffer
= NULL
;
1148 BlockDriver
*drv
= bs
->drv
;
1149 int64_t cluster_offset
;
1150 int64_t cluster_bytes
;
1153 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1154 BDRV_REQUEST_MAX_BYTES
);
1155 int64_t progress
= 0;
1158 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1165 * Do not write anything when the BDS is inactive. That is not
1166 * allowed, and it would not help.
1168 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1170 /* FIXME We cannot require callers to have write permissions when all they
1171 * are doing is a read request. If we did things right, write permissions
1172 * would be obtained anyway, but internally by the copy-on-read code. As
1173 * long as it is implemented here rather than in a separate filter driver,
1174 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1175 * it could request permissions. Therefore we have to bypass the permission
1176 * system for the moment. */
1177 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1179 /* Cover entire cluster so no additional backing file I/O is required when
1180 * allocating cluster in the image file. Note that this value may exceed
1181 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1182 * is one reason we loop rather than doing it all at once.
1184 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1185 skip_bytes
= offset
- cluster_offset
;
1187 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1188 cluster_offset
, cluster_bytes
);
1190 while (cluster_bytes
) {
1194 ret
= 1; /* "already allocated", so nothing will be copied */
1195 pnum
= MIN(cluster_bytes
, max_transfer
);
1197 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1198 MIN(cluster_bytes
, max_transfer
), &pnum
);
1201 * Safe to treat errors in querying allocation as if
1202 * unallocated; we'll probably fail again soon on the
1203 * read, but at least that will set a decent errno.
1205 pnum
= MIN(cluster_bytes
, max_transfer
);
1208 /* Stop at EOF if the image ends in the middle of the cluster */
1209 if (ret
== 0 && pnum
== 0) {
1210 assert(progress
>= bytes
);
1214 assert(skip_bytes
< pnum
);
1218 QEMUIOVector local_qiov
;
1220 /* Must copy-on-read; use the bounce buffer */
1221 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1222 if (!bounce_buffer
) {
1223 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1224 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1225 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1227 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1228 if (!bounce_buffer
) {
1233 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1235 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1241 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1242 if (drv
->bdrv_co_pwrite_zeroes
&&
1243 buffer_is_zero(bounce_buffer
, pnum
)) {
1244 /* FIXME: Should we (perhaps conditionally) be setting
1245 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1246 * that still correctly reads as zero? */
1247 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1248 BDRV_REQ_WRITE_UNCHANGED
);
1250 /* This does not change the data on the disk, it is not
1251 * necessary to flush even in cache=writethrough mode.
1253 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1255 BDRV_REQ_WRITE_UNCHANGED
);
1259 /* It might be okay to ignore write errors for guest
1260 * requests. If this is a deliberate copy-on-read
1261 * then we don't want to ignore the error. Simply
1262 * report it in all cases.
1267 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1268 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1269 bounce_buffer
+ skip_bytes
,
1270 MIN(pnum
- skip_bytes
, bytes
- progress
));
1272 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1273 /* Read directly into the destination */
1274 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1275 MIN(pnum
- skip_bytes
, bytes
- progress
),
1276 qiov
, qiov_offset
+ progress
, 0);
1282 cluster_offset
+= pnum
;
1283 cluster_bytes
-= pnum
;
1284 progress
+= pnum
- skip_bytes
;
1290 qemu_vfree(bounce_buffer
);
1295 * Forwards an already correctly aligned request to the BlockDriver. This
1296 * handles copy on read, zeroing after EOF, and fragmentation of large
1297 * reads; any other features must be implemented by the caller.
1299 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1300 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1301 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1303 BlockDriverState
*bs
= child
->bs
;
1304 int64_t total_bytes
, max_bytes
;
1306 int64_t bytes_remaining
= bytes
;
1309 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1310 assert(is_power_of_2(align
));
1311 assert((offset
& (align
- 1)) == 0);
1312 assert((bytes
& (align
- 1)) == 0);
1313 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1314 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1318 * TODO: We would need a per-BDS .supported_read_flags and
1319 * potential fallback support, if we ever implement any read flags
1320 * to pass through to drivers. For now, there aren't any
1321 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1323 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
|
1324 BDRV_REQ_REGISTERED_BUF
)));
1326 /* Handle Copy on Read and associated serialisation */
1327 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1328 /* If we touch the same cluster it counts as an overlap. This
1329 * guarantees that allocating writes will be serialized and not race
1330 * with each other for the same cluster. For example, in copy-on-read
1331 * it ensures that the CoR read and write operations are atomic and
1332 * guest writes cannot interleave between them. */
1333 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1335 bdrv_wait_serialising_requests(req
);
1338 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1341 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1342 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1344 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1349 if (!ret
|| pnum
!= bytes
) {
1350 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1351 qiov
, qiov_offset
, flags
);
1353 } else if (flags
& BDRV_REQ_PREFETCH
) {
1358 /* Forward the request to the BlockDriver, possibly fragmenting it */
1359 total_bytes
= bdrv_getlength(bs
);
1360 if (total_bytes
< 0) {
1365 assert(!(flags
& ~(bs
->supported_read_flags
| BDRV_REQ_REGISTERED_BUF
)));
1367 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1368 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1369 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1373 while (bytes_remaining
) {
1377 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1380 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1382 qiov_offset
+ bytes
- bytes_remaining
,
1386 num
= bytes_remaining
;
1387 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1388 0, bytes_remaining
);
1393 bytes_remaining
-= num
;
1397 return ret
< 0 ? ret
: 0;
1403 * |<---- align ----->| |<----- align ---->|
1404 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1406 * -*----------$-------*-------- ... --------*-----$------------*---
1408 * | offset | | end |
1409 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1410 * [buf ... ) [tail_buf )
1412 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1413 * is placed at the beginning of @buf and @tail at the @end.
1415 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1416 * around tail, if tail exists.
1418 * @merge_reads is true for small requests,
1419 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1420 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1422 typedef struct BdrvRequestPadding
{
1429 QEMUIOVector local_qiov
;
1430 } BdrvRequestPadding
;
1432 static bool bdrv_init_padding(BlockDriverState
*bs
,
1433 int64_t offset
, int64_t bytes
,
1434 BdrvRequestPadding
*pad
)
1436 int64_t align
= bs
->bl
.request_alignment
;
1439 bdrv_check_request(offset
, bytes
, &error_abort
);
1440 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1441 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1443 memset(pad
, 0, sizeof(*pad
));
1445 pad
->head
= offset
& (align
- 1);
1446 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1448 pad
->tail
= align
- pad
->tail
;
1451 if (!pad
->head
&& !pad
->tail
) {
1455 assert(bytes
); /* Nothing good in aligning zero-length requests */
1457 sum
= pad
->head
+ bytes
+ pad
->tail
;
1458 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1459 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1460 pad
->merge_reads
= sum
== pad
->buf_len
;
1462 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1468 static coroutine_fn
int bdrv_padding_rmw_read(BdrvChild
*child
,
1469 BdrvTrackedRequest
*req
,
1470 BdrvRequestPadding
*pad
,
1473 QEMUIOVector local_qiov
;
1474 BlockDriverState
*bs
= child
->bs
;
1475 uint64_t align
= bs
->bl
.request_alignment
;
1478 assert(req
->serialising
&& pad
->buf
);
1480 if (pad
->head
|| pad
->merge_reads
) {
1481 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1483 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1486 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1488 if (pad
->merge_reads
&& pad
->tail
) {
1489 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1491 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1492 align
, &local_qiov
, 0, 0);
1497 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1499 if (pad
->merge_reads
&& pad
->tail
) {
1500 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1503 if (pad
->merge_reads
) {
1509 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1511 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1512 ret
= bdrv_aligned_preadv(
1514 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1515 align
, align
, &local_qiov
, 0, 0);
1519 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1524 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1530 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1533 qemu_vfree(pad
->buf
);
1534 qemu_iovec_destroy(&pad
->local_qiov
);
1536 memset(pad
, 0, sizeof(*pad
));
1542 * Exchange request parameters with padded request if needed. Don't include RMW
1543 * read of padding, bdrv_padding_rmw_read() should be called separately if
1546 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1547 * - on function start they represent original request
1548 * - on failure or when padding is not needed they are unchanged
1549 * - on success when padding is needed they represent padded request
1551 static int bdrv_pad_request(BlockDriverState
*bs
,
1552 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1553 int64_t *offset
, int64_t *bytes
,
1554 BdrvRequestPadding
*pad
, bool *padded
,
1555 BdrvRequestFlags
*flags
)
1559 bdrv_check_qiov_request(*offset
, *bytes
, *qiov
, *qiov_offset
, &error_abort
);
1561 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1568 ret
= qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1569 *qiov
, *qiov_offset
, *bytes
,
1570 pad
->buf
+ pad
->buf_len
- pad
->tail
,
1573 bdrv_padding_destroy(pad
);
1576 *bytes
+= pad
->head
+ pad
->tail
;
1577 *offset
-= pad
->head
;
1578 *qiov
= &pad
->local_qiov
;
1584 /* Can't use optimization hint with bounce buffer */
1585 *flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1591 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1592 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1593 BdrvRequestFlags flags
)
1596 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1599 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1600 int64_t offset
, int64_t bytes
,
1601 QEMUIOVector
*qiov
, size_t qiov_offset
,
1602 BdrvRequestFlags flags
)
1604 BlockDriverState
*bs
= child
->bs
;
1605 BdrvTrackedRequest req
;
1606 BdrvRequestPadding pad
;
1610 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1612 if (!bdrv_is_inserted(bs
)) {
1616 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1621 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1623 * Aligning zero request is nonsense. Even if driver has special meaning
1624 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1625 * it to driver due to request_alignment.
1627 * Still, no reason to return an error if someone do unaligned
1628 * zero-length read occasionally.
1633 bdrv_inc_in_flight(bs
);
1635 /* Don't do copy-on-read if we read data before write operation */
1636 if (qatomic_read(&bs
->copy_on_read
)) {
1637 flags
|= BDRV_REQ_COPY_ON_READ
;
1640 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
1646 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1647 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1648 bs
->bl
.request_alignment
,
1649 qiov
, qiov_offset
, flags
);
1650 tracked_request_end(&req
);
1651 bdrv_padding_destroy(&pad
);
1654 bdrv_dec_in_flight(bs
);
1659 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1660 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
1662 BlockDriver
*drv
= bs
->drv
;
1666 bool need_flush
= false;
1670 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1672 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1673 bs
->bl
.request_alignment
);
1674 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1676 bdrv_check_request(offset
, bytes
, &error_abort
);
1682 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1686 /* By definition there is no user buffer so this flag doesn't make sense */
1687 if (flags
& BDRV_REQ_REGISTERED_BUF
) {
1691 /* Invalidate the cached block-status data range if this write overlaps */
1692 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1694 assert(alignment
% bs
->bl
.request_alignment
== 0);
1695 head
= offset
% alignment
;
1696 tail
= (offset
+ bytes
) % alignment
;
1697 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1698 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1700 while (bytes
> 0 && !ret
) {
1701 int64_t num
= bytes
;
1703 /* Align request. Block drivers can expect the "bulk" of the request
1704 * to be aligned, and that unaligned requests do not cross cluster
1708 /* Make a small request up to the first aligned sector. For
1709 * convenience, limit this request to max_transfer even if
1710 * we don't need to fall back to writes. */
1711 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1712 head
= (head
+ num
) % alignment
;
1713 assert(num
< max_write_zeroes
);
1714 } else if (tail
&& num
> alignment
) {
1715 /* Shorten the request to the last aligned sector. */
1719 /* limit request size */
1720 if (num
> max_write_zeroes
) {
1721 num
= max_write_zeroes
;
1725 /* First try the efficient write zeroes operation */
1726 if (drv
->bdrv_co_pwrite_zeroes
) {
1727 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1728 flags
& bs
->supported_zero_flags
);
1729 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1730 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1734 assert(!bs
->supported_zero_flags
);
1737 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1738 /* Fall back to bounce buffer if write zeroes is unsupported */
1739 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1741 if ((flags
& BDRV_REQ_FUA
) &&
1742 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1743 /* No need for bdrv_driver_pwrite() to do a fallback
1744 * flush on each chunk; use just one at the end */
1745 write_flags
&= ~BDRV_REQ_FUA
;
1748 num
= MIN(num
, max_transfer
);
1750 buf
= qemu_try_blockalign0(bs
, num
);
1756 qemu_iovec_init_buf(&qiov
, buf
, num
);
1758 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1760 /* Keep bounce buffer around if it is big enough for all
1761 * all future requests.
1763 if (num
< max_transfer
) {
1774 if (ret
== 0 && need_flush
) {
1775 ret
= bdrv_co_flush(bs
);
1781 static inline int coroutine_fn
1782 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1783 BdrvTrackedRequest
*req
, int flags
)
1785 BlockDriverState
*bs
= child
->bs
;
1787 bdrv_check_request(offset
, bytes
, &error_abort
);
1789 if (bdrv_is_read_only(bs
)) {
1793 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1794 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1795 assert(!(flags
& ~BDRV_REQ_MASK
));
1796 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
1798 if (flags
& BDRV_REQ_SERIALISING
) {
1799 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
1801 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
1803 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
1807 bdrv_wait_serialising_requests_locked(req
);
1809 bdrv_wait_serialising_requests(req
);
1812 assert(req
->overlap_offset
<= offset
);
1813 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1814 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
1815 child
->perm
& BLK_PERM_RESIZE
);
1817 switch (req
->type
) {
1818 case BDRV_TRACKED_WRITE
:
1819 case BDRV_TRACKED_DISCARD
:
1820 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1821 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1823 assert(child
->perm
& BLK_PERM_WRITE
);
1825 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
1827 case BDRV_TRACKED_TRUNCATE
:
1828 assert(child
->perm
& BLK_PERM_RESIZE
);
1835 static inline void coroutine_fn
1836 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1837 BdrvTrackedRequest
*req
, int ret
)
1839 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1840 BlockDriverState
*bs
= child
->bs
;
1842 bdrv_check_request(offset
, bytes
, &error_abort
);
1844 qatomic_inc(&bs
->write_gen
);
1847 * Discard cannot extend the image, but in error handling cases, such as
1848 * when reverting a qcow2 cluster allocation, the discarded range can pass
1849 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1850 * here. Instead, just skip it, since semantically a discard request
1851 * beyond EOF cannot expand the image anyway.
1854 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1855 end_sector
> bs
->total_sectors
) &&
1856 req
->type
!= BDRV_TRACKED_DISCARD
) {
1857 bs
->total_sectors
= end_sector
;
1858 bdrv_parent_cb_resize(bs
);
1859 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1862 switch (req
->type
) {
1863 case BDRV_TRACKED_WRITE
:
1864 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1865 /* fall through, to set dirty bits */
1866 case BDRV_TRACKED_DISCARD
:
1867 bdrv_set_dirty(bs
, offset
, bytes
);
1876 * Forwards an already correctly aligned write request to the BlockDriver,
1877 * after possibly fragmenting it.
1879 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1880 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1881 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
,
1882 BdrvRequestFlags flags
)
1884 BlockDriverState
*bs
= child
->bs
;
1885 BlockDriver
*drv
= bs
->drv
;
1888 int64_t bytes_remaining
= bytes
;
1891 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1897 if (bdrv_has_readonly_bitmaps(bs
)) {
1901 assert(is_power_of_2(align
));
1902 assert((offset
& (align
- 1)) == 0);
1903 assert((bytes
& (align
- 1)) == 0);
1904 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1907 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1909 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1910 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1911 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
1912 flags
|= BDRV_REQ_ZERO_WRITE
;
1913 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1914 flags
|= BDRV_REQ_MAY_UNMAP
;
1919 /* Do nothing, write notifier decided to fail this request */
1920 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1921 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1922 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1923 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1924 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
1926 } else if (bytes
<= max_transfer
) {
1927 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1928 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1930 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1931 while (bytes_remaining
) {
1932 int num
= MIN(bytes_remaining
, max_transfer
);
1933 int local_flags
= flags
;
1936 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1937 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1938 /* If FUA is going to be emulated by flush, we only
1939 * need to flush on the last iteration */
1940 local_flags
&= ~BDRV_REQ_FUA
;
1943 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1945 qiov_offset
+ bytes
- bytes_remaining
,
1950 bytes_remaining
-= num
;
1953 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1958 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
1963 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1966 BdrvRequestFlags flags
,
1967 BdrvTrackedRequest
*req
)
1969 BlockDriverState
*bs
= child
->bs
;
1970 QEMUIOVector local_qiov
;
1971 uint64_t align
= bs
->bl
.request_alignment
;
1974 BdrvRequestPadding pad
;
1976 /* This flag doesn't make sense for padding or zero writes */
1977 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1979 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
1981 assert(!(flags
& BDRV_REQ_NO_WAIT
));
1982 bdrv_make_request_serialising(req
, align
);
1984 bdrv_padding_rmw_read(child
, req
, &pad
, true);
1986 if (pad
.head
|| pad
.merge_reads
) {
1987 int64_t aligned_offset
= offset
& ~(align
- 1);
1988 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
1990 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
1991 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
1992 align
, &local_qiov
, 0,
1993 flags
& ~BDRV_REQ_ZERO_WRITE
);
1994 if (ret
< 0 || pad
.merge_reads
) {
1995 /* Error or all work is done */
1998 offset
+= write_bytes
- pad
.head
;
1999 bytes
-= write_bytes
- pad
.head
;
2003 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2004 if (bytes
>= align
) {
2005 /* Write the aligned part in the middle. */
2006 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2007 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2012 bytes
-= aligned_bytes
;
2013 offset
+= aligned_bytes
;
2016 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2018 assert(align
== pad
.tail
+ bytes
);
2020 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2021 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2023 flags
& ~BDRV_REQ_ZERO_WRITE
);
2027 bdrv_padding_destroy(&pad
);
2033 * Handle a write request in coroutine context
2035 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2036 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2037 BdrvRequestFlags flags
)
2040 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2043 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2044 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2045 BdrvRequestFlags flags
)
2047 BlockDriverState
*bs
= child
->bs
;
2048 BdrvTrackedRequest req
;
2049 uint64_t align
= bs
->bl
.request_alignment
;
2050 BdrvRequestPadding pad
;
2052 bool padded
= false;
2055 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2057 if (!bdrv_is_inserted(bs
)) {
2061 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2062 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2064 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2070 /* If the request is misaligned then we can't make it efficient */
2071 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2072 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2077 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2079 * Aligning zero request is nonsense. Even if driver has special meaning
2080 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2081 * it to driver due to request_alignment.
2083 * Still, no reason to return an error if someone do unaligned
2084 * zero-length write occasionally.
2089 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2091 * Pad request for following read-modify-write cycle.
2092 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2093 * alignment only if there is no ZERO flag.
2095 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
2102 bdrv_inc_in_flight(bs
);
2103 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2105 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2107 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2113 * Request was unaligned to request_alignment and therefore
2114 * padded. We are going to do read-modify-write, and must
2115 * serialize the request to prevent interactions of the
2116 * widened region with other transactions.
2118 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2119 bdrv_make_request_serialising(&req
, align
);
2120 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2123 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2124 qiov
, qiov_offset
, flags
);
2126 bdrv_padding_destroy(&pad
);
2129 tracked_request_end(&req
);
2130 bdrv_dec_in_flight(bs
);
2135 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2136 int64_t bytes
, BdrvRequestFlags flags
)
2139 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2141 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2142 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2145 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2146 BDRV_REQ_ZERO_WRITE
| flags
);
2150 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2152 int bdrv_flush_all(void)
2154 BdrvNextIterator it
;
2155 BlockDriverState
*bs
= NULL
;
2158 GLOBAL_STATE_CODE();
2161 * bdrv queue is managed by record/replay,
2162 * creating new flush request for stopping
2163 * the VM may break the determinism
2165 if (replay_events_enabled()) {
2169 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2170 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2173 aio_context_acquire(aio_context
);
2174 ret
= bdrv_flush(bs
);
2175 if (ret
< 0 && !result
) {
2178 aio_context_release(aio_context
);
2185 * Returns the allocation status of the specified sectors.
2186 * Drivers not implementing the functionality are assumed to not support
2187 * backing files, hence all their sectors are reported as allocated.
2189 * If 'want_zero' is true, the caller is querying for mapping
2190 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2191 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2192 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2194 * If 'offset' is beyond the end of the disk image the return value is
2195 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2197 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2198 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2199 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2201 * 'pnum' is set to the number of bytes (including and immediately
2202 * following the specified offset) that are easily known to be in the
2203 * same allocated/unallocated state. Note that a second call starting
2204 * at the original offset plus returned pnum may have the same status.
2205 * The returned value is non-zero on success except at end-of-file.
2207 * Returns negative errno on failure. Otherwise, if the
2208 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2209 * set to the host mapping and BDS corresponding to the guest offset.
2211 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2213 int64_t offset
, int64_t bytes
,
2214 int64_t *pnum
, int64_t *map
,
2215 BlockDriverState
**file
)
2218 int64_t n
; /* bytes */
2220 int64_t local_map
= 0;
2221 BlockDriverState
*local_file
= NULL
;
2222 int64_t aligned_offset
, aligned_bytes
;
2224 bool has_filtered_child
;
2228 total_size
= bdrv_getlength(bs
);
2229 if (total_size
< 0) {
2234 if (offset
>= total_size
) {
2235 ret
= BDRV_BLOCK_EOF
;
2243 n
= total_size
- offset
;
2248 /* Must be non-NULL or bdrv_getlength() would have failed */
2250 has_filtered_child
= bdrv_filter_child(bs
);
2251 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2253 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2254 if (offset
+ bytes
== total_size
) {
2255 ret
|= BDRV_BLOCK_EOF
;
2257 if (bs
->drv
->protocol_name
) {
2258 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2265 bdrv_inc_in_flight(bs
);
2267 /* Round out to request_alignment boundaries */
2268 align
= bs
->bl
.request_alignment
;
2269 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2270 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2272 if (bs
->drv
->bdrv_co_block_status
) {
2274 * Use the block-status cache only for protocol nodes: Format
2275 * drivers are generally quick to inquire the status, but protocol
2276 * drivers often need to get information from outside of qemu, so
2277 * we do not have control over the actual implementation. There
2278 * have been cases where inquiring the status took an unreasonably
2279 * long time, and we can do nothing in qemu to fix it.
2280 * This is especially problematic for images with large data areas,
2281 * because finding the few holes in them and giving them special
2282 * treatment does not gain much performance. Therefore, we try to
2283 * cache the last-identified data region.
2285 * Second, limiting ourselves to protocol nodes allows us to assume
2286 * the block status for data regions to be DATA | OFFSET_VALID, and
2287 * that the host offset is the same as the guest offset.
2289 * Note that it is possible that external writers zero parts of
2290 * the cached regions without the cache being invalidated, and so
2291 * we may report zeroes as data. This is not catastrophic,
2292 * however, because reporting zeroes as data is fine.
2294 if (QLIST_EMPTY(&bs
->children
) &&
2295 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2297 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2299 local_map
= aligned_offset
;
2301 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2302 aligned_bytes
, pnum
, &local_map
,
2306 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2307 * the cache is queried above. Technically, we do not need to check
2308 * it here; the worst that can happen is that we fill the cache for
2309 * non-protocol nodes, and then it is never used. However, filling
2310 * the cache requires an RCU update, so double check here to avoid
2311 * such an update if possible.
2313 * Check want_zero, because we only want to update the cache when we
2314 * have accurate information about what is zero and what is data.
2317 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2318 QLIST_EMPTY(&bs
->children
))
2321 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2322 * returned local_map value must be the same as the offset we
2323 * have passed (aligned_offset), and local_bs must be the node
2325 * Assert this, because we follow this rule when reading from
2326 * the cache (see the `local_file = bs` and
2327 * `local_map = aligned_offset` assignments above), and the
2328 * result the cache delivers must be the same as the driver
2331 assert(local_file
== bs
);
2332 assert(local_map
== aligned_offset
);
2333 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2337 /* Default code for filters */
2339 local_file
= bdrv_filter_bs(bs
);
2342 *pnum
= aligned_bytes
;
2343 local_map
= aligned_offset
;
2344 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2352 * The driver's result must be a non-zero multiple of request_alignment.
2353 * Clamp pnum and adjust map to original request.
2355 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2356 align
> offset
- aligned_offset
);
2357 if (ret
& BDRV_BLOCK_RECURSE
) {
2358 assert(ret
& BDRV_BLOCK_DATA
);
2359 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2360 assert(!(ret
& BDRV_BLOCK_ZERO
));
2363 *pnum
-= offset
- aligned_offset
;
2364 if (*pnum
> bytes
) {
2367 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2368 local_map
+= offset
- aligned_offset
;
2371 if (ret
& BDRV_BLOCK_RAW
) {
2372 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2373 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2374 *pnum
, pnum
, &local_map
, &local_file
);
2378 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2379 ret
|= BDRV_BLOCK_ALLOCATED
;
2380 } else if (bs
->drv
->supports_backing
) {
2381 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2384 ret
|= BDRV_BLOCK_ZERO
;
2385 } else if (want_zero
) {
2386 int64_t size2
= bdrv_getlength(cow_bs
);
2388 if (size2
>= 0 && offset
>= size2
) {
2389 ret
|= BDRV_BLOCK_ZERO
;
2394 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2395 local_file
&& local_file
!= bs
&&
2396 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2397 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2401 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2402 *pnum
, &file_pnum
, NULL
, NULL
);
2404 /* Ignore errors. This is just providing extra information, it
2405 * is useful but not necessary.
2407 if (ret2
& BDRV_BLOCK_EOF
&&
2408 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2410 * It is valid for the format block driver to read
2411 * beyond the end of the underlying file's current
2412 * size; such areas read as zero.
2414 ret
|= BDRV_BLOCK_ZERO
;
2416 /* Limit request to the range reported by the protocol driver */
2418 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2424 bdrv_dec_in_flight(bs
);
2425 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2426 ret
|= BDRV_BLOCK_EOF
;
2439 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2440 BlockDriverState
*base
,
2447 BlockDriverState
**file
,
2451 BlockDriverState
*p
;
2456 assert(!include_base
|| base
); /* Can't include NULL base */
2463 if (!include_base
&& bs
== base
) {
2468 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2470 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2474 if (ret
& BDRV_BLOCK_EOF
) {
2475 eof
= offset
+ *pnum
;
2478 assert(*pnum
<= bytes
);
2481 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2482 p
= bdrv_filter_or_cow_bs(p
))
2484 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2492 * The top layer deferred to this layer, and because this layer is
2493 * short, any zeroes that we synthesize beyond EOF behave as if they
2494 * were allocated at this layer.
2496 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2497 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2500 assert(ret
& BDRV_BLOCK_EOF
);
2505 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2508 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2510 * We've found the node and the status, we must break.
2512 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2513 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2516 ret
&= ~BDRV_BLOCK_EOF
;
2521 assert(include_base
);
2526 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2527 * let's continue the diving.
2529 assert(*pnum
<= bytes
);
2533 if (offset
+ *pnum
== eof
) {
2534 ret
|= BDRV_BLOCK_EOF
;
2540 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2541 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2542 int64_t *map
, BlockDriverState
**file
)
2545 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2546 pnum
, map
, file
, NULL
);
2549 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2550 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2553 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2554 offset
, bytes
, pnum
, map
, file
);
2558 * Check @bs (and its backing chain) to see if the range defined
2559 * by @offset and @bytes is known to read as zeroes.
2560 * Return 1 if that is the case, 0 otherwise and -errno on error.
2561 * This test is meant to be fast rather than accurate so returning 0
2562 * does not guarantee non-zero data.
2564 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2568 int64_t pnum
= bytes
;
2575 ret
= bdrv_co_common_block_status_above(bs
, NULL
, false, false, offset
,
2576 bytes
, &pnum
, NULL
, NULL
, NULL
);
2582 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2585 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2592 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2593 bytes
, pnum
? pnum
: &dummy
, NULL
,
2598 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2602 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2604 * Return a positive depth if (a prefix of) the given range is allocated
2605 * in any image between BASE and TOP (BASE is only included if include_base
2606 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2607 * BASE can be NULL to check if the given offset is allocated in any
2608 * image of the chain. Return 0 otherwise, or negative errno on
2611 * 'pnum' is set to the number of bytes (including and immediately
2612 * following the specified offset) that are known to be in the same
2613 * allocated/unallocated state. Note that a subsequent call starting
2614 * at 'offset + *pnum' may return the same allocation status (in other
2615 * words, the result is not necessarily the maximum possible range);
2616 * but 'pnum' will only be 0 when end of file is reached.
2618 int bdrv_is_allocated_above(BlockDriverState
*top
,
2619 BlockDriverState
*base
,
2620 bool include_base
, int64_t offset
,
2621 int64_t bytes
, int64_t *pnum
)
2624 int ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2625 offset
, bytes
, pnum
, NULL
, NULL
,
2632 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2639 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2641 BlockDriver
*drv
= bs
->drv
;
2642 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2646 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2655 bdrv_inc_in_flight(bs
);
2657 if (drv
->bdrv_load_vmstate
) {
2658 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2659 } else if (child_bs
) {
2660 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2665 bdrv_dec_in_flight(bs
);
2671 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2673 BlockDriver
*drv
= bs
->drv
;
2674 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2678 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2687 bdrv_inc_in_flight(bs
);
2689 if (drv
->bdrv_save_vmstate
) {
2690 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2691 } else if (child_bs
) {
2692 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2697 bdrv_dec_in_flight(bs
);
2702 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2703 int64_t pos
, int size
)
2705 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2706 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2709 return ret
< 0 ? ret
: size
;
2712 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2713 int64_t pos
, int size
)
2715 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2716 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2719 return ret
< 0 ? ret
: size
;
2722 /**************************************************************/
2725 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2729 bdrv_aio_cancel_async(acb
);
2730 while (acb
->refcnt
> 1) {
2731 if (acb
->aiocb_info
->get_aio_context
) {
2732 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2733 } else if (acb
->bs
) {
2734 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2735 * assert that we're not using an I/O thread. Thread-safe
2736 * code should use bdrv_aio_cancel_async exclusively.
2738 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2739 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2744 qemu_aio_unref(acb
);
2747 /* Async version of aio cancel. The caller is not blocked if the acb implements
2748 * cancel_async, otherwise we do nothing and let the request normally complete.
2749 * In either case the completion callback must be called. */
2750 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2753 if (acb
->aiocb_info
->cancel_async
) {
2754 acb
->aiocb_info
->cancel_async(acb
);
2758 /**************************************************************/
2759 /* Coroutine block device emulation */
2761 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2763 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2769 bdrv_inc_in_flight(bs
);
2771 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2776 qemu_co_mutex_lock(&bs
->reqs_lock
);
2777 current_gen
= qatomic_read(&bs
->write_gen
);
2779 /* Wait until any previous flushes are completed */
2780 while (bs
->active_flush_req
) {
2781 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2784 /* Flushes reach this point in nondecreasing current_gen order. */
2785 bs
->active_flush_req
= true;
2786 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2788 /* Write back all layers by calling one driver function */
2789 if (bs
->drv
->bdrv_co_flush
) {
2790 ret
= bs
->drv
->bdrv_co_flush(bs
);
2794 /* Write back cached data to the OS even with cache=unsafe */
2795 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2796 if (bs
->drv
->bdrv_co_flush_to_os
) {
2797 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2803 /* But don't actually force it to the disk with cache=unsafe */
2804 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2805 goto flush_children
;
2808 /* Check if we really need to flush anything */
2809 if (bs
->flushed_gen
== current_gen
) {
2810 goto flush_children
;
2813 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2815 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2816 * (even in case of apparent success) */
2820 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2821 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2822 } else if (bs
->drv
->bdrv_aio_flush
) {
2824 CoroutineIOCompletion co
= {
2825 .coroutine
= qemu_coroutine_self(),
2828 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2832 qemu_coroutine_yield();
2837 * Some block drivers always operate in either writethrough or unsafe
2838 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2839 * know how the server works (because the behaviour is hardcoded or
2840 * depends on server-side configuration), so we can't ensure that
2841 * everything is safe on disk. Returning an error doesn't work because
2842 * that would break guests even if the server operates in writethrough
2845 * Let's hope the user knows what he's doing.
2854 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2855 * in the case of cache=unsafe, so there are no useless flushes.
2859 QLIST_FOREACH(child
, &bs
->children
, next
) {
2860 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2861 int this_child_ret
= bdrv_co_flush(child
->bs
);
2863 ret
= this_child_ret
;
2869 /* Notify any pending flushes that we have completed */
2871 bs
->flushed_gen
= current_gen
;
2874 qemu_co_mutex_lock(&bs
->reqs_lock
);
2875 bs
->active_flush_req
= false;
2876 /* Return value is ignored - it's ok if wait queue is empty */
2877 qemu_co_queue_next(&bs
->flush_queue
);
2878 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2881 bdrv_dec_in_flight(bs
);
2885 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2888 BdrvTrackedRequest req
;
2890 int64_t max_pdiscard
;
2891 int head
, tail
, align
;
2892 BlockDriverState
*bs
= child
->bs
;
2895 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
2899 if (bdrv_has_readonly_bitmaps(bs
)) {
2903 ret
= bdrv_check_request(offset
, bytes
, NULL
);
2908 /* Do nothing if disabled. */
2909 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2913 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2917 /* Invalidate the cached block-status data range if this discard overlaps */
2918 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
2920 /* Discard is advisory, but some devices track and coalesce
2921 * unaligned requests, so we must pass everything down rather than
2922 * round here. Still, most devices will just silently ignore
2923 * unaligned requests (by returning -ENOTSUP), so we must fragment
2924 * the request accordingly. */
2925 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2926 assert(align
% bs
->bl
.request_alignment
== 0);
2927 head
= offset
% align
;
2928 tail
= (offset
+ bytes
) % align
;
2930 bdrv_inc_in_flight(bs
);
2931 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2933 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
2938 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
2940 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2943 int64_t num
= bytes
;
2946 /* Make small requests to get to alignment boundaries. */
2947 num
= MIN(bytes
, align
- head
);
2948 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2949 num
%= bs
->bl
.request_alignment
;
2951 head
= (head
+ num
) % align
;
2952 assert(num
< max_pdiscard
);
2955 /* Shorten the request to the last aligned cluster. */
2957 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2958 tail
> bs
->bl
.request_alignment
) {
2959 tail
%= bs
->bl
.request_alignment
;
2963 /* limit request size */
2964 if (num
> max_pdiscard
) {
2972 if (bs
->drv
->bdrv_co_pdiscard
) {
2973 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2976 CoroutineIOCompletion co
= {
2977 .coroutine
= qemu_coroutine_self(),
2980 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2981 bdrv_co_io_em_complete
, &co
);
2986 qemu_coroutine_yield();
2990 if (ret
&& ret
!= -ENOTSUP
) {
2999 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3000 tracked_request_end(&req
);
3001 bdrv_dec_in_flight(bs
);
3005 int coroutine_fn
bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3007 BlockDriver
*drv
= bs
->drv
;
3008 CoroutineIOCompletion co
= {
3009 .coroutine
= qemu_coroutine_self(),
3014 bdrv_inc_in_flight(bs
);
3015 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3020 if (drv
->bdrv_co_ioctl
) {
3021 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3023 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3028 qemu_coroutine_yield();
3031 bdrv_dec_in_flight(bs
);
3035 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3038 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3041 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3044 return memset(qemu_blockalign(bs
, size
), 0, size
);
3047 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3049 size_t align
= bdrv_opt_mem_align(bs
);
3052 /* Ensure that NULL is never returned on success */
3058 return qemu_try_memalign(align
, size
);
3061 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3063 void *mem
= qemu_try_blockalign(bs
, size
);
3067 memset(mem
, 0, size
);
3073 void bdrv_io_plug(BlockDriverState
*bs
)
3078 QLIST_FOREACH(child
, &bs
->children
, next
) {
3079 bdrv_io_plug(child
->bs
);
3082 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
3083 BlockDriver
*drv
= bs
->drv
;
3084 if (drv
&& drv
->bdrv_io_plug
) {
3085 drv
->bdrv_io_plug(bs
);
3090 void bdrv_io_unplug(BlockDriverState
*bs
)
3095 assert(bs
->io_plugged
);
3096 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
3097 BlockDriver
*drv
= bs
->drv
;
3098 if (drv
&& drv
->bdrv_io_unplug
) {
3099 drv
->bdrv_io_unplug(bs
);
3103 QLIST_FOREACH(child
, &bs
->children
, next
) {
3104 bdrv_io_unplug(child
->bs
);
3108 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3109 static void bdrv_register_buf_rollback(BlockDriverState
*bs
,
3112 BdrvChild
*final_child
)
3116 QLIST_FOREACH(child
, &bs
->children
, next
) {
3117 if (child
== final_child
) {
3121 bdrv_unregister_buf(child
->bs
, host
, size
);
3124 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3125 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3129 bool bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
3134 GLOBAL_STATE_CODE();
3135 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3136 if (!bs
->drv
->bdrv_register_buf(bs
, host
, size
, errp
)) {
3140 QLIST_FOREACH(child
, &bs
->children
, next
) {
3141 if (!bdrv_register_buf(child
->bs
, host
, size
, errp
)) {
3142 bdrv_register_buf_rollback(bs
, host
, size
, child
);
3149 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3153 GLOBAL_STATE_CODE();
3154 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3155 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3157 QLIST_FOREACH(child
, &bs
->children
, next
) {
3158 bdrv_unregister_buf(child
->bs
, host
, size
);
3162 static int coroutine_fn
bdrv_co_copy_range_internal(
3163 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3164 int64_t dst_offset
, int64_t bytes
,
3165 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3168 BdrvTrackedRequest req
;
3171 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3172 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3173 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3174 assert(!(read_flags
& BDRV_REQ_NO_WAIT
));
3175 assert(!(write_flags
& BDRV_REQ_NO_WAIT
));
3177 if (!dst
|| !dst
->bs
|| !bdrv_is_inserted(dst
->bs
)) {
3180 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3184 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3185 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3188 if (!src
|| !src
->bs
|| !bdrv_is_inserted(src
->bs
)) {
3191 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3196 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3197 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3198 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3203 bdrv_inc_in_flight(src
->bs
);
3204 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3207 /* BDRV_REQ_SERIALISING is only for write operation */
3208 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3209 bdrv_wait_serialising_requests(&req
);
3211 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3215 read_flags
, write_flags
);
3217 tracked_request_end(&req
);
3218 bdrv_dec_in_flight(src
->bs
);
3220 bdrv_inc_in_flight(dst
->bs
);
3221 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3222 BDRV_TRACKED_WRITE
);
3223 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3226 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3230 read_flags
, write_flags
);
3232 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3233 tracked_request_end(&req
);
3234 bdrv_dec_in_flight(dst
->bs
);
3240 /* Copy range from @src to @dst.
3242 * See the comment of bdrv_co_copy_range for the parameter and return value
3244 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3245 BdrvChild
*dst
, int64_t dst_offset
,
3247 BdrvRequestFlags read_flags
,
3248 BdrvRequestFlags write_flags
)
3251 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3252 read_flags
, write_flags
);
3253 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3254 bytes
, read_flags
, write_flags
, true);
3257 /* Copy range from @src to @dst.
3259 * See the comment of bdrv_co_copy_range for the parameter and return value
3261 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3262 BdrvChild
*dst
, int64_t dst_offset
,
3264 BdrvRequestFlags read_flags
,
3265 BdrvRequestFlags write_flags
)
3268 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3269 read_flags
, write_flags
);
3270 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3271 bytes
, read_flags
, write_flags
, false);
3274 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3275 BdrvChild
*dst
, int64_t dst_offset
,
3276 int64_t bytes
, BdrvRequestFlags read_flags
,
3277 BdrvRequestFlags write_flags
)
3280 return bdrv_co_copy_range_from(src
, src_offset
,
3282 bytes
, read_flags
, write_flags
);
3285 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3288 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3289 if (c
->klass
->resize
) {
3290 c
->klass
->resize(c
);
3296 * Truncate file to 'offset' bytes (needed only for file protocols)
3298 * If 'exact' is true, the file must be resized to exactly the given
3299 * 'offset'. Otherwise, it is sufficient for the node to be at least
3300 * 'offset' bytes in length.
3302 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3303 PreallocMode prealloc
, BdrvRequestFlags flags
,
3306 BlockDriverState
*bs
= child
->bs
;
3307 BdrvChild
*filtered
, *backing
;
3308 BlockDriver
*drv
= bs
->drv
;
3309 BdrvTrackedRequest req
;
3310 int64_t old_size
, new_bytes
;
3314 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3316 error_setg(errp
, "No medium inserted");
3320 error_setg(errp
, "Image size cannot be negative");
3324 ret
= bdrv_check_request(offset
, 0, errp
);
3329 old_size
= bdrv_getlength(bs
);
3331 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3335 if (bdrv_is_read_only(bs
)) {
3336 error_setg(errp
, "Image is read-only");
3340 if (offset
> old_size
) {
3341 new_bytes
= offset
- old_size
;
3346 bdrv_inc_in_flight(bs
);
3347 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3348 BDRV_TRACKED_TRUNCATE
);
3350 /* If we are growing the image and potentially using preallocation for the
3351 * new area, we need to make sure that no write requests are made to it
3352 * concurrently or they might be overwritten by preallocation. */
3354 bdrv_make_request_serialising(&req
, 1);
3356 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3359 error_setg_errno(errp
, -ret
,
3360 "Failed to prepare request for truncation");
3364 filtered
= bdrv_filter_child(bs
);
3365 backing
= bdrv_cow_child(bs
);
3368 * If the image has a backing file that is large enough that it would
3369 * provide data for the new area, we cannot leave it unallocated because
3370 * then the backing file content would become visible. Instead, zero-fill
3373 * Note that if the image has a backing file, but was opened without the
3374 * backing file, taking care of keeping things consistent with that backing
3375 * file is the user's responsibility.
3377 if (new_bytes
&& backing
) {
3378 int64_t backing_len
;
3380 backing_len
= bdrv_getlength(backing
->bs
);
3381 if (backing_len
< 0) {
3383 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3387 if (backing_len
> old_size
) {
3388 flags
|= BDRV_REQ_ZERO_WRITE
;
3392 if (drv
->bdrv_co_truncate
) {
3393 if (flags
& ~bs
->supported_truncate_flags
) {
3394 error_setg(errp
, "Block driver does not support requested flags");
3398 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3399 } else if (filtered
) {
3400 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3402 error_setg(errp
, "Image format driver does not support resize");
3410 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3412 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3414 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3416 /* It's possible that truncation succeeded but refresh_total_sectors
3417 * failed, but the latter doesn't affect how we should finish the request.
3418 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3419 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3422 tracked_request_end(&req
);
3423 bdrv_dec_in_flight(bs
);
3428 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3430 GLOBAL_STATE_CODE();
3431 if (!bs
|| !bs
->drv
) {
3435 if (bs
->drv
->bdrv_cancel_in_flight
) {
3436 bs
->drv
->bdrv_cancel_in_flight(bs
);
3441 bdrv_co_preadv_snapshot(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
3442 QEMUIOVector
*qiov
, size_t qiov_offset
)
3444 BlockDriverState
*bs
= child
->bs
;
3445 BlockDriver
*drv
= bs
->drv
;
3453 if (!drv
->bdrv_co_preadv_snapshot
) {
3457 bdrv_inc_in_flight(bs
);
3458 ret
= drv
->bdrv_co_preadv_snapshot(bs
, offset
, bytes
, qiov
, qiov_offset
);
3459 bdrv_dec_in_flight(bs
);
3465 bdrv_co_snapshot_block_status(BlockDriverState
*bs
,
3466 bool want_zero
, int64_t offset
, int64_t bytes
,
3467 int64_t *pnum
, int64_t *map
,
3468 BlockDriverState
**file
)
3470 BlockDriver
*drv
= bs
->drv
;
3478 if (!drv
->bdrv_co_snapshot_block_status
) {
3482 bdrv_inc_in_flight(bs
);
3483 ret
= drv
->bdrv_co_snapshot_block_status(bs
, want_zero
, offset
, bytes
,
3485 bdrv_dec_in_flight(bs
);
3491 bdrv_co_pdiscard_snapshot(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3493 BlockDriver
*drv
= bs
->drv
;
3501 if (!drv
->bdrv_co_pdiscard_snapshot
) {
3505 bdrv_inc_in_flight(bs
);
3506 ret
= drv
->bdrv_co_pdiscard_snapshot(bs
, offset
, bytes
);
3507 bdrv_dec_in_flight(bs
);