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
,
49 bool ignore_bds_parents
)
53 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
54 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
57 bdrv_parent_drained_begin_single(c
, false);
61 void bdrv_parent_drained_end_single(BdrvChild
*c
)
65 assert(c
->parent_quiesce_counter
> 0);
66 c
->parent_quiesce_counter
--;
67 if (c
->klass
->drained_end
) {
68 c
->klass
->drained_end(c
);
72 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
,
73 bool ignore_bds_parents
)
77 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
78 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
81 bdrv_parent_drained_end_single(c
);
85 static 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
, bool poll
)
111 AioContext
*ctx
= bdrv_child_get_parent_aio_context(c
);
113 c
->parent_quiesce_counter
++;
114 if (c
->klass
->drained_begin
) {
115 c
->klass
->drained_begin(c
);
118 AIO_WAIT_WHILE(ctx
, bdrv_parent_drained_poll_single(c
));
122 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
124 dst
->pdiscard_alignment
= MAX(dst
->pdiscard_alignment
,
125 src
->pdiscard_alignment
);
126 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
127 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
128 dst
->max_hw_transfer
= MIN_NON_ZERO(dst
->max_hw_transfer
,
129 src
->max_hw_transfer
);
130 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
131 src
->opt_mem_alignment
);
132 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
133 src
->min_mem_alignment
);
134 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
135 dst
->max_hw_iov
= MIN_NON_ZERO(dst
->max_hw_iov
, src
->max_hw_iov
);
138 typedef struct BdrvRefreshLimitsState
{
139 BlockDriverState
*bs
;
141 } BdrvRefreshLimitsState
;
143 static void bdrv_refresh_limits_abort(void *opaque
)
145 BdrvRefreshLimitsState
*s
= opaque
;
147 s
->bs
->bl
= s
->old_bl
;
150 static TransactionActionDrv bdrv_refresh_limits_drv
= {
151 .abort
= bdrv_refresh_limits_abort
,
155 /* @tran is allowed to be NULL, in this case no rollback is possible. */
156 void bdrv_refresh_limits(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
159 BlockDriver
*drv
= bs
->drv
;
166 BdrvRefreshLimitsState
*s
= g_new(BdrvRefreshLimitsState
, 1);
167 *s
= (BdrvRefreshLimitsState
) {
171 tran_add(tran
, &bdrv_refresh_limits_drv
, s
);
174 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
180 /* Default alignment based on whether driver has byte interface */
181 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
182 drv
->bdrv_aio_preadv
||
183 drv
->bdrv_co_preadv_part
) ? 1 : 512;
185 /* Take some limits from the children as a default */
187 QLIST_FOREACH(c
, &bs
->children
, next
) {
188 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
190 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
196 bs
->bl
.min_mem_alignment
= 512;
197 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size();
199 /* Safe default since most protocols use readv()/writev()/etc */
200 bs
->bl
.max_iov
= IOV_MAX
;
203 /* Then let the driver override it */
204 if (drv
->bdrv_refresh_limits
) {
205 drv
->bdrv_refresh_limits(bs
, errp
);
211 if (bs
->bl
.request_alignment
> BDRV_MAX_ALIGNMENT
) {
212 error_setg(errp
, "Driver requires too large request alignment");
217 * The copy-on-read flag is actually a reference count so multiple users may
218 * use the feature without worrying about clobbering its previous state.
219 * Copy-on-read stays enabled until all users have called to disable it.
221 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
224 qatomic_inc(&bs
->copy_on_read
);
227 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
229 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
236 BlockDriverState
*bs
;
242 bool ignore_bds_parents
;
245 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
246 bool bdrv_drain_poll(BlockDriverState
*bs
, bool recursive
,
247 BdrvChild
*ignore_parent
, bool ignore_bds_parents
)
249 BdrvChild
*child
, *next
;
252 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
256 if (qatomic_read(&bs
->in_flight
)) {
261 assert(!ignore_bds_parents
);
262 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
263 if (bdrv_drain_poll(child
->bs
, recursive
, child
, false)) {
272 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
, bool recursive
,
273 BdrvChild
*ignore_parent
)
275 return bdrv_drain_poll(bs
, recursive
, ignore_parent
, false);
278 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
279 BdrvChild
*parent
, bool ignore_bds_parents
,
281 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
282 BdrvChild
*parent
, bool ignore_bds_parents
);
284 static void bdrv_co_drain_bh_cb(void *opaque
)
286 BdrvCoDrainData
*data
= opaque
;
287 Coroutine
*co
= data
->co
;
288 BlockDriverState
*bs
= data
->bs
;
291 AioContext
*ctx
= bdrv_get_aio_context(bs
);
292 aio_context_acquire(ctx
);
293 bdrv_dec_in_flight(bs
);
295 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
,
296 data
->ignore_bds_parents
, data
->poll
);
299 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
,
300 data
->ignore_bds_parents
);
302 aio_context_release(ctx
);
305 bdrv_drain_all_begin();
312 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
313 bool begin
, bool recursive
,
315 bool ignore_bds_parents
,
318 BdrvCoDrainData data
;
319 Coroutine
*self
= qemu_coroutine_self();
320 AioContext
*ctx
= bdrv_get_aio_context(bs
);
321 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(self
);
323 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
324 * other coroutines run if they were queued by aio_co_enter(). */
326 assert(qemu_in_coroutine());
327 data
= (BdrvCoDrainData
) {
332 .recursive
= recursive
,
334 .ignore_bds_parents
= ignore_bds_parents
,
339 bdrv_inc_in_flight(bs
);
343 * Temporarily drop the lock across yield or we would get deadlocks.
344 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
346 * When we yield below, the lock for the current context will be
347 * released, so if this is actually the lock that protects bs, don't drop
351 aio_context_release(ctx
);
353 replay_bh_schedule_oneshot_event(ctx
, bdrv_co_drain_bh_cb
, &data
);
355 qemu_coroutine_yield();
356 /* If we are resumed from some other event (such as an aio completion or a
357 * timer callback), it is a bug in the caller that should be fixed. */
360 /* Reaquire the AioContext of bs if we dropped it */
362 aio_context_acquire(ctx
);
366 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
,
367 BdrvChild
*parent
, bool ignore_bds_parents
)
370 assert(!qemu_in_coroutine());
372 /* Stop things in parent-to-child order */
373 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
374 aio_disable_external(bdrv_get_aio_context(bs
));
377 bdrv_parent_drained_begin(bs
, parent
, ignore_bds_parents
);
378 if (bs
->drv
&& bs
->drv
->bdrv_drain_begin
) {
379 bs
->drv
->bdrv_drain_begin(bs
);
383 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
384 BdrvChild
*parent
, bool ignore_bds_parents
,
387 BdrvChild
*child
, *next
;
389 if (qemu_in_coroutine()) {
390 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
, ignore_bds_parents
,
395 bdrv_do_drained_begin_quiesce(bs
, parent
, ignore_bds_parents
);
398 assert(!ignore_bds_parents
);
399 bs
->recursive_quiesce_counter
++;
400 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
401 bdrv_do_drained_begin(child
->bs
, true, child
, ignore_bds_parents
,
407 * Wait for drained requests to finish.
409 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
410 * call is needed so things in this AioContext can make progress even
411 * though we don't return to the main AioContext loop - this automatically
412 * includes other nodes in the same AioContext and therefore all child
416 assert(!ignore_bds_parents
);
417 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, recursive
, parent
));
421 void bdrv_drained_begin(BlockDriverState
*bs
)
424 bdrv_do_drained_begin(bs
, false, NULL
, false, true);
427 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
430 bdrv_do_drained_begin(bs
, true, NULL
, false, true);
434 * This function does not poll, nor must any of its recursively called
437 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
438 BdrvChild
*parent
, bool ignore_bds_parents
)
441 int old_quiesce_counter
;
443 if (qemu_in_coroutine()) {
444 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
, ignore_bds_parents
,
448 assert(bs
->quiesce_counter
> 0);
450 /* Re-enable things in child-to-parent order */
451 if (bs
->drv
&& bs
->drv
->bdrv_drain_end
) {
452 bs
->drv
->bdrv_drain_end(bs
);
454 bdrv_parent_drained_end(bs
, parent
, ignore_bds_parents
);
456 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
457 if (old_quiesce_counter
== 1) {
458 aio_enable_external(bdrv_get_aio_context(bs
));
462 assert(!ignore_bds_parents
);
463 bs
->recursive_quiesce_counter
--;
464 QLIST_FOREACH(child
, &bs
->children
, next
) {
465 bdrv_do_drained_end(child
->bs
, true, child
, ignore_bds_parents
);
470 void bdrv_drained_end(BlockDriverState
*bs
)
473 bdrv_do_drained_end(bs
, false, NULL
, false);
476 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
479 bdrv_do_drained_end(bs
, true, NULL
, false);
482 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
487 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
488 bdrv_do_drained_begin(child
->bs
, true, child
, false, true);
492 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
497 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
498 bdrv_do_drained_end(child
->bs
, true, child
, false);
502 void bdrv_drain(BlockDriverState
*bs
)
505 bdrv_drained_begin(bs
);
506 bdrv_drained_end(bs
);
509 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
511 BdrvChild
*child
, *next
;
513 assert(qatomic_read(&bs
->in_flight
) == 0);
514 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
515 bdrv_drain_assert_idle(child
->bs
);
519 unsigned int bdrv_drain_all_count
= 0;
521 static bool bdrv_drain_all_poll(void)
523 BlockDriverState
*bs
= NULL
;
527 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
528 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
529 while ((bs
= bdrv_next_all_states(bs
))) {
530 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
531 aio_context_acquire(aio_context
);
532 result
|= bdrv_drain_poll(bs
, false, NULL
, true);
533 aio_context_release(aio_context
);
540 * Wait for pending requests to complete across all BlockDriverStates
542 * This function does not flush data to disk, use bdrv_flush_all() for that
543 * after calling this function.
545 * This pauses all block jobs and disables external clients. It must
546 * be paired with bdrv_drain_all_end().
548 * NOTE: no new block jobs or BlockDriverStates can be created between
549 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
551 void bdrv_drain_all_begin(void)
553 BlockDriverState
*bs
= NULL
;
556 if (qemu_in_coroutine()) {
557 bdrv_co_yield_to_drain(NULL
, true, false, NULL
, true, true);
562 * bdrv queue is managed by record/replay,
563 * waiting for finishing the I/O requests may
566 if (replay_events_enabled()) {
570 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
571 * loop AioContext, so make sure we're in the main context. */
572 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
573 assert(bdrv_drain_all_count
< INT_MAX
);
574 bdrv_drain_all_count
++;
576 /* Quiesce all nodes, without polling in-flight requests yet. The graph
577 * cannot change during this loop. */
578 while ((bs
= bdrv_next_all_states(bs
))) {
579 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
581 aio_context_acquire(aio_context
);
582 bdrv_do_drained_begin(bs
, false, NULL
, true, false);
583 aio_context_release(aio_context
);
586 /* Now poll the in-flight requests */
587 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
589 while ((bs
= bdrv_next_all_states(bs
))) {
590 bdrv_drain_assert_idle(bs
);
594 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
598 g_assert(bs
->quiesce_counter
> 0);
599 g_assert(!bs
->refcnt
);
601 while (bs
->quiesce_counter
) {
602 bdrv_do_drained_end(bs
, false, NULL
, true);
606 void bdrv_drain_all_end(void)
608 BlockDriverState
*bs
= NULL
;
612 * bdrv queue is managed by record/replay,
613 * waiting for finishing the I/O requests may
616 if (replay_events_enabled()) {
620 while ((bs
= bdrv_next_all_states(bs
))) {
621 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
623 aio_context_acquire(aio_context
);
624 bdrv_do_drained_end(bs
, false, NULL
, true);
625 aio_context_release(aio_context
);
628 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
629 assert(bdrv_drain_all_count
> 0);
630 bdrv_drain_all_count
--;
633 void bdrv_drain_all(void)
636 bdrv_drain_all_begin();
637 bdrv_drain_all_end();
641 * Remove an active request from the tracked requests list
643 * This function should be called when a tracked request is completing.
645 static void coroutine_fn
tracked_request_end(BdrvTrackedRequest
*req
)
647 if (req
->serialising
) {
648 qatomic_dec(&req
->bs
->serialising_in_flight
);
651 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
652 QLIST_REMOVE(req
, list
);
653 qemu_co_queue_restart_all(&req
->wait_queue
);
654 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
658 * Add an active request to the tracked requests list
660 static void coroutine_fn
tracked_request_begin(BdrvTrackedRequest
*req
,
661 BlockDriverState
*bs
,
664 enum BdrvTrackedRequestType type
)
666 bdrv_check_request(offset
, bytes
, &error_abort
);
668 *req
= (BdrvTrackedRequest
){
673 .co
= qemu_coroutine_self(),
674 .serialising
= false,
675 .overlap_offset
= offset
,
676 .overlap_bytes
= bytes
,
679 qemu_co_queue_init(&req
->wait_queue
);
681 qemu_co_mutex_lock(&bs
->reqs_lock
);
682 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
683 qemu_co_mutex_unlock(&bs
->reqs_lock
);
686 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
687 int64_t offset
, int64_t bytes
)
689 bdrv_check_request(offset
, bytes
, &error_abort
);
692 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
696 if (req
->overlap_offset
>= offset
+ bytes
) {
702 /* Called with self->bs->reqs_lock held */
703 static coroutine_fn BdrvTrackedRequest
*
704 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
706 BdrvTrackedRequest
*req
;
708 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
709 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
712 if (tracked_request_overlaps(req
, self
->overlap_offset
,
713 self
->overlap_bytes
))
716 * Hitting this means there was a reentrant request, for
717 * example, a block driver issuing nested requests. This must
718 * never happen since it means deadlock.
720 assert(qemu_coroutine_self() != req
->co
);
723 * If the request is already (indirectly) waiting for us, or
724 * will wait for us as soon as it wakes up, then just go on
725 * (instead of producing a deadlock in the former case).
727 if (!req
->waiting_for
) {
736 /* Called with self->bs->reqs_lock held */
737 static void coroutine_fn
738 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
740 BdrvTrackedRequest
*req
;
742 while ((req
= bdrv_find_conflicting_request(self
))) {
743 self
->waiting_for
= req
;
744 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
745 self
->waiting_for
= NULL
;
749 /* Called with req->bs->reqs_lock held */
750 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
753 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
754 int64_t overlap_bytes
=
755 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
757 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
759 if (!req
->serialising
) {
760 qatomic_inc(&req
->bs
->serialising_in_flight
);
761 req
->serialising
= true;
764 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
765 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
769 * Return the tracked request on @bs for the current coroutine, or
770 * NULL if there is none.
772 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
774 BdrvTrackedRequest
*req
;
775 Coroutine
*self
= qemu_coroutine_self();
778 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
779 if (req
->co
== self
) {
788 * Round a region to cluster boundaries
790 void bdrv_round_to_clusters(BlockDriverState
*bs
,
791 int64_t offset
, int64_t bytes
,
792 int64_t *cluster_offset
,
793 int64_t *cluster_bytes
)
797 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
798 *cluster_offset
= offset
;
799 *cluster_bytes
= bytes
;
801 int64_t c
= bdi
.cluster_size
;
802 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
803 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
807 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
812 ret
= bdrv_get_info(bs
, &bdi
);
813 if (ret
< 0 || bdi
.cluster_size
== 0) {
814 return bs
->bl
.request_alignment
;
816 return bdi
.cluster_size
;
820 void bdrv_inc_in_flight(BlockDriverState
*bs
)
823 qatomic_inc(&bs
->in_flight
);
826 void bdrv_wakeup(BlockDriverState
*bs
)
832 void bdrv_dec_in_flight(BlockDriverState
*bs
)
835 qatomic_dec(&bs
->in_flight
);
839 static void coroutine_fn
840 bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
842 BlockDriverState
*bs
= self
->bs
;
844 if (!qatomic_read(&bs
->serialising_in_flight
)) {
848 qemu_co_mutex_lock(&bs
->reqs_lock
);
849 bdrv_wait_serialising_requests_locked(self
);
850 qemu_co_mutex_unlock(&bs
->reqs_lock
);
853 void coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
858 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
860 tracked_request_set_serialising(req
, align
);
861 bdrv_wait_serialising_requests_locked(req
);
863 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
866 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
867 QEMUIOVector
*qiov
, size_t qiov_offset
,
871 * Check generic offset/bytes correctness
875 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
880 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
884 if (bytes
> BDRV_MAX_LENGTH
) {
885 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
886 bytes
, BDRV_MAX_LENGTH
);
890 if (offset
> BDRV_MAX_LENGTH
) {
891 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
892 offset
, BDRV_MAX_LENGTH
);
896 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
897 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
898 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
908 * Check qiov and qiov_offset
911 if (qiov_offset
> qiov
->size
) {
912 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
913 qiov_offset
, qiov
->size
);
917 if (bytes
> qiov
->size
- qiov_offset
) {
918 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
919 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
926 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
928 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
931 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
932 QEMUIOVector
*qiov
, size_t qiov_offset
)
934 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
939 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
947 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
948 * The operation is sped up by checking the block status and only writing
949 * zeroes to the device if they currently do not return zeroes. Optional
950 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
953 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
955 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
958 int64_t target_size
, bytes
, offset
= 0;
959 BlockDriverState
*bs
= child
->bs
;
962 target_size
= bdrv_getlength(bs
);
963 if (target_size
< 0) {
968 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
972 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
976 if (ret
& BDRV_BLOCK_ZERO
) {
980 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
989 * Writes to the file and ensures that no writes are reordered across this
990 * request (acts as a barrier)
992 * Returns 0 on success, -errno in error cases.
994 int coroutine_fn
bdrv_co_pwrite_sync(BdrvChild
*child
, int64_t offset
,
995 int64_t bytes
, const void *buf
,
996 BdrvRequestFlags flags
)
1001 ret
= bdrv_co_pwrite(child
, offset
, bytes
, buf
, flags
);
1006 ret
= bdrv_co_flush(child
->bs
);
1014 typedef struct CoroutineIOCompletion
{
1015 Coroutine
*coroutine
;
1017 } CoroutineIOCompletion
;
1019 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
1021 CoroutineIOCompletion
*co
= opaque
;
1024 aio_co_wake(co
->coroutine
);
1027 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
1028 int64_t offset
, int64_t bytes
,
1030 size_t qiov_offset
, int flags
)
1032 BlockDriver
*drv
= bs
->drv
;
1034 unsigned int nb_sectors
;
1035 QEMUIOVector local_qiov
;
1038 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1039 assert(!(flags
& ~bs
->supported_read_flags
));
1045 if (drv
->bdrv_co_preadv_part
) {
1046 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1050 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1051 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1055 if (drv
->bdrv_co_preadv
) {
1056 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
1060 if (drv
->bdrv_aio_preadv
) {
1062 CoroutineIOCompletion co
= {
1063 .coroutine
= qemu_coroutine_self(),
1066 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1067 bdrv_co_io_em_complete
, &co
);
1072 qemu_coroutine_yield();
1078 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1079 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1081 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1082 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1083 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1084 assert(drv
->bdrv_co_readv
);
1086 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1089 if (qiov
== &local_qiov
) {
1090 qemu_iovec_destroy(&local_qiov
);
1096 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1097 int64_t offset
, int64_t bytes
,
1100 BdrvRequestFlags flags
)
1102 BlockDriver
*drv
= bs
->drv
;
1103 bool emulate_fua
= false;
1105 unsigned int nb_sectors
;
1106 QEMUIOVector local_qiov
;
1109 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1115 if ((flags
& BDRV_REQ_FUA
) &&
1116 (~bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1117 flags
&= ~BDRV_REQ_FUA
;
1121 flags
&= bs
->supported_write_flags
;
1123 if (drv
->bdrv_co_pwritev_part
) {
1124 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1129 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1130 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1134 if (drv
->bdrv_co_pwritev
) {
1135 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1139 if (drv
->bdrv_aio_pwritev
) {
1141 CoroutineIOCompletion co
= {
1142 .coroutine
= qemu_coroutine_self(),
1145 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
, flags
,
1146 bdrv_co_io_em_complete
, &co
);
1150 qemu_coroutine_yield();
1156 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1157 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1159 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1160 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1161 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1163 assert(drv
->bdrv_co_writev
);
1164 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
, flags
);
1167 if (ret
== 0 && emulate_fua
) {
1168 ret
= bdrv_co_flush(bs
);
1171 if (qiov
== &local_qiov
) {
1172 qemu_iovec_destroy(&local_qiov
);
1178 static int coroutine_fn
1179 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1180 int64_t bytes
, QEMUIOVector
*qiov
,
1183 BlockDriver
*drv
= bs
->drv
;
1184 QEMUIOVector local_qiov
;
1187 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1193 if (!block_driver_can_compress(drv
)) {
1197 if (drv
->bdrv_co_pwritev_compressed_part
) {
1198 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1202 if (qiov_offset
== 0) {
1203 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1206 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1207 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1208 qemu_iovec_destroy(&local_qiov
);
1213 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1214 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1215 size_t qiov_offset
, int flags
)
1217 BlockDriverState
*bs
= child
->bs
;
1219 /* Perform I/O through a temporary buffer so that users who scribble over
1220 * their read buffer while the operation is in progress do not end up
1221 * modifying the image file. This is critical for zero-copy guest I/O
1222 * where anything might happen inside guest memory.
1224 void *bounce_buffer
= NULL
;
1226 BlockDriver
*drv
= bs
->drv
;
1227 int64_t cluster_offset
;
1228 int64_t cluster_bytes
;
1231 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1232 BDRV_REQUEST_MAX_BYTES
);
1233 int64_t progress
= 0;
1236 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1243 * Do not write anything when the BDS is inactive. That is not
1244 * allowed, and it would not help.
1246 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1248 /* FIXME We cannot require callers to have write permissions when all they
1249 * are doing is a read request. If we did things right, write permissions
1250 * would be obtained anyway, but internally by the copy-on-read code. As
1251 * long as it is implemented here rather than in a separate filter driver,
1252 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1253 * it could request permissions. Therefore we have to bypass the permission
1254 * system for the moment. */
1255 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1257 /* Cover entire cluster so no additional backing file I/O is required when
1258 * allocating cluster in the image file. Note that this value may exceed
1259 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1260 * is one reason we loop rather than doing it all at once.
1262 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1263 skip_bytes
= offset
- cluster_offset
;
1265 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1266 cluster_offset
, cluster_bytes
);
1268 while (cluster_bytes
) {
1272 ret
= 1; /* "already allocated", so nothing will be copied */
1273 pnum
= MIN(cluster_bytes
, max_transfer
);
1275 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1276 MIN(cluster_bytes
, max_transfer
), &pnum
);
1279 * Safe to treat errors in querying allocation as if
1280 * unallocated; we'll probably fail again soon on the
1281 * read, but at least that will set a decent errno.
1283 pnum
= MIN(cluster_bytes
, max_transfer
);
1286 /* Stop at EOF if the image ends in the middle of the cluster */
1287 if (ret
== 0 && pnum
== 0) {
1288 assert(progress
>= bytes
);
1292 assert(skip_bytes
< pnum
);
1296 QEMUIOVector local_qiov
;
1298 /* Must copy-on-read; use the bounce buffer */
1299 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1300 if (!bounce_buffer
) {
1301 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1302 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1303 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1305 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1306 if (!bounce_buffer
) {
1311 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1313 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1319 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1320 if (drv
->bdrv_co_pwrite_zeroes
&&
1321 buffer_is_zero(bounce_buffer
, pnum
)) {
1322 /* FIXME: Should we (perhaps conditionally) be setting
1323 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1324 * that still correctly reads as zero? */
1325 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1326 BDRV_REQ_WRITE_UNCHANGED
);
1328 /* This does not change the data on the disk, it is not
1329 * necessary to flush even in cache=writethrough mode.
1331 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1333 BDRV_REQ_WRITE_UNCHANGED
);
1337 /* It might be okay to ignore write errors for guest
1338 * requests. If this is a deliberate copy-on-read
1339 * then we don't want to ignore the error. Simply
1340 * report it in all cases.
1345 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1346 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1347 bounce_buffer
+ skip_bytes
,
1348 MIN(pnum
- skip_bytes
, bytes
- progress
));
1350 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1351 /* Read directly into the destination */
1352 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1353 MIN(pnum
- skip_bytes
, bytes
- progress
),
1354 qiov
, qiov_offset
+ progress
, 0);
1360 cluster_offset
+= pnum
;
1361 cluster_bytes
-= pnum
;
1362 progress
+= pnum
- skip_bytes
;
1368 qemu_vfree(bounce_buffer
);
1373 * Forwards an already correctly aligned request to the BlockDriver. This
1374 * handles copy on read, zeroing after EOF, and fragmentation of large
1375 * reads; any other features must be implemented by the caller.
1377 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1378 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1379 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1381 BlockDriverState
*bs
= child
->bs
;
1382 int64_t total_bytes
, max_bytes
;
1384 int64_t bytes_remaining
= bytes
;
1387 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1388 assert(is_power_of_2(align
));
1389 assert((offset
& (align
- 1)) == 0);
1390 assert((bytes
& (align
- 1)) == 0);
1391 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1392 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1396 * TODO: We would need a per-BDS .supported_read_flags and
1397 * potential fallback support, if we ever implement any read flags
1398 * to pass through to drivers. For now, there aren't any
1399 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1401 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
|
1402 BDRV_REQ_REGISTERED_BUF
)));
1404 /* Handle Copy on Read and associated serialisation */
1405 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1406 /* If we touch the same cluster it counts as an overlap. This
1407 * guarantees that allocating writes will be serialized and not race
1408 * with each other for the same cluster. For example, in copy-on-read
1409 * it ensures that the CoR read and write operations are atomic and
1410 * guest writes cannot interleave between them. */
1411 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1413 bdrv_wait_serialising_requests(req
);
1416 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1419 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1420 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1422 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1427 if (!ret
|| pnum
!= bytes
) {
1428 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1429 qiov
, qiov_offset
, flags
);
1431 } else if (flags
& BDRV_REQ_PREFETCH
) {
1436 /* Forward the request to the BlockDriver, possibly fragmenting it */
1437 total_bytes
= bdrv_getlength(bs
);
1438 if (total_bytes
< 0) {
1443 assert(!(flags
& ~(bs
->supported_read_flags
| BDRV_REQ_REGISTERED_BUF
)));
1445 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1446 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1447 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1451 while (bytes_remaining
) {
1455 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1458 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1460 qiov_offset
+ bytes
- bytes_remaining
,
1464 num
= bytes_remaining
;
1465 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1466 0, bytes_remaining
);
1471 bytes_remaining
-= num
;
1475 return ret
< 0 ? ret
: 0;
1481 * |<---- align ----->| |<----- align ---->|
1482 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1484 * -*----------$-------*-------- ... --------*-----$------------*---
1486 * | offset | | end |
1487 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1488 * [buf ... ) [tail_buf )
1490 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1491 * is placed at the beginning of @buf and @tail at the @end.
1493 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1494 * around tail, if tail exists.
1496 * @merge_reads is true for small requests,
1497 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1498 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1500 typedef struct BdrvRequestPadding
{
1507 QEMUIOVector local_qiov
;
1508 } BdrvRequestPadding
;
1510 static bool bdrv_init_padding(BlockDriverState
*bs
,
1511 int64_t offset
, int64_t bytes
,
1512 BdrvRequestPadding
*pad
)
1514 int64_t align
= bs
->bl
.request_alignment
;
1517 bdrv_check_request(offset
, bytes
, &error_abort
);
1518 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1519 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1521 memset(pad
, 0, sizeof(*pad
));
1523 pad
->head
= offset
& (align
- 1);
1524 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1526 pad
->tail
= align
- pad
->tail
;
1529 if (!pad
->head
&& !pad
->tail
) {
1533 assert(bytes
); /* Nothing good in aligning zero-length requests */
1535 sum
= pad
->head
+ bytes
+ pad
->tail
;
1536 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1537 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1538 pad
->merge_reads
= sum
== pad
->buf_len
;
1540 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1546 static coroutine_fn
int bdrv_padding_rmw_read(BdrvChild
*child
,
1547 BdrvTrackedRequest
*req
,
1548 BdrvRequestPadding
*pad
,
1551 QEMUIOVector local_qiov
;
1552 BlockDriverState
*bs
= child
->bs
;
1553 uint64_t align
= bs
->bl
.request_alignment
;
1556 assert(req
->serialising
&& pad
->buf
);
1558 if (pad
->head
|| pad
->merge_reads
) {
1559 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1561 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1564 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1566 if (pad
->merge_reads
&& pad
->tail
) {
1567 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1569 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1570 align
, &local_qiov
, 0, 0);
1575 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1577 if (pad
->merge_reads
&& pad
->tail
) {
1578 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1581 if (pad
->merge_reads
) {
1587 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1589 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1590 ret
= bdrv_aligned_preadv(
1592 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1593 align
, align
, &local_qiov
, 0, 0);
1597 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1602 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1608 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1611 qemu_vfree(pad
->buf
);
1612 qemu_iovec_destroy(&pad
->local_qiov
);
1614 memset(pad
, 0, sizeof(*pad
));
1620 * Exchange request parameters with padded request if needed. Don't include RMW
1621 * read of padding, bdrv_padding_rmw_read() should be called separately if
1624 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1625 * - on function start they represent original request
1626 * - on failure or when padding is not needed they are unchanged
1627 * - on success when padding is needed they represent padded request
1629 static int bdrv_pad_request(BlockDriverState
*bs
,
1630 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1631 int64_t *offset
, int64_t *bytes
,
1632 BdrvRequestPadding
*pad
, bool *padded
,
1633 BdrvRequestFlags
*flags
)
1637 bdrv_check_qiov_request(*offset
, *bytes
, *qiov
, *qiov_offset
, &error_abort
);
1639 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1646 ret
= qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1647 *qiov
, *qiov_offset
, *bytes
,
1648 pad
->buf
+ pad
->buf_len
- pad
->tail
,
1651 bdrv_padding_destroy(pad
);
1654 *bytes
+= pad
->head
+ pad
->tail
;
1655 *offset
-= pad
->head
;
1656 *qiov
= &pad
->local_qiov
;
1662 /* Can't use optimization hint with bounce buffer */
1663 *flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1669 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1670 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1671 BdrvRequestFlags flags
)
1674 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1677 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1678 int64_t offset
, int64_t bytes
,
1679 QEMUIOVector
*qiov
, size_t qiov_offset
,
1680 BdrvRequestFlags flags
)
1682 BlockDriverState
*bs
= child
->bs
;
1683 BdrvTrackedRequest req
;
1684 BdrvRequestPadding pad
;
1688 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1690 if (!bdrv_is_inserted(bs
)) {
1694 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1699 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1701 * Aligning zero request is nonsense. Even if driver has special meaning
1702 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1703 * it to driver due to request_alignment.
1705 * Still, no reason to return an error if someone do unaligned
1706 * zero-length read occasionally.
1711 bdrv_inc_in_flight(bs
);
1713 /* Don't do copy-on-read if we read data before write operation */
1714 if (qatomic_read(&bs
->copy_on_read
)) {
1715 flags
|= BDRV_REQ_COPY_ON_READ
;
1718 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
1724 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1725 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1726 bs
->bl
.request_alignment
,
1727 qiov
, qiov_offset
, flags
);
1728 tracked_request_end(&req
);
1729 bdrv_padding_destroy(&pad
);
1732 bdrv_dec_in_flight(bs
);
1737 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1738 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
1740 BlockDriver
*drv
= bs
->drv
;
1744 bool need_flush
= false;
1748 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1750 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1751 bs
->bl
.request_alignment
);
1752 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1754 bdrv_check_request(offset
, bytes
, &error_abort
);
1760 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1764 /* By definition there is no user buffer so this flag doesn't make sense */
1765 if (flags
& BDRV_REQ_REGISTERED_BUF
) {
1769 /* Invalidate the cached block-status data range if this write overlaps */
1770 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1772 assert(alignment
% bs
->bl
.request_alignment
== 0);
1773 head
= offset
% alignment
;
1774 tail
= (offset
+ bytes
) % alignment
;
1775 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1776 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1778 while (bytes
> 0 && !ret
) {
1779 int64_t num
= bytes
;
1781 /* Align request. Block drivers can expect the "bulk" of the request
1782 * to be aligned, and that unaligned requests do not cross cluster
1786 /* Make a small request up to the first aligned sector. For
1787 * convenience, limit this request to max_transfer even if
1788 * we don't need to fall back to writes. */
1789 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1790 head
= (head
+ num
) % alignment
;
1791 assert(num
< max_write_zeroes
);
1792 } else if (tail
&& num
> alignment
) {
1793 /* Shorten the request to the last aligned sector. */
1797 /* limit request size */
1798 if (num
> max_write_zeroes
) {
1799 num
= max_write_zeroes
;
1803 /* First try the efficient write zeroes operation */
1804 if (drv
->bdrv_co_pwrite_zeroes
) {
1805 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1806 flags
& bs
->supported_zero_flags
);
1807 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1808 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1812 assert(!bs
->supported_zero_flags
);
1815 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1816 /* Fall back to bounce buffer if write zeroes is unsupported */
1817 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1819 if ((flags
& BDRV_REQ_FUA
) &&
1820 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1821 /* No need for bdrv_driver_pwrite() to do a fallback
1822 * flush on each chunk; use just one at the end */
1823 write_flags
&= ~BDRV_REQ_FUA
;
1826 num
= MIN(num
, max_transfer
);
1828 buf
= qemu_try_blockalign0(bs
, num
);
1834 qemu_iovec_init_buf(&qiov
, buf
, num
);
1836 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1838 /* Keep bounce buffer around if it is big enough for all
1839 * all future requests.
1841 if (num
< max_transfer
) {
1852 if (ret
== 0 && need_flush
) {
1853 ret
= bdrv_co_flush(bs
);
1859 static inline int coroutine_fn
1860 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1861 BdrvTrackedRequest
*req
, int flags
)
1863 BlockDriverState
*bs
= child
->bs
;
1865 bdrv_check_request(offset
, bytes
, &error_abort
);
1867 if (bdrv_is_read_only(bs
)) {
1871 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1872 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1873 assert(!(flags
& ~BDRV_REQ_MASK
));
1874 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
1876 if (flags
& BDRV_REQ_SERIALISING
) {
1877 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
1879 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
1881 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
1885 bdrv_wait_serialising_requests_locked(req
);
1887 bdrv_wait_serialising_requests(req
);
1890 assert(req
->overlap_offset
<= offset
);
1891 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1892 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
1893 child
->perm
& BLK_PERM_RESIZE
);
1895 switch (req
->type
) {
1896 case BDRV_TRACKED_WRITE
:
1897 case BDRV_TRACKED_DISCARD
:
1898 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1899 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1901 assert(child
->perm
& BLK_PERM_WRITE
);
1903 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
1905 case BDRV_TRACKED_TRUNCATE
:
1906 assert(child
->perm
& BLK_PERM_RESIZE
);
1913 static inline void coroutine_fn
1914 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1915 BdrvTrackedRequest
*req
, int ret
)
1917 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1918 BlockDriverState
*bs
= child
->bs
;
1920 bdrv_check_request(offset
, bytes
, &error_abort
);
1922 qatomic_inc(&bs
->write_gen
);
1925 * Discard cannot extend the image, but in error handling cases, such as
1926 * when reverting a qcow2 cluster allocation, the discarded range can pass
1927 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1928 * here. Instead, just skip it, since semantically a discard request
1929 * beyond EOF cannot expand the image anyway.
1932 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1933 end_sector
> bs
->total_sectors
) &&
1934 req
->type
!= BDRV_TRACKED_DISCARD
) {
1935 bs
->total_sectors
= end_sector
;
1936 bdrv_parent_cb_resize(bs
);
1937 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1940 switch (req
->type
) {
1941 case BDRV_TRACKED_WRITE
:
1942 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1943 /* fall through, to set dirty bits */
1944 case BDRV_TRACKED_DISCARD
:
1945 bdrv_set_dirty(bs
, offset
, bytes
);
1954 * Forwards an already correctly aligned write request to the BlockDriver,
1955 * after possibly fragmenting it.
1957 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1958 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1959 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
,
1960 BdrvRequestFlags flags
)
1962 BlockDriverState
*bs
= child
->bs
;
1963 BlockDriver
*drv
= bs
->drv
;
1966 int64_t bytes_remaining
= bytes
;
1969 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1975 if (bdrv_has_readonly_bitmaps(bs
)) {
1979 assert(is_power_of_2(align
));
1980 assert((offset
& (align
- 1)) == 0);
1981 assert((bytes
& (align
- 1)) == 0);
1982 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1985 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1987 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1988 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1989 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
1990 flags
|= BDRV_REQ_ZERO_WRITE
;
1991 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1992 flags
|= BDRV_REQ_MAY_UNMAP
;
1997 /* Do nothing, write notifier decided to fail this request */
1998 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1999 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
2000 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
2001 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
2002 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
2004 } else if (bytes
<= max_transfer
) {
2005 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
2006 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
2008 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
2009 while (bytes_remaining
) {
2010 int num
= MIN(bytes_remaining
, max_transfer
);
2011 int local_flags
= flags
;
2014 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
2015 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
2016 /* If FUA is going to be emulated by flush, we only
2017 * need to flush on the last iteration */
2018 local_flags
&= ~BDRV_REQ_FUA
;
2021 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
2023 qiov_offset
+ bytes
- bytes_remaining
,
2028 bytes_remaining
-= num
;
2031 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
2036 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
2041 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
2044 BdrvRequestFlags flags
,
2045 BdrvTrackedRequest
*req
)
2047 BlockDriverState
*bs
= child
->bs
;
2048 QEMUIOVector local_qiov
;
2049 uint64_t align
= bs
->bl
.request_alignment
;
2052 BdrvRequestPadding pad
;
2054 /* This flag doesn't make sense for padding or zero writes */
2055 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
2057 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
2059 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2060 bdrv_make_request_serialising(req
, align
);
2062 bdrv_padding_rmw_read(child
, req
, &pad
, true);
2064 if (pad
.head
|| pad
.merge_reads
) {
2065 int64_t aligned_offset
= offset
& ~(align
- 1);
2066 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
2068 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
2069 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
2070 align
, &local_qiov
, 0,
2071 flags
& ~BDRV_REQ_ZERO_WRITE
);
2072 if (ret
< 0 || pad
.merge_reads
) {
2073 /* Error or all work is done */
2076 offset
+= write_bytes
- pad
.head
;
2077 bytes
-= write_bytes
- pad
.head
;
2081 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2082 if (bytes
>= align
) {
2083 /* Write the aligned part in the middle. */
2084 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2085 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2090 bytes
-= aligned_bytes
;
2091 offset
+= aligned_bytes
;
2094 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2096 assert(align
== pad
.tail
+ bytes
);
2098 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2099 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2101 flags
& ~BDRV_REQ_ZERO_WRITE
);
2105 bdrv_padding_destroy(&pad
);
2111 * Handle a write request in coroutine context
2113 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2114 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2115 BdrvRequestFlags flags
)
2118 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2121 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2122 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2123 BdrvRequestFlags flags
)
2125 BlockDriverState
*bs
= child
->bs
;
2126 BdrvTrackedRequest req
;
2127 uint64_t align
= bs
->bl
.request_alignment
;
2128 BdrvRequestPadding pad
;
2130 bool padded
= false;
2133 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2135 if (!bdrv_is_inserted(bs
)) {
2139 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2140 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2142 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2148 /* If the request is misaligned then we can't make it efficient */
2149 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2150 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2155 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2157 * Aligning zero request is nonsense. Even if driver has special meaning
2158 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2159 * it to driver due to request_alignment.
2161 * Still, no reason to return an error if someone do unaligned
2162 * zero-length write occasionally.
2167 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2169 * Pad request for following read-modify-write cycle.
2170 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2171 * alignment only if there is no ZERO flag.
2173 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
2180 bdrv_inc_in_flight(bs
);
2181 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2183 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2185 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2191 * Request was unaligned to request_alignment and therefore
2192 * padded. We are going to do read-modify-write, and must
2193 * serialize the request to prevent interactions of the
2194 * widened region with other transactions.
2196 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2197 bdrv_make_request_serialising(&req
, align
);
2198 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2201 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2202 qiov
, qiov_offset
, flags
);
2204 bdrv_padding_destroy(&pad
);
2207 tracked_request_end(&req
);
2208 bdrv_dec_in_flight(bs
);
2213 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2214 int64_t bytes
, BdrvRequestFlags flags
)
2217 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2219 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2220 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2223 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2224 BDRV_REQ_ZERO_WRITE
| flags
);
2228 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2230 int bdrv_flush_all(void)
2232 BdrvNextIterator it
;
2233 BlockDriverState
*bs
= NULL
;
2236 GLOBAL_STATE_CODE();
2239 * bdrv queue is managed by record/replay,
2240 * creating new flush request for stopping
2241 * the VM may break the determinism
2243 if (replay_events_enabled()) {
2247 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2248 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2251 aio_context_acquire(aio_context
);
2252 ret
= bdrv_flush(bs
);
2253 if (ret
< 0 && !result
) {
2256 aio_context_release(aio_context
);
2263 * Returns the allocation status of the specified sectors.
2264 * Drivers not implementing the functionality are assumed to not support
2265 * backing files, hence all their sectors are reported as allocated.
2267 * If 'want_zero' is true, the caller is querying for mapping
2268 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2269 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2270 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2272 * If 'offset' is beyond the end of the disk image the return value is
2273 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2275 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2276 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2277 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2279 * 'pnum' is set to the number of bytes (including and immediately
2280 * following the specified offset) that are easily known to be in the
2281 * same allocated/unallocated state. Note that a second call starting
2282 * at the original offset plus returned pnum may have the same status.
2283 * The returned value is non-zero on success except at end-of-file.
2285 * Returns negative errno on failure. Otherwise, if the
2286 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2287 * set to the host mapping and BDS corresponding to the guest offset.
2289 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2291 int64_t offset
, int64_t bytes
,
2292 int64_t *pnum
, int64_t *map
,
2293 BlockDriverState
**file
)
2296 int64_t n
; /* bytes */
2298 int64_t local_map
= 0;
2299 BlockDriverState
*local_file
= NULL
;
2300 int64_t aligned_offset
, aligned_bytes
;
2302 bool has_filtered_child
;
2306 total_size
= bdrv_getlength(bs
);
2307 if (total_size
< 0) {
2312 if (offset
>= total_size
) {
2313 ret
= BDRV_BLOCK_EOF
;
2321 n
= total_size
- offset
;
2326 /* Must be non-NULL or bdrv_getlength() would have failed */
2328 has_filtered_child
= bdrv_filter_child(bs
);
2329 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2331 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2332 if (offset
+ bytes
== total_size
) {
2333 ret
|= BDRV_BLOCK_EOF
;
2335 if (bs
->drv
->protocol_name
) {
2336 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2343 bdrv_inc_in_flight(bs
);
2345 /* Round out to request_alignment boundaries */
2346 align
= bs
->bl
.request_alignment
;
2347 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2348 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2350 if (bs
->drv
->bdrv_co_block_status
) {
2352 * Use the block-status cache only for protocol nodes: Format
2353 * drivers are generally quick to inquire the status, but protocol
2354 * drivers often need to get information from outside of qemu, so
2355 * we do not have control over the actual implementation. There
2356 * have been cases where inquiring the status took an unreasonably
2357 * long time, and we can do nothing in qemu to fix it.
2358 * This is especially problematic for images with large data areas,
2359 * because finding the few holes in them and giving them special
2360 * treatment does not gain much performance. Therefore, we try to
2361 * cache the last-identified data region.
2363 * Second, limiting ourselves to protocol nodes allows us to assume
2364 * the block status for data regions to be DATA | OFFSET_VALID, and
2365 * that the host offset is the same as the guest offset.
2367 * Note that it is possible that external writers zero parts of
2368 * the cached regions without the cache being invalidated, and so
2369 * we may report zeroes as data. This is not catastrophic,
2370 * however, because reporting zeroes as data is fine.
2372 if (QLIST_EMPTY(&bs
->children
) &&
2373 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2375 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2377 local_map
= aligned_offset
;
2379 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2380 aligned_bytes
, pnum
, &local_map
,
2384 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2385 * the cache is queried above. Technically, we do not need to check
2386 * it here; the worst that can happen is that we fill the cache for
2387 * non-protocol nodes, and then it is never used. However, filling
2388 * the cache requires an RCU update, so double check here to avoid
2389 * such an update if possible.
2391 * Check want_zero, because we only want to update the cache when we
2392 * have accurate information about what is zero and what is data.
2395 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2396 QLIST_EMPTY(&bs
->children
))
2399 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2400 * returned local_map value must be the same as the offset we
2401 * have passed (aligned_offset), and local_bs must be the node
2403 * Assert this, because we follow this rule when reading from
2404 * the cache (see the `local_file = bs` and
2405 * `local_map = aligned_offset` assignments above), and the
2406 * result the cache delivers must be the same as the driver
2409 assert(local_file
== bs
);
2410 assert(local_map
== aligned_offset
);
2411 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2415 /* Default code for filters */
2417 local_file
= bdrv_filter_bs(bs
);
2420 *pnum
= aligned_bytes
;
2421 local_map
= aligned_offset
;
2422 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2430 * The driver's result must be a non-zero multiple of request_alignment.
2431 * Clamp pnum and adjust map to original request.
2433 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2434 align
> offset
- aligned_offset
);
2435 if (ret
& BDRV_BLOCK_RECURSE
) {
2436 assert(ret
& BDRV_BLOCK_DATA
);
2437 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2438 assert(!(ret
& BDRV_BLOCK_ZERO
));
2441 *pnum
-= offset
- aligned_offset
;
2442 if (*pnum
> bytes
) {
2445 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2446 local_map
+= offset
- aligned_offset
;
2449 if (ret
& BDRV_BLOCK_RAW
) {
2450 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2451 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2452 *pnum
, pnum
, &local_map
, &local_file
);
2456 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2457 ret
|= BDRV_BLOCK_ALLOCATED
;
2458 } else if (bs
->drv
->supports_backing
) {
2459 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2462 ret
|= BDRV_BLOCK_ZERO
;
2463 } else if (want_zero
) {
2464 int64_t size2
= bdrv_getlength(cow_bs
);
2466 if (size2
>= 0 && offset
>= size2
) {
2467 ret
|= BDRV_BLOCK_ZERO
;
2472 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2473 local_file
&& local_file
!= bs
&&
2474 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2475 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2479 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2480 *pnum
, &file_pnum
, NULL
, NULL
);
2482 /* Ignore errors. This is just providing extra information, it
2483 * is useful but not necessary.
2485 if (ret2
& BDRV_BLOCK_EOF
&&
2486 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2488 * It is valid for the format block driver to read
2489 * beyond the end of the underlying file's current
2490 * size; such areas read as zero.
2492 ret
|= BDRV_BLOCK_ZERO
;
2494 /* Limit request to the range reported by the protocol driver */
2496 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2502 bdrv_dec_in_flight(bs
);
2503 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2504 ret
|= BDRV_BLOCK_EOF
;
2517 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2518 BlockDriverState
*base
,
2525 BlockDriverState
**file
,
2529 BlockDriverState
*p
;
2534 assert(!include_base
|| base
); /* Can't include NULL base */
2541 if (!include_base
&& bs
== base
) {
2546 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2548 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2552 if (ret
& BDRV_BLOCK_EOF
) {
2553 eof
= offset
+ *pnum
;
2556 assert(*pnum
<= bytes
);
2559 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2560 p
= bdrv_filter_or_cow_bs(p
))
2562 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2570 * The top layer deferred to this layer, and because this layer is
2571 * short, any zeroes that we synthesize beyond EOF behave as if they
2572 * were allocated at this layer.
2574 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2575 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2578 assert(ret
& BDRV_BLOCK_EOF
);
2583 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2586 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2588 * We've found the node and the status, we must break.
2590 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2591 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2594 ret
&= ~BDRV_BLOCK_EOF
;
2599 assert(include_base
);
2604 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2605 * let's continue the diving.
2607 assert(*pnum
<= bytes
);
2611 if (offset
+ *pnum
== eof
) {
2612 ret
|= BDRV_BLOCK_EOF
;
2618 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2619 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2620 int64_t *map
, BlockDriverState
**file
)
2623 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2624 pnum
, map
, file
, NULL
);
2627 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2628 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2631 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2632 offset
, bytes
, pnum
, map
, file
);
2636 * Check @bs (and its backing chain) to see if the range defined
2637 * by @offset and @bytes is known to read as zeroes.
2638 * Return 1 if that is the case, 0 otherwise and -errno on error.
2639 * This test is meant to be fast rather than accurate so returning 0
2640 * does not guarantee non-zero data.
2642 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2646 int64_t pnum
= bytes
;
2653 ret
= bdrv_co_common_block_status_above(bs
, NULL
, false, false, offset
,
2654 bytes
, &pnum
, NULL
, NULL
, NULL
);
2660 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2663 int bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2670 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2671 bytes
, pnum
? pnum
: &dummy
, NULL
,
2676 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2680 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2682 * Return a positive depth if (a prefix of) the given range is allocated
2683 * in any image between BASE and TOP (BASE is only included if include_base
2684 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2685 * BASE can be NULL to check if the given offset is allocated in any
2686 * image of the chain. Return 0 otherwise, or negative errno on
2689 * 'pnum' is set to the number of bytes (including and immediately
2690 * following the specified offset) that are known to be in the same
2691 * allocated/unallocated state. Note that a subsequent call starting
2692 * at 'offset + *pnum' may return the same allocation status (in other
2693 * words, the result is not necessarily the maximum possible range);
2694 * but 'pnum' will only be 0 when end of file is reached.
2696 int bdrv_is_allocated_above(BlockDriverState
*top
,
2697 BlockDriverState
*base
,
2698 bool include_base
, int64_t offset
,
2699 int64_t bytes
, int64_t *pnum
)
2702 int ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2703 offset
, bytes
, pnum
, NULL
, NULL
,
2710 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2717 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2719 BlockDriver
*drv
= bs
->drv
;
2720 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2724 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2733 bdrv_inc_in_flight(bs
);
2735 if (drv
->bdrv_load_vmstate
) {
2736 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2737 } else if (child_bs
) {
2738 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2743 bdrv_dec_in_flight(bs
);
2749 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2751 BlockDriver
*drv
= bs
->drv
;
2752 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2756 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2765 bdrv_inc_in_flight(bs
);
2767 if (drv
->bdrv_save_vmstate
) {
2768 ret
= drv
->bdrv_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 bdrv_inc_in_flight(bs
);
2849 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2854 qemu_co_mutex_lock(&bs
->reqs_lock
);
2855 current_gen
= qatomic_read(&bs
->write_gen
);
2857 /* Wait until any previous flushes are completed */
2858 while (bs
->active_flush_req
) {
2859 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2862 /* Flushes reach this point in nondecreasing current_gen order. */
2863 bs
->active_flush_req
= true;
2864 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2866 /* Write back all layers by calling one driver function */
2867 if (bs
->drv
->bdrv_co_flush
) {
2868 ret
= bs
->drv
->bdrv_co_flush(bs
);
2872 /* Write back cached data to the OS even with cache=unsafe */
2873 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2874 if (bs
->drv
->bdrv_co_flush_to_os
) {
2875 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2881 /* But don't actually force it to the disk with cache=unsafe */
2882 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2883 goto flush_children
;
2886 /* Check if we really need to flush anything */
2887 if (bs
->flushed_gen
== current_gen
) {
2888 goto flush_children
;
2891 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2893 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2894 * (even in case of apparent success) */
2898 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2899 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2900 } else if (bs
->drv
->bdrv_aio_flush
) {
2902 CoroutineIOCompletion co
= {
2903 .coroutine
= qemu_coroutine_self(),
2906 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2910 qemu_coroutine_yield();
2915 * Some block drivers always operate in either writethrough or unsafe
2916 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2917 * know how the server works (because the behaviour is hardcoded or
2918 * depends on server-side configuration), so we can't ensure that
2919 * everything is safe on disk. Returning an error doesn't work because
2920 * that would break guests even if the server operates in writethrough
2923 * Let's hope the user knows what he's doing.
2932 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2933 * in the case of cache=unsafe, so there are no useless flushes.
2937 QLIST_FOREACH(child
, &bs
->children
, next
) {
2938 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2939 int this_child_ret
= bdrv_co_flush(child
->bs
);
2941 ret
= this_child_ret
;
2947 /* Notify any pending flushes that we have completed */
2949 bs
->flushed_gen
= current_gen
;
2952 qemu_co_mutex_lock(&bs
->reqs_lock
);
2953 bs
->active_flush_req
= false;
2954 /* Return value is ignored - it's ok if wait queue is empty */
2955 qemu_co_queue_next(&bs
->flush_queue
);
2956 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2959 bdrv_dec_in_flight(bs
);
2963 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2966 BdrvTrackedRequest req
;
2968 int64_t max_pdiscard
;
2969 int head
, tail
, align
;
2970 BlockDriverState
*bs
= child
->bs
;
2973 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
2977 if (bdrv_has_readonly_bitmaps(bs
)) {
2981 ret
= bdrv_check_request(offset
, bytes
, NULL
);
2986 /* Do nothing if disabled. */
2987 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2991 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2995 /* Invalidate the cached block-status data range if this discard overlaps */
2996 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
2998 /* Discard is advisory, but some devices track and coalesce
2999 * unaligned requests, so we must pass everything down rather than
3000 * round here. Still, most devices will just silently ignore
3001 * unaligned requests (by returning -ENOTSUP), so we must fragment
3002 * the request accordingly. */
3003 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
3004 assert(align
% bs
->bl
.request_alignment
== 0);
3005 head
= offset
% align
;
3006 tail
= (offset
+ bytes
) % align
;
3008 bdrv_inc_in_flight(bs
);
3009 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
3011 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
3016 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
3018 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
3021 int64_t num
= bytes
;
3024 /* Make small requests to get to alignment boundaries. */
3025 num
= MIN(bytes
, align
- head
);
3026 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
3027 num
%= bs
->bl
.request_alignment
;
3029 head
= (head
+ num
) % align
;
3030 assert(num
< max_pdiscard
);
3033 /* Shorten the request to the last aligned cluster. */
3035 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
3036 tail
> bs
->bl
.request_alignment
) {
3037 tail
%= bs
->bl
.request_alignment
;
3041 /* limit request size */
3042 if (num
> max_pdiscard
) {
3050 if (bs
->drv
->bdrv_co_pdiscard
) {
3051 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
3054 CoroutineIOCompletion co
= {
3055 .coroutine
= qemu_coroutine_self(),
3058 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
3059 bdrv_co_io_em_complete
, &co
);
3064 qemu_coroutine_yield();
3068 if (ret
&& ret
!= -ENOTSUP
) {
3077 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3078 tracked_request_end(&req
);
3079 bdrv_dec_in_flight(bs
);
3083 int coroutine_fn
bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3085 BlockDriver
*drv
= bs
->drv
;
3086 CoroutineIOCompletion co
= {
3087 .coroutine
= qemu_coroutine_self(),
3092 bdrv_inc_in_flight(bs
);
3093 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3098 if (drv
->bdrv_co_ioctl
) {
3099 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3101 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3106 qemu_coroutine_yield();
3109 bdrv_dec_in_flight(bs
);
3113 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3116 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3119 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3122 return memset(qemu_blockalign(bs
, size
), 0, size
);
3125 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3127 size_t align
= bdrv_opt_mem_align(bs
);
3130 /* Ensure that NULL is never returned on success */
3136 return qemu_try_memalign(align
, size
);
3139 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3141 void *mem
= qemu_try_blockalign(bs
, size
);
3145 memset(mem
, 0, size
);
3151 void bdrv_io_plug(BlockDriverState
*bs
)
3156 QLIST_FOREACH(child
, &bs
->children
, next
) {
3157 bdrv_io_plug(child
->bs
);
3160 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
3161 BlockDriver
*drv
= bs
->drv
;
3162 if (drv
&& drv
->bdrv_io_plug
) {
3163 drv
->bdrv_io_plug(bs
);
3168 void bdrv_io_unplug(BlockDriverState
*bs
)
3173 assert(bs
->io_plugged
);
3174 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
3175 BlockDriver
*drv
= bs
->drv
;
3176 if (drv
&& drv
->bdrv_io_unplug
) {
3177 drv
->bdrv_io_unplug(bs
);
3181 QLIST_FOREACH(child
, &bs
->children
, next
) {
3182 bdrv_io_unplug(child
->bs
);
3186 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3187 static void bdrv_register_buf_rollback(BlockDriverState
*bs
,
3190 BdrvChild
*final_child
)
3194 QLIST_FOREACH(child
, &bs
->children
, next
) {
3195 if (child
== final_child
) {
3199 bdrv_unregister_buf(child
->bs
, host
, size
);
3202 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3203 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3207 bool bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
3212 GLOBAL_STATE_CODE();
3213 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3214 if (!bs
->drv
->bdrv_register_buf(bs
, host
, size
, errp
)) {
3218 QLIST_FOREACH(child
, &bs
->children
, next
) {
3219 if (!bdrv_register_buf(child
->bs
, host
, size
, errp
)) {
3220 bdrv_register_buf_rollback(bs
, host
, size
, child
);
3227 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3231 GLOBAL_STATE_CODE();
3232 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3233 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3235 QLIST_FOREACH(child
, &bs
->children
, next
) {
3236 bdrv_unregister_buf(child
->bs
, host
, size
);
3240 static int coroutine_fn
bdrv_co_copy_range_internal(
3241 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3242 int64_t dst_offset
, int64_t bytes
,
3243 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3246 BdrvTrackedRequest req
;
3249 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3250 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3251 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3252 assert(!(read_flags
& BDRV_REQ_NO_WAIT
));
3253 assert(!(write_flags
& BDRV_REQ_NO_WAIT
));
3255 if (!dst
|| !dst
->bs
|| !bdrv_is_inserted(dst
->bs
)) {
3258 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3262 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3263 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3266 if (!src
|| !src
->bs
|| !bdrv_is_inserted(src
->bs
)) {
3269 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3274 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3275 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3276 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3281 bdrv_inc_in_flight(src
->bs
);
3282 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3285 /* BDRV_REQ_SERIALISING is only for write operation */
3286 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3287 bdrv_wait_serialising_requests(&req
);
3289 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3293 read_flags
, write_flags
);
3295 tracked_request_end(&req
);
3296 bdrv_dec_in_flight(src
->bs
);
3298 bdrv_inc_in_flight(dst
->bs
);
3299 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3300 BDRV_TRACKED_WRITE
);
3301 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3304 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3308 read_flags
, write_flags
);
3310 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3311 tracked_request_end(&req
);
3312 bdrv_dec_in_flight(dst
->bs
);
3318 /* Copy range from @src to @dst.
3320 * See the comment of bdrv_co_copy_range for the parameter and return value
3322 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3323 BdrvChild
*dst
, int64_t dst_offset
,
3325 BdrvRequestFlags read_flags
,
3326 BdrvRequestFlags write_flags
)
3329 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3330 read_flags
, write_flags
);
3331 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3332 bytes
, read_flags
, write_flags
, true);
3335 /* Copy range from @src to @dst.
3337 * See the comment of bdrv_co_copy_range for the parameter and return value
3339 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3340 BdrvChild
*dst
, int64_t dst_offset
,
3342 BdrvRequestFlags read_flags
,
3343 BdrvRequestFlags write_flags
)
3346 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3347 read_flags
, write_flags
);
3348 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3349 bytes
, read_flags
, write_flags
, false);
3352 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3353 BdrvChild
*dst
, int64_t dst_offset
,
3354 int64_t bytes
, BdrvRequestFlags read_flags
,
3355 BdrvRequestFlags write_flags
)
3358 return bdrv_co_copy_range_from(src
, src_offset
,
3360 bytes
, read_flags
, write_flags
);
3363 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3366 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3367 if (c
->klass
->resize
) {
3368 c
->klass
->resize(c
);
3374 * Truncate file to 'offset' bytes (needed only for file protocols)
3376 * If 'exact' is true, the file must be resized to exactly the given
3377 * 'offset'. Otherwise, it is sufficient for the node to be at least
3378 * 'offset' bytes in length.
3380 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3381 PreallocMode prealloc
, BdrvRequestFlags flags
,
3384 BlockDriverState
*bs
= child
->bs
;
3385 BdrvChild
*filtered
, *backing
;
3386 BlockDriver
*drv
= bs
->drv
;
3387 BdrvTrackedRequest req
;
3388 int64_t old_size
, new_bytes
;
3392 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3394 error_setg(errp
, "No medium inserted");
3398 error_setg(errp
, "Image size cannot be negative");
3402 ret
= bdrv_check_request(offset
, 0, errp
);
3407 old_size
= bdrv_getlength(bs
);
3409 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3413 if (bdrv_is_read_only(bs
)) {
3414 error_setg(errp
, "Image is read-only");
3418 if (offset
> old_size
) {
3419 new_bytes
= offset
- old_size
;
3424 bdrv_inc_in_flight(bs
);
3425 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3426 BDRV_TRACKED_TRUNCATE
);
3428 /* If we are growing the image and potentially using preallocation for the
3429 * new area, we need to make sure that no write requests are made to it
3430 * concurrently or they might be overwritten by preallocation. */
3432 bdrv_make_request_serialising(&req
, 1);
3434 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3437 error_setg_errno(errp
, -ret
,
3438 "Failed to prepare request for truncation");
3442 filtered
= bdrv_filter_child(bs
);
3443 backing
= bdrv_cow_child(bs
);
3446 * If the image has a backing file that is large enough that it would
3447 * provide data for the new area, we cannot leave it unallocated because
3448 * then the backing file content would become visible. Instead, zero-fill
3451 * Note that if the image has a backing file, but was opened without the
3452 * backing file, taking care of keeping things consistent with that backing
3453 * file is the user's responsibility.
3455 if (new_bytes
&& backing
) {
3456 int64_t backing_len
;
3458 backing_len
= bdrv_getlength(backing
->bs
);
3459 if (backing_len
< 0) {
3461 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3465 if (backing_len
> old_size
) {
3466 flags
|= BDRV_REQ_ZERO_WRITE
;
3470 if (drv
->bdrv_co_truncate
) {
3471 if (flags
& ~bs
->supported_truncate_flags
) {
3472 error_setg(errp
, "Block driver does not support requested flags");
3476 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3477 } else if (filtered
) {
3478 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3480 error_setg(errp
, "Image format driver does not support resize");
3488 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3490 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3492 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3494 /* It's possible that truncation succeeded but refresh_total_sectors
3495 * failed, but the latter doesn't affect how we should finish the request.
3496 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3497 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3500 tracked_request_end(&req
);
3501 bdrv_dec_in_flight(bs
);
3506 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3508 GLOBAL_STATE_CODE();
3509 if (!bs
|| !bs
->drv
) {
3513 if (bs
->drv
->bdrv_cancel_in_flight
) {
3514 bs
->drv
->bdrv_cancel_in_flight(bs
);
3519 bdrv_co_preadv_snapshot(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
3520 QEMUIOVector
*qiov
, size_t qiov_offset
)
3522 BlockDriverState
*bs
= child
->bs
;
3523 BlockDriver
*drv
= bs
->drv
;
3531 if (!drv
->bdrv_co_preadv_snapshot
) {
3535 bdrv_inc_in_flight(bs
);
3536 ret
= drv
->bdrv_co_preadv_snapshot(bs
, offset
, bytes
, qiov
, qiov_offset
);
3537 bdrv_dec_in_flight(bs
);
3543 bdrv_co_snapshot_block_status(BlockDriverState
*bs
,
3544 bool want_zero
, int64_t offset
, int64_t bytes
,
3545 int64_t *pnum
, int64_t *map
,
3546 BlockDriverState
**file
)
3548 BlockDriver
*drv
= bs
->drv
;
3556 if (!drv
->bdrv_co_snapshot_block_status
) {
3560 bdrv_inc_in_flight(bs
);
3561 ret
= drv
->bdrv_co_snapshot_block_status(bs
, want_zero
, offset
, bytes
,
3563 bdrv_dec_in_flight(bs
);
3569 bdrv_co_pdiscard_snapshot(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3571 BlockDriver
*drv
= bs
->drv
;
3579 if (!drv
->bdrv_co_pdiscard_snapshot
) {
3583 bdrv_inc_in_flight(bs
);
3584 ret
= drv
->bdrv_co_pdiscard_snapshot(bs
, offset
, bytes
);
3585 bdrv_dec_in_flight(bs
);