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/dirty-bitmap.h"
34 #include "block/write-threshold.h"
35 #include "qemu/cutils.h"
36 #include "qemu/memalign.h"
37 #include "qapi/error.h"
38 #include "qemu/error-report.h"
39 #include "qemu/main-loop.h"
40 #include "sysemu/replay.h"
42 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
43 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
45 static void bdrv_parent_cb_resize(BlockDriverState
*bs
);
46 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
47 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
);
49 static void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
)
53 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
57 bdrv_parent_drained_begin_single(c
);
61 void bdrv_parent_drained_end_single(BdrvChild
*c
)
65 assert(c
->quiesced_parent
);
66 c
->quiesced_parent
= false;
68 if (c
->klass
->drained_end
) {
69 c
->klass
->drained_end(c
);
73 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
)
77 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
81 bdrv_parent_drained_end_single(c
);
85 bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
87 if (c
->klass
->drained_poll
) {
88 return c
->klass
->drained_poll(c
);
93 static bool bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
94 bool ignore_bds_parents
)
99 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
100 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
103 busy
|= bdrv_parent_drained_poll_single(c
);
109 void bdrv_parent_drained_begin_single(BdrvChild
*c
)
113 assert(!c
->quiesced_parent
);
114 c
->quiesced_parent
= true;
116 if (c
->klass
->drained_begin
) {
117 c
->klass
->drained_begin(c
);
121 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
123 dst
->pdiscard_alignment
= MAX(dst
->pdiscard_alignment
,
124 src
->pdiscard_alignment
);
125 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
126 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
127 dst
->max_hw_transfer
= MIN_NON_ZERO(dst
->max_hw_transfer
,
128 src
->max_hw_transfer
);
129 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
130 src
->opt_mem_alignment
);
131 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
132 src
->min_mem_alignment
);
133 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
134 dst
->max_hw_iov
= MIN_NON_ZERO(dst
->max_hw_iov
, src
->max_hw_iov
);
137 typedef struct BdrvRefreshLimitsState
{
138 BlockDriverState
*bs
;
140 } BdrvRefreshLimitsState
;
142 static void bdrv_refresh_limits_abort(void *opaque
)
144 BdrvRefreshLimitsState
*s
= opaque
;
146 s
->bs
->bl
= s
->old_bl
;
149 static TransactionActionDrv bdrv_refresh_limits_drv
= {
150 .abort
= bdrv_refresh_limits_abort
,
154 /* @tran is allowed to be NULL, in this case no rollback is possible. */
155 void bdrv_refresh_limits(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
158 BlockDriver
*drv
= bs
->drv
;
165 BdrvRefreshLimitsState
*s
= g_new(BdrvRefreshLimitsState
, 1);
166 *s
= (BdrvRefreshLimitsState
) {
170 tran_add(tran
, &bdrv_refresh_limits_drv
, s
);
173 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
179 /* Default alignment based on whether driver has byte interface */
180 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
181 drv
->bdrv_aio_preadv
||
182 drv
->bdrv_co_preadv_part
) ? 1 : 512;
184 /* Take some limits from the children as a default */
186 QLIST_FOREACH(c
, &bs
->children
, next
) {
187 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
189 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
193 if (c
->role
& BDRV_CHILD_FILTERED
) {
194 bs
->bl
.has_variable_length
|= c
->bs
->bl
.has_variable_length
;
199 bs
->bl
.min_mem_alignment
= 512;
200 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size();
202 /* Safe default since most protocols use readv()/writev()/etc */
203 bs
->bl
.max_iov
= IOV_MAX
;
206 /* Then let the driver override it */
207 if (drv
->bdrv_refresh_limits
) {
208 drv
->bdrv_refresh_limits(bs
, errp
);
214 if (bs
->bl
.request_alignment
> BDRV_MAX_ALIGNMENT
) {
215 error_setg(errp
, "Driver requires too large request alignment");
220 * The copy-on-read flag is actually a reference count so multiple users may
221 * use the feature without worrying about clobbering its previous state.
222 * Copy-on-read stays enabled until all users have called to disable it.
224 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
227 qatomic_inc(&bs
->copy_on_read
);
230 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
232 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
239 BlockDriverState
*bs
;
246 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
247 bool bdrv_drain_poll(BlockDriverState
*bs
, BdrvChild
*ignore_parent
,
248 bool ignore_bds_parents
)
252 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
256 if (qatomic_read(&bs
->in_flight
)) {
263 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
,
264 BdrvChild
*ignore_parent
)
266 return bdrv_drain_poll(bs
, ignore_parent
, false);
269 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
271 static void bdrv_do_drained_end(BlockDriverState
*bs
, BdrvChild
*parent
);
273 static void bdrv_co_drain_bh_cb(void *opaque
)
275 BdrvCoDrainData
*data
= opaque
;
276 Coroutine
*co
= data
->co
;
277 BlockDriverState
*bs
= data
->bs
;
280 AioContext
*ctx
= bdrv_get_aio_context(bs
);
281 aio_context_acquire(ctx
);
282 bdrv_dec_in_flight(bs
);
284 bdrv_do_drained_begin(bs
, data
->parent
, data
->poll
);
287 bdrv_do_drained_end(bs
, data
->parent
);
289 aio_context_release(ctx
);
292 bdrv_drain_all_begin();
299 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
304 BdrvCoDrainData data
;
305 Coroutine
*self
= qemu_coroutine_self();
306 AioContext
*ctx
= bdrv_get_aio_context(bs
);
307 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(self
);
309 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
310 * other coroutines run if they were queued by aio_co_enter(). */
312 assert(qemu_in_coroutine());
313 data
= (BdrvCoDrainData
) {
323 bdrv_inc_in_flight(bs
);
327 * Temporarily drop the lock across yield or we would get deadlocks.
328 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
330 * When we yield below, the lock for the current context will be
331 * released, so if this is actually the lock that protects bs, don't drop
335 aio_context_release(ctx
);
337 replay_bh_schedule_oneshot_event(ctx
, bdrv_co_drain_bh_cb
, &data
);
339 qemu_coroutine_yield();
340 /* If we are resumed from some other event (such as an aio completion or a
341 * timer callback), it is a bug in the caller that should be fixed. */
344 /* Reaquire the AioContext of bs if we dropped it */
346 aio_context_acquire(ctx
);
350 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
355 if (qemu_in_coroutine()) {
356 bdrv_co_yield_to_drain(bs
, true, parent
, poll
);
360 /* Stop things in parent-to-child order */
361 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
362 aio_disable_external(bdrv_get_aio_context(bs
));
363 bdrv_parent_drained_begin(bs
, parent
);
364 if (bs
->drv
&& bs
->drv
->bdrv_drain_begin
) {
365 bs
->drv
->bdrv_drain_begin(bs
);
370 * Wait for drained requests to finish.
372 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
373 * call is needed so things in this AioContext can make progress even
374 * though we don't return to the main AioContext loop - this automatically
375 * includes other nodes in the same AioContext and therefore all child
379 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, parent
));
383 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
, BdrvChild
*parent
)
385 bdrv_do_drained_begin(bs
, parent
, false);
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_nopoll(void)
476 BlockDriverState
*bs
= NULL
;
480 * bdrv queue is managed by record/replay,
481 * waiting for finishing the I/O requests may
484 if (replay_events_enabled()) {
488 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
489 * loop AioContext, so make sure we're in the main context. */
490 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
491 assert(bdrv_drain_all_count
< INT_MAX
);
492 bdrv_drain_all_count
++;
494 /* Quiesce all nodes, without polling in-flight requests yet. The graph
495 * cannot change during this loop. */
496 while ((bs
= bdrv_next_all_states(bs
))) {
497 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
499 aio_context_acquire(aio_context
);
500 bdrv_do_drained_begin(bs
, NULL
, false);
501 aio_context_release(aio_context
);
505 void bdrv_drain_all_begin(void)
507 BlockDriverState
*bs
= NULL
;
509 if (qemu_in_coroutine()) {
510 bdrv_co_yield_to_drain(NULL
, true, NULL
, true);
515 * bdrv queue is managed by record/replay,
516 * waiting for finishing the I/O requests may
519 if (replay_events_enabled()) {
523 bdrv_drain_all_begin_nopoll();
525 /* Now poll the in-flight requests */
526 AIO_WAIT_WHILE_UNLOCKED(NULL
, bdrv_drain_all_poll());
528 while ((bs
= bdrv_next_all_states(bs
))) {
529 bdrv_drain_assert_idle(bs
);
533 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
537 g_assert(bs
->quiesce_counter
> 0);
538 g_assert(!bs
->refcnt
);
540 while (bs
->quiesce_counter
) {
541 bdrv_do_drained_end(bs
, NULL
);
545 void bdrv_drain_all_end(void)
547 BlockDriverState
*bs
= NULL
;
551 * bdrv queue is managed by record/replay,
552 * waiting for finishing the I/O requests may
555 if (replay_events_enabled()) {
559 while ((bs
= bdrv_next_all_states(bs
))) {
560 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
562 aio_context_acquire(aio_context
);
563 bdrv_do_drained_end(bs
, NULL
);
564 aio_context_release(aio_context
);
567 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
568 assert(bdrv_drain_all_count
> 0);
569 bdrv_drain_all_count
--;
572 void bdrv_drain_all(void)
575 bdrv_drain_all_begin();
576 bdrv_drain_all_end();
580 * Remove an active request from the tracked requests list
582 * This function should be called when a tracked request is completing.
584 static void coroutine_fn
tracked_request_end(BdrvTrackedRequest
*req
)
586 if (req
->serialising
) {
587 qatomic_dec(&req
->bs
->serialising_in_flight
);
590 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
591 QLIST_REMOVE(req
, list
);
592 qemu_co_queue_restart_all(&req
->wait_queue
);
593 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
597 * Add an active request to the tracked requests list
599 static void coroutine_fn
tracked_request_begin(BdrvTrackedRequest
*req
,
600 BlockDriverState
*bs
,
603 enum BdrvTrackedRequestType type
)
605 bdrv_check_request(offset
, bytes
, &error_abort
);
607 *req
= (BdrvTrackedRequest
){
612 .co
= qemu_coroutine_self(),
613 .serialising
= false,
614 .overlap_offset
= offset
,
615 .overlap_bytes
= bytes
,
618 qemu_co_queue_init(&req
->wait_queue
);
620 qemu_co_mutex_lock(&bs
->reqs_lock
);
621 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
622 qemu_co_mutex_unlock(&bs
->reqs_lock
);
625 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
626 int64_t offset
, int64_t bytes
)
628 bdrv_check_request(offset
, bytes
, &error_abort
);
631 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
635 if (req
->overlap_offset
>= offset
+ bytes
) {
641 /* Called with self->bs->reqs_lock held */
642 static coroutine_fn BdrvTrackedRequest
*
643 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
645 BdrvTrackedRequest
*req
;
647 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
648 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
651 if (tracked_request_overlaps(req
, self
->overlap_offset
,
652 self
->overlap_bytes
))
655 * Hitting this means there was a reentrant request, for
656 * example, a block driver issuing nested requests. This must
657 * never happen since it means deadlock.
659 assert(qemu_coroutine_self() != req
->co
);
662 * If the request is already (indirectly) waiting for us, or
663 * will wait for us as soon as it wakes up, then just go on
664 * (instead of producing a deadlock in the former case).
666 if (!req
->waiting_for
) {
675 /* Called with self->bs->reqs_lock held */
676 static void coroutine_fn
677 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
679 BdrvTrackedRequest
*req
;
681 while ((req
= bdrv_find_conflicting_request(self
))) {
682 self
->waiting_for
= req
;
683 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
684 self
->waiting_for
= NULL
;
688 /* Called with req->bs->reqs_lock held */
689 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
692 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
693 int64_t overlap_bytes
=
694 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
696 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
698 if (!req
->serialising
) {
699 qatomic_inc(&req
->bs
->serialising_in_flight
);
700 req
->serialising
= true;
703 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
704 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
708 * Return the tracked request on @bs for the current coroutine, or
709 * NULL if there is none.
711 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
713 BdrvTrackedRequest
*req
;
714 Coroutine
*self
= qemu_coroutine_self();
717 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
718 if (req
->co
== self
) {
727 * Round a region to cluster boundaries
729 void coroutine_fn GRAPH_RDLOCK
730 bdrv_round_to_clusters(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
731 int64_t *cluster_offset
, int64_t *cluster_bytes
)
735 if (bdrv_co_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
736 *cluster_offset
= offset
;
737 *cluster_bytes
= bytes
;
739 int64_t c
= bdi
.cluster_size
;
740 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
741 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
745 static int coroutine_fn GRAPH_RDLOCK
bdrv_get_cluster_size(BlockDriverState
*bs
)
750 ret
= bdrv_co_get_info(bs
, &bdi
);
751 if (ret
< 0 || bdi
.cluster_size
== 0) {
752 return bs
->bl
.request_alignment
;
754 return bdi
.cluster_size
;
758 void bdrv_inc_in_flight(BlockDriverState
*bs
)
761 qatomic_inc(&bs
->in_flight
);
764 void bdrv_wakeup(BlockDriverState
*bs
)
770 void bdrv_dec_in_flight(BlockDriverState
*bs
)
773 qatomic_dec(&bs
->in_flight
);
777 static void coroutine_fn
778 bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
780 BlockDriverState
*bs
= self
->bs
;
782 if (!qatomic_read(&bs
->serialising_in_flight
)) {
786 qemu_co_mutex_lock(&bs
->reqs_lock
);
787 bdrv_wait_serialising_requests_locked(self
);
788 qemu_co_mutex_unlock(&bs
->reqs_lock
);
791 void coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
796 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
798 tracked_request_set_serialising(req
, align
);
799 bdrv_wait_serialising_requests_locked(req
);
801 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
804 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
805 QEMUIOVector
*qiov
, size_t qiov_offset
,
809 * Check generic offset/bytes correctness
813 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
818 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
822 if (bytes
> BDRV_MAX_LENGTH
) {
823 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
824 bytes
, BDRV_MAX_LENGTH
);
828 if (offset
> BDRV_MAX_LENGTH
) {
829 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
830 offset
, BDRV_MAX_LENGTH
);
834 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
835 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
836 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
846 * Check qiov and qiov_offset
849 if (qiov_offset
> qiov
->size
) {
850 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
851 qiov_offset
, qiov
->size
);
855 if (bytes
> qiov
->size
- qiov_offset
) {
856 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
857 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
864 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
866 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
869 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
870 QEMUIOVector
*qiov
, size_t qiov_offset
)
872 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
877 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
885 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
886 * The operation is sped up by checking the block status and only writing
887 * zeroes to the device if they currently do not return zeroes. Optional
888 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
891 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
893 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
896 int64_t target_size
, bytes
, offset
= 0;
897 BlockDriverState
*bs
= child
->bs
;
900 target_size
= bdrv_getlength(bs
);
901 if (target_size
< 0) {
906 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
910 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
914 if (ret
& BDRV_BLOCK_ZERO
) {
918 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
927 * Writes to the file and ensures that no writes are reordered across this
928 * request (acts as a barrier)
930 * Returns 0 on success, -errno in error cases.
932 int coroutine_fn
bdrv_co_pwrite_sync(BdrvChild
*child
, int64_t offset
,
933 int64_t bytes
, const void *buf
,
934 BdrvRequestFlags flags
)
938 assert_bdrv_graph_readable();
940 ret
= bdrv_co_pwrite(child
, offset
, bytes
, buf
, flags
);
945 ret
= bdrv_co_flush(child
->bs
);
953 typedef struct CoroutineIOCompletion
{
954 Coroutine
*coroutine
;
956 } CoroutineIOCompletion
;
958 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
960 CoroutineIOCompletion
*co
= opaque
;
963 aio_co_wake(co
->coroutine
);
966 static int coroutine_fn GRAPH_RDLOCK
967 bdrv_driver_preadv(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
968 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
970 BlockDriver
*drv
= bs
->drv
;
972 unsigned int nb_sectors
;
973 QEMUIOVector local_qiov
;
975 assert_bdrv_graph_readable();
977 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
978 assert(!(flags
& ~bs
->supported_read_flags
));
984 if (drv
->bdrv_co_preadv_part
) {
985 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
989 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
990 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
994 if (drv
->bdrv_co_preadv
) {
995 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
999 if (drv
->bdrv_aio_preadv
) {
1001 CoroutineIOCompletion co
= {
1002 .coroutine
= qemu_coroutine_self(),
1005 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1006 bdrv_co_io_em_complete
, &co
);
1011 qemu_coroutine_yield();
1017 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1018 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1020 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1021 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1022 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1023 assert(drv
->bdrv_co_readv
);
1025 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1028 if (qiov
== &local_qiov
) {
1029 qemu_iovec_destroy(&local_qiov
);
1035 static int coroutine_fn GRAPH_RDLOCK
1036 bdrv_driver_pwritev(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1037 QEMUIOVector
*qiov
, size_t qiov_offset
,
1038 BdrvRequestFlags flags
)
1040 BlockDriver
*drv
= bs
->drv
;
1041 bool emulate_fua
= false;
1043 unsigned int nb_sectors
;
1044 QEMUIOVector local_qiov
;
1046 assert_bdrv_graph_readable();
1048 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1054 if ((flags
& BDRV_REQ_FUA
) &&
1055 (~bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1056 flags
&= ~BDRV_REQ_FUA
;
1060 flags
&= bs
->supported_write_flags
;
1062 if (drv
->bdrv_co_pwritev_part
) {
1063 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1068 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1069 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1073 if (drv
->bdrv_co_pwritev
) {
1074 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1078 if (drv
->bdrv_aio_pwritev
) {
1080 CoroutineIOCompletion co
= {
1081 .coroutine
= qemu_coroutine_self(),
1084 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
, flags
,
1085 bdrv_co_io_em_complete
, &co
);
1089 qemu_coroutine_yield();
1095 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1096 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1098 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1099 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1100 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1102 assert(drv
->bdrv_co_writev
);
1103 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
, flags
);
1106 if (ret
== 0 && emulate_fua
) {
1107 ret
= bdrv_co_flush(bs
);
1110 if (qiov
== &local_qiov
) {
1111 qemu_iovec_destroy(&local_qiov
);
1117 static int coroutine_fn GRAPH_RDLOCK
1118 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1119 int64_t bytes
, QEMUIOVector
*qiov
,
1122 BlockDriver
*drv
= bs
->drv
;
1123 QEMUIOVector local_qiov
;
1125 assert_bdrv_graph_readable();
1127 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1133 if (!block_driver_can_compress(drv
)) {
1137 if (drv
->bdrv_co_pwritev_compressed_part
) {
1138 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1142 if (qiov_offset
== 0) {
1143 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1146 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1147 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1148 qemu_iovec_destroy(&local_qiov
);
1153 static int coroutine_fn GRAPH_RDLOCK
1154 bdrv_co_do_copy_on_readv(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1155 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1157 BlockDriverState
*bs
= child
->bs
;
1159 /* Perform I/O through a temporary buffer so that users who scribble over
1160 * their read buffer while the operation is in progress do not end up
1161 * modifying the image file. This is critical for zero-copy guest I/O
1162 * where anything might happen inside guest memory.
1164 void *bounce_buffer
= NULL
;
1166 BlockDriver
*drv
= bs
->drv
;
1167 int64_t cluster_offset
;
1168 int64_t cluster_bytes
;
1171 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1172 BDRV_REQUEST_MAX_BYTES
);
1173 int64_t progress
= 0;
1176 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1183 * Do not write anything when the BDS is inactive. That is not
1184 * allowed, and it would not help.
1186 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1188 /* FIXME We cannot require callers to have write permissions when all they
1189 * are doing is a read request. If we did things right, write permissions
1190 * would be obtained anyway, but internally by the copy-on-read code. As
1191 * long as it is implemented here rather than in a separate filter driver,
1192 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1193 * it could request permissions. Therefore we have to bypass the permission
1194 * system for the moment. */
1195 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1197 /* Cover entire cluster so no additional backing file I/O is required when
1198 * allocating cluster in the image file. Note that this value may exceed
1199 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1200 * is one reason we loop rather than doing it all at once.
1202 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1203 skip_bytes
= offset
- cluster_offset
;
1205 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1206 cluster_offset
, cluster_bytes
);
1208 while (cluster_bytes
) {
1212 ret
= 1; /* "already allocated", so nothing will be copied */
1213 pnum
= MIN(cluster_bytes
, max_transfer
);
1215 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1216 MIN(cluster_bytes
, max_transfer
), &pnum
);
1219 * Safe to treat errors in querying allocation as if
1220 * unallocated; we'll probably fail again soon on the
1221 * read, but at least that will set a decent errno.
1223 pnum
= MIN(cluster_bytes
, max_transfer
);
1226 /* Stop at EOF if the image ends in the middle of the cluster */
1227 if (ret
== 0 && pnum
== 0) {
1228 assert(progress
>= bytes
);
1232 assert(skip_bytes
< pnum
);
1236 QEMUIOVector local_qiov
;
1238 /* Must copy-on-read; use the bounce buffer */
1239 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1240 if (!bounce_buffer
) {
1241 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1242 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1243 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1245 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1246 if (!bounce_buffer
) {
1251 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1253 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1259 bdrv_co_debug_event(bs
, BLKDBG_COR_WRITE
);
1260 if (drv
->bdrv_co_pwrite_zeroes
&&
1261 buffer_is_zero(bounce_buffer
, pnum
)) {
1262 /* FIXME: Should we (perhaps conditionally) be setting
1263 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1264 * that still correctly reads as zero? */
1265 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1266 BDRV_REQ_WRITE_UNCHANGED
);
1268 /* This does not change the data on the disk, it is not
1269 * necessary to flush even in cache=writethrough mode.
1271 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1273 BDRV_REQ_WRITE_UNCHANGED
);
1277 /* It might be okay to ignore write errors for guest
1278 * requests. If this is a deliberate copy-on-read
1279 * then we don't want to ignore the error. Simply
1280 * report it in all cases.
1285 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1286 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1287 bounce_buffer
+ skip_bytes
,
1288 MIN(pnum
- skip_bytes
, bytes
- progress
));
1290 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1291 /* Read directly into the destination */
1292 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1293 MIN(pnum
- skip_bytes
, bytes
- progress
),
1294 qiov
, qiov_offset
+ progress
, 0);
1300 cluster_offset
+= pnum
;
1301 cluster_bytes
-= pnum
;
1302 progress
+= pnum
- skip_bytes
;
1308 qemu_vfree(bounce_buffer
);
1313 * Forwards an already correctly aligned request to the BlockDriver. This
1314 * handles copy on read, zeroing after EOF, and fragmentation of large
1315 * reads; any other features must be implemented by the caller.
1317 static int coroutine_fn GRAPH_RDLOCK
1318 bdrv_aligned_preadv(BdrvChild
*child
, BdrvTrackedRequest
*req
,
1319 int64_t offset
, int64_t bytes
, int64_t align
,
1320 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1322 BlockDriverState
*bs
= child
->bs
;
1323 int64_t total_bytes
, max_bytes
;
1325 int64_t bytes_remaining
= bytes
;
1328 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1329 assert(is_power_of_2(align
));
1330 assert((offset
& (align
- 1)) == 0);
1331 assert((bytes
& (align
- 1)) == 0);
1332 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1333 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1337 * TODO: We would need a per-BDS .supported_read_flags and
1338 * potential fallback support, if we ever implement any read flags
1339 * to pass through to drivers. For now, there aren't any
1340 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1342 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
|
1343 BDRV_REQ_REGISTERED_BUF
)));
1345 /* Handle Copy on Read and associated serialisation */
1346 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1347 /* If we touch the same cluster it counts as an overlap. This
1348 * guarantees that allocating writes will be serialized and not race
1349 * with each other for the same cluster. For example, in copy-on-read
1350 * it ensures that the CoR read and write operations are atomic and
1351 * guest writes cannot interleave between them. */
1352 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1354 bdrv_wait_serialising_requests(req
);
1357 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1360 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1361 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1363 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1368 if (!ret
|| pnum
!= bytes
) {
1369 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1370 qiov
, qiov_offset
, flags
);
1372 } else if (flags
& BDRV_REQ_PREFETCH
) {
1377 /* Forward the request to the BlockDriver, possibly fragmenting it */
1378 total_bytes
= bdrv_getlength(bs
);
1379 if (total_bytes
< 0) {
1384 assert(!(flags
& ~(bs
->supported_read_flags
| BDRV_REQ_REGISTERED_BUF
)));
1386 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1387 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1388 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1392 while (bytes_remaining
) {
1396 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1399 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1401 qiov_offset
+ bytes
- bytes_remaining
,
1405 num
= bytes_remaining
;
1406 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1407 0, bytes_remaining
);
1412 bytes_remaining
-= num
;
1416 return ret
< 0 ? ret
: 0;
1422 * |<---- align ----->| |<----- align ---->|
1423 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1425 * -*----------$-------*-------- ... --------*-----$------------*---
1427 * | offset | | end |
1428 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1429 * [buf ... ) [tail_buf )
1431 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1432 * is placed at the beginning of @buf and @tail at the @end.
1434 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1435 * around tail, if tail exists.
1437 * @merge_reads is true for small requests,
1438 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1439 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1441 typedef struct BdrvRequestPadding
{
1448 QEMUIOVector local_qiov
;
1449 } BdrvRequestPadding
;
1451 static bool bdrv_init_padding(BlockDriverState
*bs
,
1452 int64_t offset
, int64_t bytes
,
1453 BdrvRequestPadding
*pad
)
1455 int64_t align
= bs
->bl
.request_alignment
;
1458 bdrv_check_request(offset
, bytes
, &error_abort
);
1459 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1460 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1462 memset(pad
, 0, sizeof(*pad
));
1464 pad
->head
= offset
& (align
- 1);
1465 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1467 pad
->tail
= align
- pad
->tail
;
1470 if (!pad
->head
&& !pad
->tail
) {
1474 assert(bytes
); /* Nothing good in aligning zero-length requests */
1476 sum
= pad
->head
+ bytes
+ pad
->tail
;
1477 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1478 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1479 pad
->merge_reads
= sum
== pad
->buf_len
;
1481 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1487 static int coroutine_fn GRAPH_RDLOCK
1488 bdrv_padding_rmw_read(BdrvChild
*child
, BdrvTrackedRequest
*req
,
1489 BdrvRequestPadding
*pad
, bool zero_middle
)
1491 QEMUIOVector local_qiov
;
1492 BlockDriverState
*bs
= child
->bs
;
1493 uint64_t align
= bs
->bl
.request_alignment
;
1496 assert(req
->serialising
&& pad
->buf
);
1498 if (pad
->head
|| pad
->merge_reads
) {
1499 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1501 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1504 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1506 if (pad
->merge_reads
&& pad
->tail
) {
1507 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1509 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1510 align
, &local_qiov
, 0, 0);
1515 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1517 if (pad
->merge_reads
&& pad
->tail
) {
1518 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1521 if (pad
->merge_reads
) {
1527 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1529 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1530 ret
= bdrv_aligned_preadv(
1532 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1533 align
, align
, &local_qiov
, 0, 0);
1537 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1542 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1548 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1551 qemu_vfree(pad
->buf
);
1552 qemu_iovec_destroy(&pad
->local_qiov
);
1554 memset(pad
, 0, sizeof(*pad
));
1560 * Exchange request parameters with padded request if needed. Don't include RMW
1561 * read of padding, bdrv_padding_rmw_read() should be called separately if
1564 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1565 * - on function start they represent original request
1566 * - on failure or when padding is not needed they are unchanged
1567 * - on success when padding is needed they represent padded request
1569 static int bdrv_pad_request(BlockDriverState
*bs
,
1570 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1571 int64_t *offset
, int64_t *bytes
,
1572 BdrvRequestPadding
*pad
, bool *padded
,
1573 BdrvRequestFlags
*flags
)
1577 bdrv_check_qiov_request(*offset
, *bytes
, *qiov
, *qiov_offset
, &error_abort
);
1579 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1586 ret
= qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1587 *qiov
, *qiov_offset
, *bytes
,
1588 pad
->buf
+ pad
->buf_len
- pad
->tail
,
1591 bdrv_padding_destroy(pad
);
1594 *bytes
+= pad
->head
+ pad
->tail
;
1595 *offset
-= pad
->head
;
1596 *qiov
= &pad
->local_qiov
;
1602 /* Can't use optimization hint with bounce buffer */
1603 *flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1609 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1610 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1611 BdrvRequestFlags flags
)
1614 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1617 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1618 int64_t offset
, int64_t bytes
,
1619 QEMUIOVector
*qiov
, size_t qiov_offset
,
1620 BdrvRequestFlags flags
)
1622 BlockDriverState
*bs
= child
->bs
;
1623 BdrvTrackedRequest req
;
1624 BdrvRequestPadding pad
;
1628 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1630 if (!bdrv_co_is_inserted(bs
)) {
1634 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1639 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1641 * Aligning zero request is nonsense. Even if driver has special meaning
1642 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1643 * it to driver due to request_alignment.
1645 * Still, no reason to return an error if someone do unaligned
1646 * zero-length read occasionally.
1651 bdrv_inc_in_flight(bs
);
1653 /* Don't do copy-on-read if we read data before write operation */
1654 if (qatomic_read(&bs
->copy_on_read
)) {
1655 flags
|= BDRV_REQ_COPY_ON_READ
;
1658 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
1664 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1665 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1666 bs
->bl
.request_alignment
,
1667 qiov
, qiov_offset
, flags
);
1668 tracked_request_end(&req
);
1669 bdrv_padding_destroy(&pad
);
1672 bdrv_dec_in_flight(bs
);
1677 static int coroutine_fn GRAPH_RDLOCK
1678 bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1679 BdrvRequestFlags flags
)
1681 BlockDriver
*drv
= bs
->drv
;
1685 bool need_flush
= false;
1689 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1691 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1692 bs
->bl
.request_alignment
);
1693 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1695 assert_bdrv_graph_readable();
1696 bdrv_check_request(offset
, bytes
, &error_abort
);
1702 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1706 /* By definition there is no user buffer so this flag doesn't make sense */
1707 if (flags
& BDRV_REQ_REGISTERED_BUF
) {
1711 /* Invalidate the cached block-status data range if this write overlaps */
1712 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1714 assert(alignment
% bs
->bl
.request_alignment
== 0);
1715 head
= offset
% alignment
;
1716 tail
= (offset
+ bytes
) % alignment
;
1717 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1718 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1720 while (bytes
> 0 && !ret
) {
1721 int64_t num
= bytes
;
1723 /* Align request. Block drivers can expect the "bulk" of the request
1724 * to be aligned, and that unaligned requests do not cross cluster
1728 /* Make a small request up to the first aligned sector. For
1729 * convenience, limit this request to max_transfer even if
1730 * we don't need to fall back to writes. */
1731 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1732 head
= (head
+ num
) % alignment
;
1733 assert(num
< max_write_zeroes
);
1734 } else if (tail
&& num
> alignment
) {
1735 /* Shorten the request to the last aligned sector. */
1739 /* limit request size */
1740 if (num
> max_write_zeroes
) {
1741 num
= max_write_zeroes
;
1745 /* First try the efficient write zeroes operation */
1746 if (drv
->bdrv_co_pwrite_zeroes
) {
1747 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1748 flags
& bs
->supported_zero_flags
);
1749 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1750 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1754 assert(!bs
->supported_zero_flags
);
1757 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1758 /* Fall back to bounce buffer if write zeroes is unsupported */
1759 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1761 if ((flags
& BDRV_REQ_FUA
) &&
1762 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1763 /* No need for bdrv_driver_pwrite() to do a fallback
1764 * flush on each chunk; use just one at the end */
1765 write_flags
&= ~BDRV_REQ_FUA
;
1768 num
= MIN(num
, max_transfer
);
1770 buf
= qemu_try_blockalign0(bs
, num
);
1776 qemu_iovec_init_buf(&qiov
, buf
, num
);
1778 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1780 /* Keep bounce buffer around if it is big enough for all
1781 * all future requests.
1783 if (num
< max_transfer
) {
1794 if (ret
== 0 && need_flush
) {
1795 ret
= bdrv_co_flush(bs
);
1801 static inline int coroutine_fn GRAPH_RDLOCK
1802 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1803 BdrvTrackedRequest
*req
, int flags
)
1805 BlockDriverState
*bs
= child
->bs
;
1807 bdrv_check_request(offset
, bytes
, &error_abort
);
1809 if (bdrv_is_read_only(bs
)) {
1813 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1814 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1815 assert(!(flags
& ~BDRV_REQ_MASK
));
1816 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
1818 if (flags
& BDRV_REQ_SERIALISING
) {
1819 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
1821 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
1823 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
1827 bdrv_wait_serialising_requests_locked(req
);
1829 bdrv_wait_serialising_requests(req
);
1832 assert(req
->overlap_offset
<= offset
);
1833 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1834 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
1835 child
->perm
& BLK_PERM_RESIZE
);
1837 switch (req
->type
) {
1838 case BDRV_TRACKED_WRITE
:
1839 case BDRV_TRACKED_DISCARD
:
1840 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1841 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1843 assert(child
->perm
& BLK_PERM_WRITE
);
1845 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
1847 case BDRV_TRACKED_TRUNCATE
:
1848 assert(child
->perm
& BLK_PERM_RESIZE
);
1855 static inline void coroutine_fn
1856 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1857 BdrvTrackedRequest
*req
, int ret
)
1859 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1860 BlockDriverState
*bs
= child
->bs
;
1862 bdrv_check_request(offset
, bytes
, &error_abort
);
1864 qatomic_inc(&bs
->write_gen
);
1867 * Discard cannot extend the image, but in error handling cases, such as
1868 * when reverting a qcow2 cluster allocation, the discarded range can pass
1869 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1870 * here. Instead, just skip it, since semantically a discard request
1871 * beyond EOF cannot expand the image anyway.
1874 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1875 end_sector
> bs
->total_sectors
) &&
1876 req
->type
!= BDRV_TRACKED_DISCARD
) {
1877 bs
->total_sectors
= end_sector
;
1878 bdrv_parent_cb_resize(bs
);
1879 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1882 switch (req
->type
) {
1883 case BDRV_TRACKED_WRITE
:
1884 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1885 /* fall through, to set dirty bits */
1886 case BDRV_TRACKED_DISCARD
:
1887 bdrv_set_dirty(bs
, offset
, bytes
);
1896 * Forwards an already correctly aligned write request to the BlockDriver,
1897 * after possibly fragmenting it.
1899 static int coroutine_fn GRAPH_RDLOCK
1900 bdrv_aligned_pwritev(BdrvChild
*child
, BdrvTrackedRequest
*req
,
1901 int64_t offset
, int64_t bytes
, int64_t align
,
1902 QEMUIOVector
*qiov
, size_t qiov_offset
,
1903 BdrvRequestFlags flags
)
1905 BlockDriverState
*bs
= child
->bs
;
1906 BlockDriver
*drv
= bs
->drv
;
1909 int64_t bytes_remaining
= bytes
;
1912 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1918 if (bdrv_has_readonly_bitmaps(bs
)) {
1922 assert(is_power_of_2(align
));
1923 assert((offset
& (align
- 1)) == 0);
1924 assert((bytes
& (align
- 1)) == 0);
1925 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1928 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1930 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1931 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1932 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
1933 flags
|= BDRV_REQ_ZERO_WRITE
;
1934 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1935 flags
|= BDRV_REQ_MAY_UNMAP
;
1938 /* Can't use optimization hint with bufferless zero write */
1939 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1943 /* Do nothing, write notifier decided to fail this request */
1944 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1945 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1946 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1947 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1948 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
1950 } else if (bytes
<= max_transfer
) {
1951 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV
);
1952 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1954 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV
);
1955 while (bytes_remaining
) {
1956 int num
= MIN(bytes_remaining
, max_transfer
);
1957 int local_flags
= flags
;
1960 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1961 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1962 /* If FUA is going to be emulated by flush, we only
1963 * need to flush on the last iteration */
1964 local_flags
&= ~BDRV_REQ_FUA
;
1967 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1969 qiov_offset
+ bytes
- bytes_remaining
,
1974 bytes_remaining
-= num
;
1977 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1982 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
1987 static int coroutine_fn GRAPH_RDLOCK
1988 bdrv_co_do_zero_pwritev(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1989 BdrvRequestFlags flags
, BdrvTrackedRequest
*req
)
1991 BlockDriverState
*bs
= child
->bs
;
1992 QEMUIOVector local_qiov
;
1993 uint64_t align
= bs
->bl
.request_alignment
;
1996 BdrvRequestPadding pad
;
1998 /* This flag doesn't make sense for padding or zero writes */
1999 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
2001 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
2003 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2004 bdrv_make_request_serialising(req
, align
);
2006 bdrv_padding_rmw_read(child
, req
, &pad
, true);
2008 if (pad
.head
|| pad
.merge_reads
) {
2009 int64_t aligned_offset
= offset
& ~(align
- 1);
2010 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
2012 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
2013 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
2014 align
, &local_qiov
, 0,
2015 flags
& ~BDRV_REQ_ZERO_WRITE
);
2016 if (ret
< 0 || pad
.merge_reads
) {
2017 /* Error or all work is done */
2020 offset
+= write_bytes
- pad
.head
;
2021 bytes
-= write_bytes
- pad
.head
;
2025 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2026 if (bytes
>= align
) {
2027 /* Write the aligned part in the middle. */
2028 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2029 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2034 bytes
-= aligned_bytes
;
2035 offset
+= aligned_bytes
;
2038 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2040 assert(align
== pad
.tail
+ bytes
);
2042 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2043 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2045 flags
& ~BDRV_REQ_ZERO_WRITE
);
2049 bdrv_padding_destroy(&pad
);
2055 * Handle a write request in coroutine context
2057 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2058 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2059 BdrvRequestFlags flags
)
2062 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2065 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2066 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2067 BdrvRequestFlags flags
)
2069 BlockDriverState
*bs
= child
->bs
;
2070 BdrvTrackedRequest req
;
2071 uint64_t align
= bs
->bl
.request_alignment
;
2072 BdrvRequestPadding pad
;
2074 bool padded
= false;
2077 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2079 if (!bdrv_co_is_inserted(bs
)) {
2083 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2084 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2086 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2092 /* If the request is misaligned then we can't make it efficient */
2093 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2094 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2099 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2101 * Aligning zero request is nonsense. Even if driver has special meaning
2102 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2103 * it to driver due to request_alignment.
2105 * Still, no reason to return an error if someone do unaligned
2106 * zero-length write occasionally.
2111 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2113 * Pad request for following read-modify-write cycle.
2114 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2115 * alignment only if there is no ZERO flag.
2117 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
2124 bdrv_inc_in_flight(bs
);
2125 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2127 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2129 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2135 * Request was unaligned to request_alignment and therefore
2136 * padded. We are going to do read-modify-write, and must
2137 * serialize the request to prevent interactions of the
2138 * widened region with other transactions.
2140 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2141 bdrv_make_request_serialising(&req
, align
);
2142 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2145 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2146 qiov
, qiov_offset
, flags
);
2148 bdrv_padding_destroy(&pad
);
2151 tracked_request_end(&req
);
2152 bdrv_dec_in_flight(bs
);
2157 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2158 int64_t bytes
, BdrvRequestFlags flags
)
2161 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2162 assert_bdrv_graph_readable();
2164 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2165 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2168 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2169 BDRV_REQ_ZERO_WRITE
| flags
);
2173 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2175 int bdrv_flush_all(void)
2177 BdrvNextIterator it
;
2178 BlockDriverState
*bs
= NULL
;
2181 GLOBAL_STATE_CODE();
2184 * bdrv queue is managed by record/replay,
2185 * creating new flush request for stopping
2186 * the VM may break the determinism
2188 if (replay_events_enabled()) {
2192 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2193 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2196 aio_context_acquire(aio_context
);
2197 ret
= bdrv_flush(bs
);
2198 if (ret
< 0 && !result
) {
2201 aio_context_release(aio_context
);
2208 * Returns the allocation status of the specified sectors.
2209 * Drivers not implementing the functionality are assumed to not support
2210 * backing files, hence all their sectors are reported as allocated.
2212 * If 'want_zero' is true, the caller is querying for mapping
2213 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2214 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2215 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2217 * If 'offset' is beyond the end of the disk image the return value is
2218 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2220 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2221 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2222 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2224 * 'pnum' is set to the number of bytes (including and immediately
2225 * following the specified offset) that are easily known to be in the
2226 * same allocated/unallocated state. Note that a second call starting
2227 * at the original offset plus returned pnum may have the same status.
2228 * The returned value is non-zero on success except at end-of-file.
2230 * Returns negative errno on failure. Otherwise, if the
2231 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2232 * set to the host mapping and BDS corresponding to the guest offset.
2234 static int coroutine_fn GRAPH_RDLOCK
2235 bdrv_co_block_status(BlockDriverState
*bs
, bool want_zero
,
2236 int64_t offset
, int64_t bytes
,
2237 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2240 int64_t n
; /* bytes */
2242 int64_t local_map
= 0;
2243 BlockDriverState
*local_file
= NULL
;
2244 int64_t aligned_offset
, aligned_bytes
;
2246 bool has_filtered_child
;
2249 assert_bdrv_graph_readable();
2251 total_size
= bdrv_getlength(bs
);
2252 if (total_size
< 0) {
2257 if (offset
>= total_size
) {
2258 ret
= BDRV_BLOCK_EOF
;
2266 n
= total_size
- offset
;
2271 /* Must be non-NULL or bdrv_getlength() would have failed */
2273 has_filtered_child
= bdrv_filter_child(bs
);
2274 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2276 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2277 if (offset
+ bytes
== total_size
) {
2278 ret
|= BDRV_BLOCK_EOF
;
2280 if (bs
->drv
->protocol_name
) {
2281 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2288 bdrv_inc_in_flight(bs
);
2290 /* Round out to request_alignment boundaries */
2291 align
= bs
->bl
.request_alignment
;
2292 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2293 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2295 if (bs
->drv
->bdrv_co_block_status
) {
2297 * Use the block-status cache only for protocol nodes: Format
2298 * drivers are generally quick to inquire the status, but protocol
2299 * drivers often need to get information from outside of qemu, so
2300 * we do not have control over the actual implementation. There
2301 * have been cases where inquiring the status took an unreasonably
2302 * long time, and we can do nothing in qemu to fix it.
2303 * This is especially problematic for images with large data areas,
2304 * because finding the few holes in them and giving them special
2305 * treatment does not gain much performance. Therefore, we try to
2306 * cache the last-identified data region.
2308 * Second, limiting ourselves to protocol nodes allows us to assume
2309 * the block status for data regions to be DATA | OFFSET_VALID, and
2310 * that the host offset is the same as the guest offset.
2312 * Note that it is possible that external writers zero parts of
2313 * the cached regions without the cache being invalidated, and so
2314 * we may report zeroes as data. This is not catastrophic,
2315 * however, because reporting zeroes as data is fine.
2317 if (QLIST_EMPTY(&bs
->children
) &&
2318 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2320 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2322 local_map
= aligned_offset
;
2324 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2325 aligned_bytes
, pnum
, &local_map
,
2329 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2330 * the cache is queried above. Technically, we do not need to check
2331 * it here; the worst that can happen is that we fill the cache for
2332 * non-protocol nodes, and then it is never used. However, filling
2333 * the cache requires an RCU update, so double check here to avoid
2334 * such an update if possible.
2336 * Check want_zero, because we only want to update the cache when we
2337 * have accurate information about what is zero and what is data.
2340 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2341 QLIST_EMPTY(&bs
->children
))
2344 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2345 * returned local_map value must be the same as the offset we
2346 * have passed (aligned_offset), and local_bs must be the node
2348 * Assert this, because we follow this rule when reading from
2349 * the cache (see the `local_file = bs` and
2350 * `local_map = aligned_offset` assignments above), and the
2351 * result the cache delivers must be the same as the driver
2354 assert(local_file
== bs
);
2355 assert(local_map
== aligned_offset
);
2356 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2360 /* Default code for filters */
2362 local_file
= bdrv_filter_bs(bs
);
2365 *pnum
= aligned_bytes
;
2366 local_map
= aligned_offset
;
2367 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2375 * The driver's result must be a non-zero multiple of request_alignment.
2376 * Clamp pnum and adjust map to original request.
2378 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2379 align
> offset
- aligned_offset
);
2380 if (ret
& BDRV_BLOCK_RECURSE
) {
2381 assert(ret
& BDRV_BLOCK_DATA
);
2382 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2383 assert(!(ret
& BDRV_BLOCK_ZERO
));
2386 *pnum
-= offset
- aligned_offset
;
2387 if (*pnum
> bytes
) {
2390 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2391 local_map
+= offset
- aligned_offset
;
2394 if (ret
& BDRV_BLOCK_RAW
) {
2395 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2396 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2397 *pnum
, pnum
, &local_map
, &local_file
);
2401 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2402 ret
|= BDRV_BLOCK_ALLOCATED
;
2403 } else if (bs
->drv
->supports_backing
) {
2404 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2407 ret
|= BDRV_BLOCK_ZERO
;
2408 } else if (want_zero
) {
2409 int64_t size2
= bdrv_getlength(cow_bs
);
2411 if (size2
>= 0 && offset
>= size2
) {
2412 ret
|= BDRV_BLOCK_ZERO
;
2417 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2418 local_file
&& local_file
!= bs
&&
2419 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2420 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2424 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2425 *pnum
, &file_pnum
, NULL
, NULL
);
2427 /* Ignore errors. This is just providing extra information, it
2428 * is useful but not necessary.
2430 if (ret2
& BDRV_BLOCK_EOF
&&
2431 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2433 * It is valid for the format block driver to read
2434 * beyond the end of the underlying file's current
2435 * size; such areas read as zero.
2437 ret
|= BDRV_BLOCK_ZERO
;
2439 /* Limit request to the range reported by the protocol driver */
2441 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2447 bdrv_dec_in_flight(bs
);
2448 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2449 ret
|= BDRV_BLOCK_EOF
;
2462 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2463 BlockDriverState
*base
,
2470 BlockDriverState
**file
,
2474 BlockDriverState
*p
;
2479 assert(!include_base
|| base
); /* Can't include NULL base */
2480 assert_bdrv_graph_readable();
2487 if (!include_base
&& bs
== base
) {
2492 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2494 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2498 if (ret
& BDRV_BLOCK_EOF
) {
2499 eof
= offset
+ *pnum
;
2502 assert(*pnum
<= bytes
);
2505 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2506 p
= bdrv_filter_or_cow_bs(p
))
2508 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2516 * The top layer deferred to this layer, and because this layer is
2517 * short, any zeroes that we synthesize beyond EOF behave as if they
2518 * were allocated at this layer.
2520 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2521 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2524 assert(ret
& BDRV_BLOCK_EOF
);
2529 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2532 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2534 * We've found the node and the status, we must break.
2536 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2537 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2540 ret
&= ~BDRV_BLOCK_EOF
;
2545 assert(include_base
);
2550 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2551 * let's continue the diving.
2553 assert(*pnum
<= bytes
);
2557 if (offset
+ *pnum
== eof
) {
2558 ret
|= BDRV_BLOCK_EOF
;
2564 int coroutine_fn
bdrv_co_block_status_above(BlockDriverState
*bs
,
2565 BlockDriverState
*base
,
2566 int64_t offset
, int64_t bytes
,
2567 int64_t *pnum
, int64_t *map
,
2568 BlockDriverState
**file
)
2571 return bdrv_co_common_block_status_above(bs
, base
, false, true, offset
,
2572 bytes
, pnum
, map
, file
, NULL
);
2575 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2576 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2577 int64_t *map
, BlockDriverState
**file
)
2580 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2581 pnum
, map
, file
, NULL
);
2584 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2585 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2588 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2589 offset
, bytes
, pnum
, map
, file
);
2593 * Check @bs (and its backing chain) to see if the range defined
2594 * by @offset and @bytes is known to read as zeroes.
2595 * Return 1 if that is the case, 0 otherwise and -errno on error.
2596 * This test is meant to be fast rather than accurate so returning 0
2597 * does not guarantee non-zero data.
2599 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2603 int64_t pnum
= bytes
;
2610 ret
= bdrv_co_common_block_status_above(bs
, NULL
, false, false, offset
,
2611 bytes
, &pnum
, NULL
, NULL
, NULL
);
2617 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2620 int coroutine_fn
bdrv_co_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2621 int64_t bytes
, int64_t *pnum
)
2627 ret
= bdrv_co_common_block_status_above(bs
, bs
, true, false, offset
,
2628 bytes
, pnum
? pnum
: &dummy
, NULL
,
2633 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2636 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2643 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2644 bytes
, pnum
? pnum
: &dummy
, NULL
,
2649 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2652 /* See bdrv_is_allocated_above for documentation */
2653 int coroutine_fn
bdrv_co_is_allocated_above(BlockDriverState
*top
,
2654 BlockDriverState
*base
,
2655 bool include_base
, int64_t offset
,
2656 int64_t bytes
, int64_t *pnum
)
2662 ret
= bdrv_co_common_block_status_above(top
, base
, include_base
, false,
2663 offset
, bytes
, pnum
, NULL
, NULL
,
2669 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2676 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2678 * Return a positive depth if (a prefix of) the given range is allocated
2679 * in any image between BASE and TOP (BASE is only included if include_base
2680 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2681 * BASE can be NULL to check if the given offset is allocated in any
2682 * image of the chain. Return 0 otherwise, or negative errno on
2685 * 'pnum' is set to the number of bytes (including and immediately
2686 * following the specified offset) that are known to be in the same
2687 * allocated/unallocated state. Note that a subsequent call starting
2688 * at 'offset + *pnum' may return the same allocation status (in other
2689 * words, the result is not necessarily the maximum possible range);
2690 * but 'pnum' will only be 0 when end of file is reached.
2692 int bdrv_is_allocated_above(BlockDriverState
*top
,
2693 BlockDriverState
*base
,
2694 bool include_base
, int64_t offset
,
2695 int64_t bytes
, int64_t *pnum
)
2701 ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2702 offset
, bytes
, pnum
, NULL
, NULL
,
2708 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2715 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2717 BlockDriver
*drv
= bs
->drv
;
2718 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2721 assert_bdrv_graph_readable();
2723 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2732 bdrv_inc_in_flight(bs
);
2734 if (drv
->bdrv_co_load_vmstate
) {
2735 ret
= drv
->bdrv_co_load_vmstate(bs
, qiov
, pos
);
2736 } else if (child_bs
) {
2737 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2742 bdrv_dec_in_flight(bs
);
2748 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2750 BlockDriver
*drv
= bs
->drv
;
2751 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2754 assert_bdrv_graph_readable();
2756 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2765 bdrv_inc_in_flight(bs
);
2767 if (drv
->bdrv_co_save_vmstate
) {
2768 ret
= drv
->bdrv_co_save_vmstate(bs
, qiov
, pos
);
2769 } else if (child_bs
) {
2770 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2775 bdrv_dec_in_flight(bs
);
2780 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2781 int64_t pos
, int size
)
2783 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2784 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2787 return ret
< 0 ? ret
: size
;
2790 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2791 int64_t pos
, int size
)
2793 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2794 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2797 return ret
< 0 ? ret
: size
;
2800 /**************************************************************/
2803 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2807 bdrv_aio_cancel_async(acb
);
2808 while (acb
->refcnt
> 1) {
2809 if (acb
->aiocb_info
->get_aio_context
) {
2810 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2811 } else if (acb
->bs
) {
2812 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2813 * assert that we're not using an I/O thread. Thread-safe
2814 * code should use bdrv_aio_cancel_async exclusively.
2816 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2817 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2822 qemu_aio_unref(acb
);
2825 /* Async version of aio cancel. The caller is not blocked if the acb implements
2826 * cancel_async, otherwise we do nothing and let the request normally complete.
2827 * In either case the completion callback must be called. */
2828 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2831 if (acb
->aiocb_info
->cancel_async
) {
2832 acb
->aiocb_info
->cancel_async(acb
);
2836 /**************************************************************/
2837 /* Coroutine block device emulation */
2839 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2841 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2847 assert_bdrv_graph_readable();
2848 bdrv_inc_in_flight(bs
);
2850 if (!bdrv_co_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2855 qemu_co_mutex_lock(&bs
->reqs_lock
);
2856 current_gen
= qatomic_read(&bs
->write_gen
);
2858 /* Wait until any previous flushes are completed */
2859 while (bs
->active_flush_req
) {
2860 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2863 /* Flushes reach this point in nondecreasing current_gen order. */
2864 bs
->active_flush_req
= true;
2865 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2867 /* Write back all layers by calling one driver function */
2868 if (bs
->drv
->bdrv_co_flush
) {
2869 ret
= bs
->drv
->bdrv_co_flush(bs
);
2873 /* Write back cached data to the OS even with cache=unsafe */
2874 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2875 if (bs
->drv
->bdrv_co_flush_to_os
) {
2876 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2882 /* But don't actually force it to the disk with cache=unsafe */
2883 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2884 goto flush_children
;
2887 /* Check if we really need to flush anything */
2888 if (bs
->flushed_gen
== current_gen
) {
2889 goto flush_children
;
2892 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2894 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2895 * (even in case of apparent success) */
2899 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2900 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2901 } else if (bs
->drv
->bdrv_aio_flush
) {
2903 CoroutineIOCompletion co
= {
2904 .coroutine
= qemu_coroutine_self(),
2907 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2911 qemu_coroutine_yield();
2916 * Some block drivers always operate in either writethrough or unsafe
2917 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2918 * know how the server works (because the behaviour is hardcoded or
2919 * depends on server-side configuration), so we can't ensure that
2920 * everything is safe on disk. Returning an error doesn't work because
2921 * that would break guests even if the server operates in writethrough
2924 * Let's hope the user knows what he's doing.
2933 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2934 * in the case of cache=unsafe, so there are no useless flushes.
2938 QLIST_FOREACH(child
, &bs
->children
, next
) {
2939 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2940 int this_child_ret
= bdrv_co_flush(child
->bs
);
2942 ret
= this_child_ret
;
2948 /* Notify any pending flushes that we have completed */
2950 bs
->flushed_gen
= current_gen
;
2953 qemu_co_mutex_lock(&bs
->reqs_lock
);
2954 bs
->active_flush_req
= false;
2955 /* Return value is ignored - it's ok if wait queue is empty */
2956 qemu_co_queue_next(&bs
->flush_queue
);
2957 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2960 bdrv_dec_in_flight(bs
);
2964 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2967 BdrvTrackedRequest req
;
2969 int64_t max_pdiscard
;
2970 int head
, tail
, align
;
2971 BlockDriverState
*bs
= child
->bs
;
2973 assert_bdrv_graph_readable();
2975 if (!bs
|| !bs
->drv
|| !bdrv_co_is_inserted(bs
)) {
2979 if (bdrv_has_readonly_bitmaps(bs
)) {
2983 ret
= bdrv_check_request(offset
, bytes
, NULL
);
2988 /* Do nothing if disabled. */
2989 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2993 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2997 /* Invalidate the cached block-status data range if this discard overlaps */
2998 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
3000 /* Discard is advisory, but some devices track and coalesce
3001 * unaligned requests, so we must pass everything down rather than
3002 * round here. Still, most devices will just silently ignore
3003 * unaligned requests (by returning -ENOTSUP), so we must fragment
3004 * the request accordingly. */
3005 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
3006 assert(align
% bs
->bl
.request_alignment
== 0);
3007 head
= offset
% align
;
3008 tail
= (offset
+ bytes
) % align
;
3010 bdrv_inc_in_flight(bs
);
3011 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
3013 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
3018 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
3020 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
3023 int64_t num
= bytes
;
3026 /* Make small requests to get to alignment boundaries. */
3027 num
= MIN(bytes
, align
- head
);
3028 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
3029 num
%= bs
->bl
.request_alignment
;
3031 head
= (head
+ num
) % align
;
3032 assert(num
< max_pdiscard
);
3035 /* Shorten the request to the last aligned cluster. */
3037 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
3038 tail
> bs
->bl
.request_alignment
) {
3039 tail
%= bs
->bl
.request_alignment
;
3043 /* limit request size */
3044 if (num
> max_pdiscard
) {
3052 if (bs
->drv
->bdrv_co_pdiscard
) {
3053 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
3056 CoroutineIOCompletion co
= {
3057 .coroutine
= qemu_coroutine_self(),
3060 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
3061 bdrv_co_io_em_complete
, &co
);
3066 qemu_coroutine_yield();
3070 if (ret
&& ret
!= -ENOTSUP
) {
3079 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3080 tracked_request_end(&req
);
3081 bdrv_dec_in_flight(bs
);
3085 int coroutine_fn
bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3087 BlockDriver
*drv
= bs
->drv
;
3088 CoroutineIOCompletion co
= {
3089 .coroutine
= qemu_coroutine_self(),
3093 assert_bdrv_graph_readable();
3095 bdrv_inc_in_flight(bs
);
3096 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3101 if (drv
->bdrv_co_ioctl
) {
3102 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3104 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3109 qemu_coroutine_yield();
3112 bdrv_dec_in_flight(bs
);
3116 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3119 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3122 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3125 return memset(qemu_blockalign(bs
, size
), 0, size
);
3128 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3130 size_t align
= bdrv_opt_mem_align(bs
);
3133 /* Ensure that NULL is never returned on success */
3139 return qemu_try_memalign(align
, size
);
3142 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3144 void *mem
= qemu_try_blockalign(bs
, size
);
3148 memset(mem
, 0, size
);
3154 void coroutine_fn
bdrv_co_io_plug(BlockDriverState
*bs
)
3158 assert_bdrv_graph_readable();
3160 QLIST_FOREACH(child
, &bs
->children
, next
) {
3161 bdrv_co_io_plug(child
->bs
);
3164 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
3165 BlockDriver
*drv
= bs
->drv
;
3166 if (drv
&& drv
->bdrv_co_io_plug
) {
3167 drv
->bdrv_co_io_plug(bs
);
3172 void coroutine_fn
bdrv_co_io_unplug(BlockDriverState
*bs
)
3176 assert_bdrv_graph_readable();
3178 assert(bs
->io_plugged
);
3179 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
3180 BlockDriver
*drv
= bs
->drv
;
3181 if (drv
&& drv
->bdrv_co_io_unplug
) {
3182 drv
->bdrv_co_io_unplug(bs
);
3186 QLIST_FOREACH(child
, &bs
->children
, next
) {
3187 bdrv_co_io_unplug(child
->bs
);
3191 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3192 static void GRAPH_RDLOCK
3193 bdrv_register_buf_rollback(BlockDriverState
*bs
, void *host
, size_t size
,
3194 BdrvChild
*final_child
)
3198 GLOBAL_STATE_CODE();
3199 assert_bdrv_graph_readable();
3201 QLIST_FOREACH(child
, &bs
->children
, next
) {
3202 if (child
== final_child
) {
3206 bdrv_unregister_buf(child
->bs
, host
, size
);
3209 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3210 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3214 bool bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
3219 GLOBAL_STATE_CODE();
3220 GRAPH_RDLOCK_GUARD_MAINLOOP();
3222 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3223 if (!bs
->drv
->bdrv_register_buf(bs
, host
, size
, errp
)) {
3227 QLIST_FOREACH(child
, &bs
->children
, next
) {
3228 if (!bdrv_register_buf(child
->bs
, host
, size
, errp
)) {
3229 bdrv_register_buf_rollback(bs
, host
, size
, child
);
3236 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3240 GLOBAL_STATE_CODE();
3241 GRAPH_RDLOCK_GUARD_MAINLOOP();
3243 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3244 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3246 QLIST_FOREACH(child
, &bs
->children
, next
) {
3247 bdrv_unregister_buf(child
->bs
, host
, size
);
3251 static int coroutine_fn GRAPH_RDLOCK
bdrv_co_copy_range_internal(
3252 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3253 int64_t dst_offset
, int64_t bytes
,
3254 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3257 BdrvTrackedRequest req
;
3259 assert_bdrv_graph_readable();
3261 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3262 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3263 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3264 assert(!(read_flags
& BDRV_REQ_NO_WAIT
));
3265 assert(!(write_flags
& BDRV_REQ_NO_WAIT
));
3267 if (!dst
|| !dst
->bs
|| !bdrv_co_is_inserted(dst
->bs
)) {
3270 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3274 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3275 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3278 if (!src
|| !src
->bs
|| !bdrv_co_is_inserted(src
->bs
)) {
3281 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3286 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3287 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3288 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3293 bdrv_inc_in_flight(src
->bs
);
3294 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3297 /* BDRV_REQ_SERIALISING is only for write operation */
3298 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3299 bdrv_wait_serialising_requests(&req
);
3301 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3305 read_flags
, write_flags
);
3307 tracked_request_end(&req
);
3308 bdrv_dec_in_flight(src
->bs
);
3310 bdrv_inc_in_flight(dst
->bs
);
3311 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3312 BDRV_TRACKED_WRITE
);
3313 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3316 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3320 read_flags
, write_flags
);
3322 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3323 tracked_request_end(&req
);
3324 bdrv_dec_in_flight(dst
->bs
);
3330 /* Copy range from @src to @dst.
3332 * See the comment of bdrv_co_copy_range for the parameter and return value
3334 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3335 BdrvChild
*dst
, int64_t dst_offset
,
3337 BdrvRequestFlags read_flags
,
3338 BdrvRequestFlags write_flags
)
3341 assert_bdrv_graph_readable();
3342 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3343 read_flags
, write_flags
);
3344 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3345 bytes
, read_flags
, write_flags
, true);
3348 /* Copy range from @src to @dst.
3350 * See the comment of bdrv_co_copy_range for the parameter and return value
3352 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3353 BdrvChild
*dst
, int64_t dst_offset
,
3355 BdrvRequestFlags read_flags
,
3356 BdrvRequestFlags write_flags
)
3359 assert_bdrv_graph_readable();
3360 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3361 read_flags
, write_flags
);
3362 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3363 bytes
, read_flags
, write_flags
, false);
3366 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3367 BdrvChild
*dst
, int64_t dst_offset
,
3368 int64_t bytes
, BdrvRequestFlags read_flags
,
3369 BdrvRequestFlags write_flags
)
3372 assert_bdrv_graph_readable();
3374 return bdrv_co_copy_range_from(src
, src_offset
,
3376 bytes
, read_flags
, write_flags
);
3379 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3382 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3383 if (c
->klass
->resize
) {
3384 c
->klass
->resize(c
);
3390 * Truncate file to 'offset' bytes (needed only for file protocols)
3392 * If 'exact' is true, the file must be resized to exactly the given
3393 * 'offset'. Otherwise, it is sufficient for the node to be at least
3394 * 'offset' bytes in length.
3396 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3397 PreallocMode prealloc
, BdrvRequestFlags flags
,
3400 BlockDriverState
*bs
= child
->bs
;
3401 BdrvChild
*filtered
, *backing
;
3402 BlockDriver
*drv
= bs
->drv
;
3403 BdrvTrackedRequest req
;
3404 int64_t old_size
, new_bytes
;
3407 assert_bdrv_graph_readable();
3409 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3411 error_setg(errp
, "No medium inserted");
3415 error_setg(errp
, "Image size cannot be negative");
3419 ret
= bdrv_check_request(offset
, 0, errp
);
3424 old_size
= bdrv_getlength(bs
);
3426 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3430 if (bdrv_is_read_only(bs
)) {
3431 error_setg(errp
, "Image is read-only");
3435 if (offset
> old_size
) {
3436 new_bytes
= offset
- old_size
;
3441 bdrv_inc_in_flight(bs
);
3442 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3443 BDRV_TRACKED_TRUNCATE
);
3445 /* If we are growing the image and potentially using preallocation for the
3446 * new area, we need to make sure that no write requests are made to it
3447 * concurrently or they might be overwritten by preallocation. */
3449 bdrv_make_request_serialising(&req
, 1);
3451 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3454 error_setg_errno(errp
, -ret
,
3455 "Failed to prepare request for truncation");
3459 filtered
= bdrv_filter_child(bs
);
3460 backing
= bdrv_cow_child(bs
);
3463 * If the image has a backing file that is large enough that it would
3464 * provide data for the new area, we cannot leave it unallocated because
3465 * then the backing file content would become visible. Instead, zero-fill
3468 * Note that if the image has a backing file, but was opened without the
3469 * backing file, taking care of keeping things consistent with that backing
3470 * file is the user's responsibility.
3472 if (new_bytes
&& backing
) {
3473 int64_t backing_len
;
3475 backing_len
= bdrv_co_getlength(backing
->bs
);
3476 if (backing_len
< 0) {
3478 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3482 if (backing_len
> old_size
) {
3483 flags
|= BDRV_REQ_ZERO_WRITE
;
3487 if (drv
->bdrv_co_truncate
) {
3488 if (flags
& ~bs
->supported_truncate_flags
) {
3489 error_setg(errp
, "Block driver does not support requested flags");
3493 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3494 } else if (filtered
) {
3495 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3497 error_setg(errp
, "Image format driver does not support resize");
3505 ret
= bdrv_co_refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3507 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3509 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3512 * It's possible that truncation succeeded but bdrv_refresh_total_sectors
3513 * failed, but the latter doesn't affect how we should finish the request.
3514 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled.
3516 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3519 tracked_request_end(&req
);
3520 bdrv_dec_in_flight(bs
);
3525 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3527 GLOBAL_STATE_CODE();
3528 if (!bs
|| !bs
->drv
) {
3532 if (bs
->drv
->bdrv_cancel_in_flight
) {
3533 bs
->drv
->bdrv_cancel_in_flight(bs
);
3538 bdrv_co_preadv_snapshot(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
3539 QEMUIOVector
*qiov
, size_t qiov_offset
)
3541 BlockDriverState
*bs
= child
->bs
;
3542 BlockDriver
*drv
= bs
->drv
;
3545 assert_bdrv_graph_readable();
3551 if (!drv
->bdrv_co_preadv_snapshot
) {
3555 bdrv_inc_in_flight(bs
);
3556 ret
= drv
->bdrv_co_preadv_snapshot(bs
, offset
, bytes
, qiov
, qiov_offset
);
3557 bdrv_dec_in_flight(bs
);
3563 bdrv_co_snapshot_block_status(BlockDriverState
*bs
,
3564 bool want_zero
, int64_t offset
, int64_t bytes
,
3565 int64_t *pnum
, int64_t *map
,
3566 BlockDriverState
**file
)
3568 BlockDriver
*drv
= bs
->drv
;
3571 assert_bdrv_graph_readable();
3577 if (!drv
->bdrv_co_snapshot_block_status
) {
3581 bdrv_inc_in_flight(bs
);
3582 ret
= drv
->bdrv_co_snapshot_block_status(bs
, want_zero
, offset
, bytes
,
3584 bdrv_dec_in_flight(bs
);
3590 bdrv_co_pdiscard_snapshot(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3592 BlockDriver
*drv
= bs
->drv
;
3595 assert_bdrv_graph_readable();
3601 if (!drv
->bdrv_co_pdiscard_snapshot
) {
3605 bdrv_inc_in_flight(bs
);
3606 ret
= drv
->bdrv_co_pdiscard_snapshot(bs
, offset
, bytes
);
3607 bdrv_dec_in_flight(bs
);