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 static 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 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
, BdrvChild
*parent
)
352 assert(!qemu_in_coroutine());
354 /* Stop things in parent-to-child order */
355 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
356 aio_disable_external(bdrv_get_aio_context(bs
));
357 bdrv_parent_drained_begin(bs
, parent
);
358 if (bs
->drv
&& bs
->drv
->bdrv_drain_begin
) {
359 bs
->drv
->bdrv_drain_begin(bs
);
364 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
367 if (qemu_in_coroutine()) {
368 bdrv_co_yield_to_drain(bs
, true, parent
, poll
);
372 bdrv_do_drained_begin_quiesce(bs
, parent
);
375 * Wait for drained requests to finish.
377 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
378 * call is needed so things in this AioContext can make progress even
379 * though we don't return to the main AioContext loop - this automatically
380 * includes other nodes in the same AioContext and therefore all child
384 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, parent
));
388 void bdrv_drained_begin(BlockDriverState
*bs
)
391 bdrv_do_drained_begin(bs
, NULL
, true);
395 * This function does not poll, nor must any of its recursively called
398 static void bdrv_do_drained_end(BlockDriverState
*bs
, BdrvChild
*parent
)
400 int old_quiesce_counter
;
402 if (qemu_in_coroutine()) {
403 bdrv_co_yield_to_drain(bs
, false, parent
, false);
406 assert(bs
->quiesce_counter
> 0);
408 /* Re-enable things in child-to-parent order */
409 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
410 if (old_quiesce_counter
== 1) {
411 if (bs
->drv
&& bs
->drv
->bdrv_drain_end
) {
412 bs
->drv
->bdrv_drain_end(bs
);
414 bdrv_parent_drained_end(bs
, parent
);
415 aio_enable_external(bdrv_get_aio_context(bs
));
419 void bdrv_drained_end(BlockDriverState
*bs
)
422 bdrv_do_drained_end(bs
, NULL
);
425 void bdrv_drain(BlockDriverState
*bs
)
428 bdrv_drained_begin(bs
);
429 bdrv_drained_end(bs
);
432 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
434 BdrvChild
*child
, *next
;
436 assert(qatomic_read(&bs
->in_flight
) == 0);
437 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
438 bdrv_drain_assert_idle(child
->bs
);
442 unsigned int bdrv_drain_all_count
= 0;
444 static bool bdrv_drain_all_poll(void)
446 BlockDriverState
*bs
= NULL
;
450 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
451 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
452 while ((bs
= bdrv_next_all_states(bs
))) {
453 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
454 aio_context_acquire(aio_context
);
455 result
|= bdrv_drain_poll(bs
, NULL
, true);
456 aio_context_release(aio_context
);
463 * Wait for pending requests to complete across all BlockDriverStates
465 * This function does not flush data to disk, use bdrv_flush_all() for that
466 * after calling this function.
468 * This pauses all block jobs and disables external clients. It must
469 * be paired with bdrv_drain_all_end().
471 * NOTE: no new block jobs or BlockDriverStates can be created between
472 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
474 void bdrv_drain_all_begin(void)
476 BlockDriverState
*bs
= NULL
;
479 if (qemu_in_coroutine()) {
480 bdrv_co_yield_to_drain(NULL
, true, NULL
, true);
485 * bdrv queue is managed by record/replay,
486 * waiting for finishing the I/O requests may
489 if (replay_events_enabled()) {
493 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
494 * loop AioContext, so make sure we're in the main context. */
495 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
496 assert(bdrv_drain_all_count
< INT_MAX
);
497 bdrv_drain_all_count
++;
499 /* Quiesce all nodes, without polling in-flight requests yet. The graph
500 * cannot change during this loop. */
501 while ((bs
= bdrv_next_all_states(bs
))) {
502 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
504 aio_context_acquire(aio_context
);
505 bdrv_do_drained_begin(bs
, NULL
, false);
506 aio_context_release(aio_context
);
509 /* Now poll the in-flight requests */
510 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
512 while ((bs
= bdrv_next_all_states(bs
))) {
513 bdrv_drain_assert_idle(bs
);
517 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
521 g_assert(bs
->quiesce_counter
> 0);
522 g_assert(!bs
->refcnt
);
524 while (bs
->quiesce_counter
) {
525 bdrv_do_drained_end(bs
, NULL
);
529 void bdrv_drain_all_end(void)
531 BlockDriverState
*bs
= NULL
;
535 * bdrv queue is managed by record/replay,
536 * waiting for finishing the I/O requests may
539 if (replay_events_enabled()) {
543 while ((bs
= bdrv_next_all_states(bs
))) {
544 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
546 aio_context_acquire(aio_context
);
547 bdrv_do_drained_end(bs
, NULL
);
548 aio_context_release(aio_context
);
551 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
552 assert(bdrv_drain_all_count
> 0);
553 bdrv_drain_all_count
--;
556 void bdrv_drain_all(void)
559 bdrv_drain_all_begin();
560 bdrv_drain_all_end();
564 * Remove an active request from the tracked requests list
566 * This function should be called when a tracked request is completing.
568 static void coroutine_fn
tracked_request_end(BdrvTrackedRequest
*req
)
570 if (req
->serialising
) {
571 qatomic_dec(&req
->bs
->serialising_in_flight
);
574 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
575 QLIST_REMOVE(req
, list
);
576 qemu_co_queue_restart_all(&req
->wait_queue
);
577 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
581 * Add an active request to the tracked requests list
583 static void coroutine_fn
tracked_request_begin(BdrvTrackedRequest
*req
,
584 BlockDriverState
*bs
,
587 enum BdrvTrackedRequestType type
)
589 bdrv_check_request(offset
, bytes
, &error_abort
);
591 *req
= (BdrvTrackedRequest
){
596 .co
= qemu_coroutine_self(),
597 .serialising
= false,
598 .overlap_offset
= offset
,
599 .overlap_bytes
= bytes
,
602 qemu_co_queue_init(&req
->wait_queue
);
604 qemu_co_mutex_lock(&bs
->reqs_lock
);
605 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
606 qemu_co_mutex_unlock(&bs
->reqs_lock
);
609 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
610 int64_t offset
, int64_t bytes
)
612 bdrv_check_request(offset
, bytes
, &error_abort
);
615 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
619 if (req
->overlap_offset
>= offset
+ bytes
) {
625 /* Called with self->bs->reqs_lock held */
626 static coroutine_fn BdrvTrackedRequest
*
627 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
629 BdrvTrackedRequest
*req
;
631 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
632 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
635 if (tracked_request_overlaps(req
, self
->overlap_offset
,
636 self
->overlap_bytes
))
639 * Hitting this means there was a reentrant request, for
640 * example, a block driver issuing nested requests. This must
641 * never happen since it means deadlock.
643 assert(qemu_coroutine_self() != req
->co
);
646 * If the request is already (indirectly) waiting for us, or
647 * will wait for us as soon as it wakes up, then just go on
648 * (instead of producing a deadlock in the former case).
650 if (!req
->waiting_for
) {
659 /* Called with self->bs->reqs_lock held */
660 static void coroutine_fn
661 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
663 BdrvTrackedRequest
*req
;
665 while ((req
= bdrv_find_conflicting_request(self
))) {
666 self
->waiting_for
= req
;
667 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
668 self
->waiting_for
= NULL
;
672 /* Called with req->bs->reqs_lock held */
673 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
676 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
677 int64_t overlap_bytes
=
678 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
680 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
682 if (!req
->serialising
) {
683 qatomic_inc(&req
->bs
->serialising_in_flight
);
684 req
->serialising
= true;
687 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
688 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
692 * Return the tracked request on @bs for the current coroutine, or
693 * NULL if there is none.
695 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
697 BdrvTrackedRequest
*req
;
698 Coroutine
*self
= qemu_coroutine_self();
701 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
702 if (req
->co
== self
) {
711 * Round a region to cluster boundaries
713 void bdrv_round_to_clusters(BlockDriverState
*bs
,
714 int64_t offset
, int64_t bytes
,
715 int64_t *cluster_offset
,
716 int64_t *cluster_bytes
)
720 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
721 *cluster_offset
= offset
;
722 *cluster_bytes
= bytes
;
724 int64_t c
= bdi
.cluster_size
;
725 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
726 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
730 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
735 ret
= bdrv_get_info(bs
, &bdi
);
736 if (ret
< 0 || bdi
.cluster_size
== 0) {
737 return bs
->bl
.request_alignment
;
739 return bdi
.cluster_size
;
743 void bdrv_inc_in_flight(BlockDriverState
*bs
)
746 qatomic_inc(&bs
->in_flight
);
749 void bdrv_wakeup(BlockDriverState
*bs
)
755 void bdrv_dec_in_flight(BlockDriverState
*bs
)
758 qatomic_dec(&bs
->in_flight
);
762 static void coroutine_fn
763 bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
765 BlockDriverState
*bs
= self
->bs
;
767 if (!qatomic_read(&bs
->serialising_in_flight
)) {
771 qemu_co_mutex_lock(&bs
->reqs_lock
);
772 bdrv_wait_serialising_requests_locked(self
);
773 qemu_co_mutex_unlock(&bs
->reqs_lock
);
776 void coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
781 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
783 tracked_request_set_serialising(req
, align
);
784 bdrv_wait_serialising_requests_locked(req
);
786 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
789 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
790 QEMUIOVector
*qiov
, size_t qiov_offset
,
794 * Check generic offset/bytes correctness
798 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
803 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
807 if (bytes
> BDRV_MAX_LENGTH
) {
808 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
809 bytes
, BDRV_MAX_LENGTH
);
813 if (offset
> BDRV_MAX_LENGTH
) {
814 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
815 offset
, BDRV_MAX_LENGTH
);
819 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
820 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
821 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
831 * Check qiov and qiov_offset
834 if (qiov_offset
> qiov
->size
) {
835 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
836 qiov_offset
, qiov
->size
);
840 if (bytes
> qiov
->size
- qiov_offset
) {
841 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
842 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
849 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
851 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
854 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
855 QEMUIOVector
*qiov
, size_t qiov_offset
)
857 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
862 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
870 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
871 * The operation is sped up by checking the block status and only writing
872 * zeroes to the device if they currently do not return zeroes. Optional
873 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
876 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
878 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
881 int64_t target_size
, bytes
, offset
= 0;
882 BlockDriverState
*bs
= child
->bs
;
885 target_size
= bdrv_getlength(bs
);
886 if (target_size
< 0) {
891 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
895 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
899 if (ret
& BDRV_BLOCK_ZERO
) {
903 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
912 * Writes to the file and ensures that no writes are reordered across this
913 * request (acts as a barrier)
915 * Returns 0 on success, -errno in error cases.
917 int coroutine_fn
bdrv_co_pwrite_sync(BdrvChild
*child
, int64_t offset
,
918 int64_t bytes
, const void *buf
,
919 BdrvRequestFlags flags
)
924 ret
= bdrv_co_pwrite(child
, offset
, bytes
, buf
, flags
);
929 ret
= bdrv_co_flush(child
->bs
);
937 typedef struct CoroutineIOCompletion
{
938 Coroutine
*coroutine
;
940 } CoroutineIOCompletion
;
942 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
944 CoroutineIOCompletion
*co
= opaque
;
947 aio_co_wake(co
->coroutine
);
950 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
951 int64_t offset
, int64_t bytes
,
953 size_t qiov_offset
, int flags
)
955 BlockDriver
*drv
= bs
->drv
;
957 unsigned int nb_sectors
;
958 QEMUIOVector local_qiov
;
961 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
962 assert(!(flags
& ~bs
->supported_read_flags
));
968 if (drv
->bdrv_co_preadv_part
) {
969 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
973 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
974 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
978 if (drv
->bdrv_co_preadv
) {
979 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
983 if (drv
->bdrv_aio_preadv
) {
985 CoroutineIOCompletion co
= {
986 .coroutine
= qemu_coroutine_self(),
989 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
990 bdrv_co_io_em_complete
, &co
);
995 qemu_coroutine_yield();
1001 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1002 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1004 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1005 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1006 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1007 assert(drv
->bdrv_co_readv
);
1009 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1012 if (qiov
== &local_qiov
) {
1013 qemu_iovec_destroy(&local_qiov
);
1019 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1020 int64_t offset
, int64_t bytes
,
1023 BdrvRequestFlags flags
)
1025 BlockDriver
*drv
= bs
->drv
;
1026 bool emulate_fua
= false;
1028 unsigned int nb_sectors
;
1029 QEMUIOVector local_qiov
;
1032 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1038 if ((flags
& BDRV_REQ_FUA
) &&
1039 (~bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1040 flags
&= ~BDRV_REQ_FUA
;
1044 flags
&= bs
->supported_write_flags
;
1046 if (drv
->bdrv_co_pwritev_part
) {
1047 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1052 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1053 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1057 if (drv
->bdrv_co_pwritev
) {
1058 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1062 if (drv
->bdrv_aio_pwritev
) {
1064 CoroutineIOCompletion co
= {
1065 .coroutine
= qemu_coroutine_self(),
1068 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
, flags
,
1069 bdrv_co_io_em_complete
, &co
);
1073 qemu_coroutine_yield();
1079 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1080 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1082 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1083 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1084 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1086 assert(drv
->bdrv_co_writev
);
1087 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
, flags
);
1090 if (ret
== 0 && emulate_fua
) {
1091 ret
= bdrv_co_flush(bs
);
1094 if (qiov
== &local_qiov
) {
1095 qemu_iovec_destroy(&local_qiov
);
1101 static int coroutine_fn
1102 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1103 int64_t bytes
, QEMUIOVector
*qiov
,
1106 BlockDriver
*drv
= bs
->drv
;
1107 QEMUIOVector local_qiov
;
1110 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1116 if (!block_driver_can_compress(drv
)) {
1120 if (drv
->bdrv_co_pwritev_compressed_part
) {
1121 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1125 if (qiov_offset
== 0) {
1126 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1129 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1130 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1131 qemu_iovec_destroy(&local_qiov
);
1136 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1137 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1138 size_t qiov_offset
, int flags
)
1140 BlockDriverState
*bs
= child
->bs
;
1142 /* Perform I/O through a temporary buffer so that users who scribble over
1143 * their read buffer while the operation is in progress do not end up
1144 * modifying the image file. This is critical for zero-copy guest I/O
1145 * where anything might happen inside guest memory.
1147 void *bounce_buffer
= NULL
;
1149 BlockDriver
*drv
= bs
->drv
;
1150 int64_t cluster_offset
;
1151 int64_t cluster_bytes
;
1154 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1155 BDRV_REQUEST_MAX_BYTES
);
1156 int64_t progress
= 0;
1159 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1166 * Do not write anything when the BDS is inactive. That is not
1167 * allowed, and it would not help.
1169 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1171 /* FIXME We cannot require callers to have write permissions when all they
1172 * are doing is a read request. If we did things right, write permissions
1173 * would be obtained anyway, but internally by the copy-on-read code. As
1174 * long as it is implemented here rather than in a separate filter driver,
1175 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1176 * it could request permissions. Therefore we have to bypass the permission
1177 * system for the moment. */
1178 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1180 /* Cover entire cluster so no additional backing file I/O is required when
1181 * allocating cluster in the image file. Note that this value may exceed
1182 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1183 * is one reason we loop rather than doing it all at once.
1185 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1186 skip_bytes
= offset
- cluster_offset
;
1188 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1189 cluster_offset
, cluster_bytes
);
1191 while (cluster_bytes
) {
1195 ret
= 1; /* "already allocated", so nothing will be copied */
1196 pnum
= MIN(cluster_bytes
, max_transfer
);
1198 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1199 MIN(cluster_bytes
, max_transfer
), &pnum
);
1202 * Safe to treat errors in querying allocation as if
1203 * unallocated; we'll probably fail again soon on the
1204 * read, but at least that will set a decent errno.
1206 pnum
= MIN(cluster_bytes
, max_transfer
);
1209 /* Stop at EOF if the image ends in the middle of the cluster */
1210 if (ret
== 0 && pnum
== 0) {
1211 assert(progress
>= bytes
);
1215 assert(skip_bytes
< pnum
);
1219 QEMUIOVector local_qiov
;
1221 /* Must copy-on-read; use the bounce buffer */
1222 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1223 if (!bounce_buffer
) {
1224 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1225 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1226 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1228 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1229 if (!bounce_buffer
) {
1234 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1236 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1242 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1243 if (drv
->bdrv_co_pwrite_zeroes
&&
1244 buffer_is_zero(bounce_buffer
, pnum
)) {
1245 /* FIXME: Should we (perhaps conditionally) be setting
1246 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1247 * that still correctly reads as zero? */
1248 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1249 BDRV_REQ_WRITE_UNCHANGED
);
1251 /* This does not change the data on the disk, it is not
1252 * necessary to flush even in cache=writethrough mode.
1254 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1256 BDRV_REQ_WRITE_UNCHANGED
);
1260 /* It might be okay to ignore write errors for guest
1261 * requests. If this is a deliberate copy-on-read
1262 * then we don't want to ignore the error. Simply
1263 * report it in all cases.
1268 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1269 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1270 bounce_buffer
+ skip_bytes
,
1271 MIN(pnum
- skip_bytes
, bytes
- progress
));
1273 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1274 /* Read directly into the destination */
1275 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1276 MIN(pnum
- skip_bytes
, bytes
- progress
),
1277 qiov
, qiov_offset
+ progress
, 0);
1283 cluster_offset
+= pnum
;
1284 cluster_bytes
-= pnum
;
1285 progress
+= pnum
- skip_bytes
;
1291 qemu_vfree(bounce_buffer
);
1296 * Forwards an already correctly aligned request to the BlockDriver. This
1297 * handles copy on read, zeroing after EOF, and fragmentation of large
1298 * reads; any other features must be implemented by the caller.
1300 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1301 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1302 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1304 BlockDriverState
*bs
= child
->bs
;
1305 int64_t total_bytes
, max_bytes
;
1307 int64_t bytes_remaining
= bytes
;
1310 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1311 assert(is_power_of_2(align
));
1312 assert((offset
& (align
- 1)) == 0);
1313 assert((bytes
& (align
- 1)) == 0);
1314 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1315 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1319 * TODO: We would need a per-BDS .supported_read_flags and
1320 * potential fallback support, if we ever implement any read flags
1321 * to pass through to drivers. For now, there aren't any
1322 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1324 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
|
1325 BDRV_REQ_REGISTERED_BUF
)));
1327 /* Handle Copy on Read and associated serialisation */
1328 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1329 /* If we touch the same cluster it counts as an overlap. This
1330 * guarantees that allocating writes will be serialized and not race
1331 * with each other for the same cluster. For example, in copy-on-read
1332 * it ensures that the CoR read and write operations are atomic and
1333 * guest writes cannot interleave between them. */
1334 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1336 bdrv_wait_serialising_requests(req
);
1339 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1342 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1343 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1345 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1350 if (!ret
|| pnum
!= bytes
) {
1351 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1352 qiov
, qiov_offset
, flags
);
1354 } else if (flags
& BDRV_REQ_PREFETCH
) {
1359 /* Forward the request to the BlockDriver, possibly fragmenting it */
1360 total_bytes
= bdrv_getlength(bs
);
1361 if (total_bytes
< 0) {
1366 assert(!(flags
& ~(bs
->supported_read_flags
| BDRV_REQ_REGISTERED_BUF
)));
1368 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1369 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1370 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1374 while (bytes_remaining
) {
1378 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1381 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1383 qiov_offset
+ bytes
- bytes_remaining
,
1387 num
= bytes_remaining
;
1388 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1389 0, bytes_remaining
);
1394 bytes_remaining
-= num
;
1398 return ret
< 0 ? ret
: 0;
1404 * |<---- align ----->| |<----- align ---->|
1405 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1407 * -*----------$-------*-------- ... --------*-----$------------*---
1409 * | offset | | end |
1410 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1411 * [buf ... ) [tail_buf )
1413 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1414 * is placed at the beginning of @buf and @tail at the @end.
1416 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1417 * around tail, if tail exists.
1419 * @merge_reads is true for small requests,
1420 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1421 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1423 typedef struct BdrvRequestPadding
{
1430 QEMUIOVector local_qiov
;
1431 } BdrvRequestPadding
;
1433 static bool bdrv_init_padding(BlockDriverState
*bs
,
1434 int64_t offset
, int64_t bytes
,
1435 BdrvRequestPadding
*pad
)
1437 int64_t align
= bs
->bl
.request_alignment
;
1440 bdrv_check_request(offset
, bytes
, &error_abort
);
1441 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1442 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1444 memset(pad
, 0, sizeof(*pad
));
1446 pad
->head
= offset
& (align
- 1);
1447 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1449 pad
->tail
= align
- pad
->tail
;
1452 if (!pad
->head
&& !pad
->tail
) {
1456 assert(bytes
); /* Nothing good in aligning zero-length requests */
1458 sum
= pad
->head
+ bytes
+ pad
->tail
;
1459 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1460 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1461 pad
->merge_reads
= sum
== pad
->buf_len
;
1463 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1469 static coroutine_fn
int bdrv_padding_rmw_read(BdrvChild
*child
,
1470 BdrvTrackedRequest
*req
,
1471 BdrvRequestPadding
*pad
,
1474 QEMUIOVector local_qiov
;
1475 BlockDriverState
*bs
= child
->bs
;
1476 uint64_t align
= bs
->bl
.request_alignment
;
1479 assert(req
->serialising
&& pad
->buf
);
1481 if (pad
->head
|| pad
->merge_reads
) {
1482 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1484 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1487 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1489 if (pad
->merge_reads
&& pad
->tail
) {
1490 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1492 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1493 align
, &local_qiov
, 0, 0);
1498 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1500 if (pad
->merge_reads
&& pad
->tail
) {
1501 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1504 if (pad
->merge_reads
) {
1510 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1512 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1513 ret
= bdrv_aligned_preadv(
1515 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1516 align
, align
, &local_qiov
, 0, 0);
1520 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1525 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1531 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1534 qemu_vfree(pad
->buf
);
1535 qemu_iovec_destroy(&pad
->local_qiov
);
1537 memset(pad
, 0, sizeof(*pad
));
1543 * Exchange request parameters with padded request if needed. Don't include RMW
1544 * read of padding, bdrv_padding_rmw_read() should be called separately if
1547 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1548 * - on function start they represent original request
1549 * - on failure or when padding is not needed they are unchanged
1550 * - on success when padding is needed they represent padded request
1552 static int bdrv_pad_request(BlockDriverState
*bs
,
1553 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1554 int64_t *offset
, int64_t *bytes
,
1555 BdrvRequestPadding
*pad
, bool *padded
,
1556 BdrvRequestFlags
*flags
)
1560 bdrv_check_qiov_request(*offset
, *bytes
, *qiov
, *qiov_offset
, &error_abort
);
1562 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1569 ret
= qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1570 *qiov
, *qiov_offset
, *bytes
,
1571 pad
->buf
+ pad
->buf_len
- pad
->tail
,
1574 bdrv_padding_destroy(pad
);
1577 *bytes
+= pad
->head
+ pad
->tail
;
1578 *offset
-= pad
->head
;
1579 *qiov
= &pad
->local_qiov
;
1585 /* Can't use optimization hint with bounce buffer */
1586 *flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1592 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1593 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1594 BdrvRequestFlags flags
)
1597 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1600 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1601 int64_t offset
, int64_t bytes
,
1602 QEMUIOVector
*qiov
, size_t qiov_offset
,
1603 BdrvRequestFlags flags
)
1605 BlockDriverState
*bs
= child
->bs
;
1606 BdrvTrackedRequest req
;
1607 BdrvRequestPadding pad
;
1611 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1613 if (!bdrv_is_inserted(bs
)) {
1617 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1622 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1624 * Aligning zero request is nonsense. Even if driver has special meaning
1625 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1626 * it to driver due to request_alignment.
1628 * Still, no reason to return an error if someone do unaligned
1629 * zero-length read occasionally.
1634 bdrv_inc_in_flight(bs
);
1636 /* Don't do copy-on-read if we read data before write operation */
1637 if (qatomic_read(&bs
->copy_on_read
)) {
1638 flags
|= BDRV_REQ_COPY_ON_READ
;
1641 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
1647 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1648 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1649 bs
->bl
.request_alignment
,
1650 qiov
, qiov_offset
, flags
);
1651 tracked_request_end(&req
);
1652 bdrv_padding_destroy(&pad
);
1655 bdrv_dec_in_flight(bs
);
1660 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1661 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
1663 BlockDriver
*drv
= bs
->drv
;
1667 bool need_flush
= false;
1671 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1673 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1674 bs
->bl
.request_alignment
);
1675 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1677 bdrv_check_request(offset
, bytes
, &error_abort
);
1683 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1687 /* By definition there is no user buffer so this flag doesn't make sense */
1688 if (flags
& BDRV_REQ_REGISTERED_BUF
) {
1692 /* Invalidate the cached block-status data range if this write overlaps */
1693 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1695 assert(alignment
% bs
->bl
.request_alignment
== 0);
1696 head
= offset
% alignment
;
1697 tail
= (offset
+ bytes
) % alignment
;
1698 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1699 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1701 while (bytes
> 0 && !ret
) {
1702 int64_t num
= bytes
;
1704 /* Align request. Block drivers can expect the "bulk" of the request
1705 * to be aligned, and that unaligned requests do not cross cluster
1709 /* Make a small request up to the first aligned sector. For
1710 * convenience, limit this request to max_transfer even if
1711 * we don't need to fall back to writes. */
1712 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1713 head
= (head
+ num
) % alignment
;
1714 assert(num
< max_write_zeroes
);
1715 } else if (tail
&& num
> alignment
) {
1716 /* Shorten the request to the last aligned sector. */
1720 /* limit request size */
1721 if (num
> max_write_zeroes
) {
1722 num
= max_write_zeroes
;
1726 /* First try the efficient write zeroes operation */
1727 if (drv
->bdrv_co_pwrite_zeroes
) {
1728 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1729 flags
& bs
->supported_zero_flags
);
1730 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1731 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1735 assert(!bs
->supported_zero_flags
);
1738 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1739 /* Fall back to bounce buffer if write zeroes is unsupported */
1740 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1742 if ((flags
& BDRV_REQ_FUA
) &&
1743 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1744 /* No need for bdrv_driver_pwrite() to do a fallback
1745 * flush on each chunk; use just one at the end */
1746 write_flags
&= ~BDRV_REQ_FUA
;
1749 num
= MIN(num
, max_transfer
);
1751 buf
= qemu_try_blockalign0(bs
, num
);
1757 qemu_iovec_init_buf(&qiov
, buf
, num
);
1759 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1761 /* Keep bounce buffer around if it is big enough for all
1762 * all future requests.
1764 if (num
< max_transfer
) {
1775 if (ret
== 0 && need_flush
) {
1776 ret
= bdrv_co_flush(bs
);
1782 static inline int coroutine_fn
1783 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1784 BdrvTrackedRequest
*req
, int flags
)
1786 BlockDriverState
*bs
= child
->bs
;
1788 bdrv_check_request(offset
, bytes
, &error_abort
);
1790 if (bdrv_is_read_only(bs
)) {
1794 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1795 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1796 assert(!(flags
& ~BDRV_REQ_MASK
));
1797 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
1799 if (flags
& BDRV_REQ_SERIALISING
) {
1800 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
1802 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
1804 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
1808 bdrv_wait_serialising_requests_locked(req
);
1810 bdrv_wait_serialising_requests(req
);
1813 assert(req
->overlap_offset
<= offset
);
1814 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1815 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
1816 child
->perm
& BLK_PERM_RESIZE
);
1818 switch (req
->type
) {
1819 case BDRV_TRACKED_WRITE
:
1820 case BDRV_TRACKED_DISCARD
:
1821 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1822 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1824 assert(child
->perm
& BLK_PERM_WRITE
);
1826 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
1828 case BDRV_TRACKED_TRUNCATE
:
1829 assert(child
->perm
& BLK_PERM_RESIZE
);
1836 static inline void coroutine_fn
1837 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1838 BdrvTrackedRequest
*req
, int ret
)
1840 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1841 BlockDriverState
*bs
= child
->bs
;
1843 bdrv_check_request(offset
, bytes
, &error_abort
);
1845 qatomic_inc(&bs
->write_gen
);
1848 * Discard cannot extend the image, but in error handling cases, such as
1849 * when reverting a qcow2 cluster allocation, the discarded range can pass
1850 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1851 * here. Instead, just skip it, since semantically a discard request
1852 * beyond EOF cannot expand the image anyway.
1855 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1856 end_sector
> bs
->total_sectors
) &&
1857 req
->type
!= BDRV_TRACKED_DISCARD
) {
1858 bs
->total_sectors
= end_sector
;
1859 bdrv_parent_cb_resize(bs
);
1860 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1863 switch (req
->type
) {
1864 case BDRV_TRACKED_WRITE
:
1865 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1866 /* fall through, to set dirty bits */
1867 case BDRV_TRACKED_DISCARD
:
1868 bdrv_set_dirty(bs
, offset
, bytes
);
1877 * Forwards an already correctly aligned write request to the BlockDriver,
1878 * after possibly fragmenting it.
1880 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1881 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1882 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
,
1883 BdrvRequestFlags flags
)
1885 BlockDriverState
*bs
= child
->bs
;
1886 BlockDriver
*drv
= bs
->drv
;
1889 int64_t bytes_remaining
= bytes
;
1892 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1898 if (bdrv_has_readonly_bitmaps(bs
)) {
1902 assert(is_power_of_2(align
));
1903 assert((offset
& (align
- 1)) == 0);
1904 assert((bytes
& (align
- 1)) == 0);
1905 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1908 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1910 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1911 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1912 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
1913 flags
|= BDRV_REQ_ZERO_WRITE
;
1914 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1915 flags
|= BDRV_REQ_MAY_UNMAP
;
1920 /* Do nothing, write notifier decided to fail this request */
1921 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1922 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1923 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1924 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1925 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
1927 } else if (bytes
<= max_transfer
) {
1928 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1929 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1931 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1932 while (bytes_remaining
) {
1933 int num
= MIN(bytes_remaining
, max_transfer
);
1934 int local_flags
= flags
;
1937 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1938 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1939 /* If FUA is going to be emulated by flush, we only
1940 * need to flush on the last iteration */
1941 local_flags
&= ~BDRV_REQ_FUA
;
1944 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1946 qiov_offset
+ bytes
- bytes_remaining
,
1951 bytes_remaining
-= num
;
1954 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1959 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
1964 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1967 BdrvRequestFlags flags
,
1968 BdrvTrackedRequest
*req
)
1970 BlockDriverState
*bs
= child
->bs
;
1971 QEMUIOVector local_qiov
;
1972 uint64_t align
= bs
->bl
.request_alignment
;
1975 BdrvRequestPadding pad
;
1977 /* This flag doesn't make sense for padding or zero writes */
1978 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1980 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
1982 assert(!(flags
& BDRV_REQ_NO_WAIT
));
1983 bdrv_make_request_serialising(req
, align
);
1985 bdrv_padding_rmw_read(child
, req
, &pad
, true);
1987 if (pad
.head
|| pad
.merge_reads
) {
1988 int64_t aligned_offset
= offset
& ~(align
- 1);
1989 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
1991 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
1992 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
1993 align
, &local_qiov
, 0,
1994 flags
& ~BDRV_REQ_ZERO_WRITE
);
1995 if (ret
< 0 || pad
.merge_reads
) {
1996 /* Error or all work is done */
1999 offset
+= write_bytes
- pad
.head
;
2000 bytes
-= write_bytes
- pad
.head
;
2004 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2005 if (bytes
>= align
) {
2006 /* Write the aligned part in the middle. */
2007 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2008 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2013 bytes
-= aligned_bytes
;
2014 offset
+= aligned_bytes
;
2017 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2019 assert(align
== pad
.tail
+ bytes
);
2021 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2022 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2024 flags
& ~BDRV_REQ_ZERO_WRITE
);
2028 bdrv_padding_destroy(&pad
);
2034 * Handle a write request in coroutine context
2036 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2037 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2038 BdrvRequestFlags flags
)
2041 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2044 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2045 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2046 BdrvRequestFlags flags
)
2048 BlockDriverState
*bs
= child
->bs
;
2049 BdrvTrackedRequest req
;
2050 uint64_t align
= bs
->bl
.request_alignment
;
2051 BdrvRequestPadding pad
;
2053 bool padded
= false;
2056 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2058 if (!bdrv_is_inserted(bs
)) {
2062 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2063 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2065 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2071 /* If the request is misaligned then we can't make it efficient */
2072 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2073 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2078 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2080 * Aligning zero request is nonsense. Even if driver has special meaning
2081 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2082 * it to driver due to request_alignment.
2084 * Still, no reason to return an error if someone do unaligned
2085 * zero-length write occasionally.
2090 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2092 * Pad request for following read-modify-write cycle.
2093 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2094 * alignment only if there is no ZERO flag.
2096 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
2103 bdrv_inc_in_flight(bs
);
2104 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2106 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2108 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2114 * Request was unaligned to request_alignment and therefore
2115 * padded. We are going to do read-modify-write, and must
2116 * serialize the request to prevent interactions of the
2117 * widened region with other transactions.
2119 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2120 bdrv_make_request_serialising(&req
, align
);
2121 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2124 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2125 qiov
, qiov_offset
, flags
);
2127 bdrv_padding_destroy(&pad
);
2130 tracked_request_end(&req
);
2131 bdrv_dec_in_flight(bs
);
2136 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2137 int64_t bytes
, BdrvRequestFlags flags
)
2140 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2142 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2143 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2146 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2147 BDRV_REQ_ZERO_WRITE
| flags
);
2151 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2153 int bdrv_flush_all(void)
2155 BdrvNextIterator it
;
2156 BlockDriverState
*bs
= NULL
;
2159 GLOBAL_STATE_CODE();
2162 * bdrv queue is managed by record/replay,
2163 * creating new flush request for stopping
2164 * the VM may break the determinism
2166 if (replay_events_enabled()) {
2170 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2171 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2174 aio_context_acquire(aio_context
);
2175 ret
= bdrv_flush(bs
);
2176 if (ret
< 0 && !result
) {
2179 aio_context_release(aio_context
);
2186 * Returns the allocation status of the specified sectors.
2187 * Drivers not implementing the functionality are assumed to not support
2188 * backing files, hence all their sectors are reported as allocated.
2190 * If 'want_zero' is true, the caller is querying for mapping
2191 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2192 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2193 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2195 * If 'offset' is beyond the end of the disk image the return value is
2196 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2198 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2199 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2200 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2202 * 'pnum' is set to the number of bytes (including and immediately
2203 * following the specified offset) that are easily known to be in the
2204 * same allocated/unallocated state. Note that a second call starting
2205 * at the original offset plus returned pnum may have the same status.
2206 * The returned value is non-zero on success except at end-of-file.
2208 * Returns negative errno on failure. Otherwise, if the
2209 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2210 * set to the host mapping and BDS corresponding to the guest offset.
2212 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2214 int64_t offset
, int64_t bytes
,
2215 int64_t *pnum
, int64_t *map
,
2216 BlockDriverState
**file
)
2219 int64_t n
; /* bytes */
2221 int64_t local_map
= 0;
2222 BlockDriverState
*local_file
= NULL
;
2223 int64_t aligned_offset
, aligned_bytes
;
2225 bool has_filtered_child
;
2229 total_size
= bdrv_getlength(bs
);
2230 if (total_size
< 0) {
2235 if (offset
>= total_size
) {
2236 ret
= BDRV_BLOCK_EOF
;
2244 n
= total_size
- offset
;
2249 /* Must be non-NULL or bdrv_getlength() would have failed */
2251 has_filtered_child
= bdrv_filter_child(bs
);
2252 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2254 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2255 if (offset
+ bytes
== total_size
) {
2256 ret
|= BDRV_BLOCK_EOF
;
2258 if (bs
->drv
->protocol_name
) {
2259 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2266 bdrv_inc_in_flight(bs
);
2268 /* Round out to request_alignment boundaries */
2269 align
= bs
->bl
.request_alignment
;
2270 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2271 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2273 if (bs
->drv
->bdrv_co_block_status
) {
2275 * Use the block-status cache only for protocol nodes: Format
2276 * drivers are generally quick to inquire the status, but protocol
2277 * drivers often need to get information from outside of qemu, so
2278 * we do not have control over the actual implementation. There
2279 * have been cases where inquiring the status took an unreasonably
2280 * long time, and we can do nothing in qemu to fix it.
2281 * This is especially problematic for images with large data areas,
2282 * because finding the few holes in them and giving them special
2283 * treatment does not gain much performance. Therefore, we try to
2284 * cache the last-identified data region.
2286 * Second, limiting ourselves to protocol nodes allows us to assume
2287 * the block status for data regions to be DATA | OFFSET_VALID, and
2288 * that the host offset is the same as the guest offset.
2290 * Note that it is possible that external writers zero parts of
2291 * the cached regions without the cache being invalidated, and so
2292 * we may report zeroes as data. This is not catastrophic,
2293 * however, because reporting zeroes as data is fine.
2295 if (QLIST_EMPTY(&bs
->children
) &&
2296 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2298 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2300 local_map
= aligned_offset
;
2302 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2303 aligned_bytes
, pnum
, &local_map
,
2307 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2308 * the cache is queried above. Technically, we do not need to check
2309 * it here; the worst that can happen is that we fill the cache for
2310 * non-protocol nodes, and then it is never used. However, filling
2311 * the cache requires an RCU update, so double check here to avoid
2312 * such an update if possible.
2314 * Check want_zero, because we only want to update the cache when we
2315 * have accurate information about what is zero and what is data.
2318 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2319 QLIST_EMPTY(&bs
->children
))
2322 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2323 * returned local_map value must be the same as the offset we
2324 * have passed (aligned_offset), and local_bs must be the node
2326 * Assert this, because we follow this rule when reading from
2327 * the cache (see the `local_file = bs` and
2328 * `local_map = aligned_offset` assignments above), and the
2329 * result the cache delivers must be the same as the driver
2332 assert(local_file
== bs
);
2333 assert(local_map
== aligned_offset
);
2334 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2338 /* Default code for filters */
2340 local_file
= bdrv_filter_bs(bs
);
2343 *pnum
= aligned_bytes
;
2344 local_map
= aligned_offset
;
2345 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2353 * The driver's result must be a non-zero multiple of request_alignment.
2354 * Clamp pnum and adjust map to original request.
2356 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2357 align
> offset
- aligned_offset
);
2358 if (ret
& BDRV_BLOCK_RECURSE
) {
2359 assert(ret
& BDRV_BLOCK_DATA
);
2360 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2361 assert(!(ret
& BDRV_BLOCK_ZERO
));
2364 *pnum
-= offset
- aligned_offset
;
2365 if (*pnum
> bytes
) {
2368 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2369 local_map
+= offset
- aligned_offset
;
2372 if (ret
& BDRV_BLOCK_RAW
) {
2373 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2374 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2375 *pnum
, pnum
, &local_map
, &local_file
);
2379 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2380 ret
|= BDRV_BLOCK_ALLOCATED
;
2381 } else if (bs
->drv
->supports_backing
) {
2382 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2385 ret
|= BDRV_BLOCK_ZERO
;
2386 } else if (want_zero
) {
2387 int64_t size2
= bdrv_getlength(cow_bs
);
2389 if (size2
>= 0 && offset
>= size2
) {
2390 ret
|= BDRV_BLOCK_ZERO
;
2395 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2396 local_file
&& local_file
!= bs
&&
2397 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2398 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2402 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2403 *pnum
, &file_pnum
, NULL
, NULL
);
2405 /* Ignore errors. This is just providing extra information, it
2406 * is useful but not necessary.
2408 if (ret2
& BDRV_BLOCK_EOF
&&
2409 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2411 * It is valid for the format block driver to read
2412 * beyond the end of the underlying file's current
2413 * size; such areas read as zero.
2415 ret
|= BDRV_BLOCK_ZERO
;
2417 /* Limit request to the range reported by the protocol driver */
2419 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2425 bdrv_dec_in_flight(bs
);
2426 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2427 ret
|= BDRV_BLOCK_EOF
;
2440 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2441 BlockDriverState
*base
,
2448 BlockDriverState
**file
,
2452 BlockDriverState
*p
;
2457 assert(!include_base
|| base
); /* Can't include NULL base */
2464 if (!include_base
&& bs
== base
) {
2469 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2471 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2475 if (ret
& BDRV_BLOCK_EOF
) {
2476 eof
= offset
+ *pnum
;
2479 assert(*pnum
<= bytes
);
2482 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2483 p
= bdrv_filter_or_cow_bs(p
))
2485 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2493 * The top layer deferred to this layer, and because this layer is
2494 * short, any zeroes that we synthesize beyond EOF behave as if they
2495 * were allocated at this layer.
2497 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2498 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2501 assert(ret
& BDRV_BLOCK_EOF
);
2506 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2509 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2511 * We've found the node and the status, we must break.
2513 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2514 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2517 ret
&= ~BDRV_BLOCK_EOF
;
2522 assert(include_base
);
2527 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2528 * let's continue the diving.
2530 assert(*pnum
<= bytes
);
2534 if (offset
+ *pnum
== eof
) {
2535 ret
|= BDRV_BLOCK_EOF
;
2541 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2542 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2543 int64_t *map
, BlockDriverState
**file
)
2546 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2547 pnum
, map
, file
, NULL
);
2550 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2551 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2554 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2555 offset
, bytes
, pnum
, map
, file
);
2559 * Check @bs (and its backing chain) to see if the range defined
2560 * by @offset and @bytes is known to read as zeroes.
2561 * Return 1 if that is the case, 0 otherwise and -errno on error.
2562 * This test is meant to be fast rather than accurate so returning 0
2563 * does not guarantee non-zero data.
2565 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2569 int64_t pnum
= bytes
;
2576 ret
= bdrv_co_common_block_status_above(bs
, NULL
, false, false, offset
,
2577 bytes
, &pnum
, NULL
, NULL
, NULL
);
2583 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2586 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2593 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2594 bytes
, pnum
? pnum
: &dummy
, NULL
,
2599 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2603 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2605 * Return a positive depth if (a prefix of) the given range is allocated
2606 * in any image between BASE and TOP (BASE is only included if include_base
2607 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2608 * BASE can be NULL to check if the given offset is allocated in any
2609 * image of the chain. Return 0 otherwise, or negative errno on
2612 * 'pnum' is set to the number of bytes (including and immediately
2613 * following the specified offset) that are known to be in the same
2614 * allocated/unallocated state. Note that a subsequent call starting
2615 * at 'offset + *pnum' may return the same allocation status (in other
2616 * words, the result is not necessarily the maximum possible range);
2617 * but 'pnum' will only be 0 when end of file is reached.
2619 int bdrv_is_allocated_above(BlockDriverState
*top
,
2620 BlockDriverState
*base
,
2621 bool include_base
, int64_t offset
,
2622 int64_t bytes
, int64_t *pnum
)
2625 int ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2626 offset
, bytes
, pnum
, NULL
, NULL
,
2633 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2640 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2642 BlockDriver
*drv
= bs
->drv
;
2643 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2647 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2656 bdrv_inc_in_flight(bs
);
2658 if (drv
->bdrv_load_vmstate
) {
2659 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2660 } else if (child_bs
) {
2661 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2666 bdrv_dec_in_flight(bs
);
2672 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2674 BlockDriver
*drv
= bs
->drv
;
2675 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2679 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2688 bdrv_inc_in_flight(bs
);
2690 if (drv
->bdrv_save_vmstate
) {
2691 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2692 } else if (child_bs
) {
2693 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2698 bdrv_dec_in_flight(bs
);
2703 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2704 int64_t pos
, int size
)
2706 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2707 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2710 return ret
< 0 ? ret
: size
;
2713 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2714 int64_t pos
, int size
)
2716 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2717 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2720 return ret
< 0 ? ret
: size
;
2723 /**************************************************************/
2726 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2730 bdrv_aio_cancel_async(acb
);
2731 while (acb
->refcnt
> 1) {
2732 if (acb
->aiocb_info
->get_aio_context
) {
2733 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2734 } else if (acb
->bs
) {
2735 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2736 * assert that we're not using an I/O thread. Thread-safe
2737 * code should use bdrv_aio_cancel_async exclusively.
2739 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2740 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2745 qemu_aio_unref(acb
);
2748 /* Async version of aio cancel. The caller is not blocked if the acb implements
2749 * cancel_async, otherwise we do nothing and let the request normally complete.
2750 * In either case the completion callback must be called. */
2751 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2754 if (acb
->aiocb_info
->cancel_async
) {
2755 acb
->aiocb_info
->cancel_async(acb
);
2759 /**************************************************************/
2760 /* Coroutine block device emulation */
2762 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2764 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2770 bdrv_inc_in_flight(bs
);
2772 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2777 qemu_co_mutex_lock(&bs
->reqs_lock
);
2778 current_gen
= qatomic_read(&bs
->write_gen
);
2780 /* Wait until any previous flushes are completed */
2781 while (bs
->active_flush_req
) {
2782 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2785 /* Flushes reach this point in nondecreasing current_gen order. */
2786 bs
->active_flush_req
= true;
2787 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2789 /* Write back all layers by calling one driver function */
2790 if (bs
->drv
->bdrv_co_flush
) {
2791 ret
= bs
->drv
->bdrv_co_flush(bs
);
2795 /* Write back cached data to the OS even with cache=unsafe */
2796 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2797 if (bs
->drv
->bdrv_co_flush_to_os
) {
2798 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2804 /* But don't actually force it to the disk with cache=unsafe */
2805 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2806 goto flush_children
;
2809 /* Check if we really need to flush anything */
2810 if (bs
->flushed_gen
== current_gen
) {
2811 goto flush_children
;
2814 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2816 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2817 * (even in case of apparent success) */
2821 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2822 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2823 } else if (bs
->drv
->bdrv_aio_flush
) {
2825 CoroutineIOCompletion co
= {
2826 .coroutine
= qemu_coroutine_self(),
2829 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2833 qemu_coroutine_yield();
2838 * Some block drivers always operate in either writethrough or unsafe
2839 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2840 * know how the server works (because the behaviour is hardcoded or
2841 * depends on server-side configuration), so we can't ensure that
2842 * everything is safe on disk. Returning an error doesn't work because
2843 * that would break guests even if the server operates in writethrough
2846 * Let's hope the user knows what he's doing.
2855 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2856 * in the case of cache=unsafe, so there are no useless flushes.
2860 QLIST_FOREACH(child
, &bs
->children
, next
) {
2861 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2862 int this_child_ret
= bdrv_co_flush(child
->bs
);
2864 ret
= this_child_ret
;
2870 /* Notify any pending flushes that we have completed */
2872 bs
->flushed_gen
= current_gen
;
2875 qemu_co_mutex_lock(&bs
->reqs_lock
);
2876 bs
->active_flush_req
= false;
2877 /* Return value is ignored - it's ok if wait queue is empty */
2878 qemu_co_queue_next(&bs
->flush_queue
);
2879 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2882 bdrv_dec_in_flight(bs
);
2886 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2889 BdrvTrackedRequest req
;
2891 int64_t max_pdiscard
;
2892 int head
, tail
, align
;
2893 BlockDriverState
*bs
= child
->bs
;
2896 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
2900 if (bdrv_has_readonly_bitmaps(bs
)) {
2904 ret
= bdrv_check_request(offset
, bytes
, NULL
);
2909 /* Do nothing if disabled. */
2910 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2914 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2918 /* Invalidate the cached block-status data range if this discard overlaps */
2919 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
2921 /* Discard is advisory, but some devices track and coalesce
2922 * unaligned requests, so we must pass everything down rather than
2923 * round here. Still, most devices will just silently ignore
2924 * unaligned requests (by returning -ENOTSUP), so we must fragment
2925 * the request accordingly. */
2926 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2927 assert(align
% bs
->bl
.request_alignment
== 0);
2928 head
= offset
% align
;
2929 tail
= (offset
+ bytes
) % align
;
2931 bdrv_inc_in_flight(bs
);
2932 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2934 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
2939 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
2941 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2944 int64_t num
= bytes
;
2947 /* Make small requests to get to alignment boundaries. */
2948 num
= MIN(bytes
, align
- head
);
2949 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2950 num
%= bs
->bl
.request_alignment
;
2952 head
= (head
+ num
) % align
;
2953 assert(num
< max_pdiscard
);
2956 /* Shorten the request to the last aligned cluster. */
2958 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2959 tail
> bs
->bl
.request_alignment
) {
2960 tail
%= bs
->bl
.request_alignment
;
2964 /* limit request size */
2965 if (num
> max_pdiscard
) {
2973 if (bs
->drv
->bdrv_co_pdiscard
) {
2974 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2977 CoroutineIOCompletion co
= {
2978 .coroutine
= qemu_coroutine_self(),
2981 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2982 bdrv_co_io_em_complete
, &co
);
2987 qemu_coroutine_yield();
2991 if (ret
&& ret
!= -ENOTSUP
) {
3000 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3001 tracked_request_end(&req
);
3002 bdrv_dec_in_flight(bs
);
3006 int coroutine_fn
bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3008 BlockDriver
*drv
= bs
->drv
;
3009 CoroutineIOCompletion co
= {
3010 .coroutine
= qemu_coroutine_self(),
3015 bdrv_inc_in_flight(bs
);
3016 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3021 if (drv
->bdrv_co_ioctl
) {
3022 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3024 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3029 qemu_coroutine_yield();
3032 bdrv_dec_in_flight(bs
);
3036 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3039 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3042 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3045 return memset(qemu_blockalign(bs
, size
), 0, size
);
3048 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3050 size_t align
= bdrv_opt_mem_align(bs
);
3053 /* Ensure that NULL is never returned on success */
3059 return qemu_try_memalign(align
, size
);
3062 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3064 void *mem
= qemu_try_blockalign(bs
, size
);
3068 memset(mem
, 0, size
);
3074 void bdrv_io_plug(BlockDriverState
*bs
)
3079 QLIST_FOREACH(child
, &bs
->children
, next
) {
3080 bdrv_io_plug(child
->bs
);
3083 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
3084 BlockDriver
*drv
= bs
->drv
;
3085 if (drv
&& drv
->bdrv_io_plug
) {
3086 drv
->bdrv_io_plug(bs
);
3091 void bdrv_io_unplug(BlockDriverState
*bs
)
3096 assert(bs
->io_plugged
);
3097 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
3098 BlockDriver
*drv
= bs
->drv
;
3099 if (drv
&& drv
->bdrv_io_unplug
) {
3100 drv
->bdrv_io_unplug(bs
);
3104 QLIST_FOREACH(child
, &bs
->children
, next
) {
3105 bdrv_io_unplug(child
->bs
);
3109 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3110 static void bdrv_register_buf_rollback(BlockDriverState
*bs
,
3113 BdrvChild
*final_child
)
3117 QLIST_FOREACH(child
, &bs
->children
, next
) {
3118 if (child
== final_child
) {
3122 bdrv_unregister_buf(child
->bs
, host
, size
);
3125 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3126 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3130 bool bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
3135 GLOBAL_STATE_CODE();
3136 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3137 if (!bs
->drv
->bdrv_register_buf(bs
, host
, size
, errp
)) {
3141 QLIST_FOREACH(child
, &bs
->children
, next
) {
3142 if (!bdrv_register_buf(child
->bs
, host
, size
, errp
)) {
3143 bdrv_register_buf_rollback(bs
, host
, size
, child
);
3150 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3154 GLOBAL_STATE_CODE();
3155 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3156 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3158 QLIST_FOREACH(child
, &bs
->children
, next
) {
3159 bdrv_unregister_buf(child
->bs
, host
, size
);
3163 static int coroutine_fn
bdrv_co_copy_range_internal(
3164 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3165 int64_t dst_offset
, int64_t bytes
,
3166 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3169 BdrvTrackedRequest req
;
3172 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3173 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3174 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3175 assert(!(read_flags
& BDRV_REQ_NO_WAIT
));
3176 assert(!(write_flags
& BDRV_REQ_NO_WAIT
));
3178 if (!dst
|| !dst
->bs
|| !bdrv_is_inserted(dst
->bs
)) {
3181 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3185 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3186 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3189 if (!src
|| !src
->bs
|| !bdrv_is_inserted(src
->bs
)) {
3192 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3197 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3198 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3199 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3204 bdrv_inc_in_flight(src
->bs
);
3205 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3208 /* BDRV_REQ_SERIALISING is only for write operation */
3209 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3210 bdrv_wait_serialising_requests(&req
);
3212 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3216 read_flags
, write_flags
);
3218 tracked_request_end(&req
);
3219 bdrv_dec_in_flight(src
->bs
);
3221 bdrv_inc_in_flight(dst
->bs
);
3222 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3223 BDRV_TRACKED_WRITE
);
3224 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3227 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3231 read_flags
, write_flags
);
3233 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3234 tracked_request_end(&req
);
3235 bdrv_dec_in_flight(dst
->bs
);
3241 /* Copy range from @src to @dst.
3243 * See the comment of bdrv_co_copy_range for the parameter and return value
3245 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3246 BdrvChild
*dst
, int64_t dst_offset
,
3248 BdrvRequestFlags read_flags
,
3249 BdrvRequestFlags write_flags
)
3252 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3253 read_flags
, write_flags
);
3254 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3255 bytes
, read_flags
, write_flags
, true);
3258 /* Copy range from @src to @dst.
3260 * See the comment of bdrv_co_copy_range for the parameter and return value
3262 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3263 BdrvChild
*dst
, int64_t dst_offset
,
3265 BdrvRequestFlags read_flags
,
3266 BdrvRequestFlags write_flags
)
3269 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3270 read_flags
, write_flags
);
3271 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3272 bytes
, read_flags
, write_flags
, false);
3275 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3276 BdrvChild
*dst
, int64_t dst_offset
,
3277 int64_t bytes
, BdrvRequestFlags read_flags
,
3278 BdrvRequestFlags write_flags
)
3281 return bdrv_co_copy_range_from(src
, src_offset
,
3283 bytes
, read_flags
, write_flags
);
3286 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3289 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3290 if (c
->klass
->resize
) {
3291 c
->klass
->resize(c
);
3297 * Truncate file to 'offset' bytes (needed only for file protocols)
3299 * If 'exact' is true, the file must be resized to exactly the given
3300 * 'offset'. Otherwise, it is sufficient for the node to be at least
3301 * 'offset' bytes in length.
3303 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3304 PreallocMode prealloc
, BdrvRequestFlags flags
,
3307 BlockDriverState
*bs
= child
->bs
;
3308 BdrvChild
*filtered
, *backing
;
3309 BlockDriver
*drv
= bs
->drv
;
3310 BdrvTrackedRequest req
;
3311 int64_t old_size
, new_bytes
;
3315 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3317 error_setg(errp
, "No medium inserted");
3321 error_setg(errp
, "Image size cannot be negative");
3325 ret
= bdrv_check_request(offset
, 0, errp
);
3330 old_size
= bdrv_getlength(bs
);
3332 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3336 if (bdrv_is_read_only(bs
)) {
3337 error_setg(errp
, "Image is read-only");
3341 if (offset
> old_size
) {
3342 new_bytes
= offset
- old_size
;
3347 bdrv_inc_in_flight(bs
);
3348 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3349 BDRV_TRACKED_TRUNCATE
);
3351 /* If we are growing the image and potentially using preallocation for the
3352 * new area, we need to make sure that no write requests are made to it
3353 * concurrently or they might be overwritten by preallocation. */
3355 bdrv_make_request_serialising(&req
, 1);
3357 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3360 error_setg_errno(errp
, -ret
,
3361 "Failed to prepare request for truncation");
3365 filtered
= bdrv_filter_child(bs
);
3366 backing
= bdrv_cow_child(bs
);
3369 * If the image has a backing file that is large enough that it would
3370 * provide data for the new area, we cannot leave it unallocated because
3371 * then the backing file content would become visible. Instead, zero-fill
3374 * Note that if the image has a backing file, but was opened without the
3375 * backing file, taking care of keeping things consistent with that backing
3376 * file is the user's responsibility.
3378 if (new_bytes
&& backing
) {
3379 int64_t backing_len
;
3381 backing_len
= bdrv_getlength(backing
->bs
);
3382 if (backing_len
< 0) {
3384 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3388 if (backing_len
> old_size
) {
3389 flags
|= BDRV_REQ_ZERO_WRITE
;
3393 if (drv
->bdrv_co_truncate
) {
3394 if (flags
& ~bs
->supported_truncate_flags
) {
3395 error_setg(errp
, "Block driver does not support requested flags");
3399 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3400 } else if (filtered
) {
3401 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3403 error_setg(errp
, "Image format driver does not support resize");
3411 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3413 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3415 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3417 /* It's possible that truncation succeeded but refresh_total_sectors
3418 * failed, but the latter doesn't affect how we should finish the request.
3419 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3420 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3423 tracked_request_end(&req
);
3424 bdrv_dec_in_flight(bs
);
3429 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3431 GLOBAL_STATE_CODE();
3432 if (!bs
|| !bs
->drv
) {
3436 if (bs
->drv
->bdrv_cancel_in_flight
) {
3437 bs
->drv
->bdrv_cancel_in_flight(bs
);
3442 bdrv_co_preadv_snapshot(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
3443 QEMUIOVector
*qiov
, size_t qiov_offset
)
3445 BlockDriverState
*bs
= child
->bs
;
3446 BlockDriver
*drv
= bs
->drv
;
3454 if (!drv
->bdrv_co_preadv_snapshot
) {
3458 bdrv_inc_in_flight(bs
);
3459 ret
= drv
->bdrv_co_preadv_snapshot(bs
, offset
, bytes
, qiov
, qiov_offset
);
3460 bdrv_dec_in_flight(bs
);
3466 bdrv_co_snapshot_block_status(BlockDriverState
*bs
,
3467 bool want_zero
, int64_t offset
, int64_t bytes
,
3468 int64_t *pnum
, int64_t *map
,
3469 BlockDriverState
**file
)
3471 BlockDriver
*drv
= bs
->drv
;
3479 if (!drv
->bdrv_co_snapshot_block_status
) {
3483 bdrv_inc_in_flight(bs
);
3484 ret
= drv
->bdrv_co_snapshot_block_status(bs
, want_zero
, offset
, bytes
,
3486 bdrv_dec_in_flight(bs
);
3492 bdrv_co_pdiscard_snapshot(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3494 BlockDriver
*drv
= bs
->drv
;
3502 if (!drv
->bdrv_co_pdiscard_snapshot
) {
3506 bdrv_inc_in_flight(bs
);
3507 ret
= drv
->bdrv_co_pdiscard_snapshot(bs
, offset
, bytes
);
3508 bdrv_dec_in_flight(bs
);