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 "qemu/cutils.h"
33 #include "qapi/error.h"
34 #include "qemu/error-report.h"
36 #define NOT_DONE 0x7fffffff /* used while emulated sync operation in progress */
38 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
39 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
41 static void bdrv_parent_cb_resize(BlockDriverState
*bs
);
42 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
43 int64_t offset
, int bytes
, BdrvRequestFlags flags
);
45 static void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
,
46 bool ignore_bds_parents
)
50 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
51 if (c
== ignore
|| (ignore_bds_parents
&& c
->role
->parent_is_bds
)) {
54 bdrv_parent_drained_begin_single(c
, false);
58 static void bdrv_parent_drained_end_single_no_poll(BdrvChild
*c
,
59 int *drained_end_counter
)
61 assert(c
->parent_quiesce_counter
> 0);
62 c
->parent_quiesce_counter
--;
63 if (c
->role
->drained_end
) {
64 c
->role
->drained_end(c
, drained_end_counter
);
68 void bdrv_parent_drained_end_single(BdrvChild
*c
)
70 int drained_end_counter
= 0;
71 bdrv_parent_drained_end_single_no_poll(c
, &drained_end_counter
);
72 BDRV_POLL_WHILE(c
->bs
, atomic_read(&drained_end_counter
) > 0);
75 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
,
76 bool ignore_bds_parents
,
77 int *drained_end_counter
)
81 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
82 if (c
== ignore
|| (ignore_bds_parents
&& c
->role
->parent_is_bds
)) {
85 bdrv_parent_drained_end_single_no_poll(c
, drained_end_counter
);
89 static bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
91 if (c
->role
->drained_poll
) {
92 return c
->role
->drained_poll(c
);
97 static bool bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
98 bool ignore_bds_parents
)
103 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
104 if (c
== ignore
|| (ignore_bds_parents
&& c
->role
->parent_is_bds
)) {
107 busy
|= bdrv_parent_drained_poll_single(c
);
113 void bdrv_parent_drained_begin_single(BdrvChild
*c
, bool poll
)
115 c
->parent_quiesce_counter
++;
116 if (c
->role
->drained_begin
) {
117 c
->role
->drained_begin(c
);
120 BDRV_POLL_WHILE(c
->bs
, bdrv_parent_drained_poll_single(c
));
124 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
126 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
127 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
128 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
129 src
->opt_mem_alignment
);
130 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
131 src
->min_mem_alignment
);
132 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
135 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
137 BlockDriver
*drv
= bs
->drv
;
138 Error
*local_err
= NULL
;
140 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
146 /* Default alignment based on whether driver has byte interface */
147 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
148 drv
->bdrv_aio_preadv
) ? 1 : 512;
150 /* Take some limits from the children as a default */
152 bdrv_refresh_limits(bs
->file
->bs
, &local_err
);
154 error_propagate(errp
, local_err
);
157 bdrv_merge_limits(&bs
->bl
, &bs
->file
->bs
->bl
);
159 bs
->bl
.min_mem_alignment
= 512;
160 bs
->bl
.opt_mem_alignment
= getpagesize();
162 /* Safe default since most protocols use readv()/writev()/etc */
163 bs
->bl
.max_iov
= IOV_MAX
;
167 bdrv_refresh_limits(bs
->backing
->bs
, &local_err
);
169 error_propagate(errp
, local_err
);
172 bdrv_merge_limits(&bs
->bl
, &bs
->backing
->bs
->bl
);
175 /* Then let the driver override it */
176 if (drv
->bdrv_refresh_limits
) {
177 drv
->bdrv_refresh_limits(bs
, errp
);
182 * The copy-on-read flag is actually a reference count so multiple users may
183 * use the feature without worrying about clobbering its previous state.
184 * Copy-on-read stays enabled until all users have called to disable it.
186 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
188 atomic_inc(&bs
->copy_on_read
);
191 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
193 int old
= atomic_fetch_dec(&bs
->copy_on_read
);
199 BlockDriverState
*bs
;
205 bool ignore_bds_parents
;
206 int *drained_end_counter
;
209 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
211 BdrvCoDrainData
*data
= opaque
;
212 BlockDriverState
*bs
= data
->bs
;
215 bs
->drv
->bdrv_co_drain_begin(bs
);
217 bs
->drv
->bdrv_co_drain_end(bs
);
220 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
221 atomic_mb_set(&data
->done
, true);
223 atomic_dec(data
->drained_end_counter
);
225 bdrv_dec_in_flight(bs
);
230 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
231 static void bdrv_drain_invoke(BlockDriverState
*bs
, bool begin
,
232 int *drained_end_counter
)
234 BdrvCoDrainData
*data
;
236 if (!bs
->drv
|| (begin
&& !bs
->drv
->bdrv_co_drain_begin
) ||
237 (!begin
&& !bs
->drv
->bdrv_co_drain_end
)) {
241 data
= g_new(BdrvCoDrainData
, 1);
242 *data
= (BdrvCoDrainData
) {
246 .drained_end_counter
= drained_end_counter
,
250 atomic_inc(drained_end_counter
);
253 /* Make sure the driver callback completes during the polling phase for
255 bdrv_inc_in_flight(bs
);
256 data
->co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, data
);
257 aio_co_schedule(bdrv_get_aio_context(bs
), data
->co
);
260 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
261 bool bdrv_drain_poll(BlockDriverState
*bs
, bool recursive
,
262 BdrvChild
*ignore_parent
, bool ignore_bds_parents
)
264 BdrvChild
*child
, *next
;
266 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
270 if (atomic_read(&bs
->in_flight
)) {
275 assert(!ignore_bds_parents
);
276 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
277 if (bdrv_drain_poll(child
->bs
, recursive
, child
, false)) {
286 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
, bool recursive
,
287 BdrvChild
*ignore_parent
)
289 return bdrv_drain_poll(bs
, recursive
, ignore_parent
, false);
292 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
293 BdrvChild
*parent
, bool ignore_bds_parents
,
295 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
296 BdrvChild
*parent
, bool ignore_bds_parents
,
297 int *drained_end_counter
);
299 static void bdrv_co_drain_bh_cb(void *opaque
)
301 BdrvCoDrainData
*data
= opaque
;
302 Coroutine
*co
= data
->co
;
303 BlockDriverState
*bs
= data
->bs
;
306 AioContext
*ctx
= bdrv_get_aio_context(bs
);
307 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(co
);
310 * When the coroutine yielded, the lock for its home context was
311 * released, so we need to re-acquire it here. If it explicitly
312 * acquired a different context, the lock is still held and we don't
313 * want to lock it a second time (or AIO_WAIT_WHILE() would hang).
316 aio_context_acquire(ctx
);
318 bdrv_dec_in_flight(bs
);
320 assert(!data
->drained_end_counter
);
321 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
,
322 data
->ignore_bds_parents
, data
->poll
);
325 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
,
326 data
->ignore_bds_parents
,
327 data
->drained_end_counter
);
330 aio_context_release(ctx
);
334 bdrv_drain_all_begin();
341 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
342 bool begin
, bool recursive
,
344 bool ignore_bds_parents
,
346 int *drained_end_counter
)
348 BdrvCoDrainData data
;
350 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
351 * other coroutines run if they were queued by aio_co_enter(). */
353 assert(qemu_in_coroutine());
354 data
= (BdrvCoDrainData
) {
355 .co
= qemu_coroutine_self(),
359 .recursive
= recursive
,
361 .ignore_bds_parents
= ignore_bds_parents
,
363 .drained_end_counter
= drained_end_counter
,
367 bdrv_inc_in_flight(bs
);
369 aio_bh_schedule_oneshot(bdrv_get_aio_context(bs
),
370 bdrv_co_drain_bh_cb
, &data
);
372 qemu_coroutine_yield();
373 /* If we are resumed from some other event (such as an aio completion or a
374 * timer callback), it is a bug in the caller that should be fixed. */
378 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
,
379 BdrvChild
*parent
, bool ignore_bds_parents
)
381 assert(!qemu_in_coroutine());
383 /* Stop things in parent-to-child order */
384 if (atomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
385 aio_disable_external(bdrv_get_aio_context(bs
));
388 bdrv_parent_drained_begin(bs
, parent
, ignore_bds_parents
);
389 bdrv_drain_invoke(bs
, true, NULL
);
392 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
393 BdrvChild
*parent
, bool ignore_bds_parents
,
396 BdrvChild
*child
, *next
;
398 if (qemu_in_coroutine()) {
399 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
, ignore_bds_parents
,
404 bdrv_do_drained_begin_quiesce(bs
, parent
, ignore_bds_parents
);
407 assert(!ignore_bds_parents
);
408 bs
->recursive_quiesce_counter
++;
409 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
410 bdrv_do_drained_begin(child
->bs
, true, child
, ignore_bds_parents
,
416 * Wait for drained requests to finish.
418 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
419 * call is needed so things in this AioContext can make progress even
420 * though we don't return to the main AioContext loop - this automatically
421 * includes other nodes in the same AioContext and therefore all child
425 assert(!ignore_bds_parents
);
426 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, recursive
, parent
));
430 void bdrv_drained_begin(BlockDriverState
*bs
)
432 bdrv_do_drained_begin(bs
, false, NULL
, false, true);
435 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
437 bdrv_do_drained_begin(bs
, true, NULL
, false, true);
441 * This function does not poll, nor must any of its recursively called
442 * functions. The *drained_end_counter pointee will be incremented
443 * once for every background operation scheduled, and decremented once
444 * the operation settles. Therefore, the pointer must remain valid
445 * until the pointee reaches 0. That implies that whoever sets up the
446 * pointee has to poll until it is 0.
448 * We use atomic operations to access *drained_end_counter, because
449 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
450 * @bs may contain nodes in different AioContexts,
451 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
452 * regardless of which AioContext they are in.
454 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
455 BdrvChild
*parent
, bool ignore_bds_parents
,
456 int *drained_end_counter
)
459 int old_quiesce_counter
;
461 assert(drained_end_counter
!= NULL
);
463 if (qemu_in_coroutine()) {
464 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
, ignore_bds_parents
,
465 false, drained_end_counter
);
468 assert(bs
->quiesce_counter
> 0);
470 /* Re-enable things in child-to-parent order */
471 bdrv_drain_invoke(bs
, false, drained_end_counter
);
472 bdrv_parent_drained_end(bs
, parent
, ignore_bds_parents
,
473 drained_end_counter
);
475 old_quiesce_counter
= atomic_fetch_dec(&bs
->quiesce_counter
);
476 if (old_quiesce_counter
== 1) {
477 aio_enable_external(bdrv_get_aio_context(bs
));
481 assert(!ignore_bds_parents
);
482 bs
->recursive_quiesce_counter
--;
483 QLIST_FOREACH(child
, &bs
->children
, next
) {
484 bdrv_do_drained_end(child
->bs
, true, child
, ignore_bds_parents
,
485 drained_end_counter
);
490 void bdrv_drained_end(BlockDriverState
*bs
)
492 int drained_end_counter
= 0;
493 bdrv_do_drained_end(bs
, false, NULL
, false, &drained_end_counter
);
494 BDRV_POLL_WHILE(bs
, atomic_read(&drained_end_counter
) > 0);
497 void bdrv_drained_end_no_poll(BlockDriverState
*bs
, int *drained_end_counter
)
499 bdrv_do_drained_end(bs
, false, NULL
, false, drained_end_counter
);
502 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
504 int drained_end_counter
= 0;
505 bdrv_do_drained_end(bs
, true, NULL
, false, &drained_end_counter
);
506 BDRV_POLL_WHILE(bs
, atomic_read(&drained_end_counter
) > 0);
509 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
513 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
514 bdrv_do_drained_begin(child
->bs
, true, child
, false, true);
518 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
520 int drained_end_counter
= 0;
523 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
524 bdrv_do_drained_end(child
->bs
, true, child
, false,
525 &drained_end_counter
);
528 BDRV_POLL_WHILE(child
->bs
, atomic_read(&drained_end_counter
) > 0);
532 * Wait for pending requests to complete on a single BlockDriverState subtree,
533 * and suspend block driver's internal I/O until next request arrives.
535 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
538 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
540 assert(qemu_in_coroutine());
541 bdrv_drained_begin(bs
);
542 bdrv_drained_end(bs
);
545 void bdrv_drain(BlockDriverState
*bs
)
547 bdrv_drained_begin(bs
);
548 bdrv_drained_end(bs
);
551 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
553 BdrvChild
*child
, *next
;
555 assert(atomic_read(&bs
->in_flight
) == 0);
556 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
557 bdrv_drain_assert_idle(child
->bs
);
561 unsigned int bdrv_drain_all_count
= 0;
563 static bool bdrv_drain_all_poll(void)
565 BlockDriverState
*bs
= NULL
;
568 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
569 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
570 while ((bs
= bdrv_next_all_states(bs
))) {
571 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
572 aio_context_acquire(aio_context
);
573 result
|= bdrv_drain_poll(bs
, false, NULL
, true);
574 aio_context_release(aio_context
);
581 * Wait for pending requests to complete across all BlockDriverStates
583 * This function does not flush data to disk, use bdrv_flush_all() for that
584 * after calling this function.
586 * This pauses all block jobs and disables external clients. It must
587 * be paired with bdrv_drain_all_end().
589 * NOTE: no new block jobs or BlockDriverStates can be created between
590 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
592 void bdrv_drain_all_begin(void)
594 BlockDriverState
*bs
= NULL
;
596 if (qemu_in_coroutine()) {
597 bdrv_co_yield_to_drain(NULL
, true, false, NULL
, true, true, NULL
);
601 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
602 * loop AioContext, so make sure we're in the main context. */
603 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
604 assert(bdrv_drain_all_count
< INT_MAX
);
605 bdrv_drain_all_count
++;
607 /* Quiesce all nodes, without polling in-flight requests yet. The graph
608 * cannot change during this loop. */
609 while ((bs
= bdrv_next_all_states(bs
))) {
610 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
612 aio_context_acquire(aio_context
);
613 bdrv_do_drained_begin(bs
, false, NULL
, true, false);
614 aio_context_release(aio_context
);
617 /* Now poll the in-flight requests */
618 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
620 while ((bs
= bdrv_next_all_states(bs
))) {
621 bdrv_drain_assert_idle(bs
);
625 void bdrv_drain_all_end(void)
627 BlockDriverState
*bs
= NULL
;
628 int drained_end_counter
= 0;
630 while ((bs
= bdrv_next_all_states(bs
))) {
631 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
633 aio_context_acquire(aio_context
);
634 bdrv_do_drained_end(bs
, false, NULL
, true, &drained_end_counter
);
635 aio_context_release(aio_context
);
638 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
639 AIO_WAIT_WHILE(NULL
, atomic_read(&drained_end_counter
) > 0);
641 assert(bdrv_drain_all_count
> 0);
642 bdrv_drain_all_count
--;
645 void bdrv_drain_all(void)
647 bdrv_drain_all_begin();
648 bdrv_drain_all_end();
652 * Remove an active request from the tracked requests list
654 * This function should be called when a tracked request is completing.
656 static void tracked_request_end(BdrvTrackedRequest
*req
)
658 if (req
->serialising
) {
659 atomic_dec(&req
->bs
->serialising_in_flight
);
662 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
663 QLIST_REMOVE(req
, list
);
664 qemu_co_queue_restart_all(&req
->wait_queue
);
665 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
669 * Add an active request to the tracked requests list
671 static void tracked_request_begin(BdrvTrackedRequest
*req
,
672 BlockDriverState
*bs
,
675 enum BdrvTrackedRequestType type
)
677 assert(bytes
<= INT64_MAX
&& offset
<= INT64_MAX
- bytes
);
679 *req
= (BdrvTrackedRequest
){
684 .co
= qemu_coroutine_self(),
685 .serialising
= false,
686 .overlap_offset
= offset
,
687 .overlap_bytes
= bytes
,
690 qemu_co_queue_init(&req
->wait_queue
);
692 qemu_co_mutex_lock(&bs
->reqs_lock
);
693 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
694 qemu_co_mutex_unlock(&bs
->reqs_lock
);
697 static void mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
699 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
700 uint64_t overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
703 if (!req
->serialising
) {
704 atomic_inc(&req
->bs
->serialising_in_flight
);
705 req
->serialising
= true;
708 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
709 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
712 static bool is_request_serialising_and_aligned(BdrvTrackedRequest
*req
)
715 * If the request is serialising, overlap_offset and overlap_bytes are set,
716 * so we can check if the request is aligned. Otherwise, don't care and
720 return req
->serialising
&& (req
->offset
== req
->overlap_offset
) &&
721 (req
->bytes
== req
->overlap_bytes
);
725 * Round a region to cluster boundaries
727 void bdrv_round_to_clusters(BlockDriverState
*bs
,
728 int64_t offset
, int64_t bytes
,
729 int64_t *cluster_offset
,
730 int64_t *cluster_bytes
)
734 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
735 *cluster_offset
= offset
;
736 *cluster_bytes
= bytes
;
738 int64_t c
= bdi
.cluster_size
;
739 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
740 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
744 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
749 ret
= bdrv_get_info(bs
, &bdi
);
750 if (ret
< 0 || bdi
.cluster_size
== 0) {
751 return bs
->bl
.request_alignment
;
753 return bdi
.cluster_size
;
757 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
758 int64_t offset
, uint64_t bytes
)
761 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
765 if (req
->overlap_offset
>= offset
+ bytes
) {
771 void bdrv_inc_in_flight(BlockDriverState
*bs
)
773 atomic_inc(&bs
->in_flight
);
776 void bdrv_wakeup(BlockDriverState
*bs
)
781 void bdrv_dec_in_flight(BlockDriverState
*bs
)
783 atomic_dec(&bs
->in_flight
);
787 static bool coroutine_fn
wait_serialising_requests(BdrvTrackedRequest
*self
)
789 BlockDriverState
*bs
= self
->bs
;
790 BdrvTrackedRequest
*req
;
794 if (!atomic_read(&bs
->serialising_in_flight
)) {
800 qemu_co_mutex_lock(&bs
->reqs_lock
);
801 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
802 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
805 if (tracked_request_overlaps(req
, self
->overlap_offset
,
806 self
->overlap_bytes
))
808 /* Hitting this means there was a reentrant request, for
809 * example, a block driver issuing nested requests. This must
810 * never happen since it means deadlock.
812 assert(qemu_coroutine_self() != req
->co
);
814 /* If the request is already (indirectly) waiting for us, or
815 * will wait for us as soon as it wakes up, then just go on
816 * (instead of producing a deadlock in the former case). */
817 if (!req
->waiting_for
) {
818 self
->waiting_for
= req
;
819 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
820 self
->waiting_for
= NULL
;
827 qemu_co_mutex_unlock(&bs
->reqs_lock
);
833 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
836 if (size
> BDRV_REQUEST_MAX_BYTES
) {
840 if (!bdrv_is_inserted(bs
)) {
851 typedef struct RwCo
{
857 BdrvRequestFlags flags
;
860 static void coroutine_fn
bdrv_rw_co_entry(void *opaque
)
864 if (!rwco
->is_write
) {
865 rwco
->ret
= bdrv_co_preadv(rwco
->child
, rwco
->offset
,
866 rwco
->qiov
->size
, rwco
->qiov
,
869 rwco
->ret
= bdrv_co_pwritev(rwco
->child
, rwco
->offset
,
870 rwco
->qiov
->size
, rwco
->qiov
,
877 * Process a vectored synchronous request using coroutines
879 static int bdrv_prwv_co(BdrvChild
*child
, int64_t offset
,
880 QEMUIOVector
*qiov
, bool is_write
,
881 BdrvRequestFlags flags
)
888 .is_write
= is_write
,
893 if (qemu_in_coroutine()) {
894 /* Fast-path if already in coroutine context */
895 bdrv_rw_co_entry(&rwco
);
897 co
= qemu_coroutine_create(bdrv_rw_co_entry
, &rwco
);
898 bdrv_coroutine_enter(child
->bs
, co
);
899 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
904 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
905 int bytes
, BdrvRequestFlags flags
)
907 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, NULL
, bytes
);
909 return bdrv_prwv_co(child
, offset
, &qiov
, true,
910 BDRV_REQ_ZERO_WRITE
| flags
);
914 * Completely zero out a block device with the help of bdrv_pwrite_zeroes.
915 * The operation is sped up by checking the block status and only writing
916 * zeroes to the device if they currently do not return zeroes. Optional
917 * flags are passed through to bdrv_pwrite_zeroes (e.g. BDRV_REQ_MAY_UNMAP,
920 * Returns < 0 on error, 0 on success. For error codes see bdrv_write().
922 int bdrv_make_zero(BdrvChild
*child
, BdrvRequestFlags flags
)
925 int64_t target_size
, bytes
, offset
= 0;
926 BlockDriverState
*bs
= child
->bs
;
928 target_size
= bdrv_getlength(bs
);
929 if (target_size
< 0) {
934 bytes
= MIN(target_size
- offset
, BDRV_REQUEST_MAX_BYTES
);
938 ret
= bdrv_block_status(bs
, offset
, bytes
, &bytes
, NULL
, NULL
);
942 if (ret
& BDRV_BLOCK_ZERO
) {
946 ret
= bdrv_pwrite_zeroes(child
, offset
, bytes
, flags
);
954 int bdrv_preadv(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
958 ret
= bdrv_prwv_co(child
, offset
, qiov
, false, 0);
966 /* See bdrv_pwrite() for the return codes */
967 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
969 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
975 return bdrv_preadv(child
, offset
, &qiov
);
978 int bdrv_pwritev(BdrvChild
*child
, int64_t offset
, QEMUIOVector
*qiov
)
982 ret
= bdrv_prwv_co(child
, offset
, qiov
, true, 0);
990 /* Return no. of bytes on success or < 0 on error. Important errors are:
991 -EIO generic I/O error (may happen for all errors)
992 -ENOMEDIUM No media inserted.
993 -EINVAL Invalid offset or number of bytes
994 -EACCES Trying to write a read-only device
996 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
998 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
1004 return bdrv_pwritev(child
, offset
, &qiov
);
1008 * Writes to the file and ensures that no writes are reordered across this
1009 * request (acts as a barrier)
1011 * Returns 0 on success, -errno in error cases.
1013 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
1014 const void *buf
, int count
)
1018 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
1023 ret
= bdrv_flush(child
->bs
);
1031 typedef struct CoroutineIOCompletion
{
1032 Coroutine
*coroutine
;
1034 } CoroutineIOCompletion
;
1036 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
1038 CoroutineIOCompletion
*co
= opaque
;
1041 aio_co_wake(co
->coroutine
);
1044 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
1045 uint64_t offset
, uint64_t bytes
,
1046 QEMUIOVector
*qiov
, int flags
)
1048 BlockDriver
*drv
= bs
->drv
;
1050 unsigned int nb_sectors
;
1052 assert(!(flags
& ~BDRV_REQ_MASK
));
1053 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1059 if (drv
->bdrv_co_preadv
) {
1060 return drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
1063 if (drv
->bdrv_aio_preadv
) {
1065 CoroutineIOCompletion co
= {
1066 .coroutine
= qemu_coroutine_self(),
1069 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1070 bdrv_co_io_em_complete
, &co
);
1074 qemu_coroutine_yield();
1079 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1080 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1082 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1083 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1084 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1085 assert(drv
->bdrv_co_readv
);
1087 return drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1090 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1091 uint64_t offset
, uint64_t bytes
,
1092 QEMUIOVector
*qiov
, int flags
)
1094 BlockDriver
*drv
= bs
->drv
;
1096 unsigned int nb_sectors
;
1099 assert(!(flags
& ~BDRV_REQ_MASK
));
1100 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1106 if (drv
->bdrv_co_pwritev
) {
1107 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
1108 flags
& bs
->supported_write_flags
);
1109 flags
&= ~bs
->supported_write_flags
;
1113 if (drv
->bdrv_aio_pwritev
) {
1115 CoroutineIOCompletion co
= {
1116 .coroutine
= qemu_coroutine_self(),
1119 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
,
1120 flags
& bs
->supported_write_flags
,
1121 bdrv_co_io_em_complete
, &co
);
1122 flags
&= ~bs
->supported_write_flags
;
1126 qemu_coroutine_yield();
1132 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1133 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1135 assert((offset
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1136 assert((bytes
& (BDRV_SECTOR_SIZE
- 1)) == 0);
1137 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1139 assert(drv
->bdrv_co_writev
);
1140 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
,
1141 flags
& bs
->supported_write_flags
);
1142 flags
&= ~bs
->supported_write_flags
;
1145 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
1146 ret
= bdrv_co_flush(bs
);
1152 static int coroutine_fn
1153 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1154 uint64_t bytes
, QEMUIOVector
*qiov
)
1156 BlockDriver
*drv
= bs
->drv
;
1162 if (!drv
->bdrv_co_pwritev_compressed
) {
1166 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1169 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1170 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1173 BlockDriverState
*bs
= child
->bs
;
1175 /* Perform I/O through a temporary buffer so that users who scribble over
1176 * their read buffer while the operation is in progress do not end up
1177 * modifying the image file. This is critical for zero-copy guest I/O
1178 * where anything might happen inside guest memory.
1180 void *bounce_buffer
;
1182 BlockDriver
*drv
= bs
->drv
;
1183 QEMUIOVector local_qiov
;
1184 int64_t cluster_offset
;
1185 int64_t cluster_bytes
;
1188 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1189 BDRV_REQUEST_MAX_BYTES
);
1190 unsigned int progress
= 0;
1196 /* FIXME We cannot require callers to have write permissions when all they
1197 * are doing is a read request. If we did things right, write permissions
1198 * would be obtained anyway, but internally by the copy-on-read code. As
1199 * long as it is implemented here rather than in a separate filter driver,
1200 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1201 * it could request permissions. Therefore we have to bypass the permission
1202 * system for the moment. */
1203 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1205 /* Cover entire cluster so no additional backing file I/O is required when
1206 * allocating cluster in the image file. Note that this value may exceed
1207 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1208 * is one reason we loop rather than doing it all at once.
1210 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1211 skip_bytes
= offset
- cluster_offset
;
1213 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1214 cluster_offset
, cluster_bytes
);
1216 bounce_buffer
= qemu_try_blockalign(bs
,
1217 MIN(MIN(max_transfer
, cluster_bytes
),
1218 MAX_BOUNCE_BUFFER
));
1219 if (bounce_buffer
== NULL
) {
1224 while (cluster_bytes
) {
1227 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1228 MIN(cluster_bytes
, max_transfer
), &pnum
);
1230 /* Safe to treat errors in querying allocation as if
1231 * unallocated; we'll probably fail again soon on the
1232 * read, but at least that will set a decent errno.
1234 pnum
= MIN(cluster_bytes
, max_transfer
);
1237 /* Stop at EOF if the image ends in the middle of the cluster */
1238 if (ret
== 0 && pnum
== 0) {
1239 assert(progress
>= bytes
);
1243 assert(skip_bytes
< pnum
);
1246 /* Must copy-on-read; use the bounce buffer */
1247 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1248 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1250 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1256 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1257 if (drv
->bdrv_co_pwrite_zeroes
&&
1258 buffer_is_zero(bounce_buffer
, pnum
)) {
1259 /* FIXME: Should we (perhaps conditionally) be setting
1260 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1261 * that still correctly reads as zero? */
1262 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1263 BDRV_REQ_WRITE_UNCHANGED
);
1265 /* This does not change the data on the disk, it is not
1266 * necessary to flush even in cache=writethrough mode.
1268 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1270 BDRV_REQ_WRITE_UNCHANGED
);
1274 /* It might be okay to ignore write errors for guest
1275 * requests. If this is a deliberate copy-on-read
1276 * then we don't want to ignore the error. Simply
1277 * report it in all cases.
1282 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1283 qemu_iovec_from_buf(qiov
, progress
, bounce_buffer
+ skip_bytes
,
1286 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1287 /* Read directly into the destination */
1288 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1289 qemu_iovec_concat(&local_qiov
, qiov
, progress
, pnum
- skip_bytes
);
1290 ret
= bdrv_driver_preadv(bs
, offset
+ progress
, local_qiov
.size
,
1292 qemu_iovec_destroy(&local_qiov
);
1298 cluster_offset
+= pnum
;
1299 cluster_bytes
-= pnum
;
1300 progress
+= pnum
- skip_bytes
;
1306 qemu_vfree(bounce_buffer
);
1311 * Forwards an already correctly aligned request to the BlockDriver. This
1312 * handles copy on read, zeroing after EOF, and fragmentation of large
1313 * reads; any other features must be implemented by the caller.
1315 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1316 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1317 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1319 BlockDriverState
*bs
= child
->bs
;
1320 int64_t total_bytes
, max_bytes
;
1322 uint64_t bytes_remaining
= bytes
;
1325 assert(is_power_of_2(align
));
1326 assert((offset
& (align
- 1)) == 0);
1327 assert((bytes
& (align
- 1)) == 0);
1328 assert(!qiov
|| bytes
== qiov
->size
);
1329 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1330 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1333 /* TODO: We would need a per-BDS .supported_read_flags and
1334 * potential fallback support, if we ever implement any read flags
1335 * to pass through to drivers. For now, there aren't any
1336 * passthrough flags. */
1337 assert(!(flags
& ~(BDRV_REQ_NO_SERIALISING
| BDRV_REQ_COPY_ON_READ
|
1338 BDRV_REQ_PREFETCH
)));
1340 /* Handle Copy on Read and associated serialisation */
1341 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1342 /* If we touch the same cluster it counts as an overlap. This
1343 * guarantees that allocating writes will be serialized and not race
1344 * with each other for the same cluster. For example, in copy-on-read
1345 * it ensures that the CoR read and write operations are atomic and
1346 * guest writes cannot interleave between them. */
1347 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1350 /* BDRV_REQ_SERIALISING is only for write operation */
1351 assert(!(flags
& BDRV_REQ_SERIALISING
));
1353 if (!(flags
& BDRV_REQ_NO_SERIALISING
)) {
1354 wait_serialising_requests(req
);
1357 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1360 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1365 if (!ret
|| pnum
!= bytes
) {
1366 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
, qiov
, flags
);
1368 } else if (flags
& BDRV_REQ_PREFETCH
) {
1373 /* Forward the request to the BlockDriver, possibly fragmenting it */
1374 total_bytes
= bdrv_getlength(bs
);
1375 if (total_bytes
< 0) {
1380 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1381 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1382 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, 0);
1386 while (bytes_remaining
) {
1390 QEMUIOVector local_qiov
;
1392 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1394 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1395 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1397 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1398 num
, &local_qiov
, 0);
1400 qemu_iovec_destroy(&local_qiov
);
1402 num
= bytes_remaining
;
1403 ret
= qemu_iovec_memset(qiov
, bytes
- bytes_remaining
, 0,
1409 bytes_remaining
-= num
;
1413 return ret
< 0 ? ret
: 0;
1417 * Handle a read request in coroutine context
1419 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1420 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1421 BdrvRequestFlags flags
)
1423 BlockDriverState
*bs
= child
->bs
;
1424 BlockDriver
*drv
= bs
->drv
;
1425 BdrvTrackedRequest req
;
1427 uint64_t align
= bs
->bl
.request_alignment
;
1428 uint8_t *head_buf
= NULL
;
1429 uint8_t *tail_buf
= NULL
;
1430 QEMUIOVector local_qiov
;
1431 bool use_local_qiov
= false;
1434 trace_bdrv_co_preadv(child
->bs
, offset
, bytes
, flags
);
1440 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1445 bdrv_inc_in_flight(bs
);
1447 /* Don't do copy-on-read if we read data before write operation */
1448 if (atomic_read(&bs
->copy_on_read
) && !(flags
& BDRV_REQ_NO_SERIALISING
)) {
1449 flags
|= BDRV_REQ_COPY_ON_READ
;
1452 /* Align read if necessary by padding qiov */
1453 if (offset
& (align
- 1)) {
1454 head_buf
= qemu_blockalign(bs
, align
);
1455 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1456 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1457 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1458 use_local_qiov
= true;
1460 bytes
+= offset
& (align
- 1);
1461 offset
= offset
& ~(align
- 1);
1464 if ((offset
+ bytes
) & (align
- 1)) {
1465 if (!use_local_qiov
) {
1466 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1467 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1468 use_local_qiov
= true;
1470 tail_buf
= qemu_blockalign(bs
, align
);
1471 qemu_iovec_add(&local_qiov
, tail_buf
,
1472 align
- ((offset
+ bytes
) & (align
- 1)));
1474 bytes
= ROUND_UP(bytes
, align
);
1477 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1478 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
, align
,
1479 use_local_qiov
? &local_qiov
: qiov
,
1481 tracked_request_end(&req
);
1482 bdrv_dec_in_flight(bs
);
1484 if (use_local_qiov
) {
1485 qemu_iovec_destroy(&local_qiov
);
1486 qemu_vfree(head_buf
);
1487 qemu_vfree(tail_buf
);
1493 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1494 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
1496 BlockDriver
*drv
= bs
->drv
;
1500 bool need_flush
= false;
1504 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1505 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1506 bs
->bl
.request_alignment
);
1507 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1513 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1517 assert(alignment
% bs
->bl
.request_alignment
== 0);
1518 head
= offset
% alignment
;
1519 tail
= (offset
+ bytes
) % alignment
;
1520 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1521 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1523 while (bytes
> 0 && !ret
) {
1526 /* Align request. Block drivers can expect the "bulk" of the request
1527 * to be aligned, and that unaligned requests do not cross cluster
1531 /* Make a small request up to the first aligned sector. For
1532 * convenience, limit this request to max_transfer even if
1533 * we don't need to fall back to writes. */
1534 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1535 head
= (head
+ num
) % alignment
;
1536 assert(num
< max_write_zeroes
);
1537 } else if (tail
&& num
> alignment
) {
1538 /* Shorten the request to the last aligned sector. */
1542 /* limit request size */
1543 if (num
> max_write_zeroes
) {
1544 num
= max_write_zeroes
;
1548 /* First try the efficient write zeroes operation */
1549 if (drv
->bdrv_co_pwrite_zeroes
) {
1550 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1551 flags
& bs
->supported_zero_flags
);
1552 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1553 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1557 assert(!bs
->supported_zero_flags
);
1560 if (ret
< 0 && !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1561 /* Fall back to bounce buffer if write zeroes is unsupported */
1562 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1564 if ((flags
& BDRV_REQ_FUA
) &&
1565 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1566 /* No need for bdrv_driver_pwrite() to do a fallback
1567 * flush on each chunk; use just one at the end */
1568 write_flags
&= ~BDRV_REQ_FUA
;
1571 num
= MIN(num
, max_transfer
);
1573 buf
= qemu_try_blockalign0(bs
, num
);
1579 qemu_iovec_init_buf(&qiov
, buf
, num
);
1581 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, write_flags
);
1583 /* Keep bounce buffer around if it is big enough for all
1584 * all future requests.
1586 if (num
< max_transfer
) {
1597 if (ret
== 0 && need_flush
) {
1598 ret
= bdrv_co_flush(bs
);
1604 static inline int coroutine_fn
1605 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, uint64_t bytes
,
1606 BdrvTrackedRequest
*req
, int flags
)
1608 BlockDriverState
*bs
= child
->bs
;
1610 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1612 if (bs
->read_only
) {
1616 /* BDRV_REQ_NO_SERIALISING is only for read operation */
1617 assert(!(flags
& BDRV_REQ_NO_SERIALISING
));
1618 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1619 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1620 assert(!(flags
& ~BDRV_REQ_MASK
));
1622 if (flags
& BDRV_REQ_SERIALISING
) {
1623 mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1626 waited
= wait_serialising_requests(req
);
1628 assert(!waited
|| !req
->serialising
||
1629 is_request_serialising_and_aligned(req
));
1630 assert(req
->overlap_offset
<= offset
);
1631 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1632 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1634 switch (req
->type
) {
1635 case BDRV_TRACKED_WRITE
:
1636 case BDRV_TRACKED_DISCARD
:
1637 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1638 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1640 assert(child
->perm
& BLK_PERM_WRITE
);
1642 return notifier_with_return_list_notify(&bs
->before_write_notifiers
,
1644 case BDRV_TRACKED_TRUNCATE
:
1645 assert(child
->perm
& BLK_PERM_RESIZE
);
1652 static inline void coroutine_fn
1653 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, uint64_t bytes
,
1654 BdrvTrackedRequest
*req
, int ret
)
1656 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1657 BlockDriverState
*bs
= child
->bs
;
1659 atomic_inc(&bs
->write_gen
);
1662 * Discard cannot extend the image, but in error handling cases, such as
1663 * when reverting a qcow2 cluster allocation, the discarded range can pass
1664 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1665 * here. Instead, just skip it, since semantically a discard request
1666 * beyond EOF cannot expand the image anyway.
1669 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1670 end_sector
> bs
->total_sectors
) &&
1671 req
->type
!= BDRV_TRACKED_DISCARD
) {
1672 bs
->total_sectors
= end_sector
;
1673 bdrv_parent_cb_resize(bs
);
1674 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1677 switch (req
->type
) {
1678 case BDRV_TRACKED_WRITE
:
1679 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1680 /* fall through, to set dirty bits */
1681 case BDRV_TRACKED_DISCARD
:
1682 bdrv_set_dirty(bs
, offset
, bytes
);
1691 * Forwards an already correctly aligned write request to the BlockDriver,
1692 * after possibly fragmenting it.
1694 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1695 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1696 int64_t align
, QEMUIOVector
*qiov
, int flags
)
1698 BlockDriverState
*bs
= child
->bs
;
1699 BlockDriver
*drv
= bs
->drv
;
1702 uint64_t bytes_remaining
= bytes
;
1709 if (bdrv_has_readonly_bitmaps(bs
)) {
1713 assert(is_power_of_2(align
));
1714 assert((offset
& (align
- 1)) == 0);
1715 assert((bytes
& (align
- 1)) == 0);
1716 assert(!qiov
|| bytes
== qiov
->size
);
1717 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1720 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1722 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1723 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1724 qemu_iovec_is_zero(qiov
)) {
1725 flags
|= BDRV_REQ_ZERO_WRITE
;
1726 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1727 flags
|= BDRV_REQ_MAY_UNMAP
;
1732 /* Do nothing, write notifier decided to fail this request */
1733 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1734 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1735 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1736 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1737 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1738 } else if (bytes
<= max_transfer
) {
1739 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1740 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, flags
);
1742 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1743 while (bytes_remaining
) {
1744 int num
= MIN(bytes_remaining
, max_transfer
);
1745 QEMUIOVector local_qiov
;
1746 int local_flags
= flags
;
1749 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1750 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1751 /* If FUA is going to be emulated by flush, we only
1752 * need to flush on the last iteration */
1753 local_flags
&= ~BDRV_REQ_FUA
;
1755 qemu_iovec_init(&local_qiov
, qiov
->niov
);
1756 qemu_iovec_concat(&local_qiov
, qiov
, bytes
- bytes_remaining
, num
);
1758 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1759 num
, &local_qiov
, local_flags
);
1760 qemu_iovec_destroy(&local_qiov
);
1764 bytes_remaining
-= num
;
1767 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1772 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
1777 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1780 BdrvRequestFlags flags
,
1781 BdrvTrackedRequest
*req
)
1783 BlockDriverState
*bs
= child
->bs
;
1784 uint8_t *buf
= NULL
;
1785 QEMUIOVector local_qiov
;
1786 uint64_t align
= bs
->bl
.request_alignment
;
1787 unsigned int head_padding_bytes
, tail_padding_bytes
;
1790 head_padding_bytes
= offset
& (align
- 1);
1791 tail_padding_bytes
= (align
- (offset
+ bytes
)) & (align
- 1);
1794 assert(flags
& BDRV_REQ_ZERO_WRITE
);
1795 if (head_padding_bytes
|| tail_padding_bytes
) {
1796 buf
= qemu_blockalign(bs
, align
);
1797 qemu_iovec_init_buf(&local_qiov
, buf
, align
);
1799 if (head_padding_bytes
) {
1800 uint64_t zero_bytes
= MIN(bytes
, align
- head_padding_bytes
);
1802 /* RMW the unaligned part before head. */
1803 mark_request_serialising(req
, align
);
1804 wait_serialising_requests(req
);
1805 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1806 ret
= bdrv_aligned_preadv(child
, req
, offset
& ~(align
- 1), align
,
1807 align
, &local_qiov
, 0);
1811 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1813 memset(buf
+ head_padding_bytes
, 0, zero_bytes
);
1814 ret
= bdrv_aligned_pwritev(child
, req
, offset
& ~(align
- 1), align
,
1816 flags
& ~BDRV_REQ_ZERO_WRITE
);
1820 offset
+= zero_bytes
;
1821 bytes
-= zero_bytes
;
1824 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1825 if (bytes
>= align
) {
1826 /* Write the aligned part in the middle. */
1827 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
1828 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
1833 bytes
-= aligned_bytes
;
1834 offset
+= aligned_bytes
;
1837 assert(!bytes
|| (offset
& (align
- 1)) == 0);
1839 assert(align
== tail_padding_bytes
+ bytes
);
1840 /* RMW the unaligned part after tail. */
1841 mark_request_serialising(req
, align
);
1842 wait_serialising_requests(req
);
1843 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1844 ret
= bdrv_aligned_preadv(child
, req
, offset
, align
,
1845 align
, &local_qiov
, 0);
1849 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1851 memset(buf
, 0, bytes
);
1852 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
1853 &local_qiov
, flags
& ~BDRV_REQ_ZERO_WRITE
);
1862 * Handle a write request in coroutine context
1864 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
1865 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1866 BdrvRequestFlags flags
)
1868 BlockDriverState
*bs
= child
->bs
;
1869 BdrvTrackedRequest req
;
1870 uint64_t align
= bs
->bl
.request_alignment
;
1871 uint8_t *head_buf
= NULL
;
1872 uint8_t *tail_buf
= NULL
;
1873 QEMUIOVector local_qiov
;
1874 bool use_local_qiov
= false;
1877 trace_bdrv_co_pwritev(child
->bs
, offset
, bytes
, flags
);
1883 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1888 bdrv_inc_in_flight(bs
);
1890 * Align write if necessary by performing a read-modify-write cycle.
1891 * Pad qiov with the read parts and be sure to have a tracked request not
1892 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
1894 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
1896 if (flags
& BDRV_REQ_ZERO_WRITE
) {
1897 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
1901 if (offset
& (align
- 1)) {
1902 QEMUIOVector head_qiov
;
1904 mark_request_serialising(&req
, align
);
1905 wait_serialising_requests(&req
);
1907 head_buf
= qemu_blockalign(bs
, align
);
1908 qemu_iovec_init_buf(&head_qiov
, head_buf
, align
);
1910 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1911 ret
= bdrv_aligned_preadv(child
, &req
, offset
& ~(align
- 1), align
,
1912 align
, &head_qiov
, 0);
1916 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1918 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 2);
1919 qemu_iovec_add(&local_qiov
, head_buf
, offset
& (align
- 1));
1920 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1921 use_local_qiov
= true;
1923 bytes
+= offset
& (align
- 1);
1924 offset
= offset
& ~(align
- 1);
1926 /* We have read the tail already if the request is smaller
1927 * than one aligned block.
1929 if (bytes
< align
) {
1930 qemu_iovec_add(&local_qiov
, head_buf
+ bytes
, align
- bytes
);
1935 if ((offset
+ bytes
) & (align
- 1)) {
1936 QEMUIOVector tail_qiov
;
1940 mark_request_serialising(&req
, align
);
1941 waited
= wait_serialising_requests(&req
);
1942 assert(!waited
|| !use_local_qiov
);
1944 tail_buf
= qemu_blockalign(bs
, align
);
1945 qemu_iovec_init_buf(&tail_qiov
, tail_buf
, align
);
1947 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1948 ret
= bdrv_aligned_preadv(child
, &req
, (offset
+ bytes
) & ~(align
- 1),
1949 align
, align
, &tail_qiov
, 0);
1953 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1955 if (!use_local_qiov
) {
1956 qemu_iovec_init(&local_qiov
, qiov
->niov
+ 1);
1957 qemu_iovec_concat(&local_qiov
, qiov
, 0, qiov
->size
);
1958 use_local_qiov
= true;
1961 tail_bytes
= (offset
+ bytes
) & (align
- 1);
1962 qemu_iovec_add(&local_qiov
, tail_buf
+ tail_bytes
, align
- tail_bytes
);
1964 bytes
= ROUND_UP(bytes
, align
);
1967 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
1968 use_local_qiov
? &local_qiov
: qiov
,
1973 if (use_local_qiov
) {
1974 qemu_iovec_destroy(&local_qiov
);
1976 qemu_vfree(head_buf
);
1977 qemu_vfree(tail_buf
);
1979 tracked_request_end(&req
);
1980 bdrv_dec_in_flight(bs
);
1984 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
1985 int bytes
, BdrvRequestFlags flags
)
1987 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
1989 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
1990 flags
&= ~BDRV_REQ_MAY_UNMAP
;
1993 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
1994 BDRV_REQ_ZERO_WRITE
| flags
);
1998 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2000 int bdrv_flush_all(void)
2002 BdrvNextIterator it
;
2003 BlockDriverState
*bs
= NULL
;
2006 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2007 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2010 aio_context_acquire(aio_context
);
2011 ret
= bdrv_flush(bs
);
2012 if (ret
< 0 && !result
) {
2015 aio_context_release(aio_context
);
2022 typedef struct BdrvCoBlockStatusData
{
2023 BlockDriverState
*bs
;
2024 BlockDriverState
*base
;
2030 BlockDriverState
**file
;
2033 } BdrvCoBlockStatusData
;
2035 int coroutine_fn
bdrv_co_block_status_from_file(BlockDriverState
*bs
,
2041 BlockDriverState
**file
)
2043 assert(bs
->file
&& bs
->file
->bs
);
2046 *file
= bs
->file
->bs
;
2047 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2050 int coroutine_fn
bdrv_co_block_status_from_backing(BlockDriverState
*bs
,
2056 BlockDriverState
**file
)
2058 assert(bs
->backing
&& bs
->backing
->bs
);
2061 *file
= bs
->backing
->bs
;
2062 return BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2066 * Returns the allocation status of the specified sectors.
2067 * Drivers not implementing the functionality are assumed to not support
2068 * backing files, hence all their sectors are reported as allocated.
2070 * If 'want_zero' is true, the caller is querying for mapping
2071 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2072 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2073 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2075 * If 'offset' is beyond the end of the disk image the return value is
2076 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2078 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2079 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2080 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2082 * 'pnum' is set to the number of bytes (including and immediately
2083 * following the specified offset) that are easily known to be in the
2084 * same allocated/unallocated state. Note that a second call starting
2085 * at the original offset plus returned pnum may have the same status.
2086 * The returned value is non-zero on success except at end-of-file.
2088 * Returns negative errno on failure. Otherwise, if the
2089 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2090 * set to the host mapping and BDS corresponding to the guest offset.
2092 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2094 int64_t offset
, int64_t bytes
,
2095 int64_t *pnum
, int64_t *map
,
2096 BlockDriverState
**file
)
2099 int64_t n
; /* bytes */
2101 int64_t local_map
= 0;
2102 BlockDriverState
*local_file
= NULL
;
2103 int64_t aligned_offset
, aligned_bytes
;
2108 total_size
= bdrv_getlength(bs
);
2109 if (total_size
< 0) {
2114 if (offset
>= total_size
) {
2115 ret
= BDRV_BLOCK_EOF
;
2123 n
= total_size
- offset
;
2128 /* Must be non-NULL or bdrv_getlength() would have failed */
2130 if (!bs
->drv
->bdrv_co_block_status
) {
2132 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2133 if (offset
+ bytes
== total_size
) {
2134 ret
|= BDRV_BLOCK_EOF
;
2136 if (bs
->drv
->protocol_name
) {
2137 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2144 bdrv_inc_in_flight(bs
);
2146 /* Round out to request_alignment boundaries */
2147 align
= bs
->bl
.request_alignment
;
2148 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2149 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2151 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2152 aligned_bytes
, pnum
, &local_map
,
2160 * The driver's result must be a non-zero multiple of request_alignment.
2161 * Clamp pnum and adjust map to original request.
2163 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2164 align
> offset
- aligned_offset
);
2165 if (ret
& BDRV_BLOCK_RECURSE
) {
2166 assert(ret
& BDRV_BLOCK_DATA
);
2167 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2168 assert(!(ret
& BDRV_BLOCK_ZERO
));
2171 *pnum
-= offset
- aligned_offset
;
2172 if (*pnum
> bytes
) {
2175 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2176 local_map
+= offset
- aligned_offset
;
2179 if (ret
& BDRV_BLOCK_RAW
) {
2180 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2181 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2182 *pnum
, pnum
, &local_map
, &local_file
);
2186 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2187 ret
|= BDRV_BLOCK_ALLOCATED
;
2188 } else if (want_zero
) {
2189 if (bdrv_unallocated_blocks_are_zero(bs
)) {
2190 ret
|= BDRV_BLOCK_ZERO
;
2191 } else if (bs
->backing
) {
2192 BlockDriverState
*bs2
= bs
->backing
->bs
;
2193 int64_t size2
= bdrv_getlength(bs2
);
2195 if (size2
>= 0 && offset
>= size2
) {
2196 ret
|= BDRV_BLOCK_ZERO
;
2201 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2202 local_file
&& local_file
!= bs
&&
2203 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2204 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2208 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2209 *pnum
, &file_pnum
, NULL
, NULL
);
2211 /* Ignore errors. This is just providing extra information, it
2212 * is useful but not necessary.
2214 if (ret2
& BDRV_BLOCK_EOF
&&
2215 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2217 * It is valid for the format block driver to read
2218 * beyond the end of the underlying file's current
2219 * size; such areas read as zero.
2221 ret
|= BDRV_BLOCK_ZERO
;
2223 /* Limit request to the range reported by the protocol driver */
2225 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2231 bdrv_dec_in_flight(bs
);
2232 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2233 ret
|= BDRV_BLOCK_EOF
;
2245 static int coroutine_fn
bdrv_co_block_status_above(BlockDriverState
*bs
,
2246 BlockDriverState
*base
,
2252 BlockDriverState
**file
)
2254 BlockDriverState
*p
;
2259 for (p
= bs
; p
!= base
; p
= backing_bs(p
)) {
2260 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2265 if (ret
& BDRV_BLOCK_ZERO
&& ret
& BDRV_BLOCK_EOF
&& !first
) {
2267 * Reading beyond the end of the file continues to read
2268 * zeroes, but we can only widen the result to the
2269 * unallocated length we learned from an earlier
2274 if (ret
& (BDRV_BLOCK_ZERO
| BDRV_BLOCK_DATA
)) {
2277 /* [offset, pnum] unallocated on this layer, which could be only
2278 * the first part of [offset, bytes]. */
2279 bytes
= MIN(bytes
, *pnum
);
2285 /* Coroutine wrapper for bdrv_block_status_above() */
2286 static void coroutine_fn
bdrv_block_status_above_co_entry(void *opaque
)
2288 BdrvCoBlockStatusData
*data
= opaque
;
2290 data
->ret
= bdrv_co_block_status_above(data
->bs
, data
->base
,
2292 data
->offset
, data
->bytes
,
2293 data
->pnum
, data
->map
, data
->file
);
2299 * Synchronous wrapper around bdrv_co_block_status_above().
2301 * See bdrv_co_block_status_above() for details.
2303 static int bdrv_common_block_status_above(BlockDriverState
*bs
,
2304 BlockDriverState
*base
,
2305 bool want_zero
, int64_t offset
,
2306 int64_t bytes
, int64_t *pnum
,
2308 BlockDriverState
**file
)
2311 BdrvCoBlockStatusData data
= {
2314 .want_zero
= want_zero
,
2323 if (qemu_in_coroutine()) {
2324 /* Fast-path if already in coroutine context */
2325 bdrv_block_status_above_co_entry(&data
);
2327 co
= qemu_coroutine_create(bdrv_block_status_above_co_entry
, &data
);
2328 bdrv_coroutine_enter(bs
, co
);
2329 BDRV_POLL_WHILE(bs
, !data
.done
);
2334 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2335 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2336 int64_t *map
, BlockDriverState
**file
)
2338 return bdrv_common_block_status_above(bs
, base
, true, offset
, bytes
,
2342 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2343 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2345 return bdrv_block_status_above(bs
, backing_bs(bs
),
2346 offset
, bytes
, pnum
, map
, file
);
2349 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2350 int64_t bytes
, int64_t *pnum
)
2355 ret
= bdrv_common_block_status_above(bs
, backing_bs(bs
), false, offset
,
2356 bytes
, pnum
? pnum
: &dummy
, NULL
,
2361 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2365 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2367 * Return 1 if (a prefix of) the given range is allocated in any image
2368 * between BASE and TOP (BASE is only included if include_base is set).
2369 * BASE can be NULL to check if the given offset is allocated in any
2370 * image of the chain. Return 0 otherwise, or negative errno on
2373 * 'pnum' is set to the number of bytes (including and immediately
2374 * following the specified offset) that are known to be in the same
2375 * allocated/unallocated state. Note that a subsequent call starting
2376 * at 'offset + *pnum' may return the same allocation status (in other
2377 * words, the result is not necessarily the maximum possible range);
2378 * but 'pnum' will only be 0 when end of file is reached.
2381 int bdrv_is_allocated_above(BlockDriverState
*top
,
2382 BlockDriverState
*base
,
2383 bool include_base
, int64_t offset
,
2384 int64_t bytes
, int64_t *pnum
)
2386 BlockDriverState
*intermediate
;
2390 assert(base
|| !include_base
);
2393 while (include_base
|| intermediate
!= base
) {
2397 assert(intermediate
);
2398 ret
= bdrv_is_allocated(intermediate
, offset
, bytes
, &pnum_inter
);
2407 size_inter
= bdrv_getlength(intermediate
);
2408 if (size_inter
< 0) {
2411 if (n
> pnum_inter
&&
2412 (intermediate
== top
|| offset
+ pnum_inter
< size_inter
)) {
2416 if (intermediate
== base
) {
2420 intermediate
= backing_bs(intermediate
);
2427 typedef struct BdrvVmstateCo
{
2428 BlockDriverState
*bs
;
2435 static int coroutine_fn
2436 bdrv_co_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2439 BlockDriver
*drv
= bs
->drv
;
2442 bdrv_inc_in_flight(bs
);
2446 } else if (drv
->bdrv_load_vmstate
) {
2448 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2450 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2452 } else if (bs
->file
) {
2453 ret
= bdrv_co_rw_vmstate(bs
->file
->bs
, qiov
, pos
, is_read
);
2456 bdrv_dec_in_flight(bs
);
2460 static void coroutine_fn
bdrv_co_rw_vmstate_entry(void *opaque
)
2462 BdrvVmstateCo
*co
= opaque
;
2463 co
->ret
= bdrv_co_rw_vmstate(co
->bs
, co
->qiov
, co
->pos
, co
->is_read
);
2468 bdrv_rw_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
,
2471 if (qemu_in_coroutine()) {
2472 return bdrv_co_rw_vmstate(bs
, qiov
, pos
, is_read
);
2474 BdrvVmstateCo data
= {
2479 .ret
= -EINPROGRESS
,
2481 Coroutine
*co
= qemu_coroutine_create(bdrv_co_rw_vmstate_entry
, &data
);
2483 bdrv_coroutine_enter(bs
, co
);
2484 BDRV_POLL_WHILE(bs
, data
.ret
== -EINPROGRESS
);
2489 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2490 int64_t pos
, int size
)
2492 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2495 ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2503 int bdrv_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2505 return bdrv_rw_vmstate(bs
, qiov
, pos
, false);
2508 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2509 int64_t pos
, int size
)
2511 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2514 ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2522 int bdrv_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2524 return bdrv_rw_vmstate(bs
, qiov
, pos
, true);
2527 /**************************************************************/
2530 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2533 bdrv_aio_cancel_async(acb
);
2534 while (acb
->refcnt
> 1) {
2535 if (acb
->aiocb_info
->get_aio_context
) {
2536 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2537 } else if (acb
->bs
) {
2538 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2539 * assert that we're not using an I/O thread. Thread-safe
2540 * code should use bdrv_aio_cancel_async exclusively.
2542 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2543 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2548 qemu_aio_unref(acb
);
2551 /* Async version of aio cancel. The caller is not blocked if the acb implements
2552 * cancel_async, otherwise we do nothing and let the request normally complete.
2553 * In either case the completion callback must be called. */
2554 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2556 if (acb
->aiocb_info
->cancel_async
) {
2557 acb
->aiocb_info
->cancel_async(acb
);
2561 /**************************************************************/
2562 /* Coroutine block device emulation */
2564 typedef struct FlushCo
{
2565 BlockDriverState
*bs
;
2570 static void coroutine_fn
bdrv_flush_co_entry(void *opaque
)
2572 FlushCo
*rwco
= opaque
;
2574 rwco
->ret
= bdrv_co_flush(rwco
->bs
);
2578 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2583 bdrv_inc_in_flight(bs
);
2585 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2590 qemu_co_mutex_lock(&bs
->reqs_lock
);
2591 current_gen
= atomic_read(&bs
->write_gen
);
2593 /* Wait until any previous flushes are completed */
2594 while (bs
->active_flush_req
) {
2595 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2598 /* Flushes reach this point in nondecreasing current_gen order. */
2599 bs
->active_flush_req
= true;
2600 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2602 /* Write back all layers by calling one driver function */
2603 if (bs
->drv
->bdrv_co_flush
) {
2604 ret
= bs
->drv
->bdrv_co_flush(bs
);
2608 /* Write back cached data to the OS even with cache=unsafe */
2609 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_OS
);
2610 if (bs
->drv
->bdrv_co_flush_to_os
) {
2611 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2617 /* But don't actually force it to the disk with cache=unsafe */
2618 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2622 /* Check if we really need to flush anything */
2623 if (bs
->flushed_gen
== current_gen
) {
2627 BLKDBG_EVENT(bs
->file
, BLKDBG_FLUSH_TO_DISK
);
2629 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2630 * (even in case of apparent success) */
2634 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2635 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2636 } else if (bs
->drv
->bdrv_aio_flush
) {
2638 CoroutineIOCompletion co
= {
2639 .coroutine
= qemu_coroutine_self(),
2642 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2646 qemu_coroutine_yield();
2651 * Some block drivers always operate in either writethrough or unsafe
2652 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2653 * know how the server works (because the behaviour is hardcoded or
2654 * depends on server-side configuration), so we can't ensure that
2655 * everything is safe on disk. Returning an error doesn't work because
2656 * that would break guests even if the server operates in writethrough
2659 * Let's hope the user knows what he's doing.
2668 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2669 * in the case of cache=unsafe, so there are no useless flushes.
2672 ret
= bs
->file
? bdrv_co_flush(bs
->file
->bs
) : 0;
2674 /* Notify any pending flushes that we have completed */
2676 bs
->flushed_gen
= current_gen
;
2679 qemu_co_mutex_lock(&bs
->reqs_lock
);
2680 bs
->active_flush_req
= false;
2681 /* Return value is ignored - it's ok if wait queue is empty */
2682 qemu_co_queue_next(&bs
->flush_queue
);
2683 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2686 bdrv_dec_in_flight(bs
);
2690 int bdrv_flush(BlockDriverState
*bs
)
2693 FlushCo flush_co
= {
2698 if (qemu_in_coroutine()) {
2699 /* Fast-path if already in coroutine context */
2700 bdrv_flush_co_entry(&flush_co
);
2702 co
= qemu_coroutine_create(bdrv_flush_co_entry
, &flush_co
);
2703 bdrv_coroutine_enter(bs
, co
);
2704 BDRV_POLL_WHILE(bs
, flush_co
.ret
== NOT_DONE
);
2707 return flush_co
.ret
;
2710 typedef struct DiscardCo
{
2716 static void coroutine_fn
bdrv_pdiscard_co_entry(void *opaque
)
2718 DiscardCo
*rwco
= opaque
;
2720 rwco
->ret
= bdrv_co_pdiscard(rwco
->child
, rwco
->offset
, rwco
->bytes
);
2724 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2727 BdrvTrackedRequest req
;
2728 int max_pdiscard
, ret
;
2729 int head
, tail
, align
;
2730 BlockDriverState
*bs
= child
->bs
;
2732 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
2736 if (bdrv_has_readonly_bitmaps(bs
)) {
2740 if (offset
< 0 || bytes
< 0 || bytes
> INT64_MAX
- offset
) {
2744 /* Do nothing if disabled. */
2745 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2749 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2753 /* Discard is advisory, but some devices track and coalesce
2754 * unaligned requests, so we must pass everything down rather than
2755 * round here. Still, most devices will just silently ignore
2756 * unaligned requests (by returning -ENOTSUP), so we must fragment
2757 * the request accordingly. */
2758 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2759 assert(align
% bs
->bl
.request_alignment
== 0);
2760 head
= offset
% align
;
2761 tail
= (offset
+ bytes
) % align
;
2763 bdrv_inc_in_flight(bs
);
2764 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2766 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
2771 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2773 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2776 int64_t num
= bytes
;
2779 /* Make small requests to get to alignment boundaries. */
2780 num
= MIN(bytes
, align
- head
);
2781 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2782 num
%= bs
->bl
.request_alignment
;
2784 head
= (head
+ num
) % align
;
2785 assert(num
< max_pdiscard
);
2788 /* Shorten the request to the last aligned cluster. */
2790 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2791 tail
> bs
->bl
.request_alignment
) {
2792 tail
%= bs
->bl
.request_alignment
;
2796 /* limit request size */
2797 if (num
> max_pdiscard
) {
2805 if (bs
->drv
->bdrv_co_pdiscard
) {
2806 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2809 CoroutineIOCompletion co
= {
2810 .coroutine
= qemu_coroutine_self(),
2813 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2814 bdrv_co_io_em_complete
, &co
);
2819 qemu_coroutine_yield();
2823 if (ret
&& ret
!= -ENOTSUP
) {
2832 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
2833 tracked_request_end(&req
);
2834 bdrv_dec_in_flight(bs
);
2838 int bdrv_pdiscard(BdrvChild
*child
, int64_t offset
, int64_t bytes
)
2848 if (qemu_in_coroutine()) {
2849 /* Fast-path if already in coroutine context */
2850 bdrv_pdiscard_co_entry(&rwco
);
2852 co
= qemu_coroutine_create(bdrv_pdiscard_co_entry
, &rwco
);
2853 bdrv_coroutine_enter(child
->bs
, co
);
2854 BDRV_POLL_WHILE(child
->bs
, rwco
.ret
== NOT_DONE
);
2860 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2862 BlockDriver
*drv
= bs
->drv
;
2863 CoroutineIOCompletion co
= {
2864 .coroutine
= qemu_coroutine_self(),
2868 bdrv_inc_in_flight(bs
);
2869 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2874 if (drv
->bdrv_co_ioctl
) {
2875 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2877 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2882 qemu_coroutine_yield();
2885 bdrv_dec_in_flight(bs
);
2889 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2891 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2894 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2896 return memset(qemu_blockalign(bs
, size
), 0, size
);
2899 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2901 size_t align
= bdrv_opt_mem_align(bs
);
2903 /* Ensure that NULL is never returned on success */
2909 return qemu_try_memalign(align
, size
);
2912 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2914 void *mem
= qemu_try_blockalign(bs
, size
);
2917 memset(mem
, 0, size
);
2924 * Check if all memory in this vector is sector aligned.
2926 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2929 size_t alignment
= bdrv_min_mem_align(bs
);
2931 for (i
= 0; i
< qiov
->niov
; i
++) {
2932 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2935 if (qiov
->iov
[i
].iov_len
% alignment
) {
2943 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2944 NotifierWithReturn
*notifier
)
2946 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2949 void bdrv_io_plug(BlockDriverState
*bs
)
2953 QLIST_FOREACH(child
, &bs
->children
, next
) {
2954 bdrv_io_plug(child
->bs
);
2957 if (atomic_fetch_inc(&bs
->io_plugged
) == 0) {
2958 BlockDriver
*drv
= bs
->drv
;
2959 if (drv
&& drv
->bdrv_io_plug
) {
2960 drv
->bdrv_io_plug(bs
);
2965 void bdrv_io_unplug(BlockDriverState
*bs
)
2969 assert(bs
->io_plugged
);
2970 if (atomic_fetch_dec(&bs
->io_plugged
) == 1) {
2971 BlockDriver
*drv
= bs
->drv
;
2972 if (drv
&& drv
->bdrv_io_unplug
) {
2973 drv
->bdrv_io_unplug(bs
);
2977 QLIST_FOREACH(child
, &bs
->children
, next
) {
2978 bdrv_io_unplug(child
->bs
);
2982 void bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
2986 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
2987 bs
->drv
->bdrv_register_buf(bs
, host
, size
);
2989 QLIST_FOREACH(child
, &bs
->children
, next
) {
2990 bdrv_register_buf(child
->bs
, host
, size
);
2994 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
)
2998 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
2999 bs
->drv
->bdrv_unregister_buf(bs
, host
);
3001 QLIST_FOREACH(child
, &bs
->children
, next
) {
3002 bdrv_unregister_buf(child
->bs
, host
);
3006 static int coroutine_fn
bdrv_co_copy_range_internal(
3007 BdrvChild
*src
, uint64_t src_offset
, BdrvChild
*dst
,
3008 uint64_t dst_offset
, uint64_t bytes
,
3009 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3012 BdrvTrackedRequest req
;
3015 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3016 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3017 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3019 if (!dst
|| !dst
->bs
) {
3022 ret
= bdrv_check_byte_request(dst
->bs
, dst_offset
, bytes
);
3026 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3027 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3030 if (!src
|| !src
->bs
) {
3033 ret
= bdrv_check_byte_request(src
->bs
, src_offset
, bytes
);
3038 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3039 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3040 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3045 bdrv_inc_in_flight(src
->bs
);
3046 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3049 /* BDRV_REQ_SERIALISING is only for write operation */
3050 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3051 if (!(read_flags
& BDRV_REQ_NO_SERIALISING
)) {
3052 wait_serialising_requests(&req
);
3055 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3059 read_flags
, write_flags
);
3061 tracked_request_end(&req
);
3062 bdrv_dec_in_flight(src
->bs
);
3064 bdrv_inc_in_flight(dst
->bs
);
3065 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3066 BDRV_TRACKED_WRITE
);
3067 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3070 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3074 read_flags
, write_flags
);
3076 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3077 tracked_request_end(&req
);
3078 bdrv_dec_in_flight(dst
->bs
);
3084 /* Copy range from @src to @dst.
3086 * See the comment of bdrv_co_copy_range for the parameter and return value
3088 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, uint64_t src_offset
,
3089 BdrvChild
*dst
, uint64_t dst_offset
,
3091 BdrvRequestFlags read_flags
,
3092 BdrvRequestFlags write_flags
)
3094 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3095 read_flags
, write_flags
);
3096 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3097 bytes
, read_flags
, write_flags
, true);
3100 /* Copy range from @src to @dst.
3102 * See the comment of bdrv_co_copy_range for the parameter and return value
3104 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, uint64_t src_offset
,
3105 BdrvChild
*dst
, uint64_t dst_offset
,
3107 BdrvRequestFlags read_flags
,
3108 BdrvRequestFlags write_flags
)
3110 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3111 read_flags
, write_flags
);
3112 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3113 bytes
, read_flags
, write_flags
, false);
3116 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, uint64_t src_offset
,
3117 BdrvChild
*dst
, uint64_t dst_offset
,
3118 uint64_t bytes
, BdrvRequestFlags read_flags
,
3119 BdrvRequestFlags write_flags
)
3121 return bdrv_co_copy_range_from(src
, src_offset
,
3123 bytes
, read_flags
, write_flags
);
3126 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3129 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3130 if (c
->role
->resize
) {
3137 * Truncate file to 'offset' bytes (needed only for file protocols)
3139 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
,
3140 PreallocMode prealloc
, Error
**errp
)
3142 BlockDriverState
*bs
= child
->bs
;
3143 BlockDriver
*drv
= bs
->drv
;
3144 BdrvTrackedRequest req
;
3145 int64_t old_size
, new_bytes
;
3149 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3151 error_setg(errp
, "No medium inserted");
3155 error_setg(errp
, "Image size cannot be negative");
3159 old_size
= bdrv_getlength(bs
);
3161 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3165 if (offset
> old_size
) {
3166 new_bytes
= offset
- old_size
;
3171 bdrv_inc_in_flight(bs
);
3172 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3173 BDRV_TRACKED_TRUNCATE
);
3175 /* If we are growing the image and potentially using preallocation for the
3176 * new area, we need to make sure that no write requests are made to it
3177 * concurrently or they might be overwritten by preallocation. */
3179 mark_request_serialising(&req
, 1);
3181 if (bs
->read_only
) {
3182 error_setg(errp
, "Image is read-only");
3186 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3189 error_setg_errno(errp
, -ret
,
3190 "Failed to prepare request for truncation");
3194 if (!drv
->bdrv_co_truncate
) {
3195 if (bs
->file
&& drv
->is_filter
) {
3196 ret
= bdrv_co_truncate(bs
->file
, offset
, prealloc
, errp
);
3199 error_setg(errp
, "Image format driver does not support resize");
3204 ret
= drv
->bdrv_co_truncate(bs
, offset
, prealloc
, errp
);
3208 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3210 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3212 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3214 /* It's possible that truncation succeeded but refresh_total_sectors
3215 * failed, but the latter doesn't affect how we should finish the request.
3216 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3217 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3220 tracked_request_end(&req
);
3221 bdrv_dec_in_flight(bs
);
3226 typedef struct TruncateCo
{
3229 PreallocMode prealloc
;
3234 static void coroutine_fn
bdrv_truncate_co_entry(void *opaque
)
3236 TruncateCo
*tco
= opaque
;
3237 tco
->ret
= bdrv_co_truncate(tco
->child
, tco
->offset
, tco
->prealloc
,
3242 int bdrv_truncate(BdrvChild
*child
, int64_t offset
, PreallocMode prealloc
,
3249 .prealloc
= prealloc
,
3254 if (qemu_in_coroutine()) {
3255 /* Fast-path if already in coroutine context */
3256 bdrv_truncate_co_entry(&tco
);
3258 co
= qemu_coroutine_create(bdrv_truncate_co_entry
, &tco
);
3259 bdrv_coroutine_enter(child
->bs
, co
);
3260 BDRV_POLL_WHILE(child
->bs
, tco
.ret
== NOT_DONE
);