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 "qapi/error.h"
36 #include "qemu/error-report.h"
37 #include "qemu/main-loop.h"
38 #include "sysemu/replay.h"
40 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
41 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
43 static void bdrv_parent_cb_resize(BlockDriverState
*bs
);
44 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
45 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
);
47 static void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
,
48 bool ignore_bds_parents
)
52 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
53 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
56 bdrv_parent_drained_begin_single(c
, false);
60 static void bdrv_parent_drained_end_single_no_poll(BdrvChild
*c
,
61 int *drained_end_counter
)
63 assert(c
->parent_quiesce_counter
> 0);
64 c
->parent_quiesce_counter
--;
65 if (c
->klass
->drained_end
) {
66 c
->klass
->drained_end(c
, drained_end_counter
);
70 void bdrv_parent_drained_end_single(BdrvChild
*c
)
72 int drained_end_counter
= 0;
74 bdrv_parent_drained_end_single_no_poll(c
, &drained_end_counter
);
75 BDRV_POLL_WHILE(c
->bs
, qatomic_read(&drained_end_counter
) > 0);
78 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
,
79 bool ignore_bds_parents
,
80 int *drained_end_counter
)
84 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
85 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
88 bdrv_parent_drained_end_single_no_poll(c
, drained_end_counter
);
92 static bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
94 if (c
->klass
->drained_poll
) {
95 return c
->klass
->drained_poll(c
);
100 static bool bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
101 bool ignore_bds_parents
)
106 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
107 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
110 busy
|= bdrv_parent_drained_poll_single(c
);
116 void bdrv_parent_drained_begin_single(BdrvChild
*c
, bool poll
)
119 c
->parent_quiesce_counter
++;
120 if (c
->klass
->drained_begin
) {
121 c
->klass
->drained_begin(c
);
124 BDRV_POLL_WHILE(c
->bs
, bdrv_parent_drained_poll_single(c
));
128 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
130 dst
->pdiscard_alignment
= MAX(dst
->pdiscard_alignment
,
131 src
->pdiscard_alignment
);
132 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
133 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
134 dst
->max_hw_transfer
= MIN_NON_ZERO(dst
->max_hw_transfer
,
135 src
->max_hw_transfer
);
136 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
137 src
->opt_mem_alignment
);
138 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
139 src
->min_mem_alignment
);
140 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
141 dst
->max_hw_iov
= MIN_NON_ZERO(dst
->max_hw_iov
, src
->max_hw_iov
);
144 typedef struct BdrvRefreshLimitsState
{
145 BlockDriverState
*bs
;
147 } BdrvRefreshLimitsState
;
149 static void bdrv_refresh_limits_abort(void *opaque
)
151 BdrvRefreshLimitsState
*s
= opaque
;
153 s
->bs
->bl
= s
->old_bl
;
156 static TransactionActionDrv bdrv_refresh_limits_drv
= {
157 .abort
= bdrv_refresh_limits_abort
,
161 /* @tran is allowed to be NULL, in this case no rollback is possible. */
162 void bdrv_refresh_limits(BlockDriverState
*bs
, Transaction
*tran
, Error
**errp
)
165 BlockDriver
*drv
= bs
->drv
;
172 BdrvRefreshLimitsState
*s
= g_new(BdrvRefreshLimitsState
, 1);
173 *s
= (BdrvRefreshLimitsState
) {
177 tran_add(tran
, &bdrv_refresh_limits_drv
, s
);
180 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
186 /* Default alignment based on whether driver has byte interface */
187 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
188 drv
->bdrv_aio_preadv
||
189 drv
->bdrv_co_preadv_part
) ? 1 : 512;
191 /* Take some limits from the children as a default */
193 QLIST_FOREACH(c
, &bs
->children
, next
) {
194 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
196 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
202 bs
->bl
.min_mem_alignment
= 512;
203 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size
;
205 /* Safe default since most protocols use readv()/writev()/etc */
206 bs
->bl
.max_iov
= IOV_MAX
;
209 /* Then let the driver override it */
210 if (drv
->bdrv_refresh_limits
) {
211 drv
->bdrv_refresh_limits(bs
, errp
);
217 if (bs
->bl
.request_alignment
> BDRV_MAX_ALIGNMENT
) {
218 error_setg(errp
, "Driver requires too large request alignment");
223 * The copy-on-read flag is actually a reference count so multiple users may
224 * use the feature without worrying about clobbering its previous state.
225 * Copy-on-read stays enabled until all users have called to disable it.
227 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
230 qatomic_inc(&bs
->copy_on_read
);
233 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
235 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
242 BlockDriverState
*bs
;
248 bool ignore_bds_parents
;
249 int *drained_end_counter
;
252 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
254 BdrvCoDrainData
*data
= opaque
;
255 BlockDriverState
*bs
= data
->bs
;
258 bs
->drv
->bdrv_co_drain_begin(bs
);
260 bs
->drv
->bdrv_co_drain_end(bs
);
263 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
264 qatomic_mb_set(&data
->done
, true);
266 qatomic_dec(data
->drained_end_counter
);
268 bdrv_dec_in_flight(bs
);
273 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
274 static void bdrv_drain_invoke(BlockDriverState
*bs
, bool begin
,
275 int *drained_end_counter
)
277 BdrvCoDrainData
*data
;
279 if (!bs
->drv
|| (begin
&& !bs
->drv
->bdrv_co_drain_begin
) ||
280 (!begin
&& !bs
->drv
->bdrv_co_drain_end
)) {
284 data
= g_new(BdrvCoDrainData
, 1);
285 *data
= (BdrvCoDrainData
) {
289 .drained_end_counter
= drained_end_counter
,
293 qatomic_inc(drained_end_counter
);
296 /* Make sure the driver callback completes during the polling phase for
298 bdrv_inc_in_flight(bs
);
299 data
->co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, data
);
300 aio_co_schedule(bdrv_get_aio_context(bs
), data
->co
);
303 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
304 bool bdrv_drain_poll(BlockDriverState
*bs
, bool recursive
,
305 BdrvChild
*ignore_parent
, bool ignore_bds_parents
)
307 BdrvChild
*child
, *next
;
310 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
314 if (qatomic_read(&bs
->in_flight
)) {
319 assert(!ignore_bds_parents
);
320 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
321 if (bdrv_drain_poll(child
->bs
, recursive
, child
, false)) {
330 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
, bool recursive
,
331 BdrvChild
*ignore_parent
)
333 return bdrv_drain_poll(bs
, recursive
, ignore_parent
, false);
336 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
337 BdrvChild
*parent
, bool ignore_bds_parents
,
339 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
340 BdrvChild
*parent
, bool ignore_bds_parents
,
341 int *drained_end_counter
);
343 static void bdrv_co_drain_bh_cb(void *opaque
)
345 BdrvCoDrainData
*data
= opaque
;
346 Coroutine
*co
= data
->co
;
347 BlockDriverState
*bs
= data
->bs
;
350 AioContext
*ctx
= bdrv_get_aio_context(bs
);
351 aio_context_acquire(ctx
);
352 bdrv_dec_in_flight(bs
);
354 assert(!data
->drained_end_counter
);
355 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
,
356 data
->ignore_bds_parents
, data
->poll
);
359 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
,
360 data
->ignore_bds_parents
,
361 data
->drained_end_counter
);
363 aio_context_release(ctx
);
366 bdrv_drain_all_begin();
373 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
374 bool begin
, bool recursive
,
376 bool ignore_bds_parents
,
378 int *drained_end_counter
)
380 BdrvCoDrainData data
;
381 Coroutine
*self
= qemu_coroutine_self();
382 AioContext
*ctx
= bdrv_get_aio_context(bs
);
383 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(self
);
385 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
386 * other coroutines run if they were queued by aio_co_enter(). */
388 assert(qemu_in_coroutine());
389 data
= (BdrvCoDrainData
) {
394 .recursive
= recursive
,
396 .ignore_bds_parents
= ignore_bds_parents
,
398 .drained_end_counter
= drained_end_counter
,
402 bdrv_inc_in_flight(bs
);
406 * Temporarily drop the lock across yield or we would get deadlocks.
407 * bdrv_co_drain_bh_cb() reaquires the lock as needed.
409 * When we yield below, the lock for the current context will be
410 * released, so if this is actually the lock that protects bs, don't drop
414 aio_context_release(ctx
);
416 replay_bh_schedule_oneshot_event(ctx
, bdrv_co_drain_bh_cb
, &data
);
418 qemu_coroutine_yield();
419 /* If we are resumed from some other event (such as an aio completion or a
420 * timer callback), it is a bug in the caller that should be fixed. */
423 /* Reaquire the AioContext of bs if we dropped it */
425 aio_context_acquire(ctx
);
429 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
,
430 BdrvChild
*parent
, bool ignore_bds_parents
)
433 assert(!qemu_in_coroutine());
435 /* Stop things in parent-to-child order */
436 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
437 aio_disable_external(bdrv_get_aio_context(bs
));
440 bdrv_parent_drained_begin(bs
, parent
, ignore_bds_parents
);
441 bdrv_drain_invoke(bs
, true, NULL
);
444 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
445 BdrvChild
*parent
, bool ignore_bds_parents
,
448 BdrvChild
*child
, *next
;
450 if (qemu_in_coroutine()) {
451 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
, ignore_bds_parents
,
456 bdrv_do_drained_begin_quiesce(bs
, parent
, ignore_bds_parents
);
459 assert(!ignore_bds_parents
);
460 bs
->recursive_quiesce_counter
++;
461 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
462 bdrv_do_drained_begin(child
->bs
, true, child
, ignore_bds_parents
,
468 * Wait for drained requests to finish.
470 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
471 * call is needed so things in this AioContext can make progress even
472 * though we don't return to the main AioContext loop - this automatically
473 * includes other nodes in the same AioContext and therefore all child
477 assert(!ignore_bds_parents
);
478 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, recursive
, parent
));
482 void bdrv_drained_begin(BlockDriverState
*bs
)
485 bdrv_do_drained_begin(bs
, false, NULL
, false, true);
488 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
491 bdrv_do_drained_begin(bs
, true, NULL
, false, true);
495 * This function does not poll, nor must any of its recursively called
496 * functions. The *drained_end_counter pointee will be incremented
497 * once for every background operation scheduled, and decremented once
498 * the operation settles. Therefore, the pointer must remain valid
499 * until the pointee reaches 0. That implies that whoever sets up the
500 * pointee has to poll until it is 0.
502 * We use atomic operations to access *drained_end_counter, because
503 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
504 * @bs may contain nodes in different AioContexts,
505 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
506 * regardless of which AioContext they are in.
508 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
509 BdrvChild
*parent
, bool ignore_bds_parents
,
510 int *drained_end_counter
)
513 int old_quiesce_counter
;
515 assert(drained_end_counter
!= NULL
);
517 if (qemu_in_coroutine()) {
518 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
, ignore_bds_parents
,
519 false, drained_end_counter
);
522 assert(bs
->quiesce_counter
> 0);
524 /* Re-enable things in child-to-parent order */
525 bdrv_drain_invoke(bs
, false, drained_end_counter
);
526 bdrv_parent_drained_end(bs
, parent
, ignore_bds_parents
,
527 drained_end_counter
);
529 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
530 if (old_quiesce_counter
== 1) {
531 aio_enable_external(bdrv_get_aio_context(bs
));
535 assert(!ignore_bds_parents
);
536 bs
->recursive_quiesce_counter
--;
537 QLIST_FOREACH(child
, &bs
->children
, next
) {
538 bdrv_do_drained_end(child
->bs
, true, child
, ignore_bds_parents
,
539 drained_end_counter
);
544 void bdrv_drained_end(BlockDriverState
*bs
)
546 int drained_end_counter
= 0;
548 bdrv_do_drained_end(bs
, false, NULL
, false, &drained_end_counter
);
549 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
552 void bdrv_drained_end_no_poll(BlockDriverState
*bs
, int *drained_end_counter
)
555 bdrv_do_drained_end(bs
, false, NULL
, false, drained_end_counter
);
558 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
560 int drained_end_counter
= 0;
562 bdrv_do_drained_end(bs
, true, NULL
, false, &drained_end_counter
);
563 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
566 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
571 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
572 bdrv_do_drained_begin(child
->bs
, true, child
, false, true);
576 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
578 int drained_end_counter
= 0;
582 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
583 bdrv_do_drained_end(child
->bs
, true, child
, false,
584 &drained_end_counter
);
587 BDRV_POLL_WHILE(child
->bs
, qatomic_read(&drained_end_counter
) > 0);
591 * Wait for pending requests to complete on a single BlockDriverState subtree,
592 * and suspend block driver's internal I/O until next request arrives.
594 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
597 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
600 assert(qemu_in_coroutine());
601 bdrv_drained_begin(bs
);
602 bdrv_drained_end(bs
);
605 void bdrv_drain(BlockDriverState
*bs
)
608 bdrv_drained_begin(bs
);
609 bdrv_drained_end(bs
);
612 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
614 BdrvChild
*child
, *next
;
616 assert(qatomic_read(&bs
->in_flight
) == 0);
617 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
618 bdrv_drain_assert_idle(child
->bs
);
622 unsigned int bdrv_drain_all_count
= 0;
624 static bool bdrv_drain_all_poll(void)
626 BlockDriverState
*bs
= NULL
;
630 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
631 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
632 while ((bs
= bdrv_next_all_states(bs
))) {
633 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
634 aio_context_acquire(aio_context
);
635 result
|= bdrv_drain_poll(bs
, false, NULL
, true);
636 aio_context_release(aio_context
);
643 * Wait for pending requests to complete across all BlockDriverStates
645 * This function does not flush data to disk, use bdrv_flush_all() for that
646 * after calling this function.
648 * This pauses all block jobs and disables external clients. It must
649 * be paired with bdrv_drain_all_end().
651 * NOTE: no new block jobs or BlockDriverStates can be created between
652 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
654 void bdrv_drain_all_begin(void)
656 BlockDriverState
*bs
= NULL
;
659 if (qemu_in_coroutine()) {
660 bdrv_co_yield_to_drain(NULL
, true, false, NULL
, true, true, NULL
);
665 * bdrv queue is managed by record/replay,
666 * waiting for finishing the I/O requests may
669 if (replay_events_enabled()) {
673 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
674 * loop AioContext, so make sure we're in the main context. */
675 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
676 assert(bdrv_drain_all_count
< INT_MAX
);
677 bdrv_drain_all_count
++;
679 /* Quiesce all nodes, without polling in-flight requests yet. The graph
680 * cannot change during this loop. */
681 while ((bs
= bdrv_next_all_states(bs
))) {
682 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
684 aio_context_acquire(aio_context
);
685 bdrv_do_drained_begin(bs
, false, NULL
, true, false);
686 aio_context_release(aio_context
);
689 /* Now poll the in-flight requests */
690 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
692 while ((bs
= bdrv_next_all_states(bs
))) {
693 bdrv_drain_assert_idle(bs
);
697 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
699 int drained_end_counter
= 0;
702 g_assert(bs
->quiesce_counter
> 0);
703 g_assert(!bs
->refcnt
);
705 while (bs
->quiesce_counter
) {
706 bdrv_do_drained_end(bs
, false, NULL
, true, &drained_end_counter
);
708 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
711 void bdrv_drain_all_end(void)
713 BlockDriverState
*bs
= NULL
;
714 int drained_end_counter
= 0;
718 * bdrv queue is managed by record/replay,
719 * waiting for finishing the I/O requests may
722 if (replay_events_enabled()) {
726 while ((bs
= bdrv_next_all_states(bs
))) {
727 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
729 aio_context_acquire(aio_context
);
730 bdrv_do_drained_end(bs
, false, NULL
, true, &drained_end_counter
);
731 aio_context_release(aio_context
);
734 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
735 AIO_WAIT_WHILE(NULL
, qatomic_read(&drained_end_counter
) > 0);
737 assert(bdrv_drain_all_count
> 0);
738 bdrv_drain_all_count
--;
741 void bdrv_drain_all(void)
744 bdrv_drain_all_begin();
745 bdrv_drain_all_end();
749 * Remove an active request from the tracked requests list
751 * This function should be called when a tracked request is completing.
753 static void tracked_request_end(BdrvTrackedRequest
*req
)
755 if (req
->serialising
) {
756 qatomic_dec(&req
->bs
->serialising_in_flight
);
759 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
760 QLIST_REMOVE(req
, list
);
761 qemu_co_queue_restart_all(&req
->wait_queue
);
762 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
766 * Add an active request to the tracked requests list
768 static void tracked_request_begin(BdrvTrackedRequest
*req
,
769 BlockDriverState
*bs
,
772 enum BdrvTrackedRequestType type
)
774 bdrv_check_request(offset
, bytes
, &error_abort
);
776 *req
= (BdrvTrackedRequest
){
781 .co
= qemu_coroutine_self(),
782 .serialising
= false,
783 .overlap_offset
= offset
,
784 .overlap_bytes
= bytes
,
787 qemu_co_queue_init(&req
->wait_queue
);
789 qemu_co_mutex_lock(&bs
->reqs_lock
);
790 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
791 qemu_co_mutex_unlock(&bs
->reqs_lock
);
794 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
795 int64_t offset
, int64_t bytes
)
797 bdrv_check_request(offset
, bytes
, &error_abort
);
800 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
804 if (req
->overlap_offset
>= offset
+ bytes
) {
810 /* Called with self->bs->reqs_lock held */
811 static BdrvTrackedRequest
*
812 bdrv_find_conflicting_request(BdrvTrackedRequest
*self
)
814 BdrvTrackedRequest
*req
;
816 QLIST_FOREACH(req
, &self
->bs
->tracked_requests
, list
) {
817 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
820 if (tracked_request_overlaps(req
, self
->overlap_offset
,
821 self
->overlap_bytes
))
824 * Hitting this means there was a reentrant request, for
825 * example, a block driver issuing nested requests. This must
826 * never happen since it means deadlock.
828 assert(qemu_coroutine_self() != req
->co
);
831 * If the request is already (indirectly) waiting for us, or
832 * will wait for us as soon as it wakes up, then just go on
833 * (instead of producing a deadlock in the former case).
835 if (!req
->waiting_for
) {
844 /* Called with self->bs->reqs_lock held */
845 static bool coroutine_fn
846 bdrv_wait_serialising_requests_locked(BdrvTrackedRequest
*self
)
848 BdrvTrackedRequest
*req
;
851 while ((req
= bdrv_find_conflicting_request(self
))) {
852 self
->waiting_for
= req
;
853 qemu_co_queue_wait(&req
->wait_queue
, &self
->bs
->reqs_lock
);
854 self
->waiting_for
= NULL
;
861 /* Called with req->bs->reqs_lock held */
862 static void tracked_request_set_serialising(BdrvTrackedRequest
*req
,
865 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
866 int64_t overlap_bytes
=
867 ROUND_UP(req
->offset
+ req
->bytes
, align
) - overlap_offset
;
869 bdrv_check_request(req
->offset
, req
->bytes
, &error_abort
);
871 if (!req
->serialising
) {
872 qatomic_inc(&req
->bs
->serialising_in_flight
);
873 req
->serialising
= true;
876 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
877 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
881 * Return the tracked request on @bs for the current coroutine, or
882 * NULL if there is none.
884 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
886 BdrvTrackedRequest
*req
;
887 Coroutine
*self
= qemu_coroutine_self();
890 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
891 if (req
->co
== self
) {
900 * Round a region to cluster boundaries
902 void bdrv_round_to_clusters(BlockDriverState
*bs
,
903 int64_t offset
, int64_t bytes
,
904 int64_t *cluster_offset
,
905 int64_t *cluster_bytes
)
909 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
910 *cluster_offset
= offset
;
911 *cluster_bytes
= bytes
;
913 int64_t c
= bdi
.cluster_size
;
914 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
915 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
919 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
924 ret
= bdrv_get_info(bs
, &bdi
);
925 if (ret
< 0 || bdi
.cluster_size
== 0) {
926 return bs
->bl
.request_alignment
;
928 return bdi
.cluster_size
;
932 void bdrv_inc_in_flight(BlockDriverState
*bs
)
935 qatomic_inc(&bs
->in_flight
);
938 void bdrv_wakeup(BlockDriverState
*bs
)
944 void bdrv_dec_in_flight(BlockDriverState
*bs
)
947 qatomic_dec(&bs
->in_flight
);
951 static bool coroutine_fn
bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
953 BlockDriverState
*bs
= self
->bs
;
956 if (!qatomic_read(&bs
->serialising_in_flight
)) {
960 qemu_co_mutex_lock(&bs
->reqs_lock
);
961 waited
= bdrv_wait_serialising_requests_locked(self
);
962 qemu_co_mutex_unlock(&bs
->reqs_lock
);
967 bool coroutine_fn
bdrv_make_request_serialising(BdrvTrackedRequest
*req
,
973 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
975 tracked_request_set_serialising(req
, align
);
976 waited
= bdrv_wait_serialising_requests_locked(req
);
978 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
983 int bdrv_check_qiov_request(int64_t offset
, int64_t bytes
,
984 QEMUIOVector
*qiov
, size_t qiov_offset
,
988 * Check generic offset/bytes correctness
992 error_setg(errp
, "offset is negative: %" PRIi64
, offset
);
997 error_setg(errp
, "bytes is negative: %" PRIi64
, bytes
);
1001 if (bytes
> BDRV_MAX_LENGTH
) {
1002 error_setg(errp
, "bytes(%" PRIi64
") exceeds maximum(%" PRIi64
")",
1003 bytes
, BDRV_MAX_LENGTH
);
1007 if (offset
> BDRV_MAX_LENGTH
) {
1008 error_setg(errp
, "offset(%" PRIi64
") exceeds maximum(%" PRIi64
")",
1009 offset
, BDRV_MAX_LENGTH
);
1013 if (offset
> BDRV_MAX_LENGTH
- bytes
) {
1014 error_setg(errp
, "sum of offset(%" PRIi64
") and bytes(%" PRIi64
") "
1015 "exceeds maximum(%" PRIi64
")", offset
, bytes
,
1025 * Check qiov and qiov_offset
1028 if (qiov_offset
> qiov
->size
) {
1029 error_setg(errp
, "qiov_offset(%zu) overflow io vector size(%zu)",
1030 qiov_offset
, qiov
->size
);
1034 if (bytes
> qiov
->size
- qiov_offset
) {
1035 error_setg(errp
, "bytes(%" PRIi64
") + qiov_offset(%zu) overflow io "
1036 "vector size(%zu)", bytes
, qiov_offset
, qiov
->size
);
1043 int bdrv_check_request(int64_t offset
, int64_t bytes
, Error
**errp
)
1045 return bdrv_check_qiov_request(offset
, bytes
, NULL
, 0, errp
);
1048 static int bdrv_check_request32(int64_t offset
, int64_t bytes
,
1049 QEMUIOVector
*qiov
, size_t qiov_offset
)
1051 int ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
1056 if (bytes
> BDRV_REQUEST_MAX_BYTES
) {
1063 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1064 int64_t bytes
, BdrvRequestFlags flags
)
1067 return bdrv_pwritev(child
, offset
, bytes
, NULL
,
1068 BDRV_REQ_ZERO_WRITE
| flags
);
1072 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
1073 * The operation is sped up by checking the block status and only writing
1074 * zeroes to the device if they currently do not return zeroes. Optional
1075 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
1078 * Returns < 0 on error, 0 on success. For error codes see bdrv_pwrite().
1080 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
1083 int64_t target_size
, bytes
, offset
= 0;
1084 BlockDriverState
*bs
= child
->bs
;
1087 target_size
= bdrv_getlength(bs
);
1088 if (target_size
< 0) {
1093 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
1097 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
1101 if (ret
& BDRV_BLOCK_ZERO
) {
1105 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
1113 /* See bdrv_pwrite() for the return codes */
1114 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int64_t bytes
)
1117 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
1124 ret
= bdrv_preadv(child
, offset
, bytes
, &qiov
, 0);
1126 return ret
< 0 ? ret
: bytes
;
1129 /* Return no. of bytes on success or < 0 on error. Important errors are:
1130 -EIO generic I/O error (may happen for all errors)
1131 -ENOMEDIUM No media inserted.
1132 -EINVAL Invalid offset or number of bytes
1133 -EACCES Trying to write a read-only device
1135 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
,
1139 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
1146 ret
= bdrv_pwritev(child
, offset
, bytes
, &qiov
, 0);
1148 return ret
< 0 ? ret
: bytes
;
1152 * Writes to the file and ensures that no writes are reordered across this
1153 * request (acts as a barrier)
1155 * Returns 0 on success, -errno in error cases.
1157 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
1158 const void *buf
, int64_t count
)
1163 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
1168 ret
= bdrv_flush(child
->bs
);
1176 typedef struct CoroutineIOCompletion
{
1177 Coroutine
*coroutine
;
1179 } CoroutineIOCompletion
;
1181 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
1183 CoroutineIOCompletion
*co
= opaque
;
1186 aio_co_wake(co
->coroutine
);
1189 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
1190 int64_t offset
, int64_t bytes
,
1192 size_t qiov_offset
, int flags
)
1194 BlockDriver
*drv
= bs
->drv
;
1196 unsigned int nb_sectors
;
1197 QEMUIOVector local_qiov
;
1200 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1201 assert(!(flags
& ~BDRV_REQ_MASK
));
1202 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1208 if (drv
->bdrv_co_preadv_part
) {
1209 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1213 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1214 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1218 if (drv
->bdrv_co_preadv
) {
1219 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
1223 if (drv
->bdrv_aio_preadv
) {
1225 CoroutineIOCompletion co
= {
1226 .coroutine
= qemu_coroutine_self(),
1229 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1230 bdrv_co_io_em_complete
, &co
);
1235 qemu_coroutine_yield();
1241 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1242 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1244 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1245 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1246 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1247 assert(drv
->bdrv_co_readv
);
1249 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1252 if (qiov
== &local_qiov
) {
1253 qemu_iovec_destroy(&local_qiov
);
1259 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1260 int64_t offset
, int64_t bytes
,
1263 BdrvRequestFlags flags
)
1265 BlockDriver
*drv
= bs
->drv
;
1267 unsigned int nb_sectors
;
1268 QEMUIOVector local_qiov
;
1271 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1272 assert(!(flags
& ~BDRV_REQ_MASK
));
1273 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1279 if (drv
->bdrv_co_pwritev_part
) {
1280 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1281 flags
& bs
->supported_write_flags
);
1282 flags
&= ~bs
->supported_write_flags
;
1286 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1287 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1291 if (drv
->bdrv_co_pwritev
) {
1292 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
1293 flags
& bs
->supported_write_flags
);
1294 flags
&= ~bs
->supported_write_flags
;
1298 if (drv
->bdrv_aio_pwritev
) {
1300 CoroutineIOCompletion co
= {
1301 .coroutine
= qemu_coroutine_self(),
1304 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
,
1305 flags
& bs
->supported_write_flags
,
1306 bdrv_co_io_em_complete
, &co
);
1307 flags
&= ~bs
->supported_write_flags
;
1311 qemu_coroutine_yield();
1317 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1318 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1320 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1321 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1322 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1324 assert(drv
->bdrv_co_writev
);
1325 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
,
1326 flags
& bs
->supported_write_flags
);
1327 flags
&= ~bs
->supported_write_flags
;
1330 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
1331 ret
= bdrv_co_flush(bs
);
1334 if (qiov
== &local_qiov
) {
1335 qemu_iovec_destroy(&local_qiov
);
1341 static int coroutine_fn
1342 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, int64_t offset
,
1343 int64_t bytes
, QEMUIOVector
*qiov
,
1346 BlockDriver
*drv
= bs
->drv
;
1347 QEMUIOVector local_qiov
;
1350 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1356 if (!block_driver_can_compress(drv
)) {
1360 if (drv
->bdrv_co_pwritev_compressed_part
) {
1361 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1365 if (qiov_offset
== 0) {
1366 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1369 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1370 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1371 qemu_iovec_destroy(&local_qiov
);
1376 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1377 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1378 size_t qiov_offset
, int flags
)
1380 BlockDriverState
*bs
= child
->bs
;
1382 /* Perform I/O through a temporary buffer so that users who scribble over
1383 * their read buffer while the operation is in progress do not end up
1384 * modifying the image file. This is critical for zero-copy guest I/O
1385 * where anything might happen inside guest memory.
1387 void *bounce_buffer
= NULL
;
1389 BlockDriver
*drv
= bs
->drv
;
1390 int64_t cluster_offset
;
1391 int64_t cluster_bytes
;
1394 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1395 BDRV_REQUEST_MAX_BYTES
);
1396 int64_t progress
= 0;
1399 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1406 * Do not write anything when the BDS is inactive. That is not
1407 * allowed, and it would not help.
1409 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1411 /* FIXME We cannot require callers to have write permissions when all they
1412 * are doing is a read request. If we did things right, write permissions
1413 * would be obtained anyway, but internally by the copy-on-read code. As
1414 * long as it is implemented here rather than in a separate filter driver,
1415 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1416 * it could request permissions. Therefore we have to bypass the permission
1417 * system for the moment. */
1418 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1420 /* Cover entire cluster so no additional backing file I/O is required when
1421 * allocating cluster in the image file. Note that this value may exceed
1422 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1423 * is one reason we loop rather than doing it all at once.
1425 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1426 skip_bytes
= offset
- cluster_offset
;
1428 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1429 cluster_offset
, cluster_bytes
);
1431 while (cluster_bytes
) {
1435 ret
= 1; /* "already allocated", so nothing will be copied */
1436 pnum
= MIN(cluster_bytes
, max_transfer
);
1438 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1439 MIN(cluster_bytes
, max_transfer
), &pnum
);
1442 * Safe to treat errors in querying allocation as if
1443 * unallocated; we'll probably fail again soon on the
1444 * read, but at least that will set a decent errno.
1446 pnum
= MIN(cluster_bytes
, max_transfer
);
1449 /* Stop at EOF if the image ends in the middle of the cluster */
1450 if (ret
== 0 && pnum
== 0) {
1451 assert(progress
>= bytes
);
1455 assert(skip_bytes
< pnum
);
1459 QEMUIOVector local_qiov
;
1461 /* Must copy-on-read; use the bounce buffer */
1462 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1463 if (!bounce_buffer
) {
1464 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1465 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1466 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1468 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1469 if (!bounce_buffer
) {
1474 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1476 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1482 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1483 if (drv
->bdrv_co_pwrite_zeroes
&&
1484 buffer_is_zero(bounce_buffer
, pnum
)) {
1485 /* FIXME: Should we (perhaps conditionally) be setting
1486 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1487 * that still correctly reads as zero? */
1488 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1489 BDRV_REQ_WRITE_UNCHANGED
);
1491 /* This does not change the data on the disk, it is not
1492 * necessary to flush even in cache=writethrough mode.
1494 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1496 BDRV_REQ_WRITE_UNCHANGED
);
1500 /* It might be okay to ignore write errors for guest
1501 * requests. If this is a deliberate copy-on-read
1502 * then we don't want to ignore the error. Simply
1503 * report it in all cases.
1508 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1509 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1510 bounce_buffer
+ skip_bytes
,
1511 MIN(pnum
- skip_bytes
, bytes
- progress
));
1513 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1514 /* Read directly into the destination */
1515 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1516 MIN(pnum
- skip_bytes
, bytes
- progress
),
1517 qiov
, qiov_offset
+ progress
, 0);
1523 cluster_offset
+= pnum
;
1524 cluster_bytes
-= pnum
;
1525 progress
+= pnum
- skip_bytes
;
1531 qemu_vfree(bounce_buffer
);
1536 * Forwards an already correctly aligned request to the BlockDriver. This
1537 * handles copy on read, zeroing after EOF, and fragmentation of large
1538 * reads; any other features must be implemented by the caller.
1540 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1541 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
1542 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1544 BlockDriverState
*bs
= child
->bs
;
1545 int64_t total_bytes
, max_bytes
;
1547 int64_t bytes_remaining
= bytes
;
1550 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
1551 assert(is_power_of_2(align
));
1552 assert((offset
& (align
- 1)) == 0);
1553 assert((bytes
& (align
- 1)) == 0);
1554 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1555 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1558 /* TODO: We would need a per-BDS .supported_read_flags and
1559 * potential fallback support, if we ever implement any read flags
1560 * to pass through to drivers. For now, there aren't any
1561 * passthrough flags. */
1562 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
)));
1564 /* Handle Copy on Read and associated serialisation */
1565 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1566 /* If we touch the same cluster it counts as an overlap. This
1567 * guarantees that allocating writes will be serialized and not race
1568 * with each other for the same cluster. For example, in copy-on-read
1569 * it ensures that the CoR read and write operations are atomic and
1570 * guest writes cannot interleave between them. */
1571 bdrv_make_request_serialising(req
, bdrv_get_cluster_size(bs
));
1573 bdrv_wait_serialising_requests(req
);
1576 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1579 /* The flag BDRV_REQ_COPY_ON_READ has reached its addressee */
1580 flags
&= ~BDRV_REQ_COPY_ON_READ
;
1582 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1587 if (!ret
|| pnum
!= bytes
) {
1588 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1589 qiov
, qiov_offset
, flags
);
1591 } else if (flags
& BDRV_REQ_PREFETCH
) {
1596 /* Forward the request to the BlockDriver, possibly fragmenting it */
1597 total_bytes
= bdrv_getlength(bs
);
1598 if (total_bytes
< 0) {
1603 assert(!(flags
& ~bs
->supported_read_flags
));
1605 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1606 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1607 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1611 while (bytes_remaining
) {
1615 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1618 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1620 qiov_offset
+ bytes
- bytes_remaining
,
1624 num
= bytes_remaining
;
1625 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1626 0, bytes_remaining
);
1631 bytes_remaining
-= num
;
1635 return ret
< 0 ? ret
: 0;
1641 * |<---- align ----->| |<----- align ---->|
1642 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1644 * -*----------$-------*-------- ... --------*-----$------------*---
1646 * | offset | | end |
1647 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1648 * [buf ... ) [tail_buf )
1650 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1651 * is placed at the beginning of @buf and @tail at the @end.
1653 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1654 * around tail, if tail exists.
1656 * @merge_reads is true for small requests,
1657 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1658 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1660 typedef struct BdrvRequestPadding
{
1667 QEMUIOVector local_qiov
;
1668 } BdrvRequestPadding
;
1670 static bool bdrv_init_padding(BlockDriverState
*bs
,
1671 int64_t offset
, int64_t bytes
,
1672 BdrvRequestPadding
*pad
)
1674 int64_t align
= bs
->bl
.request_alignment
;
1677 bdrv_check_request(offset
, bytes
, &error_abort
);
1678 assert(align
<= INT_MAX
); /* documented in block/block_int.h */
1679 assert(align
<= SIZE_MAX
/ 2); /* so we can allocate the buffer */
1681 memset(pad
, 0, sizeof(*pad
));
1683 pad
->head
= offset
& (align
- 1);
1684 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1686 pad
->tail
= align
- pad
->tail
;
1689 if (!pad
->head
&& !pad
->tail
) {
1693 assert(bytes
); /* Nothing good in aligning zero-length requests */
1695 sum
= pad
->head
+ bytes
+ pad
->tail
;
1696 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1697 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1698 pad
->merge_reads
= sum
== pad
->buf_len
;
1700 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1706 static int bdrv_padding_rmw_read(BdrvChild
*child
,
1707 BdrvTrackedRequest
*req
,
1708 BdrvRequestPadding
*pad
,
1711 QEMUIOVector local_qiov
;
1712 BlockDriverState
*bs
= child
->bs
;
1713 uint64_t align
= bs
->bl
.request_alignment
;
1716 assert(req
->serialising
&& pad
->buf
);
1718 if (pad
->head
|| pad
->merge_reads
) {
1719 int64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1721 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1724 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1726 if (pad
->merge_reads
&& pad
->tail
) {
1727 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1729 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1730 align
, &local_qiov
, 0, 0);
1735 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1737 if (pad
->merge_reads
&& pad
->tail
) {
1738 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1741 if (pad
->merge_reads
) {
1747 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1749 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1750 ret
= bdrv_aligned_preadv(
1752 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1753 align
, align
, &local_qiov
, 0, 0);
1757 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1762 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1768 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1771 qemu_vfree(pad
->buf
);
1772 qemu_iovec_destroy(&pad
->local_qiov
);
1774 memset(pad
, 0, sizeof(*pad
));
1780 * Exchange request parameters with padded request if needed. Don't include RMW
1781 * read of padding, bdrv_padding_rmw_read() should be called separately if
1784 * Request parameters (@qiov, &qiov_offset, &offset, &bytes) are in-out:
1785 * - on function start they represent original request
1786 * - on failure or when padding is not needed they are unchanged
1787 * - on success when padding is needed they represent padded request
1789 static int bdrv_pad_request(BlockDriverState
*bs
,
1790 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1791 int64_t *offset
, int64_t *bytes
,
1792 BdrvRequestPadding
*pad
, bool *padded
)
1796 bdrv_check_qiov_request(*offset
, *bytes
, *qiov
, *qiov_offset
, &error_abort
);
1798 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1805 ret
= qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1806 *qiov
, *qiov_offset
, *bytes
,
1807 pad
->buf
+ pad
->buf_len
- pad
->tail
,
1810 bdrv_padding_destroy(pad
);
1813 *bytes
+= pad
->head
+ pad
->tail
;
1814 *offset
-= pad
->head
;
1815 *qiov
= &pad
->local_qiov
;
1824 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1825 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
1826 BdrvRequestFlags flags
)
1829 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1832 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1833 int64_t offset
, int64_t bytes
,
1834 QEMUIOVector
*qiov
, size_t qiov_offset
,
1835 BdrvRequestFlags flags
)
1837 BlockDriverState
*bs
= child
->bs
;
1838 BdrvTrackedRequest req
;
1839 BdrvRequestPadding pad
;
1843 trace_bdrv_co_preadv_part(bs
, offset
, bytes
, flags
);
1845 if (!bdrv_is_inserted(bs
)) {
1849 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
1854 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1856 * Aligning zero request is nonsense. Even if driver has special meaning
1857 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1858 * it to driver due to request_alignment.
1860 * Still, no reason to return an error if someone do unaligned
1861 * zero-length read occasionally.
1866 bdrv_inc_in_flight(bs
);
1868 /* Don't do copy-on-read if we read data before write operation */
1869 if (qatomic_read(&bs
->copy_on_read
)) {
1870 flags
|= BDRV_REQ_COPY_ON_READ
;
1873 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
1879 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1880 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1881 bs
->bl
.request_alignment
,
1882 qiov
, qiov_offset
, flags
);
1883 tracked_request_end(&req
);
1884 bdrv_padding_destroy(&pad
);
1887 bdrv_dec_in_flight(bs
);
1892 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1893 int64_t offset
, int64_t bytes
, BdrvRequestFlags flags
)
1895 BlockDriver
*drv
= bs
->drv
;
1899 bool need_flush
= false;
1903 int64_t max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
,
1905 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1906 bs
->bl
.request_alignment
);
1907 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1909 bdrv_check_request(offset
, bytes
, &error_abort
);
1915 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1919 /* Invalidate the cached block-status data range if this write overlaps */
1920 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
1922 assert(alignment
% bs
->bl
.request_alignment
== 0);
1923 head
= offset
% alignment
;
1924 tail
= (offset
+ bytes
) % alignment
;
1925 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1926 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1928 while (bytes
> 0 && !ret
) {
1929 int64_t num
= bytes
;
1931 /* Align request. Block drivers can expect the "bulk" of the request
1932 * to be aligned, and that unaligned requests do not cross cluster
1936 /* Make a small request up to the first aligned sector. For
1937 * convenience, limit this request to max_transfer even if
1938 * we don't need to fall back to writes. */
1939 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1940 head
= (head
+ num
) % alignment
;
1941 assert(num
< max_write_zeroes
);
1942 } else if (tail
&& num
> alignment
) {
1943 /* Shorten the request to the last aligned sector. */
1947 /* limit request size */
1948 if (num
> max_write_zeroes
) {
1949 num
= max_write_zeroes
;
1953 /* First try the efficient write zeroes operation */
1954 if (drv
->bdrv_co_pwrite_zeroes
) {
1955 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1956 flags
& bs
->supported_zero_flags
);
1957 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1958 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1962 assert(!bs
->supported_zero_flags
);
1965 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1966 /* Fall back to bounce buffer if write zeroes is unsupported */
1967 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1969 if ((flags
& BDRV_REQ_FUA
) &&
1970 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1971 /* No need for bdrv_driver_pwrite() to do a fallback
1972 * flush on each chunk; use just one at the end */
1973 write_flags
&= ~BDRV_REQ_FUA
;
1976 num
= MIN(num
, max_transfer
);
1978 buf
= qemu_try_blockalign0(bs
, num
);
1984 qemu_iovec_init_buf(&qiov
, buf
, num
);
1986 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1988 /* Keep bounce buffer around if it is big enough for all
1989 * all future requests.
1991 if (num
< max_transfer
) {
2002 if (ret
== 0 && need_flush
) {
2003 ret
= bdrv_co_flush(bs
);
2009 static inline int coroutine_fn
2010 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
2011 BdrvTrackedRequest
*req
, int flags
)
2013 BlockDriverState
*bs
= child
->bs
;
2015 bdrv_check_request(offset
, bytes
, &error_abort
);
2017 if (bdrv_is_read_only(bs
)) {
2021 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
2022 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
2023 assert(!(flags
& ~BDRV_REQ_MASK
));
2024 assert(!((flags
& BDRV_REQ_NO_WAIT
) && !(flags
& BDRV_REQ_SERIALISING
)));
2026 if (flags
& BDRV_REQ_SERIALISING
) {
2027 QEMU_LOCK_GUARD(&bs
->reqs_lock
);
2029 tracked_request_set_serialising(req
, bdrv_get_cluster_size(bs
));
2031 if ((flags
& BDRV_REQ_NO_WAIT
) && bdrv_find_conflicting_request(req
)) {
2035 bdrv_wait_serialising_requests_locked(req
);
2037 bdrv_wait_serialising_requests(req
);
2040 assert(req
->overlap_offset
<= offset
);
2041 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
2042 assert(offset
+ bytes
<= bs
->total_sectors
* BDRV_SECTOR_SIZE
||
2043 child
->perm
& BLK_PERM_RESIZE
);
2045 switch (req
->type
) {
2046 case BDRV_TRACKED_WRITE
:
2047 case BDRV_TRACKED_DISCARD
:
2048 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
2049 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
2051 assert(child
->perm
& BLK_PERM_WRITE
);
2053 bdrv_write_threshold_check_write(bs
, offset
, bytes
);
2055 case BDRV_TRACKED_TRUNCATE
:
2056 assert(child
->perm
& BLK_PERM_RESIZE
);
2063 static inline void coroutine_fn
2064 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, int64_t bytes
,
2065 BdrvTrackedRequest
*req
, int ret
)
2067 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
2068 BlockDriverState
*bs
= child
->bs
;
2070 bdrv_check_request(offset
, bytes
, &error_abort
);
2072 qatomic_inc(&bs
->write_gen
);
2075 * Discard cannot extend the image, but in error handling cases, such as
2076 * when reverting a qcow2 cluster allocation, the discarded range can pass
2077 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
2078 * here. Instead, just skip it, since semantically a discard request
2079 * beyond EOF cannot expand the image anyway.
2082 (req
->type
== BDRV_TRACKED_TRUNCATE
||
2083 end_sector
> bs
->total_sectors
) &&
2084 req
->type
!= BDRV_TRACKED_DISCARD
) {
2085 bs
->total_sectors
= end_sector
;
2086 bdrv_parent_cb_resize(bs
);
2087 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
2090 switch (req
->type
) {
2091 case BDRV_TRACKED_WRITE
:
2092 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
2093 /* fall through, to set dirty bits */
2094 case BDRV_TRACKED_DISCARD
:
2095 bdrv_set_dirty(bs
, offset
, bytes
);
2104 * Forwards an already correctly aligned write request to the BlockDriver,
2105 * after possibly fragmenting it.
2107 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
2108 BdrvTrackedRequest
*req
, int64_t offset
, int64_t bytes
,
2109 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2110 BdrvRequestFlags flags
)
2112 BlockDriverState
*bs
= child
->bs
;
2113 BlockDriver
*drv
= bs
->drv
;
2116 int64_t bytes_remaining
= bytes
;
2119 bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, &error_abort
);
2125 if (bdrv_has_readonly_bitmaps(bs
)) {
2129 assert(is_power_of_2(align
));
2130 assert((offset
& (align
- 1)) == 0);
2131 assert((bytes
& (align
- 1)) == 0);
2132 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
2135 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
2137 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
2138 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
2139 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
2140 flags
|= BDRV_REQ_ZERO_WRITE
;
2141 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
2142 flags
|= BDRV_REQ_MAY_UNMAP
;
2147 /* Do nothing, write notifier decided to fail this request */
2148 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
2149 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
2150 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
2151 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
2152 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
2154 } else if (bytes
<= max_transfer
) {
2155 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
2156 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
2158 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
2159 while (bytes_remaining
) {
2160 int num
= MIN(bytes_remaining
, max_transfer
);
2161 int local_flags
= flags
;
2164 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
2165 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
2166 /* If FUA is going to be emulated by flush, we only
2167 * need to flush on the last iteration */
2168 local_flags
&= ~BDRV_REQ_FUA
;
2171 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
2173 qiov_offset
+ bytes
- bytes_remaining
,
2178 bytes_remaining
-= num
;
2181 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
2186 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
2191 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
2194 BdrvRequestFlags flags
,
2195 BdrvTrackedRequest
*req
)
2197 BlockDriverState
*bs
= child
->bs
;
2198 QEMUIOVector local_qiov
;
2199 uint64_t align
= bs
->bl
.request_alignment
;
2202 BdrvRequestPadding pad
;
2204 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
2206 bdrv_make_request_serialising(req
, align
);
2208 bdrv_padding_rmw_read(child
, req
, &pad
, true);
2210 if (pad
.head
|| pad
.merge_reads
) {
2211 int64_t aligned_offset
= offset
& ~(align
- 1);
2212 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
2214 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
2215 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
2216 align
, &local_qiov
, 0,
2217 flags
& ~BDRV_REQ_ZERO_WRITE
);
2218 if (ret
< 0 || pad
.merge_reads
) {
2219 /* Error or all work is done */
2222 offset
+= write_bytes
- pad
.head
;
2223 bytes
-= write_bytes
- pad
.head
;
2227 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2228 if (bytes
>= align
) {
2229 /* Write the aligned part in the middle. */
2230 int64_t aligned_bytes
= bytes
& ~(align
- 1);
2231 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2236 bytes
-= aligned_bytes
;
2237 offset
+= aligned_bytes
;
2240 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2242 assert(align
== pad
.tail
+ bytes
);
2244 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2245 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2247 flags
& ~BDRV_REQ_ZERO_WRITE
);
2251 bdrv_padding_destroy(&pad
);
2257 * Handle a write request in coroutine context
2259 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2260 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
,
2261 BdrvRequestFlags flags
)
2264 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2267 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2268 int64_t offset
, int64_t bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2269 BdrvRequestFlags flags
)
2271 BlockDriverState
*bs
= child
->bs
;
2272 BdrvTrackedRequest req
;
2273 uint64_t align
= bs
->bl
.request_alignment
;
2274 BdrvRequestPadding pad
;
2276 bool padded
= false;
2279 trace_bdrv_co_pwritev_part(child
->bs
, offset
, bytes
, flags
);
2281 if (!bdrv_is_inserted(bs
)) {
2285 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2286 ret
= bdrv_check_qiov_request(offset
, bytes
, qiov
, qiov_offset
, NULL
);
2288 ret
= bdrv_check_request32(offset
, bytes
, qiov
, qiov_offset
);
2294 /* If the request is misaligned then we can't make it efficient */
2295 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2296 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2301 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2303 * Aligning zero request is nonsense. Even if driver has special meaning
2304 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2305 * it to driver due to request_alignment.
2307 * Still, no reason to return an error if someone do unaligned
2308 * zero-length write occasionally.
2313 if (!(flags
& BDRV_REQ_ZERO_WRITE
)) {
2315 * Pad request for following read-modify-write cycle.
2316 * bdrv_co_do_zero_pwritev() does aligning by itself, so, we do
2317 * alignment only if there is no ZERO flag.
2319 ret
= bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
,
2326 bdrv_inc_in_flight(bs
);
2327 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2329 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2331 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2337 * Request was unaligned to request_alignment and therefore
2338 * padded. We are going to do read-modify-write, and must
2339 * serialize the request to prevent interactions of the
2340 * widened region with other transactions.
2342 bdrv_make_request_serialising(&req
, align
);
2343 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2346 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2347 qiov
, qiov_offset
, flags
);
2349 bdrv_padding_destroy(&pad
);
2352 tracked_request_end(&req
);
2353 bdrv_dec_in_flight(bs
);
2358 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2359 int64_t bytes
, BdrvRequestFlags flags
)
2362 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2364 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2365 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2368 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2369 BDRV_REQ_ZERO_WRITE
| flags
);
2373 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2375 int bdrv_flush_all(void)
2377 BdrvNextIterator it
;
2378 BlockDriverState
*bs
= NULL
;
2381 GLOBAL_STATE_CODE();
2384 * bdrv queue is managed by record/replay,
2385 * creating new flush request for stopping
2386 * the VM may break the determinism
2388 if (replay_events_enabled()) {
2392 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2393 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2396 aio_context_acquire(aio_context
);
2397 ret
= bdrv_flush(bs
);
2398 if (ret
< 0 && !result
) {
2401 aio_context_release(aio_context
);
2408 * Returns the allocation status of the specified sectors.
2409 * Drivers not implementing the functionality are assumed to not support
2410 * backing files, hence all their sectors are reported as allocated.
2412 * If 'want_zero' is true, the caller is querying for mapping
2413 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2414 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2415 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2417 * If 'offset' is beyond the end of the disk image the return value is
2418 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2420 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2421 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2422 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2424 * 'pnum' is set to the number of bytes (including and immediately
2425 * following the specified offset) that are easily known to be in the
2426 * same allocated/unallocated state. Note that a second call starting
2427 * at the original offset plus returned pnum may have the same status.
2428 * The returned value is non-zero on success except at end-of-file.
2430 * Returns negative errno on failure. Otherwise, if the
2431 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2432 * set to the host mapping and BDS corresponding to the guest offset.
2434 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2436 int64_t offset
, int64_t bytes
,
2437 int64_t *pnum
, int64_t *map
,
2438 BlockDriverState
**file
)
2441 int64_t n
; /* bytes */
2443 int64_t local_map
= 0;
2444 BlockDriverState
*local_file
= NULL
;
2445 int64_t aligned_offset
, aligned_bytes
;
2447 bool has_filtered_child
;
2451 total_size
= bdrv_getlength(bs
);
2452 if (total_size
< 0) {
2457 if (offset
>= total_size
) {
2458 ret
= BDRV_BLOCK_EOF
;
2466 n
= total_size
- offset
;
2471 /* Must be non-NULL or bdrv_getlength() would have failed */
2473 has_filtered_child
= bdrv_filter_child(bs
);
2474 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2476 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2477 if (offset
+ bytes
== total_size
) {
2478 ret
|= BDRV_BLOCK_EOF
;
2480 if (bs
->drv
->protocol_name
) {
2481 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2488 bdrv_inc_in_flight(bs
);
2490 /* Round out to request_alignment boundaries */
2491 align
= bs
->bl
.request_alignment
;
2492 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2493 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2495 if (bs
->drv
->bdrv_co_block_status
) {
2497 * Use the block-status cache only for protocol nodes: Format
2498 * drivers are generally quick to inquire the status, but protocol
2499 * drivers often need to get information from outside of qemu, so
2500 * we do not have control over the actual implementation. There
2501 * have been cases where inquiring the status took an unreasonably
2502 * long time, and we can do nothing in qemu to fix it.
2503 * This is especially problematic for images with large data areas,
2504 * because finding the few holes in them and giving them special
2505 * treatment does not gain much performance. Therefore, we try to
2506 * cache the last-identified data region.
2508 * Second, limiting ourselves to protocol nodes allows us to assume
2509 * the block status for data regions to be DATA | OFFSET_VALID, and
2510 * that the host offset is the same as the guest offset.
2512 * Note that it is possible that external writers zero parts of
2513 * the cached regions without the cache being invalidated, and so
2514 * we may report zeroes as data. This is not catastrophic,
2515 * however, because reporting zeroes as data is fine.
2517 if (QLIST_EMPTY(&bs
->children
) &&
2518 bdrv_bsc_is_data(bs
, aligned_offset
, pnum
))
2520 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
;
2522 local_map
= aligned_offset
;
2524 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2525 aligned_bytes
, pnum
, &local_map
,
2529 * Note that checking QLIST_EMPTY(&bs->children) is also done when
2530 * the cache is queried above. Technically, we do not need to check
2531 * it here; the worst that can happen is that we fill the cache for
2532 * non-protocol nodes, and then it is never used. However, filling
2533 * the cache requires an RCU update, so double check here to avoid
2534 * such an update if possible.
2536 * Check want_zero, because we only want to update the cache when we
2537 * have accurate information about what is zero and what is data.
2540 ret
== (BDRV_BLOCK_DATA
| BDRV_BLOCK_OFFSET_VALID
) &&
2541 QLIST_EMPTY(&bs
->children
))
2544 * When a protocol driver reports BLOCK_OFFSET_VALID, the
2545 * returned local_map value must be the same as the offset we
2546 * have passed (aligned_offset), and local_bs must be the node
2548 * Assert this, because we follow this rule when reading from
2549 * the cache (see the `local_file = bs` and
2550 * `local_map = aligned_offset` assignments above), and the
2551 * result the cache delivers must be the same as the driver
2554 assert(local_file
== bs
);
2555 assert(local_map
== aligned_offset
);
2556 bdrv_bsc_fill(bs
, aligned_offset
, *pnum
);
2560 /* Default code for filters */
2562 local_file
= bdrv_filter_bs(bs
);
2565 *pnum
= aligned_bytes
;
2566 local_map
= aligned_offset
;
2567 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2575 * The driver's result must be a non-zero multiple of request_alignment.
2576 * Clamp pnum and adjust map to original request.
2578 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2579 align
> offset
- aligned_offset
);
2580 if (ret
& BDRV_BLOCK_RECURSE
) {
2581 assert(ret
& BDRV_BLOCK_DATA
);
2582 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2583 assert(!(ret
& BDRV_BLOCK_ZERO
));
2586 *pnum
-= offset
- aligned_offset
;
2587 if (*pnum
> bytes
) {
2590 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2591 local_map
+= offset
- aligned_offset
;
2594 if (ret
& BDRV_BLOCK_RAW
) {
2595 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2596 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2597 *pnum
, pnum
, &local_map
, &local_file
);
2601 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2602 ret
|= BDRV_BLOCK_ALLOCATED
;
2603 } else if (bs
->drv
->supports_backing
) {
2604 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2607 ret
|= BDRV_BLOCK_ZERO
;
2608 } else if (want_zero
) {
2609 int64_t size2
= bdrv_getlength(cow_bs
);
2611 if (size2
>= 0 && offset
>= size2
) {
2612 ret
|= BDRV_BLOCK_ZERO
;
2617 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2618 local_file
&& local_file
!= bs
&&
2619 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2620 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2624 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2625 *pnum
, &file_pnum
, NULL
, NULL
);
2627 /* Ignore errors. This is just providing extra information, it
2628 * is useful but not necessary.
2630 if (ret2
& BDRV_BLOCK_EOF
&&
2631 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2633 * It is valid for the format block driver to read
2634 * beyond the end of the underlying file's current
2635 * size; such areas read as zero.
2637 ret
|= BDRV_BLOCK_ZERO
;
2639 /* Limit request to the range reported by the protocol driver */
2641 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2647 bdrv_dec_in_flight(bs
);
2648 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2649 ret
|= BDRV_BLOCK_EOF
;
2662 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2663 BlockDriverState
*base
,
2670 BlockDriverState
**file
,
2674 BlockDriverState
*p
;
2679 assert(!include_base
|| base
); /* Can't include NULL base */
2686 if (!include_base
&& bs
== base
) {
2691 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2693 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2697 if (ret
& BDRV_BLOCK_EOF
) {
2698 eof
= offset
+ *pnum
;
2701 assert(*pnum
<= bytes
);
2704 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2705 p
= bdrv_filter_or_cow_bs(p
))
2707 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2715 * The top layer deferred to this layer, and because this layer is
2716 * short, any zeroes that we synthesize beyond EOF behave as if they
2717 * were allocated at this layer.
2719 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2720 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2723 assert(ret
& BDRV_BLOCK_EOF
);
2728 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2731 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2733 * We've found the node and the status, we must break.
2735 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2736 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2739 ret
&= ~BDRV_BLOCK_EOF
;
2744 assert(include_base
);
2749 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2750 * let's continue the diving.
2752 assert(*pnum
<= bytes
);
2756 if (offset
+ *pnum
== eof
) {
2757 ret
|= BDRV_BLOCK_EOF
;
2763 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2764 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2765 int64_t *map
, BlockDriverState
**file
)
2768 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2769 pnum
, map
, file
, NULL
);
2772 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2773 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2776 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2777 offset
, bytes
, pnum
, map
, file
);
2781 * Check @bs (and its backing chain) to see if the range defined
2782 * by @offset and @bytes is known to read as zeroes.
2783 * Return 1 if that is the case, 0 otherwise and -errno on error.
2784 * This test is meant to be fast rather than accurate so returning 0
2785 * does not guarantee non-zero data.
2787 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2791 int64_t pnum
= bytes
;
2798 ret
= bdrv_common_block_status_above(bs
, NULL
, false, false, offset
,
2799 bytes
, &pnum
, NULL
, NULL
, NULL
);
2805 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2808 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2809 int64_t bytes
, int64_t *pnum
)
2815 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2816 bytes
, pnum
? pnum
: &dummy
, NULL
,
2821 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2825 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2827 * Return a positive depth if (a prefix of) the given range is allocated
2828 * in any image between BASE and TOP (BASE is only included if include_base
2829 * is set). Depth 1 is TOP, 2 is the first backing layer, and so forth.
2830 * BASE can be NULL to check if the given offset is allocated in any
2831 * image of the chain. Return 0 otherwise, or negative errno on
2834 * 'pnum' is set to the number of bytes (including and immediately
2835 * following the specified offset) that are known to be in the same
2836 * allocated/unallocated state. Note that a subsequent call starting
2837 * at 'offset + *pnum' may return the same allocation status (in other
2838 * words, the result is not necessarily the maximum possible range);
2839 * but 'pnum' will only be 0 when end of file is reached.
2841 int bdrv_is_allocated_above(BlockDriverState
*top
,
2842 BlockDriverState
*base
,
2843 bool include_base
, int64_t offset
,
2844 int64_t bytes
, int64_t *pnum
)
2847 int ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2848 offset
, bytes
, pnum
, NULL
, NULL
,
2855 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2862 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2864 BlockDriver
*drv
= bs
->drv
;
2865 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2869 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2878 bdrv_inc_in_flight(bs
);
2880 if (drv
->bdrv_load_vmstate
) {
2881 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2882 } else if (child_bs
) {
2883 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2888 bdrv_dec_in_flight(bs
);
2894 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2896 BlockDriver
*drv
= bs
->drv
;
2897 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2901 ret
= bdrv_check_qiov_request(pos
, qiov
->size
, qiov
, 0, NULL
);
2910 bdrv_inc_in_flight(bs
);
2912 if (drv
->bdrv_save_vmstate
) {
2913 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2914 } else if (child_bs
) {
2915 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2920 bdrv_dec_in_flight(bs
);
2925 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2926 int64_t pos
, int size
)
2928 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2929 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2932 return ret
< 0 ? ret
: size
;
2935 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2936 int64_t pos
, int size
)
2938 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2939 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2942 return ret
< 0 ? ret
: size
;
2945 /**************************************************************/
2948 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2952 bdrv_aio_cancel_async(acb
);
2953 while (acb
->refcnt
> 1) {
2954 if (acb
->aiocb_info
->get_aio_context
) {
2955 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2956 } else if (acb
->bs
) {
2957 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2958 * assert that we're not using an I/O thread. Thread-safe
2959 * code should use bdrv_aio_cancel_async exclusively.
2961 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2962 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2967 qemu_aio_unref(acb
);
2970 /* Async version of aio cancel. The caller is not blocked if the acb implements
2971 * cancel_async, otherwise we do nothing and let the request normally complete.
2972 * In either case the completion callback must be called. */
2973 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2976 if (acb
->aiocb_info
->cancel_async
) {
2977 acb
->aiocb_info
->cancel_async(acb
);
2981 /**************************************************************/
2982 /* Coroutine block device emulation */
2984 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2986 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2992 bdrv_inc_in_flight(bs
);
2994 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2999 qemu_co_mutex_lock(&bs
->reqs_lock
);
3000 current_gen
= qatomic_read(&bs
->write_gen
);
3002 /* Wait until any previous flushes are completed */
3003 while (bs
->active_flush_req
) {
3004 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
3007 /* Flushes reach this point in nondecreasing current_gen order. */
3008 bs
->active_flush_req
= true;
3009 qemu_co_mutex_unlock(&bs
->reqs_lock
);
3011 /* Write back all layers by calling one driver function */
3012 if (bs
->drv
->bdrv_co_flush
) {
3013 ret
= bs
->drv
->bdrv_co_flush(bs
);
3017 /* Write back cached data to the OS even with cache=unsafe */
3018 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
3019 if (bs
->drv
->bdrv_co_flush_to_os
) {
3020 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
3026 /* But don't actually force it to the disk with cache=unsafe */
3027 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
3028 goto flush_children
;
3031 /* Check if we really need to flush anything */
3032 if (bs
->flushed_gen
== current_gen
) {
3033 goto flush_children
;
3036 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
3038 /* bs->drv->bdrv_co_flush() might have ejected the BDS
3039 * (even in case of apparent success) */
3043 if (bs
->drv
->bdrv_co_flush_to_disk
) {
3044 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
3045 } else if (bs
->drv
->bdrv_aio_flush
) {
3047 CoroutineIOCompletion co
= {
3048 .coroutine
= qemu_coroutine_self(),
3051 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
3055 qemu_coroutine_yield();
3060 * Some block drivers always operate in either writethrough or unsafe
3061 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
3062 * know how the server works (because the behaviour is hardcoded or
3063 * depends on server-side configuration), so we can't ensure that
3064 * everything is safe on disk. Returning an error doesn't work because
3065 * that would break guests even if the server operates in writethrough
3068 * Let's hope the user knows what he's doing.
3077 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
3078 * in the case of cache=unsafe, so there are no useless flushes.
3082 QLIST_FOREACH(child
, &bs
->children
, next
) {
3083 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
3084 int this_child_ret
= bdrv_co_flush(child
->bs
);
3086 ret
= this_child_ret
;
3092 /* Notify any pending flushes that we have completed */
3094 bs
->flushed_gen
= current_gen
;
3097 qemu_co_mutex_lock(&bs
->reqs_lock
);
3098 bs
->active_flush_req
= false;
3099 /* Return value is ignored - it's ok if wait queue is empty */
3100 qemu_co_queue_next(&bs
->flush_queue
);
3101 qemu_co_mutex_unlock(&bs
->reqs_lock
);
3104 bdrv_dec_in_flight(bs
);
3108 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
3111 BdrvTrackedRequest req
;
3113 int64_t max_pdiscard
;
3114 int head
, tail
, align
;
3115 BlockDriverState
*bs
= child
->bs
;
3118 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
3122 if (bdrv_has_readonly_bitmaps(bs
)) {
3126 ret
= bdrv_check_request(offset
, bytes
, NULL
);
3131 /* Do nothing if disabled. */
3132 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
3136 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
3140 /* Invalidate the cached block-status data range if this discard overlaps */
3141 bdrv_bsc_invalidate_range(bs
, offset
, bytes
);
3143 /* Discard is advisory, but some devices track and coalesce
3144 * unaligned requests, so we must pass everything down rather than
3145 * round here. Still, most devices will just silently ignore
3146 * unaligned requests (by returning -ENOTSUP), so we must fragment
3147 * the request accordingly. */
3148 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
3149 assert(align
% bs
->bl
.request_alignment
== 0);
3150 head
= offset
% align
;
3151 tail
= (offset
+ bytes
) % align
;
3153 bdrv_inc_in_flight(bs
);
3154 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
3156 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
3161 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT64_MAX
),
3163 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
3166 int64_t num
= bytes
;
3169 /* Make small requests to get to alignment boundaries. */
3170 num
= MIN(bytes
, align
- head
);
3171 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
3172 num
%= bs
->bl
.request_alignment
;
3174 head
= (head
+ num
) % align
;
3175 assert(num
< max_pdiscard
);
3178 /* Shorten the request to the last aligned cluster. */
3180 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
3181 tail
> bs
->bl
.request_alignment
) {
3182 tail
%= bs
->bl
.request_alignment
;
3186 /* limit request size */
3187 if (num
> max_pdiscard
) {
3195 if (bs
->drv
->bdrv_co_pdiscard
) {
3196 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
3199 CoroutineIOCompletion co
= {
3200 .coroutine
= qemu_coroutine_self(),
3203 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
3204 bdrv_co_io_em_complete
, &co
);
3209 qemu_coroutine_yield();
3213 if (ret
&& ret
!= -ENOTSUP
) {
3222 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
3223 tracked_request_end(&req
);
3224 bdrv_dec_in_flight(bs
);
3228 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
3230 BlockDriver
*drv
= bs
->drv
;
3231 CoroutineIOCompletion co
= {
3232 .coroutine
= qemu_coroutine_self(),
3237 bdrv_inc_in_flight(bs
);
3238 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
3243 if (drv
->bdrv_co_ioctl
) {
3244 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
3246 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
3251 qemu_coroutine_yield();
3254 bdrv_dec_in_flight(bs
);
3258 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
3261 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
3264 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
3267 return memset(qemu_blockalign(bs
, size
), 0, size
);
3270 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
3272 size_t align
= bdrv_opt_mem_align(bs
);
3275 /* Ensure that NULL is never returned on success */
3281 return qemu_try_memalign(align
, size
);
3284 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
3286 void *mem
= qemu_try_blockalign(bs
, size
);
3290 memset(mem
, 0, size
);
3297 * Check if all memory in this vector is sector aligned.
3299 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
3302 size_t alignment
= bdrv_min_mem_align(bs
);
3305 for (i
= 0; i
< qiov
->niov
; i
++) {
3306 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
3309 if (qiov
->iov
[i
].iov_len
% alignment
) {
3317 void bdrv_io_plug(BlockDriverState
*bs
)
3322 QLIST_FOREACH(child
, &bs
->children
, next
) {
3323 bdrv_io_plug(child
->bs
);
3326 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
3327 BlockDriver
*drv
= bs
->drv
;
3328 if (drv
&& drv
->bdrv_io_plug
) {
3329 drv
->bdrv_io_plug(bs
);
3334 void bdrv_io_unplug(BlockDriverState
*bs
)
3339 assert(bs
->io_plugged
);
3340 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
3341 BlockDriver
*drv
= bs
->drv
;
3342 if (drv
&& drv
->bdrv_io_unplug
) {
3343 drv
->bdrv_io_unplug(bs
);
3347 QLIST_FOREACH(child
, &bs
->children
, next
) {
3348 bdrv_io_unplug(child
->bs
);
3352 void bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3356 GLOBAL_STATE_CODE();
3357 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3358 bs
->drv
->bdrv_register_buf(bs
, host
, size
);
3360 QLIST_FOREACH(child
, &bs
->children
, next
) {
3361 bdrv_register_buf(child
->bs
, host
, size
);
3365 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
)
3369 GLOBAL_STATE_CODE();
3370 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3371 bs
->drv
->bdrv_unregister_buf(bs
, host
);
3373 QLIST_FOREACH(child
, &bs
->children
, next
) {
3374 bdrv_unregister_buf(child
->bs
, host
);
3378 static int coroutine_fn
bdrv_co_copy_range_internal(
3379 BdrvChild
*src
, int64_t src_offset
, BdrvChild
*dst
,
3380 int64_t dst_offset
, int64_t bytes
,
3381 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3384 BdrvTrackedRequest req
;
3387 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3388 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3389 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3391 if (!dst
|| !dst
->bs
|| !bdrv_is_inserted(dst
->bs
)) {
3394 ret
= bdrv_check_request32(dst_offset
, bytes
, NULL
, 0);
3398 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3399 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3402 if (!src
|| !src
->bs
|| !bdrv_is_inserted(src
->bs
)) {
3405 ret
= bdrv_check_request32(src_offset
, bytes
, NULL
, 0);
3410 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3411 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3412 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3417 bdrv_inc_in_flight(src
->bs
);
3418 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3421 /* BDRV_REQ_SERIALISING is only for write operation */
3422 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3423 bdrv_wait_serialising_requests(&req
);
3425 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3429 read_flags
, write_flags
);
3431 tracked_request_end(&req
);
3432 bdrv_dec_in_flight(src
->bs
);
3434 bdrv_inc_in_flight(dst
->bs
);
3435 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3436 BDRV_TRACKED_WRITE
);
3437 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3440 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3444 read_flags
, write_flags
);
3446 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3447 tracked_request_end(&req
);
3448 bdrv_dec_in_flight(dst
->bs
);
3454 /* Copy range from @src to @dst.
3456 * See the comment of bdrv_co_copy_range for the parameter and return value
3458 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, int64_t src_offset
,
3459 BdrvChild
*dst
, int64_t dst_offset
,
3461 BdrvRequestFlags read_flags
,
3462 BdrvRequestFlags write_flags
)
3465 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3466 read_flags
, write_flags
);
3467 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3468 bytes
, read_flags
, write_flags
, true);
3471 /* Copy range from @src to @dst.
3473 * See the comment of bdrv_co_copy_range for the parameter and return value
3475 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, int64_t src_offset
,
3476 BdrvChild
*dst
, int64_t dst_offset
,
3478 BdrvRequestFlags read_flags
,
3479 BdrvRequestFlags write_flags
)
3482 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3483 read_flags
, write_flags
);
3484 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3485 bytes
, read_flags
, write_flags
, false);
3488 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, int64_t src_offset
,
3489 BdrvChild
*dst
, int64_t dst_offset
,
3490 int64_t bytes
, BdrvRequestFlags read_flags
,
3491 BdrvRequestFlags write_flags
)
3494 return bdrv_co_copy_range_from(src
, src_offset
,
3496 bytes
, read_flags
, write_flags
);
3499 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3502 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3503 if (c
->klass
->resize
) {
3504 c
->klass
->resize(c
);
3510 * Truncate file to 'offset' bytes (needed only for file protocols)
3512 * If 'exact' is true, the file must be resized to exactly the given
3513 * 'offset'. Otherwise, it is sufficient for the node to be at least
3514 * 'offset' bytes in length.
3516 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3517 PreallocMode prealloc
, BdrvRequestFlags flags
,
3520 BlockDriverState
*bs
= child
->bs
;
3521 BdrvChild
*filtered
, *backing
;
3522 BlockDriver
*drv
= bs
->drv
;
3523 BdrvTrackedRequest req
;
3524 int64_t old_size
, new_bytes
;
3528 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3530 error_setg(errp
, "No medium inserted");
3534 error_setg(errp
, "Image size cannot be negative");
3538 ret
= bdrv_check_request(offset
, 0, errp
);
3543 old_size
= bdrv_getlength(bs
);
3545 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3549 if (bdrv_is_read_only(bs
)) {
3550 error_setg(errp
, "Image is read-only");
3554 if (offset
> old_size
) {
3555 new_bytes
= offset
- old_size
;
3560 bdrv_inc_in_flight(bs
);
3561 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3562 BDRV_TRACKED_TRUNCATE
);
3564 /* If we are growing the image and potentially using preallocation for the
3565 * new area, we need to make sure that no write requests are made to it
3566 * concurrently or they might be overwritten by preallocation. */
3568 bdrv_make_request_serialising(&req
, 1);
3570 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3573 error_setg_errno(errp
, -ret
,
3574 "Failed to prepare request for truncation");
3578 filtered
= bdrv_filter_child(bs
);
3579 backing
= bdrv_cow_child(bs
);
3582 * If the image has a backing file that is large enough that it would
3583 * provide data for the new area, we cannot leave it unallocated because
3584 * then the backing file content would become visible. Instead, zero-fill
3587 * Note that if the image has a backing file, but was opened without the
3588 * backing file, taking care of keeping things consistent with that backing
3589 * file is the user's responsibility.
3591 if (new_bytes
&& backing
) {
3592 int64_t backing_len
;
3594 backing_len
= bdrv_getlength(backing
->bs
);
3595 if (backing_len
< 0) {
3597 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3601 if (backing_len
> old_size
) {
3602 flags
|= BDRV_REQ_ZERO_WRITE
;
3606 if (drv
->bdrv_co_truncate
) {
3607 if (flags
& ~bs
->supported_truncate_flags
) {
3608 error_setg(errp
, "Block driver does not support requested flags");
3612 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3613 } else if (filtered
) {
3614 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3616 error_setg(errp
, "Image format driver does not support resize");
3624 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3626 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3628 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3630 /* It's possible that truncation succeeded but refresh_total_sectors
3631 * failed, but the latter doesn't affect how we should finish the request.
3632 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3633 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3636 tracked_request_end(&req
);
3637 bdrv_dec_in_flight(bs
);
3642 void bdrv_cancel_in_flight(BlockDriverState
*bs
)
3644 GLOBAL_STATE_CODE();
3645 if (!bs
|| !bs
->drv
) {
3649 if (bs
->drv
->bdrv_cancel_in_flight
) {
3650 bs
->drv
->bdrv_cancel_in_flight(bs
);