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 coroutine_fn GRAPH_RDLOCK
46 bdrv_parent_cb_resize(BlockDriverState
*bs
);
48 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
49 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
);
51 static void GRAPH_RDLOCK
52 bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
)
56 assert_bdrv_graph_readable();
58 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
62 bdrv_parent_drained_begin_single(c
);
66 void bdrv_parent_drained_end_single(BdrvChild
*c
)
70 assert(c
->quiesced_parent
);
71 c
->quiesced_parent
= false;
73 if (c
->klass
->drained_end
) {
74 c
->klass
->drained_end(c
);
78 static void GRAPH_RDLOCK
79 bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
)
83 assert_bdrv_graph_readable();
85 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
89 bdrv_parent_drained_end_single(c
);
93 bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
97 if (c
->klass
->drained_poll
) {
98 return c
->klass
->drained_poll(c
);
103 static bool GRAPH_RDLOCK
104 bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
105 bool ignore_bds_parents
)
110 assert_bdrv_graph_readable();
112 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
113 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
116 busy
|= bdrv_parent_drained_poll_single(c
);
122 void bdrv_parent_drained_begin_single(BdrvChild
*c
)
126 assert(!c
->quiesced_parent
);
127 c
->quiesced_parent
= true;
129 if (c
->klass
->drained_begin
) {
130 /* called with rdlock taken, but it doesn't really need it. */
131 c
->klass
->drained_begin(c
);
135 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
137 dst
->pdiscard_alignment
= MAX(dst
->pdiscard_alignment
,
138 src
->pdiscard_alignment
);
139 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
140 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
141 dst
->max_hw_transfer
= MIN_NON_ZERO(dst
->max_hw_transfer
,
142 src
->max_hw_transfer
);
143 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
144 src
->opt_mem_alignment
);
145 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
146 src
->min_mem_alignment
);
147 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
148 dst
->max_hw_iov
= MIN_NON_ZERO(dst
->max_hw_iov
, src
->max_hw_iov
);
151 typedef struct BdrvRefreshLimitsState
{
152 BlockDriverState
*bs
;
154 } BdrvRefreshLimitsState
;
156 static void bdrv_refresh_limits_abort(void *opaque
)
158 BdrvRefreshLimitsState
*s
= opaque
;
160 s
->bs
->bl
= s
->old_bl
;
163 static TransactionActionDrv bdrv_refresh_limits_drv
= {
164 .abort
= bdrv_refresh_limits_abort
,
168 /* @tran is allowed to be NULL, in this case no rollback is possible. */
169 void bdrv_refresh_limits(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
172 BlockDriver
*drv
= bs
->drv
;
179 BdrvRefreshLimitsState
*s
= g_new(BdrvRefreshLimitsState
, 1);
180 *s
= (BdrvRefreshLimitsState
) {
184 tran_add(tran
, &bdrv_refresh_limits_drv
, s
);
187 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
193 /* Default alignment based on whether driver has byte interface */
194 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
195 drv
->bdrv_aio_preadv
||
196 drv
->bdrv_co_preadv_part
) ? 1 : 512;
198 /* Take some limits from the children as a default */
200 QLIST_FOREACH(c
, &bs
->children
, next
) {
201 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
203 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
207 if (c
->role
& BDRV_CHILD_FILTERED
) {
208 bs
->bl
.has_variable_length
|= c
->bs
->bl
.has_variable_length
;
213 bs
->bl
.min_mem_alignment
= 512;
214 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size();
216 /* Safe default since most protocols use readv()/writev()/etc */
217 bs
->bl
.max_iov
= IOV_MAX
;
220 /* Then let the driver override it */
221 if (drv
->bdrv_refresh_limits
) {
222 drv
->bdrv_refresh_limits(bs
, errp
);
228 if (bs
->bl
.request_alignment
> BDRV_MAX_ALIGNMENT
) {
229 error_setg(errp
, "Driver requires too large request alignment");
234 * The copy-on-read flag is actually a reference count so multiple users may
235 * use the feature without worrying about clobbering its previous state.
236 * Copy-on-read stays enabled until all users have called to disable it.
238 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
241 qatomic_inc(&bs
->copy_on_read
);
244 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
246 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
253 BlockDriverState
*bs
;
260 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
261 bool bdrv_drain_poll(BlockDriverState
*bs
, BdrvChild
*ignore_parent
,
262 bool ignore_bds_parents
)
266 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
270 if (qatomic_read(&bs
->in_flight
)) {
277 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
,
278 BdrvChild
*ignore_parent
)
281 GRAPH_RDLOCK_GUARD_MAINLOOP();
283 return bdrv_drain_poll(bs
, ignore_parent
, false);
286 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
288 static void bdrv_do_drained_end(BlockDriverState
*bs
, BdrvChild
*parent
);
290 static void bdrv_co_drain_bh_cb(void *opaque
)
292 BdrvCoDrainData
*data
= opaque
;
293 Coroutine
*co
= data
->co
;
294 BlockDriverState
*bs
= data
->bs
;
297 bdrv_dec_in_flight(bs
);
299 bdrv_do_drained_begin(bs
, data
->parent
, data
->poll
);
302 bdrv_do_drained_end(bs
, data
->parent
);
306 bdrv_drain_all_begin();
313 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
318 BdrvCoDrainData data
;
319 Coroutine
*self
= qemu_coroutine_self();
321 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
322 * other coroutines run if they were queued by aio_co_enter(). */
324 assert(qemu_in_coroutine());
325 data
= (BdrvCoDrainData
) {
335 bdrv_inc_in_flight(bs
);
338 replay_bh_schedule_oneshot_event(qemu_get_aio_context(),
339 bdrv_co_drain_bh_cb
, &data
);
341 qemu_coroutine_yield();
342 /* If we are resumed from some other event (such as an aio completion or a
343 * timer callback), it is a bug in the caller that should be fixed. */
347 static void bdrv_do_drained_begin(BlockDriverState
*bs
, BdrvChild
*parent
,
352 if (qemu_in_coroutine()) {
353 bdrv_co_yield_to_drain(bs
, true, parent
, poll
);
359 /* Stop things in parent-to-child order */
360 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
361 GRAPH_RDLOCK_GUARD_MAINLOOP();
362 bdrv_parent_drained_begin(bs
, parent
);
363 if (bs
->drv
&& bs
->drv
->bdrv_drain_begin
) {
364 bs
->drv
->bdrv_drain_begin(bs
);
369 * Wait for drained requests to finish.
371 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
372 * call is needed so things in this AioContext can make progress even
373 * though we don't return to the main AioContext loop - this automatically
374 * includes other nodes in the same AioContext and therefore all child
378 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, parent
));
382 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
, BdrvChild
*parent
)
384 bdrv_do_drained_begin(bs
, parent
, false);
387 void coroutine_mixed_fn
388 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
;
404 if (qemu_in_coroutine()) {
405 bdrv_co_yield_to_drain(bs
, false, parent
, false);
409 /* At this point, we should be always running in the main loop. */
411 assert(bs
->quiesce_counter
> 0);
414 /* Re-enable things in child-to-parent order */
415 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
416 if (old_quiesce_counter
== 1) {
417 GRAPH_RDLOCK_GUARD_MAINLOOP();
418 if (bs
->drv
&& bs
->drv
->bdrv_drain_end
) {
419 bs
->drv
->bdrv_drain_end(bs
);
421 bdrv_parent_drained_end(bs
, parent
);
425 void bdrv_drained_end(BlockDriverState
*bs
)
428 bdrv_do_drained_end(bs
, NULL
);
431 void bdrv_drain(BlockDriverState
*bs
)
434 bdrv_drained_begin(bs
);
435 bdrv_drained_end(bs
);
438 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
440 BdrvChild
*child
, *next
;
442 GRAPH_RDLOCK_GUARD_MAINLOOP();
444 assert(qatomic_read(&bs
->in_flight
) == 0);
445 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
446 bdrv_drain_assert_idle(child
->bs
);
450 unsigned int bdrv_drain_all_count
= 0;
452 static bool bdrv_drain_all_poll(void)
454 BlockDriverState
*bs
= NULL
;
458 GRAPH_RDLOCK_GUARD_MAINLOOP();
461 * bdrv_drain_poll() can't make changes to the graph and we hold the BQL,
462 * so iterating bdrv_next_all_states() is safe.
464 while ((bs
= bdrv_next_all_states(bs
))) {
465 result
|= bdrv_drain_poll(bs
, NULL
, true);
472 * Wait for pending requests to complete across all BlockDriverStates
474 * This function does not flush data to disk, use bdrv_flush_all() for that
475 * after calling this function.
477 * This pauses all block jobs and disables external clients. It must
478 * be paired with bdrv_drain_all_end().
480 * NOTE: no new block jobs or BlockDriverStates can be created between
481 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
483 void bdrv_drain_all_begin_nopoll(void)
485 BlockDriverState
*bs
= NULL
;
489 * bdrv queue is managed by record/replay,
490 * waiting for finishing the I/O requests may
493 if (replay_events_enabled()) {
497 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
498 * loop AioContext, so make sure we're in the main context. */
499 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
500 assert(bdrv_drain_all_count
< INT_MAX
);
501 bdrv_drain_all_count
++;
503 /* Quiesce all nodes, without polling in-flight requests yet. The graph
504 * cannot change during this loop. */
505 while ((bs
= bdrv_next_all_states(bs
))) {
506 bdrv_do_drained_begin(bs
, NULL
, false);
510 void coroutine_mixed_fn
bdrv_drain_all_begin(void)
512 BlockDriverState
*bs
= NULL
;
514 if (qemu_in_coroutine()) {
515 bdrv_co_yield_to_drain(NULL
, true, NULL
, true);
520 * bdrv queue is managed by record/replay,
521 * waiting for finishing the I/O requests may
524 if (replay_events_enabled()) {
528 bdrv_drain_all_begin_nopoll();
530 /* Now poll the in-flight requests */
531 AIO_WAIT_WHILE_UNLOCKED(NULL
, bdrv_drain_all_poll());
533 while ((bs
= bdrv_next_all_states(bs
))) {
534 bdrv_drain_assert_idle(bs
);
538 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
542 g_assert(bs
->quiesce_counter
> 0);
543 g_assert(!bs
->refcnt
);
545 while (bs
->quiesce_counter
) {
546 bdrv_do_drained_end(bs
, NULL
);
550 void bdrv_drain_all_end(void)
552 BlockDriverState
*bs
= NULL
;
556 * bdrv queue is managed by record/replay,
557 * waiting for finishing the I/O requests may
560 if (replay_events_enabled()) {
564 while ((bs
= bdrv_next_all_states(bs
))) {
565 bdrv_do_drained_end(bs
, NULL
);
568 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
569 assert(bdrv_drain_all_count
> 0);
570 bdrv_drain_all_count
--;
573 void bdrv_drain_all(void)
576 bdrv_drain_all_begin();
577 bdrv_drain_all_end();
581 * Remove an active request from the tracked requests list
583 * This function should be called when a tracked request is completing.
585 static void coroutine_fn
tracked_request_end(BdrvTrackedRequest
*req
)
587 if (req
->serialising
) {
588 qatomic_dec(&req
->bs
->serialising_in_flight
);
591 qemu_mutex_lock(&req
->bs
->reqs_lock
);
592 QLIST_REMOVE(req
, list
);
593 qemu_mutex_unlock(&req
->bs
->reqs_lock
);
596 * At this point qemu_co_queue_wait(&req->wait_queue, ...) won't be called
597 * anymore because the request has been removed from the list, so it's safe
598 * to restart the queue outside reqs_lock to minimize the critical section.
600 qemu_co_queue_restart_all(&req
->wait_queue
);
604 * Add an active request to the tracked requests list
606 static void coroutine_fn
tracked_request_begin(BdrvTrackedRequest
*req
,
607 BlockDriverState
*bs
,
610 enum BdrvTrackedRequestType type
)
612 bdrv_check_request(offset
, bytes
, &error_abort
);
614 *req
= (BdrvTrackedRequest
){
619 .co
= qemu_coroutine_self(),
620 .serialising
= false,
621 .overlap_offset
= offset
,
622 .overlap_bytes
= bytes
,
625 qemu_co_queue_init(&req
->wait_queue
);
627 qemu_mutex_lock(&bs
->reqs_lock
);
628 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
629 qemu_mutex_unlock(&bs
->reqs_lock
);
632 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
633 int64_t offset
, int64_t bytes
)
635 bdrv_check_request(offset
, bytes
, &error_abort
);
638 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
642 if (req
->overlap_offset
>= offset
+ bytes
) {
648 /* Called with self->bs->reqs_lock held */
649 static coroutine_fn BdrvTrackedRequest
*
650 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
652 BdrvTrackedRequest
*req
;
654 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
655 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
658 if (tracked_request_overlaps(req
, self
->overlap_offset
,
659 self
->overlap_bytes
))
662 * Hitting this means there was a reentrant request, for
663 * example, a block driver issuing nested requests. This must
664 * never happen since it means deadlock.
666 assert(qemu_coroutine_self() != req
->co
);
669 * If the request is already (indirectly) waiting for us, or
670 * will wait for us as soon as it wakes up, then just go on
671 * (instead of producing a deadlock in the former case).
673 if (!req
->waiting_for
) {
682 /* Called with self->bs->reqs_lock held */
683 static void coroutine_fn
684 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
686 BdrvTrackedRequest
*req
;
688 while ((req
= bdrv_find_conflicting_request(self
))) {
689 self
->waiting_for
= req
;
690 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
691 self
->waiting_for
= NULL
;
695 /* Called with req->bs->reqs_lock held */
696 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
699 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
700 int64_t overlap_bytes
=
701 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
703 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
705 if (!req
->serialising
) {
706 qatomic_inc(&req
->bs
->serialising_in_flight
);
707 req
->serialising
= true;
710 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
711 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
715 * Return the tracked request on @bs for the current coroutine, or
716 * NULL if there is none.
718 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
720 BdrvTrackedRequest
*req
;
721 Coroutine
*self
= qemu_coroutine_self();
724 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
725 if (req
->co
== self
) {
734 * Round a region to subcluster (if supported) or cluster boundaries
736 void coroutine_fn GRAPH_RDLOCK
737 bdrv_round_to_subclusters(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
738 int64_t *align_offset
, int64_t *align_bytes
)
742 if (bdrv_co_get_info(bs
, &bdi
) < 0 || bdi
.subcluster_size
== 0) {
743 *align_offset
= offset
;
744 *align_bytes
= bytes
;
746 int64_t c
= bdi
.subcluster_size
;
747 *align_offset
= QEMU_ALIGN_DOWN(offset
, c
);
748 *align_bytes
= QEMU_ALIGN_UP(offset
- *align_offset
+ bytes
, c
);
752 static int coroutine_fn GRAPH_RDLOCK
bdrv_get_cluster_size(BlockDriverState
*bs
)
757 ret
= bdrv_co_get_info(bs
, &bdi
);
758 if (ret
< 0 || bdi
.cluster_size
== 0) {
759 return bs
->bl
.request_alignment
;
761 return bdi
.cluster_size
;
765 void bdrv_inc_in_flight(BlockDriverState
*bs
)
768 qatomic_inc(&bs
->in_flight
);
771 void bdrv_wakeup(BlockDriverState
*bs
)
777 void bdrv_dec_in_flight(BlockDriverState
*bs
)
780 qatomic_dec(&bs
->in_flight
);
784 static void coroutine_fn
785 bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
787 BlockDriverState
*bs
= self
->bs
;
789 if (!qatomic_read(&bs
->serialising_in_flight
)) {
793 qemu_mutex_lock(&bs
->reqs_lock
);
794 bdrv_wait_serialising_requests_locked(self
);
795 qemu_mutex_unlock(&bs
->reqs_lock
);
798 void coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
803 qemu_mutex_lock(&req
->bs
->reqs_lock
);
805 tracked_request_set_serialising(req
, align
);
806 bdrv_wait_serialising_requests_locked(req
);
808 qemu_mutex_unlock(&req
->bs
->reqs_lock
);
811 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
812 QEMUIOVector
*qiov
, size_t qiov_offset
,
816 * Check generic offset/bytes correctness
820 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
825 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
829 if (bytes
> BDRV_MAX_LENGTH
) {
830 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
831 bytes
, BDRV_MAX_LENGTH
);
835 if (offset
> BDRV_MAX_LENGTH
) {
836 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
837 offset
, BDRV_MAX_LENGTH
);
841 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
842 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
843 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
853 * Check qiov and qiov_offset
856 if (qiov_offset
> qiov
->size
) {
857 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
858 qiov_offset
, qiov
->size
);
862 if (bytes
> qiov
->size
- qiov_offset
) {
863 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
864 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
871 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
873 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
876 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
877 QEMUIOVector
*qiov
, size_t qiov_offset
)
879 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
884 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
892 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
893 * The operation is sped up by checking the block status and only writing
894 * zeroes to the device if they currently do not return zeroes. Optional
895 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
898 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
900 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
903 int64_t target_size
, bytes
, offset
= 0;
904 BlockDriverState
*bs
= child
->bs
;
907 target_size
= bdrv_getlength(bs
);
908 if (target_size
< 0) {
913 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
917 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
921 if (ret
& BDRV_BLOCK_ZERO
) {
925 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
934 * Writes to the file and ensures that no writes are reordered across this
935 * request (acts as a barrier)
937 * Returns 0 on success, -errno in error cases.
939 int coroutine_fn
bdrv_co_pwrite_sync(BdrvChild
*child
, int64_t offset
,
940 int64_t bytes
, const void *buf
,
941 BdrvRequestFlags flags
)
945 assert_bdrv_graph_readable();
947 ret
= bdrv_co_pwrite(child
, offset
, bytes
, buf
, flags
);
952 ret
= bdrv_co_flush(child
->bs
);
960 typedef struct CoroutineIOCompletion
{
961 Coroutine
*coroutine
;
963 } CoroutineIOCompletion
;
965 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
967 CoroutineIOCompletion
*co
= opaque
;
970 aio_co_wake(co
->coroutine
);
973 static int coroutine_fn GRAPH_RDLOCK
974 bdrv_driver_preadv(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
975 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
977 BlockDriver
*drv
= bs
->drv
;
979 unsigned int nb_sectors
;
980 QEMUIOVector local_qiov
;
982 assert_bdrv_graph_readable();
984 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
985 assert(!(flags
& ~bs
->supported_read_flags
));
991 if (drv
->bdrv_co_preadv_part
) {
992 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
996 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
997 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1001 if (drv
->bdrv_co_preadv
) {
1002 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
1006 if (drv
->bdrv_aio_preadv
) {
1008 CoroutineIOCompletion co
= {
1009 .coroutine
= qemu_coroutine_self(),
1012 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1013 bdrv_co_io_em_complete
, &co
);
1018 qemu_coroutine_yield();
1024 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1025 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1027 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1028 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1029 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1030 assert(drv
->bdrv_co_readv
);
1032 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1035 if (qiov
== &local_qiov
) {
1036 qemu_iovec_destroy(&local_qiov
);
1042 static int coroutine_fn GRAPH_RDLOCK
1043 bdrv_driver_pwritev(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1044 QEMUIOVector
*qiov
, size_t qiov_offset
,
1045 BdrvRequestFlags flags
)
1047 BlockDriver
*drv
= bs
->drv
;
1048 bool emulate_fua
= false;
1050 unsigned int nb_sectors
;
1051 QEMUIOVector local_qiov
;
1053 assert_bdrv_graph_readable();
1055 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1061 if ((flags
& BDRV_REQ_FUA
) &&
1062 (~bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1063 flags
&= ~BDRV_REQ_FUA
;
1067 flags
&= bs
->supported_write_flags
;
1069 if (drv
->bdrv_co_pwritev_part
) {
1070 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1075 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1076 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1080 if (drv
->bdrv_co_pwritev
) {
1081 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1085 if (drv
->bdrv_aio_pwritev
) {
1087 CoroutineIOCompletion co
= {
1088 .coroutine
= qemu_coroutine_self(),
1091 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
, flags
,
1092 bdrv_co_io_em_complete
, &co
);
1096 qemu_coroutine_yield();
1102 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1103 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1105 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1106 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1107 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1109 assert(drv
->bdrv_co_writev
);
1110 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
, flags
);
1113 if (ret
== 0 && emulate_fua
) {
1114 ret
= bdrv_co_flush(bs
);
1117 if (qiov
== &local_qiov
) {
1118 qemu_iovec_destroy(&local_qiov
);
1124 static int coroutine_fn GRAPH_RDLOCK
1125 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1126 int64_t bytes
, QEMUIOVector
*qiov
,
1129 BlockDriver
*drv
= bs
->drv
;
1130 QEMUIOVector local_qiov
;
1132 assert_bdrv_graph_readable();
1134 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1140 if (!block_driver_can_compress(drv
)) {
1144 if (drv
->bdrv_co_pwritev_compressed_part
) {
1145 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1149 if (qiov_offset
== 0) {
1150 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1153 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1154 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1155 qemu_iovec_destroy(&local_qiov
);
1160 static int coroutine_fn GRAPH_RDLOCK
1161 bdrv_co_do_copy_on_readv(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1162 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1164 BlockDriverState
*bs
= child
->bs
;
1166 /* Perform I/O through a temporary buffer so that users who scribble over
1167 * their read buffer while the operation is in progress do not end up
1168 * modifying the image file. This is critical for zero-copy guest I/O
1169 * where anything might happen inside guest memory.
1171 void *bounce_buffer
= NULL
;
1173 BlockDriver
*drv
= bs
->drv
;
1174 int64_t align_offset
;
1175 int64_t align_bytes
;
1178 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1179 BDRV_REQUEST_MAX_BYTES
);
1180 int64_t progress
= 0;
1183 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1190 * Do not write anything when the BDS is inactive. That is not
1191 * allowed, and it would not help.
1193 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1195 /* FIXME We cannot require callers to have write permissions when all they
1196 * are doing is a read request. If we did things right, write permissions
1197 * would be obtained anyway, but internally by the copy-on-read code. As
1198 * long as it is implemented here rather than in a separate filter driver,
1199 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1200 * it could request permissions. Therefore we have to bypass the permission
1201 * system for the moment. */
1202 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1204 /* Cover entire cluster so no additional backing file I/O is required when
1205 * allocating cluster in the image file. Note that this value may exceed
1206 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1207 * is one reason we loop rather than doing it all at once.
1209 bdrv_round_to_subclusters(bs
, offset
, bytes
, &align_offset
, &align_bytes
);
1210 skip_bytes
= offset
- align_offset
;
1212 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1213 align_offset
, align_bytes
);
1215 while (align_bytes
) {
1219 ret
= 1; /* "already allocated", so nothing will be copied */
1220 pnum
= MIN(align_bytes
, max_transfer
);
1222 ret
= bdrv_co_is_allocated(bs
, align_offset
,
1223 MIN(align_bytes
, max_transfer
), &pnum
);
1226 * Safe to treat errors in querying allocation as if
1227 * unallocated; we'll probably fail again soon on the
1228 * read, but at least that will set a decent errno.
1230 pnum
= MIN(align_bytes
, max_transfer
);
1233 /* Stop at EOF if the image ends in the middle of the cluster */
1234 if (ret
== 0 && pnum
== 0) {
1235 assert(progress
>= bytes
);
1239 assert(skip_bytes
< pnum
);
1243 QEMUIOVector local_qiov
;
1245 /* Must copy-on-read; use the bounce buffer */
1246 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1247 if (!bounce_buffer
) {
1248 int64_t max_we_need
= MAX(pnum
, align_bytes
- pnum
);
1249 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1250 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1252 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1253 if (!bounce_buffer
) {
1258 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1260 ret
= bdrv_driver_preadv(bs
, align_offset
, pnum
,
1266 bdrv_co_debug_event(bs
, BLKDBG_COR_WRITE
);
1267 if (drv
->bdrv_co_pwrite_zeroes
&&
1268 buffer_is_zero(bounce_buffer
, pnum
)) {
1269 /* FIXME: Should we (perhaps conditionally) be setting
1270 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1271 * that still correctly reads as zero? */
1272 ret
= bdrv_co_do_pwrite_zeroes(bs
, align_offset
, pnum
,
1273 BDRV_REQ_WRITE_UNCHANGED
);
1275 /* This does not change the data on the disk, it is not
1276 * necessary to flush even in cache=writethrough mode.
1278 ret
= bdrv_driver_pwritev(bs
, align_offset
, pnum
,
1280 BDRV_REQ_WRITE_UNCHANGED
);
1284 /* It might be okay to ignore write errors for guest
1285 * requests. If this is a deliberate copy-on-read
1286 * then we don't want to ignore the error. Simply
1287 * report it in all cases.
1292 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1293 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1294 bounce_buffer
+ skip_bytes
,
1295 MIN(pnum
- skip_bytes
, bytes
- progress
));
1297 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1298 /* Read directly into the destination */
1299 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1300 MIN(pnum
- skip_bytes
, bytes
- progress
),
1301 qiov
, qiov_offset
+ progress
, 0);
1307 align_offset
+= pnum
;
1308 align_bytes
-= pnum
;
1309 progress
+= pnum
- skip_bytes
;
1315 qemu_vfree(bounce_buffer
);
1320 * Forwards an already correctly aligned request to the BlockDriver. This
1321 * handles copy on read, zeroing after EOF, and fragmentation of large
1322 * reads; any other features must be implemented by the caller.
1324 static int coroutine_fn GRAPH_RDLOCK
1325 bdrv_aligned_preadv(BdrvChild
*child
, BdrvTrackedRequest
*req
,
1326 int64_t offset
, int64_t bytes
, int64_t align
,
1327 QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1329 BlockDriverState
*bs
= child
->bs
;
1330 int64_t total_bytes
, max_bytes
;
1332 int64_t bytes_remaining
= bytes
;
1335 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1336 assert(is_power_of_2(align
));
1337 assert((offset
& (align
- 1)) == 0);
1338 assert((bytes
& (align
- 1)) == 0);
1339 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1340 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1344 * TODO: We would need a per-BDS .supported_read_flags and
1345 * potential fallback support, if we ever implement any read flags
1346 * to pass through to drivers. For now, there aren't any
1347 * passthrough flags except the BDRV_REQ_REGISTERED_BUF optimization hint.
1349 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
|
1350 BDRV_REQ_REGISTERED_BUF
)));
1352 /* Handle Copy on Read and associated serialisation */
1353 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1354 /* If we touch the same cluster it counts as an overlap. This
1355 * guarantees that allocating writes will be serialized and not race
1356 * with each other for the same cluster. For example, in copy-on-read
1357 * it ensures that the CoR read and write operations are atomic and
1358 * guest writes cannot interleave between them. */
1359 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1361 bdrv_wait_serialising_requests(req
);
1364 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1367 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1368 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1370 ret
= bdrv_co_is_allocated(bs
, offset
, bytes
, &pnum
);
1375 if (!ret
|| pnum
!= bytes
) {
1376 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1377 qiov
, qiov_offset
, flags
);
1379 } else if (flags
& BDRV_REQ_PREFETCH
) {
1384 /* Forward the request to the BlockDriver, possibly fragmenting it */
1385 total_bytes
= bdrv_co_getlength(bs
);
1386 if (total_bytes
< 0) {
1391 assert(!(flags
& ~(bs
->supported_read_flags
| BDRV_REQ_REGISTERED_BUF
)));
1393 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1394 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1395 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1399 while (bytes_remaining
) {
1403 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1406 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1408 qiov_offset
+ bytes
- bytes_remaining
,
1412 num
= bytes_remaining
;
1413 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1414 0, bytes_remaining
);
1419 bytes_remaining
-= num
;
1423 return ret
< 0 ? ret
: 0;
1429 * |<---- align ----->| |<----- align ---->|
1430 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1432 * -*----------$-------*-------- ... --------*-----$------------*---
1434 * | offset | | end |
1435 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1436 * [buf ... ) [tail_buf )
1438 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1439 * is placed at the beginning of @buf and @tail at the @end.
1441 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1442 * around tail, if tail exists.
1444 * @merge_reads is true for small requests,
1445 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1446 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1448 * @write is true for write requests, false for read requests.
1450 * If padding makes the vector too long (exceeding IOV_MAX), then we need to
1451 * merge existing vector elements into a single one. @collapse_bounce_buf acts
1452 * as the bounce buffer in such cases. @pre_collapse_qiov has the pre-collapse
1453 * I/O vector elements so for read requests, the data can be copied back after
1456 typedef struct BdrvRequestPadding
{
1464 QEMUIOVector local_qiov
;
1466 uint8_t *collapse_bounce_buf
;
1467 size_t collapse_len
;
1468 QEMUIOVector pre_collapse_qiov
;
1469 } BdrvRequestPadding
;
1471 static bool bdrv_init_padding(BlockDriverState
*bs
,
1472 int64_t offset
, int64_t bytes
,
1474 BdrvRequestPadding
*pad
)
1476 int64_t align
= bs
->bl
.request_alignment
;
1479 bdrv_check_request(offset
, bytes
, &error_abort
);
1480 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1481 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1483 memset(pad
, 0, sizeof(*pad
));
1485 pad
->head
= offset
& (align
- 1);
1486 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1488 pad
->tail
= align
- pad
->tail
;
1491 if (!pad
->head
&& !pad
->tail
) {
1495 assert(bytes
); /* Nothing good in aligning zero-length requests */
1497 sum
= pad
->head
+ bytes
+ pad
->tail
;
1498 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1499 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1500 pad
->merge_reads
= sum
== pad
->buf_len
;
1502 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1510 static int coroutine_fn GRAPH_RDLOCK
1511 bdrv_padding_rmw_read(BdrvChild
*child
, BdrvTrackedRequest
*req
,
1512 BdrvRequestPadding
*pad
, bool zero_middle
)
1514 QEMUIOVector local_qiov
;
1515 BlockDriverState
*bs
= child
->bs
;
1516 uint64_t align
= bs
->bl
.request_alignment
;
1519 assert(req
->serialising
&& pad
->buf
);
1521 if (pad
->head
|| pad
->merge_reads
) {
1522 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1524 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1527 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1529 if (pad
->merge_reads
&& pad
->tail
) {
1530 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1532 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1533 align
, &local_qiov
, 0, 0);
1538 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1540 if (pad
->merge_reads
&& pad
->tail
) {
1541 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1544 if (pad
->merge_reads
) {
1550 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1552 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1553 ret
= bdrv_aligned_preadv(
1555 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1556 align
, align
, &local_qiov
, 0, 0);
1560 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1565 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1572 * Free *pad's associated buffers, and perform any necessary finalization steps.
1574 static void bdrv_padding_finalize(BdrvRequestPadding
*pad
)
1576 if (pad
->collapse_bounce_buf
) {
1579 * If padding required elements in the vector to be collapsed into a
1580 * bounce buffer, copy the bounce buffer content back
1582 qemu_iovec_from_buf(&pad
->pre_collapse_qiov
, 0,
1583 pad
->collapse_bounce_buf
, pad
->collapse_len
);
1585 qemu_vfree(pad
->collapse_bounce_buf
);
1586 qemu_iovec_destroy(&pad
->pre_collapse_qiov
);
1589 qemu_vfree(pad
->buf
);
1590 qemu_iovec_destroy(&pad
->local_qiov
);
1592 memset(pad
, 0, sizeof(*pad
));
1596 * Create pad->local_qiov by wrapping @iov in the padding head and tail, while
1597 * ensuring that the resulting vector will not exceed IOV_MAX elements.
1599 * To ensure this, when necessary, the first two or three elements of @iov are
1600 * merged into pad->collapse_bounce_buf and replaced by a reference to that
1601 * bounce buffer in pad->local_qiov.
1603 * After performing a read request, the data from the bounce buffer must be
1604 * copied back into pad->pre_collapse_qiov (e.g. by bdrv_padding_finalize()).
1606 static int bdrv_create_padded_qiov(BlockDriverState
*bs
,
1607 BdrvRequestPadding
*pad
,
1608 struct iovec
*iov
, int niov
,
1609 size_t iov_offset
, size_t bytes
)
1611 int padded_niov
, surplus_count
, collapse_count
;
1613 /* Assert this invariant */
1614 assert(niov
<= IOV_MAX
);
1617 * Cannot pad if resulting length would exceed SIZE_MAX. Returning an error
1618 * to the guest is not ideal, but there is little else we can do. At least
1619 * this will practically never happen on 64-bit systems.
1621 if (SIZE_MAX
- pad
->head
< bytes
||
1622 SIZE_MAX
- pad
->head
- bytes
< pad
->tail
)
1627 /* Length of the resulting IOV if we just concatenated everything */
1628 padded_niov
= !!pad
->head
+ niov
+ !!pad
->tail
;
1630 qemu_iovec_init(&pad
->local_qiov
, MIN(padded_niov
, IOV_MAX
));
1633 qemu_iovec_add(&pad
->local_qiov
, pad
->buf
, pad
->head
);
1637 * If padded_niov > IOV_MAX, we cannot just concatenate everything.
1638 * Instead, merge the first two or three elements of @iov to reduce the
1639 * number of vector elements as necessary.
1641 if (padded_niov
> IOV_MAX
) {
1643 * Only head and tail can have lead to the number of entries exceeding
1644 * IOV_MAX, so we can exceed it by the head and tail at most. We need
1645 * to reduce the number of elements by `surplus_count`, so we merge that
1646 * many elements plus one into one element.
1648 surplus_count
= padded_niov
- IOV_MAX
;
1649 assert(surplus_count
<= !!pad
->head
+ !!pad
->tail
);
1650 collapse_count
= surplus_count
+ 1;
1653 * Move the elements to collapse into `pad->pre_collapse_qiov`, then
1654 * advance `iov` (and associated variables) by those elements.
1656 qemu_iovec_init(&pad
->pre_collapse_qiov
, collapse_count
);
1657 qemu_iovec_concat_iov(&pad
->pre_collapse_qiov
, iov
,
1658 collapse_count
, iov_offset
, SIZE_MAX
);
1659 iov
+= collapse_count
;
1661 niov
-= collapse_count
;
1662 bytes
-= pad
->pre_collapse_qiov
.size
;
1665 * Construct the bounce buffer to match the length of the to-collapse
1666 * vector elements, and for write requests, initialize it with the data
1667 * from those elements. Then add it to `pad->local_qiov`.
1669 pad
->collapse_len
= pad
->pre_collapse_qiov
.size
;
1670 pad
->collapse_bounce_buf
= qemu_blockalign(bs
, pad
->collapse_len
);
1672 qemu_iovec_to_buf(&pad
->pre_collapse_qiov
, 0,
1673 pad
->collapse_bounce_buf
, pad
->collapse_len
);
1675 qemu_iovec_add(&pad
->local_qiov
,
1676 pad
->collapse_bounce_buf
, pad
->collapse_len
);
1679 qemu_iovec_concat_iov(&pad
->local_qiov
, iov
, niov
, iov_offset
, bytes
);
1682 qemu_iovec_add(&pad
->local_qiov
,
1683 pad
->buf
+ pad
->buf_len
- pad
->tail
, pad
->tail
);
1686 assert(pad
->local_qiov
.niov
== MIN(padded_niov
, IOV_MAX
));
1693 * Exchange request parameters with padded request if needed. Don't include RMW
1694 * read of padding, bdrv_padding_rmw_read() should be called separately if
1697 * @write is true for write requests, false for read requests.
1699 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1700 * - on function start they represent original request
1701 * - on failure or when padding is not needed they are unchanged
1702 * - on success when padding is needed they represent padded request
1704 static int bdrv_pad_request(BlockDriverState
*bs
,
1705 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1706 int64_t *offset
, int64_t *bytes
,
1708 BdrvRequestPadding
*pad
, bool *padded
,
1709 BdrvRequestFlags
*flags
)
1712 struct iovec
*sliced_iov
;
1714 size_t sliced_head
, sliced_tail
;
1716 /* Should have been checked by the caller already */
1717 ret
= bdrv_check_request32(*offset
, *bytes
, *qiov
, *qiov_offset
);
1722 if (!bdrv_init_padding(bs
, *offset
, *bytes
, write
, pad
)) {
1729 sliced_iov
= qemu_iovec_slice(*qiov
, *qiov_offset
, *bytes
,
1730 &sliced_head
, &sliced_tail
,
1733 /* Guaranteed by bdrv_check_request32() */
1734 assert(*bytes
<= SIZE_MAX
);
1735 ret
= bdrv_create_padded_qiov(bs
, pad
, sliced_iov
, sliced_niov
,
1736 sliced_head
, *bytes
);
1738 bdrv_padding_finalize(pad
);
1741 *bytes
+= pad
->head
+ pad
->tail
;
1742 *offset
-= pad
->head
;
1743 *qiov
= &pad
->local_qiov
;
1749 /* Can't use optimization hint with bounce buffer */
1750 *flags
&= ~BDRV_REQ_REGISTERED_BUF
;
1756 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1757 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1758 BdrvRequestFlags flags
)
1761 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1764 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1765 int64_t offset
, int64_t bytes
,
1766 QEMUIOVector
*qiov
, size_t qiov_offset
,
1767 BdrvRequestFlags flags
)
1769 BlockDriverState
*bs
= child
->bs
;
1770 BdrvTrackedRequest req
;
1771 BdrvRequestPadding pad
;
1775 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1777 if (!bdrv_co_is_inserted(bs
)) {
1781 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1786 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1788 * Aligning zero request is nonsense. Even if driver has special meaning
1789 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1790 * it to driver due to request_alignment.
1792 * Still, no reason to return an error if someone do unaligned
1793 * zero-length read occasionally.
1798 bdrv_inc_in_flight(bs
);
1800 /* Don't do copy-on-read if we read data before write operation */
1801 if (qatomic_read(&bs
->copy_on_read
)) {
1802 flags
|= BDRV_REQ_COPY_ON_READ
;
1805 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, false,
1806 &pad
, NULL
, &flags
);
1811 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1812 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1813 bs
->bl
.request_alignment
,
1814 qiov
, qiov_offset
, flags
);
1815 tracked_request_end(&req
);
1816 bdrv_padding_finalize(&pad
);
1819 bdrv_dec_in_flight(bs
);
1824 static int coroutine_fn GRAPH_RDLOCK
1825 bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
1826 BdrvRequestFlags flags
)
1828 BlockDriver
*drv
= bs
->drv
;
1832 bool need_flush
= false;
1836 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1838 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1839 bs
->bl
.request_alignment
);
1840 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1842 assert_bdrv_graph_readable();
1843 bdrv_check_request(offset
, bytes
, &error_abort
);
1849 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1853 /* By definition there is no user buffer so this flag doesn't make sense */
1854 if (flags
& BDRV_REQ_REGISTERED_BUF
) {
1858 /* Invalidate the cached block-status data range if this write overlaps */
1859 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1861 assert(alignment
% bs
->bl
.request_alignment
== 0);
1862 head
= offset
% alignment
;
1863 tail
= (offset
+ bytes
) % alignment
;
1864 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1865 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1867 while (bytes
> 0 && !ret
) {
1868 int64_t num
= bytes
;
1870 /* Align request. Block drivers can expect the "bulk" of the request
1871 * to be aligned, and that unaligned requests do not cross cluster
1875 /* Make a small request up to the first aligned sector. For
1876 * convenience, limit this request to max_transfer even if
1877 * we don't need to fall back to writes. */
1878 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1879 head
= (head
+ num
) % alignment
;
1880 assert(num
< max_write_zeroes
);
1881 } else if (tail
&& num
> alignment
) {
1882 /* Shorten the request to the last aligned sector. */
1886 /* limit request size */
1887 if (num
> max_write_zeroes
) {
1888 num
= max_write_zeroes
;
1892 /* First try the efficient write zeroes operation */
1893 if (drv
->bdrv_co_pwrite_zeroes
) {
1894 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1895 flags
& bs
->supported_zero_flags
);
1896 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1897 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1901 assert(!bs
->supported_zero_flags
);
1904 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1905 /* Fall back to bounce buffer if write zeroes is unsupported */
1906 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1908 if ((flags
& BDRV_REQ_FUA
) &&
1909 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1910 /* No need for bdrv_driver_pwrite() to do a fallback
1911 * flush on each chunk; use just one at the end */
1912 write_flags
&= ~BDRV_REQ_FUA
;
1915 num
= MIN(num
, max_transfer
);
1917 buf
= qemu_try_blockalign0(bs
, num
);
1923 qemu_iovec_init_buf(&qiov
, buf
, num
);
1925 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1927 /* Keep bounce buffer around if it is big enough for all
1928 * all future requests.
1930 if (num
< max_transfer
) {
1941 if (ret
== 0 && need_flush
) {
1942 ret
= bdrv_co_flush(bs
);
1948 static inline int coroutine_fn GRAPH_RDLOCK
1949 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
1950 BdrvTrackedRequest
*req
, int flags
)
1952 BlockDriverState
*bs
= child
->bs
;
1954 bdrv_check_request(offset
, bytes
, &error_abort
);
1956 if (bdrv_is_read_only(bs
)) {
1960 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1961 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1962 assert(!(flags
& ~BDRV_REQ_MASK
));
1963 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
1965 if (flags
& BDRV_REQ_SERIALISING
) {
1966 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
1968 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
1970 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
1974 bdrv_wait_serialising_requests_locked(req
);
1976 bdrv_wait_serialising_requests(req
);
1979 assert(req
->overlap_offset
<= offset
);
1980 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1981 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
1982 child
->perm
& BLK_PERM_RESIZE
);
1984 switch (req
->type
) {
1985 case BDRV_TRACKED_WRITE
:
1986 case BDRV_TRACKED_DISCARD
:
1987 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1988 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1990 assert(child
->perm
& BLK_PERM_WRITE
);
1992 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
1994 case BDRV_TRACKED_TRUNCATE
:
1995 assert(child
->perm
& BLK_PERM_RESIZE
);
2002 static inline void coroutine_fn GRAPH_RDLOCK
2003 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
2004 BdrvTrackedRequest
*req
, int ret
)
2006 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
2007 BlockDriverState
*bs
= child
->bs
;
2009 bdrv_check_request(offset
, bytes
, &error_abort
);
2011 qatomic_inc(&bs
->write_gen
);
2014 * Discard cannot extend the image, but in error handling cases, such as
2015 * when reverting a qcow2 cluster allocation, the discarded range can pass
2016 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
2017 * here. Instead, just skip it, since semantically a discard request
2018 * beyond EOF cannot expand the image anyway.
2021 (req
->type
== BDRV_TRACKED_TRUNCATE
||
2022 end_sector
> bs
->total_sectors
) &&
2023 req
->type
!= BDRV_TRACKED_DISCARD
) {
2024 bs
->total_sectors
= end_sector
;
2025 bdrv_parent_cb_resize(bs
);
2026 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
2029 switch (req
->type
) {
2030 case BDRV_TRACKED_WRITE
:
2031 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
2032 /* fall through, to set dirty bits */
2033 case BDRV_TRACKED_DISCARD
:
2034 bdrv_set_dirty(bs
, offset
, bytes
);
2043 * Forwards an already correctly aligned write request to the BlockDriver,
2044 * after possibly fragmenting it.
2046 static int coroutine_fn GRAPH_RDLOCK
2047 bdrv_aligned_pwritev(BdrvChild
*child
, BdrvTrackedRequest
*req
,
2048 int64_t offset
, int64_t bytes
, int64_t align
,
2049 QEMUIOVector
*qiov
, size_t qiov_offset
,
2050 BdrvRequestFlags flags
)
2052 BlockDriverState
*bs
= child
->bs
;
2053 BlockDriver
*drv
= bs
->drv
;
2056 int64_t bytes_remaining
= bytes
;
2059 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
2065 if (bdrv_has_readonly_bitmaps(bs
)) {
2069 assert(is_power_of_2(align
));
2070 assert((offset
& (align
- 1)) == 0);
2071 assert((bytes
& (align
- 1)) == 0);
2072 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
2075 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
2077 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
2078 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
2079 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
2080 flags
|= BDRV_REQ_ZERO_WRITE
;
2081 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
2082 flags
|= BDRV_REQ_MAY_UNMAP
;
2085 /* Can't use optimization hint with bufferless zero write */
2086 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
2090 /* Do nothing, write notifier decided to fail this request */
2091 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
2092 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
2093 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
2094 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
2095 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
2097 } else if (bytes
<= max_transfer
) {
2098 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV
);
2099 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
2101 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV
);
2102 while (bytes_remaining
) {
2103 int num
= MIN(bytes_remaining
, max_transfer
);
2104 int local_flags
= flags
;
2107 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
2108 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
2109 /* If FUA is going to be emulated by flush, we only
2110 * need to flush on the last iteration */
2111 local_flags
&= ~BDRV_REQ_FUA
;
2114 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
2116 qiov_offset
+ bytes
- bytes_remaining
,
2121 bytes_remaining
-= num
;
2124 bdrv_co_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
2129 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
2134 static int coroutine_fn GRAPH_RDLOCK
2135 bdrv_co_do_zero_pwritev(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
2136 BdrvRequestFlags flags
, BdrvTrackedRequest
*req
)
2138 BlockDriverState
*bs
= child
->bs
;
2139 QEMUIOVector local_qiov
;
2140 uint64_t align
= bs
->bl
.request_alignment
;
2143 BdrvRequestPadding pad
;
2145 /* This flag doesn't make sense for padding or zero writes */
2146 flags
&= ~BDRV_REQ_REGISTERED_BUF
;
2148 padding
= bdrv_init_padding(bs
, offset
, bytes
, true, &pad
);
2150 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2151 bdrv_make_request_serialising(req
, align
);
2153 bdrv_padding_rmw_read(child
, req
, &pad
, true);
2155 if (pad
.head
|| pad
.merge_reads
) {
2156 int64_t aligned_offset
= offset
& ~(align
- 1);
2157 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
2159 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
2160 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
2161 align
, &local_qiov
, 0,
2162 flags
& ~BDRV_REQ_ZERO_WRITE
);
2163 if (ret
< 0 || pad
.merge_reads
) {
2164 /* Error or all work is done */
2167 offset
+= write_bytes
- pad
.head
;
2168 bytes
-= write_bytes
- pad
.head
;
2172 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2173 if (bytes
>= align
) {
2174 /* Write the aligned part in the middle. */
2175 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2176 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2181 bytes
-= aligned_bytes
;
2182 offset
+= aligned_bytes
;
2185 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2187 assert(align
== pad
.tail
+ bytes
);
2189 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2190 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2192 flags
& ~BDRV_REQ_ZERO_WRITE
);
2196 bdrv_padding_finalize(&pad
);
2202 * Handle a write request in coroutine context
2204 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2205 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2206 BdrvRequestFlags flags
)
2209 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2212 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2213 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2214 BdrvRequestFlags flags
)
2216 BlockDriverState
*bs
= child
->bs
;
2217 BdrvTrackedRequest req
;
2218 uint64_t align
= bs
->bl
.request_alignment
;
2219 BdrvRequestPadding pad
;
2221 bool padded
= false;
2224 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2226 if (!bdrv_co_is_inserted(bs
)) {
2230 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2231 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2233 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2239 /* If the request is misaligned then we can't make it efficient */
2240 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2241 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2246 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2248 * Aligning zero request is nonsense. Even if driver has special meaning
2249 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2250 * it to driver due to request_alignment.
2252 * Still, no reason to return an error if someone do unaligned
2253 * zero-length write occasionally.
2258 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2260 * Pad request for following read-modify-write cycle.
2261 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2262 * alignment only if there is no ZERO flag.
2264 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, true,
2265 &pad
, &padded
, &flags
);
2271 bdrv_inc_in_flight(bs
);
2272 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2274 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2276 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2282 * Request was unaligned to request_alignment and therefore
2283 * padded. We are going to do read-modify-write, and must
2284 * serialize the request to prevent interactions of the
2285 * widened region with other transactions.
2287 assert(!(flags
& BDRV_REQ_NO_WAIT
));
2288 bdrv_make_request_serialising(&req
, align
);
2289 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2292 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2293 qiov
, qiov_offset
, flags
);
2295 bdrv_padding_finalize(&pad
);
2298 tracked_request_end(&req
);
2299 bdrv_dec_in_flight(bs
);
2304 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2305 int64_t bytes
, BdrvRequestFlags flags
)
2308 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2309 assert_bdrv_graph_readable();
2311 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2312 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2315 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2316 BDRV_REQ_ZERO_WRITE
| flags
);
2320 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2322 int bdrv_flush_all(void)
2324 BdrvNextIterator it
;
2325 BlockDriverState
*bs
= NULL
;
2328 GLOBAL_STATE_CODE();
2329 GRAPH_RDLOCK_GUARD_MAINLOOP();
2332 * bdrv queue is managed by record/replay,
2333 * creating new flush request for stopping
2334 * the VM may break the determinism
2336 if (replay_events_enabled()) {
2340 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2341 int ret
= bdrv_flush(bs
);
2342 if (ret
< 0 && !result
) {
2351 * Returns the allocation status of the specified sectors.
2352 * Drivers not implementing the functionality are assumed to not support
2353 * backing files, hence all their sectors are reported as allocated.
2355 * If 'want_zero' is true, the caller is querying for mapping
2356 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2357 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2358 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2360 * If 'offset' is beyond the end of the disk image the return value is
2361 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2363 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2364 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2365 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2367 * 'pnum' is set to the number of bytes (including and immediately
2368 * following the specified offset) that are easily known to be in the
2369 * same allocated/unallocated state. Note that a second call starting
2370 * at the original offset plus returned pnum may have the same status.
2371 * The returned value is non-zero on success except at end-of-file.
2373 * Returns negative errno on failure. Otherwise, if the
2374 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2375 * set to the host mapping and BDS corresponding to the guest offset.
2377 static int coroutine_fn GRAPH_RDLOCK
2378 bdrv_co_do_block_status(BlockDriverState
*bs
, bool want_zero
,
2379 int64_t offset
, int64_t bytes
,
2380 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2383 int64_t n
; /* bytes */
2385 int64_t local_map
= 0;
2386 BlockDriverState
*local_file
= NULL
;
2387 int64_t aligned_offset
, aligned_bytes
;
2389 bool has_filtered_child
;
2392 assert_bdrv_graph_readable();
2394 total_size
= bdrv_co_getlength(bs
);
2395 if (total_size
< 0) {
2400 if (offset
>= total_size
) {
2401 ret
= BDRV_BLOCK_EOF
;
2409 n
= total_size
- offset
;
2414 /* Must be non-NULL or bdrv_co_getlength() would have failed */
2416 has_filtered_child
= bdrv_filter_child(bs
);
2417 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2419 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2420 if (offset
+ bytes
== total_size
) {
2421 ret
|= BDRV_BLOCK_EOF
;
2423 if (bs
->drv
->protocol_name
) {
2424 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2431 bdrv_inc_in_flight(bs
);
2433 /* Round out to request_alignment boundaries */
2434 align
= bs
->bl
.request_alignment
;
2435 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2436 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2438 if (bs
->drv
->bdrv_co_block_status
) {
2440 * Use the block-status cache only for protocol nodes: Format
2441 * drivers are generally quick to inquire the status, but protocol
2442 * drivers often need to get information from outside of qemu, so
2443 * we do not have control over the actual implementation. There
2444 * have been cases where inquiring the status took an unreasonably
2445 * long time, and we can do nothing in qemu to fix it.
2446 * This is especially problematic for images with large data areas,
2447 * because finding the few holes in them and giving them special
2448 * treatment does not gain much performance. Therefore, we try to
2449 * cache the last-identified data region.
2451 * Second, limiting ourselves to protocol nodes allows us to assume
2452 * the block status for data regions to be DATA | OFFSET_VALID, and
2453 * that the host offset is the same as the guest offset.
2455 * Note that it is possible that external writers zero parts of
2456 * the cached regions without the cache being invalidated, and so
2457 * we may report zeroes as data. This is not catastrophic,
2458 * however, because reporting zeroes as data is fine.
2460 if (QLIST_EMPTY(&bs
->children
) &&
2461 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2463 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2465 local_map
= aligned_offset
;
2467 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2468 aligned_bytes
, pnum
, &local_map
,
2472 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2473 * the cache is queried above. Technically, we do not need to check
2474 * it here; the worst that can happen is that we fill the cache for
2475 * non-protocol nodes, and then it is never used. However, filling
2476 * the cache requires an RCU update, so double check here to avoid
2477 * such an update if possible.
2479 * Check want_zero, because we only want to update the cache when we
2480 * have accurate information about what is zero and what is data.
2483 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2484 QLIST_EMPTY(&bs
->children
))
2487 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2488 * returned local_map value must be the same as the offset we
2489 * have passed (aligned_offset), and local_bs must be the node
2491 * Assert this, because we follow this rule when reading from
2492 * the cache (see the `local_file = bs` and
2493 * `local_map = aligned_offset` assignments above), and the
2494 * result the cache delivers must be the same as the driver
2497 assert(local_file
== bs
);
2498 assert(local_map
== aligned_offset
);
2499 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2503 /* Default code for filters */
2505 local_file
= bdrv_filter_bs(bs
);
2508 *pnum
= aligned_bytes
;
2509 local_map
= aligned_offset
;
2510 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2518 * The driver's result must be a non-zero multiple of request_alignment.
2519 * Clamp pnum and adjust map to original request.
2521 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2522 align
> offset
- aligned_offset
);
2523 if (ret
& BDRV_BLOCK_RECURSE
) {
2524 assert(ret
& BDRV_BLOCK_DATA
);
2525 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2526 assert(!(ret
& BDRV_BLOCK_ZERO
));
2529 *pnum
-= offset
- aligned_offset
;
2530 if (*pnum
> bytes
) {
2533 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2534 local_map
+= offset
- aligned_offset
;
2537 if (ret
& BDRV_BLOCK_RAW
) {
2538 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2539 ret
= bdrv_co_do_block_status(local_file
, want_zero
, local_map
,
2540 *pnum
, pnum
, &local_map
, &local_file
);
2544 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2545 ret
|= BDRV_BLOCK_ALLOCATED
;
2546 } else if (bs
->drv
->supports_backing
) {
2547 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2550 ret
|= BDRV_BLOCK_ZERO
;
2551 } else if (want_zero
) {
2552 int64_t size2
= bdrv_co_getlength(cow_bs
);
2554 if (size2
>= 0 && offset
>= size2
) {
2555 ret
|= BDRV_BLOCK_ZERO
;
2560 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2561 local_file
&& local_file
!= bs
&&
2562 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2563 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2567 ret2
= bdrv_co_do_block_status(local_file
, want_zero
, local_map
,
2568 *pnum
, &file_pnum
, NULL
, NULL
);
2570 /* Ignore errors. This is just providing extra information, it
2571 * is useful but not necessary.
2573 if (ret2
& BDRV_BLOCK_EOF
&&
2574 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2576 * It is valid for the format block driver to read
2577 * beyond the end of the underlying file's current
2578 * size; such areas read as zero.
2580 ret
|= BDRV_BLOCK_ZERO
;
2582 /* Limit request to the range reported by the protocol driver */
2584 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2590 bdrv_dec_in_flight(bs
);
2591 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2592 ret
|= BDRV_BLOCK_EOF
;
2605 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2606 BlockDriverState
*base
,
2613 BlockDriverState
**file
,
2617 BlockDriverState
*p
;
2622 assert(!include_base
|| base
); /* Can't include NULL base */
2623 assert_bdrv_graph_readable();
2630 if (!include_base
&& bs
== base
) {
2635 ret
= bdrv_co_do_block_status(bs
, want_zero
, offset
, bytes
, pnum
,
2638 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2642 if (ret
& BDRV_BLOCK_EOF
) {
2643 eof
= offset
+ *pnum
;
2646 assert(*pnum
<= bytes
);
2649 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2650 p
= bdrv_filter_or_cow_bs(p
))
2652 ret
= bdrv_co_do_block_status(p
, want_zero
, offset
, bytes
, pnum
,
2660 * The top layer deferred to this layer, and because this layer is
2661 * short, any zeroes that we synthesize beyond EOF behave as if they
2662 * were allocated at this layer.
2664 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2665 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2668 assert(ret
& BDRV_BLOCK_EOF
);
2673 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2676 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2678 * We've found the node and the status, we must break.
2680 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2681 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2684 ret
&= ~BDRV_BLOCK_EOF
;
2689 assert(include_base
);
2694 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2695 * let's continue the diving.
2697 assert(*pnum
<= bytes
);
2701 if (offset
+ *pnum
== eof
) {
2702 ret
|= BDRV_BLOCK_EOF
;
2708 int coroutine_fn
bdrv_co_block_status_above(BlockDriverState
*bs
,
2709 BlockDriverState
*base
,
2710 int64_t offset
, int64_t bytes
,
2711 int64_t *pnum
, int64_t *map
,
2712 BlockDriverState
**file
)
2715 return bdrv_co_common_block_status_above(bs
, base
, false, true, offset
,
2716 bytes
, pnum
, map
, file
, NULL
);
2719 int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
, int64_t offset
,
2720 int64_t bytes
, int64_t *pnum
,
2721 int64_t *map
, BlockDriverState
**file
)
2724 return bdrv_co_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2725 offset
, bytes
, pnum
, map
, file
);
2729 * Check @bs (and its backing chain) to see if the range defined
2730 * by @offset and @bytes is known to read as zeroes.
2731 * Return 1 if that is the case, 0 otherwise and -errno on error.
2732 * This test is meant to be fast rather than accurate so returning 0
2733 * does not guarantee non-zero data.
2735 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2739 int64_t pnum
= bytes
;
2746 ret
= bdrv_co_common_block_status_above(bs
, NULL
, false, false, offset
,
2747 bytes
, &pnum
, NULL
, NULL
, NULL
);
2753 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2756 int coroutine_fn
bdrv_co_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2757 int64_t bytes
, int64_t *pnum
)
2763 ret
= bdrv_co_common_block_status_above(bs
, bs
, true, false, offset
,
2764 bytes
, pnum
? pnum
: &dummy
, NULL
,
2769 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2773 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2775 * Return a positive depth if (a prefix of) the given range is allocated
2776 * in any image between BASE and TOP (BASE is only included if include_base
2777 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2778 * BASE can be NULL to check if the given offset is allocated in any
2779 * image of the chain. Return 0 otherwise, or negative errno on
2782 * 'pnum' is set to the number of bytes (including and immediately
2783 * following the specified offset) that are known to be in the same
2784 * allocated/unallocated state. Note that a subsequent call starting
2785 * at 'offset + *pnum' may return the same allocation status (in other
2786 * words, the result is not necessarily the maximum possible range);
2787 * but 'pnum' will only be 0 when end of file is reached.
2789 int coroutine_fn
bdrv_co_is_allocated_above(BlockDriverState
*bs
,
2790 BlockDriverState
*base
,
2791 bool include_base
, int64_t offset
,
2792 int64_t bytes
, int64_t *pnum
)
2798 ret
= bdrv_co_common_block_status_above(bs
, base
, include_base
, false,
2799 offset
, bytes
, pnum
, NULL
, NULL
,
2805 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2812 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2814 BlockDriver
*drv
= bs
->drv
;
2815 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2818 assert_bdrv_graph_readable();
2820 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2829 bdrv_inc_in_flight(bs
);
2831 if (drv
->bdrv_co_load_vmstate
) {
2832 ret
= drv
->bdrv_co_load_vmstate(bs
, qiov
, pos
);
2833 } else if (child_bs
) {
2834 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2839 bdrv_dec_in_flight(bs
);
2845 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2847 BlockDriver
*drv
= bs
->drv
;
2848 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2851 assert_bdrv_graph_readable();
2853 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2862 bdrv_inc_in_flight(bs
);
2864 if (drv
->bdrv_co_save_vmstate
) {
2865 ret
= drv
->bdrv_co_save_vmstate(bs
, qiov
, pos
);
2866 } else if (child_bs
) {
2867 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2872 bdrv_dec_in_flight(bs
);
2877 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2878 int64_t pos
, int size
)
2880 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2881 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2884 return ret
< 0 ? ret
: size
;
2887 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2888 int64_t pos
, int size
)
2890 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2891 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2894 return ret
< 0 ? ret
: size
;
2897 /**************************************************************/
2901 * Synchronously cancels an acb. Must be called with the BQL held and the acb
2902 * must be processed with the BQL held too (IOThreads are not allowed).
2904 * Use bdrv_aio_cancel_async() instead when possible.
2906 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2908 GLOBAL_STATE_CODE();
2910 bdrv_aio_cancel_async(acb
);
2911 AIO_WAIT_WHILE_UNLOCKED(NULL
, acb
->refcnt
> 1);
2912 qemu_aio_unref(acb
);
2915 /* Async version of aio cancel. The caller is not blocked if the acb implements
2916 * cancel_async, otherwise we do nothing and let the request normally complete.
2917 * In either case the completion callback must be called. */
2918 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2921 if (acb
->aiocb_info
->cancel_async
) {
2922 acb
->aiocb_info
->cancel_async(acb
);
2926 /**************************************************************/
2927 /* Coroutine block device emulation */
2929 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2931 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2937 assert_bdrv_graph_readable();
2938 bdrv_inc_in_flight(bs
);
2940 if (!bdrv_co_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2945 qemu_mutex_lock(&bs
->reqs_lock
);
2946 current_gen
= qatomic_read(&bs
->write_gen
);
2948 /* Wait until any previous flushes are completed */
2949 while (bs
->active_flush_req
) {
2950 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2953 /* Flushes reach this point in nondecreasing current_gen order. */
2954 bs
->active_flush_req
= true;
2955 qemu_mutex_unlock(&bs
->reqs_lock
);
2957 /* Write back all layers by calling one driver function */
2958 if (bs
->drv
->bdrv_co_flush
) {
2959 ret
= bs
->drv
->bdrv_co_flush(bs
);
2963 /* Write back cached data to the OS even with cache=unsafe */
2964 BLKDBG_CO_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2965 if (bs
->drv
->bdrv_co_flush_to_os
) {
2966 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2972 /* But don't actually force it to the disk with cache=unsafe */
2973 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2974 goto flush_children
;
2977 /* Check if we really need to flush anything */
2978 if (bs
->flushed_gen
== current_gen
) {
2979 goto flush_children
;
2982 BLKDBG_CO_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2984 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2985 * (even in case of apparent success) */
2989 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2990 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2991 } else if (bs
->drv
->bdrv_aio_flush
) {
2993 CoroutineIOCompletion co
= {
2994 .coroutine
= qemu_coroutine_self(),
2997 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3001 qemu_coroutine_yield();
3006 * Some block drivers always operate in either writethrough or unsafe
3007 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
3008 * know how the server works (because the behaviour is hardcoded or
3009 * depends on server-side configuration), so we can't ensure that
3010 * everything is safe on disk. Returning an error doesn't work because
3011 * that would break guests even if the server operates in writethrough
3014 * Let's hope the user knows what he's doing.
3023 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
3024 * in the case of cache=unsafe, so there are no useless flushes.
3028 QLIST_FOREACH(child
, &bs
->children
, next
) {
3029 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
3030 int this_child_ret
= bdrv_co_flush(child
->bs
);
3032 ret
= this_child_ret
;
3038 /* Notify any pending flushes that we have completed */
3040 bs
->flushed_gen
= current_gen
;
3043 qemu_mutex_lock(&bs
->reqs_lock
);
3044 bs
->active_flush_req
= false;
3045 /* Return value is ignored - it's ok if wait queue is empty */
3046 qemu_co_queue_next(&bs
->flush_queue
);
3047 qemu_mutex_unlock(&bs
->reqs_lock
);
3050 bdrv_dec_in_flight(bs
);
3054 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
3057 BdrvTrackedRequest req
;
3059 int64_t max_pdiscard
;
3060 int head
, tail
, align
;
3061 BlockDriverState
*bs
= child
->bs
;
3063 assert_bdrv_graph_readable();
3065 if (!bs
|| !bs
->drv
|| !bdrv_co_is_inserted(bs
)) {
3069 if (bdrv_has_readonly_bitmaps(bs
)) {
3073 ret
= bdrv_check_request(offset
, bytes
, NULL
);
3078 /* Do nothing if disabled. */
3079 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
3083 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
3087 /* Invalidate the cached block-status data range if this discard overlaps */
3088 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
3090 /* Discard is advisory, but some devices track and coalesce
3091 * unaligned requests, so we must pass everything down rather than
3092 * round here. Still, most devices will just silently ignore
3093 * unaligned requests (by returning -ENOTSUP), so we must fragment
3094 * the request accordingly. */
3095 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
3096 assert(align
% bs
->bl
.request_alignment
== 0);
3097 head
= offset
% align
;
3098 tail
= (offset
+ bytes
) % align
;
3100 bdrv_inc_in_flight(bs
);
3101 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
3103 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
3108 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
3110 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
3113 int64_t num
= bytes
;
3116 /* Make small requests to get to alignment boundaries. */
3117 num
= MIN(bytes
, align
- head
);
3118 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
3119 num
%= bs
->bl
.request_alignment
;
3121 head
= (head
+ num
) % align
;
3122 assert(num
< max_pdiscard
);
3125 /* Shorten the request to the last aligned cluster. */
3127 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
3128 tail
> bs
->bl
.request_alignment
) {
3129 tail
%= bs
->bl
.request_alignment
;
3133 /* limit request size */
3134 if (num
> max_pdiscard
) {
3142 if (bs
->drv
->bdrv_co_pdiscard
) {
3143 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
3146 CoroutineIOCompletion co
= {
3147 .coroutine
= qemu_coroutine_self(),
3150 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
3151 bdrv_co_io_em_complete
, &co
);
3156 qemu_coroutine_yield();
3160 if (ret
&& ret
!= -ENOTSUP
) {
3169 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3170 tracked_request_end(&req
);
3171 bdrv_dec_in_flight(bs
);
3175 int coroutine_fn
bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3177 BlockDriver
*drv
= bs
->drv
;
3178 CoroutineIOCompletion co
= {
3179 .coroutine
= qemu_coroutine_self(),
3183 assert_bdrv_graph_readable();
3185 bdrv_inc_in_flight(bs
);
3186 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3191 if (drv
->bdrv_co_ioctl
) {
3192 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3194 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3199 qemu_coroutine_yield();
3202 bdrv_dec_in_flight(bs
);
3206 int coroutine_fn
bdrv_co_zone_report(BlockDriverState
*bs
, int64_t offset
,
3207 unsigned int *nr_zones
,
3208 BlockZoneDescriptor
*zones
)
3210 BlockDriver
*drv
= bs
->drv
;
3211 CoroutineIOCompletion co
= {
3212 .coroutine
= qemu_coroutine_self(),
3216 bdrv_inc_in_flight(bs
);
3217 if (!drv
|| !drv
->bdrv_co_zone_report
|| bs
->bl
.zoned
== BLK_Z_NONE
) {
3221 co
.ret
= drv
->bdrv_co_zone_report(bs
, offset
, nr_zones
, zones
);
3223 bdrv_dec_in_flight(bs
);
3227 int coroutine_fn
bdrv_co_zone_mgmt(BlockDriverState
*bs
, BlockZoneOp op
,
3228 int64_t offset
, int64_t len
)
3230 BlockDriver
*drv
= bs
->drv
;
3231 CoroutineIOCompletion co
= {
3232 .coroutine
= qemu_coroutine_self(),
3236 bdrv_inc_in_flight(bs
);
3237 if (!drv
|| !drv
->bdrv_co_zone_mgmt
|| bs
->bl
.zoned
== BLK_Z_NONE
) {
3241 co
.ret
= drv
->bdrv_co_zone_mgmt(bs
, op
, offset
, len
);
3243 bdrv_dec_in_flight(bs
);
3247 int coroutine_fn
bdrv_co_zone_append(BlockDriverState
*bs
, int64_t *offset
,
3249 BdrvRequestFlags flags
)
3252 BlockDriver
*drv
= bs
->drv
;
3253 CoroutineIOCompletion co
= {
3254 .coroutine
= qemu_coroutine_self(),
3258 ret
= bdrv_check_qiov_request(*offset
, qiov
->size
, qiov
, 0, NULL
);
3263 bdrv_inc_in_flight(bs
);
3264 if (!drv
|| !drv
->bdrv_co_zone_append
|| bs
->bl
.zoned
== BLK_Z_NONE
) {
3268 co
.ret
= drv
->bdrv_co_zone_append(bs
, offset
, qiov
, flags
);
3270 bdrv_dec_in_flight(bs
);
3274 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3277 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3280 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3283 return memset(qemu_blockalign(bs
, size
), 0, size
);
3286 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3288 size_t align
= bdrv_opt_mem_align(bs
);
3291 /* Ensure that NULL is never returned on success */
3297 return qemu_try_memalign(align
, size
);
3300 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3302 void *mem
= qemu_try_blockalign(bs
, size
);
3306 memset(mem
, 0, size
);
3312 /* Helper that undoes bdrv_register_buf() when it fails partway through */
3313 static void GRAPH_RDLOCK
3314 bdrv_register_buf_rollback(BlockDriverState
*bs
, void *host
, size_t size
,
3315 BdrvChild
*final_child
)
3319 GLOBAL_STATE_CODE();
3320 assert_bdrv_graph_readable();
3322 QLIST_FOREACH(child
, &bs
->children
, next
) {
3323 if (child
== final_child
) {
3327 bdrv_unregister_buf(child
->bs
, host
, size
);
3330 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3331 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3335 bool bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
,
3340 GLOBAL_STATE_CODE();
3341 GRAPH_RDLOCK_GUARD_MAINLOOP();
3343 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3344 if (!bs
->drv
->bdrv_register_buf(bs
, host
, size
, errp
)) {
3348 QLIST_FOREACH(child
, &bs
->children
, next
) {
3349 if (!bdrv_register_buf(child
->bs
, host
, size
, errp
)) {
3350 bdrv_register_buf_rollback(bs
, host
, size
, child
);
3357 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3361 GLOBAL_STATE_CODE();
3362 GRAPH_RDLOCK_GUARD_MAINLOOP();
3364 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3365 bs
->drv
->bdrv_unregister_buf(bs
, host
, size
);
3367 QLIST_FOREACH(child
, &bs
->children
, next
) {
3368 bdrv_unregister_buf(child
->bs
, host
, size
);
3372 static int coroutine_fn GRAPH_RDLOCK
bdrv_co_copy_range_internal(
3373 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3374 int64_t dst_offset
, int64_t bytes
,
3375 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3378 BdrvTrackedRequest req
;
3380 assert_bdrv_graph_readable();
3382 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3383 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3384 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3385 assert(!(read_flags
& BDRV_REQ_NO_WAIT
));
3386 assert(!(write_flags
& BDRV_REQ_NO_WAIT
));
3388 if (!dst
|| !dst
->bs
|| !bdrv_co_is_inserted(dst
->bs
)) {
3391 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3395 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3396 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3399 if (!src
|| !src
->bs
|| !bdrv_co_is_inserted(src
->bs
)) {
3402 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3407 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3408 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3409 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3414 bdrv_inc_in_flight(src
->bs
);
3415 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3418 /* BDRV_REQ_SERIALISING is only for write operation */
3419 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3420 bdrv_wait_serialising_requests(&req
);
3422 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3426 read_flags
, write_flags
);
3428 tracked_request_end(&req
);
3429 bdrv_dec_in_flight(src
->bs
);
3431 bdrv_inc_in_flight(dst
->bs
);
3432 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3433 BDRV_TRACKED_WRITE
);
3434 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3437 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3441 read_flags
, write_flags
);
3443 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3444 tracked_request_end(&req
);
3445 bdrv_dec_in_flight(dst
->bs
);
3451 /* Copy range from @src to @dst.
3453 * See the comment of bdrv_co_copy_range for the parameter and return value
3455 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3456 BdrvChild
*dst
, int64_t dst_offset
,
3458 BdrvRequestFlags read_flags
,
3459 BdrvRequestFlags write_flags
)
3462 assert_bdrv_graph_readable();
3463 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3464 read_flags
, write_flags
);
3465 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3466 bytes
, read_flags
, write_flags
, true);
3469 /* Copy range from @src to @dst.
3471 * See the comment of bdrv_co_copy_range for the parameter and return value
3473 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3474 BdrvChild
*dst
, int64_t dst_offset
,
3476 BdrvRequestFlags read_flags
,
3477 BdrvRequestFlags write_flags
)
3480 assert_bdrv_graph_readable();
3481 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3482 read_flags
, write_flags
);
3483 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3484 bytes
, read_flags
, write_flags
, false);
3487 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3488 BdrvChild
*dst
, int64_t dst_offset
,
3489 int64_t bytes
, BdrvRequestFlags read_flags
,
3490 BdrvRequestFlags write_flags
)
3493 assert_bdrv_graph_readable();
3495 return bdrv_co_copy_range_from(src
, src_offset
,
3497 bytes
, read_flags
, write_flags
);
3500 static void coroutine_fn GRAPH_RDLOCK
3501 bdrv_parent_cb_resize(BlockDriverState
*bs
)
3505 assert_bdrv_graph_readable();
3507 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3508 if (c
->klass
->resize
) {
3509 c
->klass
->resize(c
);
3515 * Truncate file to 'offset' bytes (needed only for file protocols)
3517 * If 'exact' is true, the file must be resized to exactly the given
3518 * 'offset'. Otherwise, it is sufficient for the node to be at least
3519 * 'offset' bytes in length.
3521 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3522 PreallocMode prealloc
, BdrvRequestFlags flags
,
3525 BlockDriverState
*bs
= child
->bs
;
3526 BdrvChild
*filtered
, *backing
;
3527 BlockDriver
*drv
= bs
->drv
;
3528 BdrvTrackedRequest req
;
3529 int64_t old_size
, new_bytes
;
3532 assert_bdrv_graph_readable();
3534 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3536 error_setg(errp
, "No medium inserted");
3540 error_setg(errp
, "Image size cannot be negative");
3544 ret
= bdrv_check_request(offset
, 0, errp
);
3549 old_size
= bdrv_co_getlength(bs
);
3551 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3555 if (bdrv_is_read_only(bs
)) {
3556 error_setg(errp
, "Image is read-only");
3560 if (offset
> old_size
) {
3561 new_bytes
= offset
- old_size
;
3566 bdrv_inc_in_flight(bs
);
3567 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3568 BDRV_TRACKED_TRUNCATE
);
3570 /* If we are growing the image and potentially using preallocation for the
3571 * new area, we need to make sure that no write requests are made to it
3572 * concurrently or they might be overwritten by preallocation. */
3574 bdrv_make_request_serialising(&req
, 1);
3576 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3579 error_setg_errno(errp
, -ret
,
3580 "Failed to prepare request for truncation");
3584 filtered
= bdrv_filter_child(bs
);
3585 backing
= bdrv_cow_child(bs
);
3588 * If the image has a backing file that is large enough that it would
3589 * provide data for the new area, we cannot leave it unallocated because
3590 * then the backing file content would become visible. Instead, zero-fill
3593 * Note that if the image has a backing file, but was opened without the
3594 * backing file, taking care of keeping things consistent with that backing
3595 * file is the user's responsibility.
3597 if (new_bytes
&& backing
) {
3598 int64_t backing_len
;
3600 backing_len
= bdrv_co_getlength(backing
->bs
);
3601 if (backing_len
< 0) {
3603 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3607 if (backing_len
> old_size
) {
3608 flags
|= BDRV_REQ_ZERO_WRITE
;
3612 if (drv
->bdrv_co_truncate
) {
3613 if (flags
& ~bs
->supported_truncate_flags
) {
3614 error_setg(errp
, "Block driver does not support requested flags");
3618 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3619 } else if (filtered
) {
3620 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3622 error_setg(errp
, "Image format driver does not support resize");
3630 ret
= bdrv_co_refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3632 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3634 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3637 * It's possible that truncation succeeded but bdrv_refresh_total_sectors
3638 * failed, but the latter doesn't affect how we should finish the request.
3639 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled.
3641 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3644 tracked_request_end(&req
);
3645 bdrv_dec_in_flight(bs
);
3650 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3652 GLOBAL_STATE_CODE();
3653 GRAPH_RDLOCK_GUARD_MAINLOOP();
3655 if (!bs
|| !bs
->drv
) {
3659 if (bs
->drv
->bdrv_cancel_in_flight
) {
3660 bs
->drv
->bdrv_cancel_in_flight(bs
);
3665 bdrv_co_preadv_snapshot(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
3666 QEMUIOVector
*qiov
, size_t qiov_offset
)
3668 BlockDriverState
*bs
= child
->bs
;
3669 BlockDriver
*drv
= bs
->drv
;
3672 assert_bdrv_graph_readable();
3678 if (!drv
->bdrv_co_preadv_snapshot
) {
3682 bdrv_inc_in_flight(bs
);
3683 ret
= drv
->bdrv_co_preadv_snapshot(bs
, offset
, bytes
, qiov
, qiov_offset
);
3684 bdrv_dec_in_flight(bs
);
3690 bdrv_co_snapshot_block_status(BlockDriverState
*bs
,
3691 bool want_zero
, int64_t offset
, int64_t bytes
,
3692 int64_t *pnum
, int64_t *map
,
3693 BlockDriverState
**file
)
3695 BlockDriver
*drv
= bs
->drv
;
3698 assert_bdrv_graph_readable();
3704 if (!drv
->bdrv_co_snapshot_block_status
) {
3708 bdrv_inc_in_flight(bs
);
3709 ret
= drv
->bdrv_co_snapshot_block_status(bs
, want_zero
, offset
, bytes
,
3711 bdrv_dec_in_flight(bs
);
3717 bdrv_co_pdiscard_snapshot(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
)
3719 BlockDriver
*drv
= bs
->drv
;
3722 assert_bdrv_graph_readable();
3728 if (!drv
->bdrv_co_pdiscard_snapshot
) {
3732 bdrv_inc_in_flight(bs
);
3733 ret
= drv
->bdrv_co_pdiscard_snapshot(bs
, offset
, bytes
);
3734 bdrv_dec_in_flight(bs
);