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 "qemu/cutils.h"
34 #include "qapi/error.h"
35 #include "qemu/error-report.h"
36 #include "qemu/main-loop.h"
37 #include "sysemu/replay.h"
39 /* Maximum bounce buffer for copy-on-read and write zeroes, in bytes */
40 #define MAX_BOUNCE_BUFFER (32768 << BDRV_SECTOR_BITS)
42 static void bdrv_parent_cb_resize(BlockDriverState
*bs
);
43 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
44 int64_t offset
, int bytes
, BdrvRequestFlags flags
);
46 static void bdrv_parent_drained_begin(BlockDriverState
*bs
, BdrvChild
*ignore
,
47 bool ignore_bds_parents
)
51 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
52 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
55 bdrv_parent_drained_begin_single(c
, false);
59 static void bdrv_parent_drained_end_single_no_poll(BdrvChild
*c
,
60 int *drained_end_counter
)
62 assert(c
->parent_quiesce_counter
> 0);
63 c
->parent_quiesce_counter
--;
64 if (c
->klass
->drained_end
) {
65 c
->klass
->drained_end(c
, drained_end_counter
);
69 void bdrv_parent_drained_end_single(BdrvChild
*c
)
71 int drained_end_counter
= 0;
72 bdrv_parent_drained_end_single_no_poll(c
, &drained_end_counter
);
73 BDRV_POLL_WHILE(c
->bs
, qatomic_read(&drained_end_counter
) > 0);
76 static void bdrv_parent_drained_end(BlockDriverState
*bs
, BdrvChild
*ignore
,
77 bool ignore_bds_parents
,
78 int *drained_end_counter
)
82 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
83 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
86 bdrv_parent_drained_end_single_no_poll(c
, drained_end_counter
);
90 static bool bdrv_parent_drained_poll_single(BdrvChild
*c
)
92 if (c
->klass
->drained_poll
) {
93 return c
->klass
->drained_poll(c
);
98 static bool bdrv_parent_drained_poll(BlockDriverState
*bs
, BdrvChild
*ignore
,
99 bool ignore_bds_parents
)
104 QLIST_FOREACH_SAFE(c
, &bs
->parents
, next_parent
, next
) {
105 if (c
== ignore
|| (ignore_bds_parents
&& c
->klass
->parent_is_bds
)) {
108 busy
|= bdrv_parent_drained_poll_single(c
);
114 void bdrv_parent_drained_begin_single(BdrvChild
*c
, bool poll
)
116 c
->parent_quiesce_counter
++;
117 if (c
->klass
->drained_begin
) {
118 c
->klass
->drained_begin(c
);
121 BDRV_POLL_WHILE(c
->bs
, bdrv_parent_drained_poll_single(c
));
125 static void bdrv_merge_limits(BlockLimits
*dst
, const BlockLimits
*src
)
127 dst
->opt_transfer
= MAX(dst
->opt_transfer
, src
->opt_transfer
);
128 dst
->max_transfer
= MIN_NON_ZERO(dst
->max_transfer
, src
->max_transfer
);
129 dst
->opt_mem_alignment
= MAX(dst
->opt_mem_alignment
,
130 src
->opt_mem_alignment
);
131 dst
->min_mem_alignment
= MAX(dst
->min_mem_alignment
,
132 src
->min_mem_alignment
);
133 dst
->max_iov
= MIN_NON_ZERO(dst
->max_iov
, src
->max_iov
);
136 void bdrv_refresh_limits(BlockDriverState
*bs
, Error
**errp
)
138 BlockDriver
*drv
= bs
->drv
;
141 Error
*local_err
= NULL
;
143 memset(&bs
->bl
, 0, sizeof(bs
->bl
));
149 /* Default alignment based on whether driver has byte interface */
150 bs
->bl
.request_alignment
= (drv
->bdrv_co_preadv
||
151 drv
->bdrv_aio_preadv
||
152 drv
->bdrv_co_preadv_part
) ? 1 : 512;
154 /* Take some limits from the children as a default */
156 QLIST_FOREACH(c
, &bs
->children
, next
) {
157 if (c
->role
& (BDRV_CHILD_DATA
| BDRV_CHILD_FILTERED
| BDRV_CHILD_COW
))
159 bdrv_refresh_limits(c
->bs
, &local_err
);
161 error_propagate(errp
, local_err
);
164 bdrv_merge_limits(&bs
->bl
, &c
->bs
->bl
);
170 bs
->bl
.min_mem_alignment
= 512;
171 bs
->bl
.opt_mem_alignment
= qemu_real_host_page_size
;
173 /* Safe default since most protocols use readv()/writev()/etc */
174 bs
->bl
.max_iov
= IOV_MAX
;
177 /* Then let the driver override it */
178 if (drv
->bdrv_refresh_limits
) {
179 drv
->bdrv_refresh_limits(bs
, errp
);
184 * The copy-on-read flag is actually a reference count so multiple users may
185 * use the feature without worrying about clobbering its previous state.
186 * Copy-on-read stays enabled until all users have called to disable it.
188 void bdrv_enable_copy_on_read(BlockDriverState
*bs
)
190 qatomic_inc(&bs
->copy_on_read
);
193 void bdrv_disable_copy_on_read(BlockDriverState
*bs
)
195 int old
= qatomic_fetch_dec(&bs
->copy_on_read
);
201 BlockDriverState
*bs
;
207 bool ignore_bds_parents
;
208 int *drained_end_counter
;
211 static void coroutine_fn
bdrv_drain_invoke_entry(void *opaque
)
213 BdrvCoDrainData
*data
= opaque
;
214 BlockDriverState
*bs
= data
->bs
;
217 bs
->drv
->bdrv_co_drain_begin(bs
);
219 bs
->drv
->bdrv_co_drain_end(bs
);
222 /* Set data->done and decrement drained_end_counter before bdrv_wakeup() */
223 qatomic_mb_set(&data
->done
, true);
225 qatomic_dec(data
->drained_end_counter
);
227 bdrv_dec_in_flight(bs
);
232 /* Recursively call BlockDriver.bdrv_co_drain_begin/end callbacks */
233 static void bdrv_drain_invoke(BlockDriverState
*bs
, bool begin
,
234 int *drained_end_counter
)
236 BdrvCoDrainData
*data
;
238 if (!bs
->drv
|| (begin
&& !bs
->drv
->bdrv_co_drain_begin
) ||
239 (!begin
&& !bs
->drv
->bdrv_co_drain_end
)) {
243 data
= g_new(BdrvCoDrainData
, 1);
244 *data
= (BdrvCoDrainData
) {
248 .drained_end_counter
= drained_end_counter
,
252 qatomic_inc(drained_end_counter
);
255 /* Make sure the driver callback completes during the polling phase for
257 bdrv_inc_in_flight(bs
);
258 data
->co
= qemu_coroutine_create(bdrv_drain_invoke_entry
, data
);
259 aio_co_schedule(bdrv_get_aio_context(bs
), data
->co
);
262 /* Returns true if BDRV_POLL_WHILE() should go into a blocking aio_poll() */
263 bool bdrv_drain_poll(BlockDriverState
*bs
, bool recursive
,
264 BdrvChild
*ignore_parent
, bool ignore_bds_parents
)
266 BdrvChild
*child
, *next
;
268 if (bdrv_parent_drained_poll(bs
, ignore_parent
, ignore_bds_parents
)) {
272 if (qatomic_read(&bs
->in_flight
)) {
277 assert(!ignore_bds_parents
);
278 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
279 if (bdrv_drain_poll(child
->bs
, recursive
, child
, false)) {
288 static bool bdrv_drain_poll_top_level(BlockDriverState
*bs
, bool recursive
,
289 BdrvChild
*ignore_parent
)
291 return bdrv_drain_poll(bs
, recursive
, ignore_parent
, false);
294 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
295 BdrvChild
*parent
, bool ignore_bds_parents
,
297 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
298 BdrvChild
*parent
, bool ignore_bds_parents
,
299 int *drained_end_counter
);
301 static void bdrv_co_drain_bh_cb(void *opaque
)
303 BdrvCoDrainData
*data
= opaque
;
304 Coroutine
*co
= data
->co
;
305 BlockDriverState
*bs
= data
->bs
;
308 AioContext
*ctx
= bdrv_get_aio_context(bs
);
309 AioContext
*co_ctx
= qemu_coroutine_get_aio_context(co
);
312 * When the coroutine yielded, the lock for its home context was
313 * released, so we need to re-acquire it here. If it explicitly
314 * acquired a different context, the lock is still held and we don't
315 * want to lock it a second time (or AIO_WAIT_WHILE() would hang).
318 aio_context_acquire(ctx
);
320 bdrv_dec_in_flight(bs
);
322 assert(!data
->drained_end_counter
);
323 bdrv_do_drained_begin(bs
, data
->recursive
, data
->parent
,
324 data
->ignore_bds_parents
, data
->poll
);
327 bdrv_do_drained_end(bs
, data
->recursive
, data
->parent
,
328 data
->ignore_bds_parents
,
329 data
->drained_end_counter
);
332 aio_context_release(ctx
);
336 bdrv_drain_all_begin();
343 static void coroutine_fn
bdrv_co_yield_to_drain(BlockDriverState
*bs
,
344 bool begin
, bool recursive
,
346 bool ignore_bds_parents
,
348 int *drained_end_counter
)
350 BdrvCoDrainData data
;
352 /* Calling bdrv_drain() from a BH ensures the current coroutine yields and
353 * other coroutines run if they were queued by aio_co_enter(). */
355 assert(qemu_in_coroutine());
356 data
= (BdrvCoDrainData
) {
357 .co
= qemu_coroutine_self(),
361 .recursive
= recursive
,
363 .ignore_bds_parents
= ignore_bds_parents
,
365 .drained_end_counter
= drained_end_counter
,
369 bdrv_inc_in_flight(bs
);
371 replay_bh_schedule_oneshot_event(bdrv_get_aio_context(bs
),
372 bdrv_co_drain_bh_cb
, &data
);
374 qemu_coroutine_yield();
375 /* If we are resumed from some other event (such as an aio completion or a
376 * timer callback), it is a bug in the caller that should be fixed. */
380 void bdrv_do_drained_begin_quiesce(BlockDriverState
*bs
,
381 BdrvChild
*parent
, bool ignore_bds_parents
)
383 assert(!qemu_in_coroutine());
385 /* Stop things in parent-to-child order */
386 if (qatomic_fetch_inc(&bs
->quiesce_counter
) == 0) {
387 aio_disable_external(bdrv_get_aio_context(bs
));
390 bdrv_parent_drained_begin(bs
, parent
, ignore_bds_parents
);
391 bdrv_drain_invoke(bs
, true, NULL
);
394 static void bdrv_do_drained_begin(BlockDriverState
*bs
, bool recursive
,
395 BdrvChild
*parent
, bool ignore_bds_parents
,
398 BdrvChild
*child
, *next
;
400 if (qemu_in_coroutine()) {
401 bdrv_co_yield_to_drain(bs
, true, recursive
, parent
, ignore_bds_parents
,
406 bdrv_do_drained_begin_quiesce(bs
, parent
, ignore_bds_parents
);
409 assert(!ignore_bds_parents
);
410 bs
->recursive_quiesce_counter
++;
411 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
412 bdrv_do_drained_begin(child
->bs
, true, child
, ignore_bds_parents
,
418 * Wait for drained requests to finish.
420 * Calling BDRV_POLL_WHILE() only once for the top-level node is okay: The
421 * call is needed so things in this AioContext can make progress even
422 * though we don't return to the main AioContext loop - this automatically
423 * includes other nodes in the same AioContext and therefore all child
427 assert(!ignore_bds_parents
);
428 BDRV_POLL_WHILE(bs
, bdrv_drain_poll_top_level(bs
, recursive
, parent
));
432 void bdrv_drained_begin(BlockDriverState
*bs
)
434 bdrv_do_drained_begin(bs
, false, NULL
, false, true);
437 void bdrv_subtree_drained_begin(BlockDriverState
*bs
)
439 bdrv_do_drained_begin(bs
, true, NULL
, false, true);
443 * This function does not poll, nor must any of its recursively called
444 * functions. The *drained_end_counter pointee will be incremented
445 * once for every background operation scheduled, and decremented once
446 * the operation settles. Therefore, the pointer must remain valid
447 * until the pointee reaches 0. That implies that whoever sets up the
448 * pointee has to poll until it is 0.
450 * We use atomic operations to access *drained_end_counter, because
451 * (1) when called from bdrv_set_aio_context_ignore(), the subgraph of
452 * @bs may contain nodes in different AioContexts,
453 * (2) bdrv_drain_all_end() uses the same counter for all nodes,
454 * regardless of which AioContext they are in.
456 static void bdrv_do_drained_end(BlockDriverState
*bs
, bool recursive
,
457 BdrvChild
*parent
, bool ignore_bds_parents
,
458 int *drained_end_counter
)
461 int old_quiesce_counter
;
463 assert(drained_end_counter
!= NULL
);
465 if (qemu_in_coroutine()) {
466 bdrv_co_yield_to_drain(bs
, false, recursive
, parent
, ignore_bds_parents
,
467 false, drained_end_counter
);
470 assert(bs
->quiesce_counter
> 0);
472 /* Re-enable things in child-to-parent order */
473 bdrv_drain_invoke(bs
, false, drained_end_counter
);
474 bdrv_parent_drained_end(bs
, parent
, ignore_bds_parents
,
475 drained_end_counter
);
477 old_quiesce_counter
= qatomic_fetch_dec(&bs
->quiesce_counter
);
478 if (old_quiesce_counter
== 1) {
479 aio_enable_external(bdrv_get_aio_context(bs
));
483 assert(!ignore_bds_parents
);
484 bs
->recursive_quiesce_counter
--;
485 QLIST_FOREACH(child
, &bs
->children
, next
) {
486 bdrv_do_drained_end(child
->bs
, true, child
, ignore_bds_parents
,
487 drained_end_counter
);
492 void bdrv_drained_end(BlockDriverState
*bs
)
494 int drained_end_counter
= 0;
495 bdrv_do_drained_end(bs
, false, NULL
, false, &drained_end_counter
);
496 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
499 void bdrv_drained_end_no_poll(BlockDriverState
*bs
, int *drained_end_counter
)
501 bdrv_do_drained_end(bs
, false, NULL
, false, drained_end_counter
);
504 void bdrv_subtree_drained_end(BlockDriverState
*bs
)
506 int drained_end_counter
= 0;
507 bdrv_do_drained_end(bs
, true, NULL
, false, &drained_end_counter
);
508 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
511 void bdrv_apply_subtree_drain(BdrvChild
*child
, BlockDriverState
*new_parent
)
515 for (i
= 0; i
< new_parent
->recursive_quiesce_counter
; i
++) {
516 bdrv_do_drained_begin(child
->bs
, true, child
, false, true);
520 void bdrv_unapply_subtree_drain(BdrvChild
*child
, BlockDriverState
*old_parent
)
522 int drained_end_counter
= 0;
525 for (i
= 0; i
< old_parent
->recursive_quiesce_counter
; i
++) {
526 bdrv_do_drained_end(child
->bs
, true, child
, false,
527 &drained_end_counter
);
530 BDRV_POLL_WHILE(child
->bs
, qatomic_read(&drained_end_counter
) > 0);
534 * Wait for pending requests to complete on a single BlockDriverState subtree,
535 * and suspend block driver's internal I/O until next request arrives.
537 * Note that unlike bdrv_drain_all(), the caller must hold the BlockDriverState
540 void coroutine_fn
bdrv_co_drain(BlockDriverState
*bs
)
542 assert(qemu_in_coroutine());
543 bdrv_drained_begin(bs
);
544 bdrv_drained_end(bs
);
547 void bdrv_drain(BlockDriverState
*bs
)
549 bdrv_drained_begin(bs
);
550 bdrv_drained_end(bs
);
553 static void bdrv_drain_assert_idle(BlockDriverState
*bs
)
555 BdrvChild
*child
, *next
;
557 assert(qatomic_read(&bs
->in_flight
) == 0);
558 QLIST_FOREACH_SAFE(child
, &bs
->children
, next
, next
) {
559 bdrv_drain_assert_idle(child
->bs
);
563 unsigned int bdrv_drain_all_count
= 0;
565 static bool bdrv_drain_all_poll(void)
567 BlockDriverState
*bs
= NULL
;
570 /* bdrv_drain_poll() can't make changes to the graph and we are holding the
571 * main AioContext lock, so iterating bdrv_next_all_states() is safe. */
572 while ((bs
= bdrv_next_all_states(bs
))) {
573 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
574 aio_context_acquire(aio_context
);
575 result
|= bdrv_drain_poll(bs
, false, NULL
, true);
576 aio_context_release(aio_context
);
583 * Wait for pending requests to complete across all BlockDriverStates
585 * This function does not flush data to disk, use bdrv_flush_all() for that
586 * after calling this function.
588 * This pauses all block jobs and disables external clients. It must
589 * be paired with bdrv_drain_all_end().
591 * NOTE: no new block jobs or BlockDriverStates can be created between
592 * the bdrv_drain_all_begin() and bdrv_drain_all_end() calls.
594 void bdrv_drain_all_begin(void)
596 BlockDriverState
*bs
= NULL
;
598 if (qemu_in_coroutine()) {
599 bdrv_co_yield_to_drain(NULL
, true, false, NULL
, true, true, NULL
);
604 * bdrv queue is managed by record/replay,
605 * waiting for finishing the I/O requests may
608 if (replay_events_enabled()) {
612 /* AIO_WAIT_WHILE() with a NULL context can only be called from the main
613 * loop AioContext, so make sure we're in the main context. */
614 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
615 assert(bdrv_drain_all_count
< INT_MAX
);
616 bdrv_drain_all_count
++;
618 /* Quiesce all nodes, without polling in-flight requests yet. The graph
619 * cannot change during this loop. */
620 while ((bs
= bdrv_next_all_states(bs
))) {
621 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
623 aio_context_acquire(aio_context
);
624 bdrv_do_drained_begin(bs
, false, NULL
, true, false);
625 aio_context_release(aio_context
);
628 /* Now poll the in-flight requests */
629 AIO_WAIT_WHILE(NULL
, bdrv_drain_all_poll());
631 while ((bs
= bdrv_next_all_states(bs
))) {
632 bdrv_drain_assert_idle(bs
);
636 void bdrv_drain_all_end_quiesce(BlockDriverState
*bs
)
638 int drained_end_counter
= 0;
640 g_assert(bs
->quiesce_counter
> 0);
641 g_assert(!bs
->refcnt
);
643 while (bs
->quiesce_counter
) {
644 bdrv_do_drained_end(bs
, false, NULL
, true, &drained_end_counter
);
646 BDRV_POLL_WHILE(bs
, qatomic_read(&drained_end_counter
) > 0);
649 void bdrv_drain_all_end(void)
651 BlockDriverState
*bs
= NULL
;
652 int drained_end_counter
= 0;
655 * bdrv queue is managed by record/replay,
656 * waiting for finishing the I/O requests may
659 if (replay_events_enabled()) {
663 while ((bs
= bdrv_next_all_states(bs
))) {
664 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
666 aio_context_acquire(aio_context
);
667 bdrv_do_drained_end(bs
, false, NULL
, true, &drained_end_counter
);
668 aio_context_release(aio_context
);
671 assert(qemu_get_current_aio_context() == qemu_get_aio_context());
672 AIO_WAIT_WHILE(NULL
, qatomic_read(&drained_end_counter
) > 0);
674 assert(bdrv_drain_all_count
> 0);
675 bdrv_drain_all_count
--;
678 void bdrv_drain_all(void)
680 bdrv_drain_all_begin();
681 bdrv_drain_all_end();
685 * Remove an active request from the tracked requests list
687 * This function should be called when a tracked request is completing.
689 static void tracked_request_end(BdrvTrackedRequest
*req
)
691 if (req
->serialising
) {
692 qatomic_dec(&req
->bs
->serialising_in_flight
);
695 qemu_co_mutex_lock(&req
->bs
->reqs_lock
);
696 QLIST_REMOVE(req
, list
);
697 qemu_co_queue_restart_all(&req
->wait_queue
);
698 qemu_co_mutex_unlock(&req
->bs
->reqs_lock
);
702 * Add an active request to the tracked requests list
704 static void tracked_request_begin(BdrvTrackedRequest
*req
,
705 BlockDriverState
*bs
,
708 enum BdrvTrackedRequestType type
)
710 assert(bytes
<= INT64_MAX
&& offset
<= INT64_MAX
- bytes
);
712 *req
= (BdrvTrackedRequest
){
717 .co
= qemu_coroutine_self(),
718 .serialising
= false,
719 .overlap_offset
= offset
,
720 .overlap_bytes
= bytes
,
723 qemu_co_queue_init(&req
->wait_queue
);
725 qemu_co_mutex_lock(&bs
->reqs_lock
);
726 QLIST_INSERT_HEAD(&bs
->tracked_requests
, req
, list
);
727 qemu_co_mutex_unlock(&bs
->reqs_lock
);
730 static bool tracked_request_overlaps(BdrvTrackedRequest
*req
,
731 int64_t offset
, uint64_t bytes
)
734 if (offset
>= req
->overlap_offset
+ req
->overlap_bytes
) {
738 if (req
->overlap_offset
>= offset
+ bytes
) {
744 static bool coroutine_fn
745 bdrv_wait_serialising_requests_locked(BlockDriverState
*bs
,
746 BdrvTrackedRequest
*self
)
748 BdrvTrackedRequest
*req
;
754 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
755 if (req
== self
|| (!req
->serialising
&& !self
->serialising
)) {
758 if (tracked_request_overlaps(req
, self
->overlap_offset
,
759 self
->overlap_bytes
))
761 /* Hitting this means there was a reentrant request, for
762 * example, a block driver issuing nested requests. This must
763 * never happen since it means deadlock.
765 assert(qemu_coroutine_self() != req
->co
);
767 /* If the request is already (indirectly) waiting for us, or
768 * will wait for us as soon as it wakes up, then just go on
769 * (instead of producing a deadlock in the former case). */
770 if (!req
->waiting_for
) {
771 self
->waiting_for
= req
;
772 qemu_co_queue_wait(&req
->wait_queue
, &bs
->reqs_lock
);
773 self
->waiting_for
= NULL
;
784 bool bdrv_mark_request_serialising(BdrvTrackedRequest
*req
, uint64_t align
)
786 BlockDriverState
*bs
= req
->bs
;
787 int64_t overlap_offset
= req
->offset
& ~(align
- 1);
788 uint64_t overlap_bytes
= ROUND_UP(req
->offset
+ req
->bytes
, align
)
792 qemu_co_mutex_lock(&bs
->reqs_lock
);
793 if (!req
->serialising
) {
794 qatomic_inc(&req
->bs
->serialising_in_flight
);
795 req
->serialising
= true;
798 req
->overlap_offset
= MIN(req
->overlap_offset
, overlap_offset
);
799 req
->overlap_bytes
= MAX(req
->overlap_bytes
, overlap_bytes
);
800 waited
= bdrv_wait_serialising_requests_locked(bs
, req
);
801 qemu_co_mutex_unlock(&bs
->reqs_lock
);
806 * Return the tracked request on @bs for the current coroutine, or
807 * NULL if there is none.
809 BdrvTrackedRequest
*coroutine_fn
bdrv_co_get_self_request(BlockDriverState
*bs
)
811 BdrvTrackedRequest
*req
;
812 Coroutine
*self
= qemu_coroutine_self();
814 QLIST_FOREACH(req
, &bs
->tracked_requests
, list
) {
815 if (req
->co
== self
) {
824 * Round a region to cluster boundaries
826 void bdrv_round_to_clusters(BlockDriverState
*bs
,
827 int64_t offset
, int64_t bytes
,
828 int64_t *cluster_offset
,
829 int64_t *cluster_bytes
)
833 if (bdrv_get_info(bs
, &bdi
) < 0 || bdi
.cluster_size
== 0) {
834 *cluster_offset
= offset
;
835 *cluster_bytes
= bytes
;
837 int64_t c
= bdi
.cluster_size
;
838 *cluster_offset
= QEMU_ALIGN_DOWN(offset
, c
);
839 *cluster_bytes
= QEMU_ALIGN_UP(offset
- *cluster_offset
+ bytes
, c
);
843 static int bdrv_get_cluster_size(BlockDriverState
*bs
)
848 ret
= bdrv_get_info(bs
, &bdi
);
849 if (ret
< 0 || bdi
.cluster_size
== 0) {
850 return bs
->bl
.request_alignment
;
852 return bdi
.cluster_size
;
856 void bdrv_inc_in_flight(BlockDriverState
*bs
)
858 qatomic_inc(&bs
->in_flight
);
861 void bdrv_wakeup(BlockDriverState
*bs
)
866 void bdrv_dec_in_flight(BlockDriverState
*bs
)
868 qatomic_dec(&bs
->in_flight
);
872 static bool coroutine_fn
bdrv_wait_serialising_requests(BdrvTrackedRequest
*self
)
874 BlockDriverState
*bs
= self
->bs
;
877 if (!qatomic_read(&bs
->serialising_in_flight
)) {
881 qemu_co_mutex_lock(&bs
->reqs_lock
);
882 waited
= bdrv_wait_serialising_requests_locked(bs
, self
);
883 qemu_co_mutex_unlock(&bs
->reqs_lock
);
888 static int bdrv_check_byte_request(BlockDriverState
*bs
, int64_t offset
,
891 if (size
> BDRV_REQUEST_MAX_BYTES
) {
895 if (!bdrv_is_inserted(bs
)) {
906 int bdrv_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
907 int bytes
, BdrvRequestFlags flags
)
909 return bdrv_pwritev(child
, offset
, bytes
, NULL
,
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_pwrite().
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 /* See bdrv_pwrite() for the return codes */
955 int bdrv_pread(BdrvChild
*child
, int64_t offset
, void *buf
, int bytes
)
958 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
964 ret
= bdrv_preadv(child
, offset
, bytes
, &qiov
, 0);
966 return ret
< 0 ? ret
: bytes
;
969 /* Return no. of bytes on success or < 0 on error. Important errors are:
970 -EIO generic I/O error (may happen for all errors)
971 -ENOMEDIUM No media inserted.
972 -EINVAL Invalid offset or number of bytes
973 -EACCES Trying to write a read-only device
975 int bdrv_pwrite(BdrvChild
*child
, int64_t offset
, const void *buf
, int bytes
)
978 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, bytes
);
984 ret
= bdrv_pwritev(child
, offset
, bytes
, &qiov
, 0);
986 return ret
< 0 ? ret
: bytes
;
990 * Writes to the file and ensures that no writes are reordered across this
991 * request (acts as a barrier)
993 * Returns 0 on success, -errno in error cases.
995 int bdrv_pwrite_sync(BdrvChild
*child
, int64_t offset
,
996 const void *buf
, int count
)
1000 ret
= bdrv_pwrite(child
, offset
, buf
, count
);
1005 ret
= bdrv_flush(child
->bs
);
1013 typedef struct CoroutineIOCompletion
{
1014 Coroutine
*coroutine
;
1016 } CoroutineIOCompletion
;
1018 static void bdrv_co_io_em_complete(void *opaque
, int ret
)
1020 CoroutineIOCompletion
*co
= opaque
;
1023 aio_co_wake(co
->coroutine
);
1026 static int coroutine_fn
bdrv_driver_preadv(BlockDriverState
*bs
,
1027 uint64_t offset
, uint64_t bytes
,
1029 size_t qiov_offset
, int flags
)
1031 BlockDriver
*drv
= bs
->drv
;
1033 unsigned int nb_sectors
;
1034 QEMUIOVector local_qiov
;
1037 assert(!(flags
& ~BDRV_REQ_MASK
));
1038 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1044 if (drv
->bdrv_co_preadv_part
) {
1045 return drv
->bdrv_co_preadv_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1049 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1050 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1054 if (drv
->bdrv_co_preadv
) {
1055 ret
= drv
->bdrv_co_preadv(bs
, offset
, bytes
, qiov
, flags
);
1059 if (drv
->bdrv_aio_preadv
) {
1061 CoroutineIOCompletion co
= {
1062 .coroutine
= qemu_coroutine_self(),
1065 acb
= drv
->bdrv_aio_preadv(bs
, offset
, bytes
, qiov
, flags
,
1066 bdrv_co_io_em_complete
, &co
);
1071 qemu_coroutine_yield();
1077 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1078 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1080 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1081 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1082 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1083 assert(drv
->bdrv_co_readv
);
1085 ret
= drv
->bdrv_co_readv(bs
, sector_num
, nb_sectors
, qiov
);
1088 if (qiov
== &local_qiov
) {
1089 qemu_iovec_destroy(&local_qiov
);
1095 static int coroutine_fn
bdrv_driver_pwritev(BlockDriverState
*bs
,
1096 uint64_t offset
, uint64_t bytes
,
1098 size_t qiov_offset
, int flags
)
1100 BlockDriver
*drv
= bs
->drv
;
1102 unsigned int nb_sectors
;
1103 QEMUIOVector local_qiov
;
1106 assert(!(flags
& ~BDRV_REQ_MASK
));
1107 assert(!(flags
& BDRV_REQ_NO_FALLBACK
));
1113 if (drv
->bdrv_co_pwritev_part
) {
1114 ret
= drv
->bdrv_co_pwritev_part(bs
, offset
, bytes
, qiov
, qiov_offset
,
1115 flags
& bs
->supported_write_flags
);
1116 flags
&= ~bs
->supported_write_flags
;
1120 if (qiov_offset
> 0 || bytes
!= qiov
->size
) {
1121 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1125 if (drv
->bdrv_co_pwritev
) {
1126 ret
= drv
->bdrv_co_pwritev(bs
, offset
, bytes
, qiov
,
1127 flags
& bs
->supported_write_flags
);
1128 flags
&= ~bs
->supported_write_flags
;
1132 if (drv
->bdrv_aio_pwritev
) {
1134 CoroutineIOCompletion co
= {
1135 .coroutine
= qemu_coroutine_self(),
1138 acb
= drv
->bdrv_aio_pwritev(bs
, offset
, bytes
, qiov
,
1139 flags
& bs
->supported_write_flags
,
1140 bdrv_co_io_em_complete
, &co
);
1141 flags
&= ~bs
->supported_write_flags
;
1145 qemu_coroutine_yield();
1151 sector_num
= offset
>> BDRV_SECTOR_BITS
;
1152 nb_sectors
= bytes
>> BDRV_SECTOR_BITS
;
1154 assert(QEMU_IS_ALIGNED(offset
, BDRV_SECTOR_SIZE
));
1155 assert(QEMU_IS_ALIGNED(bytes
, BDRV_SECTOR_SIZE
));
1156 assert(bytes
<= BDRV_REQUEST_MAX_BYTES
);
1158 assert(drv
->bdrv_co_writev
);
1159 ret
= drv
->bdrv_co_writev(bs
, sector_num
, nb_sectors
, qiov
,
1160 flags
& bs
->supported_write_flags
);
1161 flags
&= ~bs
->supported_write_flags
;
1164 if (ret
== 0 && (flags
& BDRV_REQ_FUA
)) {
1165 ret
= bdrv_co_flush(bs
);
1168 if (qiov
== &local_qiov
) {
1169 qemu_iovec_destroy(&local_qiov
);
1175 static int coroutine_fn
1176 bdrv_driver_pwritev_compressed(BlockDriverState
*bs
, uint64_t offset
,
1177 uint64_t bytes
, QEMUIOVector
*qiov
,
1180 BlockDriver
*drv
= bs
->drv
;
1181 QEMUIOVector local_qiov
;
1188 if (!block_driver_can_compress(drv
)) {
1192 if (drv
->bdrv_co_pwritev_compressed_part
) {
1193 return drv
->bdrv_co_pwritev_compressed_part(bs
, offset
, bytes
,
1197 if (qiov_offset
== 0) {
1198 return drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, qiov
);
1201 qemu_iovec_init_slice(&local_qiov
, qiov
, qiov_offset
, bytes
);
1202 ret
= drv
->bdrv_co_pwritev_compressed(bs
, offset
, bytes
, &local_qiov
);
1203 qemu_iovec_destroy(&local_qiov
);
1208 static int coroutine_fn
bdrv_co_do_copy_on_readv(BdrvChild
*child
,
1209 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1210 size_t qiov_offset
, int flags
)
1212 BlockDriverState
*bs
= child
->bs
;
1214 /* Perform I/O through a temporary buffer so that users who scribble over
1215 * their read buffer while the operation is in progress do not end up
1216 * modifying the image file. This is critical for zero-copy guest I/O
1217 * where anything might happen inside guest memory.
1219 void *bounce_buffer
= NULL
;
1221 BlockDriver
*drv
= bs
->drv
;
1222 int64_t cluster_offset
;
1223 int64_t cluster_bytes
;
1226 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
,
1227 BDRV_REQUEST_MAX_BYTES
);
1228 unsigned int progress
= 0;
1236 * Do not write anything when the BDS is inactive. That is not
1237 * allowed, and it would not help.
1239 skip_write
= (bs
->open_flags
& BDRV_O_INACTIVE
);
1241 /* FIXME We cannot require callers to have write permissions when all they
1242 * are doing is a read request. If we did things right, write permissions
1243 * would be obtained anyway, but internally by the copy-on-read code. As
1244 * long as it is implemented here rather than in a separate filter driver,
1245 * the copy-on-read code doesn't have its own BdrvChild, however, for which
1246 * it could request permissions. Therefore we have to bypass the permission
1247 * system for the moment. */
1248 // assert(child->perm & (BLK_PERM_WRITE_UNCHANGED | BLK_PERM_WRITE));
1250 /* Cover entire cluster so no additional backing file I/O is required when
1251 * allocating cluster in the image file. Note that this value may exceed
1252 * BDRV_REQUEST_MAX_BYTES (even when the original read did not), which
1253 * is one reason we loop rather than doing it all at once.
1255 bdrv_round_to_clusters(bs
, offset
, bytes
, &cluster_offset
, &cluster_bytes
);
1256 skip_bytes
= offset
- cluster_offset
;
1258 trace_bdrv_co_do_copy_on_readv(bs
, offset
, bytes
,
1259 cluster_offset
, cluster_bytes
);
1261 while (cluster_bytes
) {
1265 ret
= 1; /* "already allocated", so nothing will be copied */
1266 pnum
= MIN(cluster_bytes
, max_transfer
);
1268 ret
= bdrv_is_allocated(bs
, cluster_offset
,
1269 MIN(cluster_bytes
, max_transfer
), &pnum
);
1272 * Safe to treat errors in querying allocation as if
1273 * unallocated; we'll probably fail again soon on the
1274 * read, but at least that will set a decent errno.
1276 pnum
= MIN(cluster_bytes
, max_transfer
);
1279 /* Stop at EOF if the image ends in the middle of the cluster */
1280 if (ret
== 0 && pnum
== 0) {
1281 assert(progress
>= bytes
);
1285 assert(skip_bytes
< pnum
);
1289 QEMUIOVector local_qiov
;
1291 /* Must copy-on-read; use the bounce buffer */
1292 pnum
= MIN(pnum
, MAX_BOUNCE_BUFFER
);
1293 if (!bounce_buffer
) {
1294 int64_t max_we_need
= MAX(pnum
, cluster_bytes
- pnum
);
1295 int64_t max_allowed
= MIN(max_transfer
, MAX_BOUNCE_BUFFER
);
1296 int64_t bounce_buffer_len
= MIN(max_we_need
, max_allowed
);
1298 bounce_buffer
= qemu_try_blockalign(bs
, bounce_buffer_len
);
1299 if (!bounce_buffer
) {
1304 qemu_iovec_init_buf(&local_qiov
, bounce_buffer
, pnum
);
1306 ret
= bdrv_driver_preadv(bs
, cluster_offset
, pnum
,
1312 bdrv_debug_event(bs
, BLKDBG_COR_WRITE
);
1313 if (drv
->bdrv_co_pwrite_zeroes
&&
1314 buffer_is_zero(bounce_buffer
, pnum
)) {
1315 /* FIXME: Should we (perhaps conditionally) be setting
1316 * BDRV_REQ_MAY_UNMAP, if it will allow for a sparser copy
1317 * that still correctly reads as zero? */
1318 ret
= bdrv_co_do_pwrite_zeroes(bs
, cluster_offset
, pnum
,
1319 BDRV_REQ_WRITE_UNCHANGED
);
1321 /* This does not change the data on the disk, it is not
1322 * necessary to flush even in cache=writethrough mode.
1324 ret
= bdrv_driver_pwritev(bs
, cluster_offset
, pnum
,
1326 BDRV_REQ_WRITE_UNCHANGED
);
1330 /* It might be okay to ignore write errors for guest
1331 * requests. If this is a deliberate copy-on-read
1332 * then we don't want to ignore the error. Simply
1333 * report it in all cases.
1338 if (!(flags
& BDRV_REQ_PREFETCH
)) {
1339 qemu_iovec_from_buf(qiov
, qiov_offset
+ progress
,
1340 bounce_buffer
+ skip_bytes
,
1341 MIN(pnum
- skip_bytes
, bytes
- progress
));
1343 } else if (!(flags
& BDRV_REQ_PREFETCH
)) {
1344 /* Read directly into the destination */
1345 ret
= bdrv_driver_preadv(bs
, offset
+ progress
,
1346 MIN(pnum
- skip_bytes
, bytes
- progress
),
1347 qiov
, qiov_offset
+ progress
, 0);
1353 cluster_offset
+= pnum
;
1354 cluster_bytes
-= pnum
;
1355 progress
+= pnum
- skip_bytes
;
1361 qemu_vfree(bounce_buffer
);
1366 * Forwards an already correctly aligned request to the BlockDriver. This
1367 * handles copy on read, zeroing after EOF, and fragmentation of large
1368 * reads; any other features must be implemented by the caller.
1370 static int coroutine_fn
bdrv_aligned_preadv(BdrvChild
*child
,
1371 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1372 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1374 BlockDriverState
*bs
= child
->bs
;
1375 int64_t total_bytes
, max_bytes
;
1377 uint64_t bytes_remaining
= bytes
;
1380 assert(is_power_of_2(align
));
1381 assert((offset
& (align
- 1)) == 0);
1382 assert((bytes
& (align
- 1)) == 0);
1383 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1384 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1387 /* TODO: We would need a per-BDS .supported_read_flags and
1388 * potential fallback support, if we ever implement any read flags
1389 * to pass through to drivers. For now, there aren't any
1390 * passthrough flags. */
1391 assert(!(flags
& ~(BDRV_REQ_COPY_ON_READ
| BDRV_REQ_PREFETCH
)));
1393 /* Handle Copy on Read and associated serialisation */
1394 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1395 /* If we touch the same cluster it counts as an overlap. This
1396 * guarantees that allocating writes will be serialized and not race
1397 * with each other for the same cluster. For example, in copy-on-read
1398 * it ensures that the CoR read and write operations are atomic and
1399 * guest writes cannot interleave between them. */
1400 bdrv_mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1402 bdrv_wait_serialising_requests(req
);
1405 if (flags
& BDRV_REQ_COPY_ON_READ
) {
1408 ret
= bdrv_is_allocated(bs
, offset
, bytes
, &pnum
);
1413 if (!ret
|| pnum
!= bytes
) {
1414 ret
= bdrv_co_do_copy_on_readv(child
, offset
, bytes
,
1415 qiov
, qiov_offset
, flags
);
1417 } else if (flags
& BDRV_REQ_PREFETCH
) {
1422 /* Forward the request to the BlockDriver, possibly fragmenting it */
1423 total_bytes
= bdrv_getlength(bs
);
1424 if (total_bytes
< 0) {
1429 max_bytes
= ROUND_UP(MAX(0, total_bytes
- offset
), align
);
1430 if (bytes
<= max_bytes
&& bytes
<= max_transfer
) {
1431 ret
= bdrv_driver_preadv(bs
, offset
, bytes
, qiov
, qiov_offset
, 0);
1435 while (bytes_remaining
) {
1439 num
= MIN(bytes_remaining
, MIN(max_bytes
, max_transfer
));
1442 ret
= bdrv_driver_preadv(bs
, offset
+ bytes
- bytes_remaining
,
1444 qiov_offset
+ bytes
- bytes_remaining
, 0);
1447 num
= bytes_remaining
;
1448 ret
= qemu_iovec_memset(qiov
, qiov_offset
+ bytes
- bytes_remaining
,
1449 0, bytes_remaining
);
1454 bytes_remaining
-= num
;
1458 return ret
< 0 ? ret
: 0;
1464 * |<---- align ----->| |<----- align ---->|
1465 * |<- head ->|<------------- bytes ------------->|<-- tail -->|
1467 * -*----------$-------*-------- ... --------*-----$------------*---
1469 * | offset | | end |
1470 * ALIGN_DOWN(offset) ALIGN_UP(offset) ALIGN_DOWN(end) ALIGN_UP(end)
1471 * [buf ... ) [tail_buf )
1473 * @buf is an aligned allocation needed to store @head and @tail paddings. @head
1474 * is placed at the beginning of @buf and @tail at the @end.
1476 * @tail_buf is a pointer to sub-buffer, corresponding to align-sized chunk
1477 * around tail, if tail exists.
1479 * @merge_reads is true for small requests,
1480 * if @buf_len == @head + bytes + @tail. In this case it is possible that both
1481 * head and tail exist but @buf_len == align and @tail_buf == @buf.
1483 typedef struct BdrvRequestPadding
{
1490 QEMUIOVector local_qiov
;
1491 } BdrvRequestPadding
;
1493 static bool bdrv_init_padding(BlockDriverState
*bs
,
1494 int64_t offset
, int64_t bytes
,
1495 BdrvRequestPadding
*pad
)
1497 uint64_t align
= bs
->bl
.request_alignment
;
1500 memset(pad
, 0, sizeof(*pad
));
1502 pad
->head
= offset
& (align
- 1);
1503 pad
->tail
= ((offset
+ bytes
) & (align
- 1));
1505 pad
->tail
= align
- pad
->tail
;
1508 if (!pad
->head
&& !pad
->tail
) {
1512 assert(bytes
); /* Nothing good in aligning zero-length requests */
1514 sum
= pad
->head
+ bytes
+ pad
->tail
;
1515 pad
->buf_len
= (sum
> align
&& pad
->head
&& pad
->tail
) ? 2 * align
: align
;
1516 pad
->buf
= qemu_blockalign(bs
, pad
->buf_len
);
1517 pad
->merge_reads
= sum
== pad
->buf_len
;
1519 pad
->tail_buf
= pad
->buf
+ pad
->buf_len
- align
;
1525 static int bdrv_padding_rmw_read(BdrvChild
*child
,
1526 BdrvTrackedRequest
*req
,
1527 BdrvRequestPadding
*pad
,
1530 QEMUIOVector local_qiov
;
1531 BlockDriverState
*bs
= child
->bs
;
1532 uint64_t align
= bs
->bl
.request_alignment
;
1535 assert(req
->serialising
&& pad
->buf
);
1537 if (pad
->head
|| pad
->merge_reads
) {
1538 uint64_t bytes
= pad
->merge_reads
? pad
->buf_len
: align
;
1540 qemu_iovec_init_buf(&local_qiov
, pad
->buf
, bytes
);
1543 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_HEAD
);
1545 if (pad
->merge_reads
&& pad
->tail
) {
1546 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1548 ret
= bdrv_aligned_preadv(child
, req
, req
->overlap_offset
, bytes
,
1549 align
, &local_qiov
, 0, 0);
1554 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_HEAD
);
1556 if (pad
->merge_reads
&& pad
->tail
) {
1557 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1560 if (pad
->merge_reads
) {
1566 qemu_iovec_init_buf(&local_qiov
, pad
->tail_buf
, align
);
1568 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_TAIL
);
1569 ret
= bdrv_aligned_preadv(
1571 req
->overlap_offset
+ req
->overlap_bytes
- align
,
1572 align
, align
, &local_qiov
, 0, 0);
1576 bdrv_debug_event(bs
, BLKDBG_PWRITEV_RMW_AFTER_TAIL
);
1581 memset(pad
->buf
+ pad
->head
, 0, pad
->buf_len
- pad
->head
- pad
->tail
);
1587 static void bdrv_padding_destroy(BdrvRequestPadding
*pad
)
1590 qemu_vfree(pad
->buf
);
1591 qemu_iovec_destroy(&pad
->local_qiov
);
1598 * Exchange request parameters with padded request if needed. Don't include RMW
1599 * read of padding, bdrv_padding_rmw_read() should be called separately if
1602 * All parameters except @bs are in-out: they represent original request at
1603 * function call and padded (if padding needed) at function finish.
1605 * Function always succeeds.
1607 static bool bdrv_pad_request(BlockDriverState
*bs
,
1608 QEMUIOVector
**qiov
, size_t *qiov_offset
,
1609 int64_t *offset
, unsigned int *bytes
,
1610 BdrvRequestPadding
*pad
)
1612 if (!bdrv_init_padding(bs
, *offset
, *bytes
, pad
)) {
1616 qemu_iovec_init_extended(&pad
->local_qiov
, pad
->buf
, pad
->head
,
1617 *qiov
, *qiov_offset
, *bytes
,
1618 pad
->buf
+ pad
->buf_len
- pad
->tail
, pad
->tail
);
1619 *bytes
+= pad
->head
+ pad
->tail
;
1620 *offset
-= pad
->head
;
1621 *qiov
= &pad
->local_qiov
;
1627 int coroutine_fn
bdrv_co_preadv(BdrvChild
*child
,
1628 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
1629 BdrvRequestFlags flags
)
1631 return bdrv_co_preadv_part(child
, offset
, bytes
, qiov
, 0, flags
);
1634 int coroutine_fn
bdrv_co_preadv_part(BdrvChild
*child
,
1635 int64_t offset
, unsigned int bytes
,
1636 QEMUIOVector
*qiov
, size_t qiov_offset
,
1637 BdrvRequestFlags flags
)
1639 BlockDriverState
*bs
= child
->bs
;
1640 BdrvTrackedRequest req
;
1641 BdrvRequestPadding pad
;
1644 trace_bdrv_co_preadv(bs
, offset
, bytes
, flags
);
1646 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
1651 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
1653 * Aligning zero request is nonsense. Even if driver has special meaning
1654 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
1655 * it to driver due to request_alignment.
1657 * Still, no reason to return an error if someone do unaligned
1658 * zero-length read occasionally.
1663 bdrv_inc_in_flight(bs
);
1665 /* Don't do copy-on-read if we read data before write operation */
1666 if (qatomic_read(&bs
->copy_on_read
)) {
1667 flags
|= BDRV_REQ_COPY_ON_READ
;
1670 bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
);
1672 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_READ
);
1673 ret
= bdrv_aligned_preadv(child
, &req
, offset
, bytes
,
1674 bs
->bl
.request_alignment
,
1675 qiov
, qiov_offset
, flags
);
1676 tracked_request_end(&req
);
1677 bdrv_dec_in_flight(bs
);
1679 bdrv_padding_destroy(&pad
);
1684 static int coroutine_fn
bdrv_co_do_pwrite_zeroes(BlockDriverState
*bs
,
1685 int64_t offset
, int bytes
, BdrvRequestFlags flags
)
1687 BlockDriver
*drv
= bs
->drv
;
1691 bool need_flush
= false;
1695 int max_write_zeroes
= MIN_NON_ZERO(bs
->bl
.max_pwrite_zeroes
, INT_MAX
);
1696 int alignment
= MAX(bs
->bl
.pwrite_zeroes_alignment
,
1697 bs
->bl
.request_alignment
);
1698 int max_transfer
= MIN_NON_ZERO(bs
->bl
.max_transfer
, MAX_BOUNCE_BUFFER
);
1704 if ((flags
& ~bs
->supported_zero_flags
) & BDRV_REQ_NO_FALLBACK
) {
1708 assert(alignment
% bs
->bl
.request_alignment
== 0);
1709 head
= offset
% alignment
;
1710 tail
= (offset
+ bytes
) % alignment
;
1711 max_write_zeroes
= QEMU_ALIGN_DOWN(max_write_zeroes
, alignment
);
1712 assert(max_write_zeroes
>= bs
->bl
.request_alignment
);
1714 while (bytes
> 0 && !ret
) {
1717 /* Align request. Block drivers can expect the "bulk" of the request
1718 * to be aligned, and that unaligned requests do not cross cluster
1722 /* Make a small request up to the first aligned sector. For
1723 * convenience, limit this request to max_transfer even if
1724 * we don't need to fall back to writes. */
1725 num
= MIN(MIN(bytes
, max_transfer
), alignment
- head
);
1726 head
= (head
+ num
) % alignment
;
1727 assert(num
< max_write_zeroes
);
1728 } else if (tail
&& num
> alignment
) {
1729 /* Shorten the request to the last aligned sector. */
1733 /* limit request size */
1734 if (num
> max_write_zeroes
) {
1735 num
= max_write_zeroes
;
1739 /* First try the efficient write zeroes operation */
1740 if (drv
->bdrv_co_pwrite_zeroes
) {
1741 ret
= drv
->bdrv_co_pwrite_zeroes(bs
, offset
, num
,
1742 flags
& bs
->supported_zero_flags
);
1743 if (ret
!= -ENOTSUP
&& (flags
& BDRV_REQ_FUA
) &&
1744 !(bs
->supported_zero_flags
& BDRV_REQ_FUA
)) {
1748 assert(!bs
->supported_zero_flags
);
1751 if (ret
== -ENOTSUP
&& !(flags
& BDRV_REQ_NO_FALLBACK
)) {
1752 /* Fall back to bounce buffer if write zeroes is unsupported */
1753 BdrvRequestFlags write_flags
= flags
& ~BDRV_REQ_ZERO_WRITE
;
1755 if ((flags
& BDRV_REQ_FUA
) &&
1756 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1757 /* No need for bdrv_driver_pwrite() to do a fallback
1758 * flush on each chunk; use just one at the end */
1759 write_flags
&= ~BDRV_REQ_FUA
;
1762 num
= MIN(num
, max_transfer
);
1764 buf
= qemu_try_blockalign0(bs
, num
);
1770 qemu_iovec_init_buf(&qiov
, buf
, num
);
1772 ret
= bdrv_driver_pwritev(bs
, offset
, num
, &qiov
, 0, write_flags
);
1774 /* Keep bounce buffer around if it is big enough for all
1775 * all future requests.
1777 if (num
< max_transfer
) {
1788 if (ret
== 0 && need_flush
) {
1789 ret
= bdrv_co_flush(bs
);
1795 static inline int coroutine_fn
1796 bdrv_co_write_req_prepare(BdrvChild
*child
, int64_t offset
, uint64_t bytes
,
1797 BdrvTrackedRequest
*req
, int flags
)
1799 BlockDriverState
*bs
= child
->bs
;
1801 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1803 if (bs
->read_only
) {
1807 assert(!(bs
->open_flags
& BDRV_O_INACTIVE
));
1808 assert((bs
->open_flags
& BDRV_O_NO_IO
) == 0);
1809 assert(!(flags
& ~BDRV_REQ_MASK
));
1811 if (flags
& BDRV_REQ_SERIALISING
) {
1812 waited
= bdrv_mark_request_serialising(req
, bdrv_get_cluster_size(bs
));
1814 * For a misaligned request we should have already waited earlier,
1815 * because we come after bdrv_padding_rmw_read which must be called
1816 * with the request already marked as serialising.
1819 (req
->offset
== req
->overlap_offset
&&
1820 req
->bytes
== req
->overlap_bytes
));
1822 bdrv_wait_serialising_requests(req
);
1825 assert(req
->overlap_offset
<= offset
);
1826 assert(offset
+ bytes
<= req
->overlap_offset
+ req
->overlap_bytes
);
1827 assert(end_sector
<= bs
->total_sectors
|| child
->perm
& BLK_PERM_RESIZE
);
1829 switch (req
->type
) {
1830 case BDRV_TRACKED_WRITE
:
1831 case BDRV_TRACKED_DISCARD
:
1832 if (flags
& BDRV_REQ_WRITE_UNCHANGED
) {
1833 assert(child
->perm
& (BLK_PERM_WRITE_UNCHANGED
| BLK_PERM_WRITE
));
1835 assert(child
->perm
& BLK_PERM_WRITE
);
1837 return notifier_with_return_list_notify(&bs
->before_write_notifiers
,
1839 case BDRV_TRACKED_TRUNCATE
:
1840 assert(child
->perm
& BLK_PERM_RESIZE
);
1847 static inline void coroutine_fn
1848 bdrv_co_write_req_finish(BdrvChild
*child
, int64_t offset
, uint64_t bytes
,
1849 BdrvTrackedRequest
*req
, int ret
)
1851 int64_t end_sector
= DIV_ROUND_UP(offset
+ bytes
, BDRV_SECTOR_SIZE
);
1852 BlockDriverState
*bs
= child
->bs
;
1854 qatomic_inc(&bs
->write_gen
);
1857 * Discard cannot extend the image, but in error handling cases, such as
1858 * when reverting a qcow2 cluster allocation, the discarded range can pass
1859 * the end of image file, so we cannot assert about BDRV_TRACKED_DISCARD
1860 * here. Instead, just skip it, since semantically a discard request
1861 * beyond EOF cannot expand the image anyway.
1864 (req
->type
== BDRV_TRACKED_TRUNCATE
||
1865 end_sector
> bs
->total_sectors
) &&
1866 req
->type
!= BDRV_TRACKED_DISCARD
) {
1867 bs
->total_sectors
= end_sector
;
1868 bdrv_parent_cb_resize(bs
);
1869 bdrv_dirty_bitmap_truncate(bs
, end_sector
<< BDRV_SECTOR_BITS
);
1872 switch (req
->type
) {
1873 case BDRV_TRACKED_WRITE
:
1874 stat64_max(&bs
->wr_highest_offset
, offset
+ bytes
);
1875 /* fall through, to set dirty bits */
1876 case BDRV_TRACKED_DISCARD
:
1877 bdrv_set_dirty(bs
, offset
, bytes
);
1886 * Forwards an already correctly aligned write request to the BlockDriver,
1887 * after possibly fragmenting it.
1889 static int coroutine_fn
bdrv_aligned_pwritev(BdrvChild
*child
,
1890 BdrvTrackedRequest
*req
, int64_t offset
, unsigned int bytes
,
1891 int64_t align
, QEMUIOVector
*qiov
, size_t qiov_offset
, int flags
)
1893 BlockDriverState
*bs
= child
->bs
;
1894 BlockDriver
*drv
= bs
->drv
;
1897 uint64_t bytes_remaining
= bytes
;
1904 if (bdrv_has_readonly_bitmaps(bs
)) {
1908 assert(is_power_of_2(align
));
1909 assert((offset
& (align
- 1)) == 0);
1910 assert((bytes
& (align
- 1)) == 0);
1911 assert(!qiov
|| qiov_offset
+ bytes
<= qiov
->size
);
1912 max_transfer
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_transfer
, INT_MAX
),
1915 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, req
, flags
);
1917 if (!ret
&& bs
->detect_zeroes
!= BLOCKDEV_DETECT_ZEROES_OPTIONS_OFF
&&
1918 !(flags
& BDRV_REQ_ZERO_WRITE
) && drv
->bdrv_co_pwrite_zeroes
&&
1919 qemu_iovec_is_zero(qiov
, qiov_offset
, bytes
)) {
1920 flags
|= BDRV_REQ_ZERO_WRITE
;
1921 if (bs
->detect_zeroes
== BLOCKDEV_DETECT_ZEROES_OPTIONS_UNMAP
) {
1922 flags
|= BDRV_REQ_MAY_UNMAP
;
1927 /* Do nothing, write notifier decided to fail this request */
1928 } else if (flags
& BDRV_REQ_ZERO_WRITE
) {
1929 bdrv_debug_event(bs
, BLKDBG_PWRITEV_ZERO
);
1930 ret
= bdrv_co_do_pwrite_zeroes(bs
, offset
, bytes
, flags
);
1931 } else if (flags
& BDRV_REQ_WRITE_COMPRESSED
) {
1932 ret
= bdrv_driver_pwritev_compressed(bs
, offset
, bytes
,
1934 } else if (bytes
<= max_transfer
) {
1935 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1936 ret
= bdrv_driver_pwritev(bs
, offset
, bytes
, qiov
, qiov_offset
, flags
);
1938 bdrv_debug_event(bs
, BLKDBG_PWRITEV
);
1939 while (bytes_remaining
) {
1940 int num
= MIN(bytes_remaining
, max_transfer
);
1941 int local_flags
= flags
;
1944 if (num
< bytes_remaining
&& (flags
& BDRV_REQ_FUA
) &&
1945 !(bs
->supported_write_flags
& BDRV_REQ_FUA
)) {
1946 /* If FUA is going to be emulated by flush, we only
1947 * need to flush on the last iteration */
1948 local_flags
&= ~BDRV_REQ_FUA
;
1951 ret
= bdrv_driver_pwritev(bs
, offset
+ bytes
- bytes_remaining
,
1953 qiov_offset
+ bytes
- bytes_remaining
,
1958 bytes_remaining
-= num
;
1961 bdrv_debug_event(bs
, BLKDBG_PWRITEV_DONE
);
1966 bdrv_co_write_req_finish(child
, offset
, bytes
, req
, ret
);
1971 static int coroutine_fn
bdrv_co_do_zero_pwritev(BdrvChild
*child
,
1974 BdrvRequestFlags flags
,
1975 BdrvTrackedRequest
*req
)
1977 BlockDriverState
*bs
= child
->bs
;
1978 QEMUIOVector local_qiov
;
1979 uint64_t align
= bs
->bl
.request_alignment
;
1982 BdrvRequestPadding pad
;
1984 padding
= bdrv_init_padding(bs
, offset
, bytes
, &pad
);
1986 bdrv_mark_request_serialising(req
, align
);
1988 bdrv_padding_rmw_read(child
, req
, &pad
, true);
1990 if (pad
.head
|| pad
.merge_reads
) {
1991 int64_t aligned_offset
= offset
& ~(align
- 1);
1992 int64_t write_bytes
= pad
.merge_reads
? pad
.buf_len
: align
;
1994 qemu_iovec_init_buf(&local_qiov
, pad
.buf
, write_bytes
);
1995 ret
= bdrv_aligned_pwritev(child
, req
, aligned_offset
, write_bytes
,
1996 align
, &local_qiov
, 0,
1997 flags
& ~BDRV_REQ_ZERO_WRITE
);
1998 if (ret
< 0 || pad
.merge_reads
) {
1999 /* Error or all work is done */
2002 offset
+= write_bytes
- pad
.head
;
2003 bytes
-= write_bytes
- pad
.head
;
2007 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2008 if (bytes
>= align
) {
2009 /* Write the aligned part in the middle. */
2010 uint64_t aligned_bytes
= bytes
& ~(align
- 1);
2011 ret
= bdrv_aligned_pwritev(child
, req
, offset
, aligned_bytes
, align
,
2016 bytes
-= aligned_bytes
;
2017 offset
+= aligned_bytes
;
2020 assert(!bytes
|| (offset
& (align
- 1)) == 0);
2022 assert(align
== pad
.tail
+ bytes
);
2024 qemu_iovec_init_buf(&local_qiov
, pad
.tail_buf
, align
);
2025 ret
= bdrv_aligned_pwritev(child
, req
, offset
, align
, align
,
2027 flags
& ~BDRV_REQ_ZERO_WRITE
);
2031 bdrv_padding_destroy(&pad
);
2037 * Handle a write request in coroutine context
2039 int coroutine_fn
bdrv_co_pwritev(BdrvChild
*child
,
2040 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
,
2041 BdrvRequestFlags flags
)
2043 return bdrv_co_pwritev_part(child
, offset
, bytes
, qiov
, 0, flags
);
2046 int coroutine_fn
bdrv_co_pwritev_part(BdrvChild
*child
,
2047 int64_t offset
, unsigned int bytes
, QEMUIOVector
*qiov
, size_t qiov_offset
,
2048 BdrvRequestFlags flags
)
2050 BlockDriverState
*bs
= child
->bs
;
2051 BdrvTrackedRequest req
;
2052 uint64_t align
= bs
->bl
.request_alignment
;
2053 BdrvRequestPadding pad
;
2056 trace_bdrv_co_pwritev(child
->bs
, offset
, bytes
, flags
);
2062 ret
= bdrv_check_byte_request(bs
, offset
, bytes
);
2067 /* If the request is misaligned then we can't make it efficient */
2068 if ((flags
& BDRV_REQ_NO_FALLBACK
) &&
2069 !QEMU_IS_ALIGNED(offset
| bytes
, align
))
2074 if (bytes
== 0 && !QEMU_IS_ALIGNED(offset
, bs
->bl
.request_alignment
)) {
2076 * Aligning zero request is nonsense. Even if driver has special meaning
2077 * of zero-length (like qcow2_co_pwritev_compressed_part), we can't pass
2078 * it to driver due to request_alignment.
2080 * Still, no reason to return an error if someone do unaligned
2081 * zero-length write occasionally.
2086 bdrv_inc_in_flight(bs
);
2088 * Align write if necessary by performing a read-modify-write cycle.
2089 * Pad qiov with the read parts and be sure to have a tracked request not
2090 * only for bdrv_aligned_pwritev, but also for the reads of the RMW cycle.
2092 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_WRITE
);
2094 if (flags
& BDRV_REQ_ZERO_WRITE
) {
2095 ret
= bdrv_co_do_zero_pwritev(child
, offset
, bytes
, flags
, &req
);
2099 if (bdrv_pad_request(bs
, &qiov
, &qiov_offset
, &offset
, &bytes
, &pad
)) {
2100 bdrv_mark_request_serialising(&req
, align
);
2101 bdrv_padding_rmw_read(child
, &req
, &pad
, false);
2104 ret
= bdrv_aligned_pwritev(child
, &req
, offset
, bytes
, align
,
2105 qiov
, qiov_offset
, flags
);
2107 bdrv_padding_destroy(&pad
);
2110 tracked_request_end(&req
);
2111 bdrv_dec_in_flight(bs
);
2116 int coroutine_fn
bdrv_co_pwrite_zeroes(BdrvChild
*child
, int64_t offset
,
2117 int bytes
, BdrvRequestFlags flags
)
2119 trace_bdrv_co_pwrite_zeroes(child
->bs
, offset
, bytes
, flags
);
2121 if (!(child
->bs
->open_flags
& BDRV_O_UNMAP
)) {
2122 flags
&= ~BDRV_REQ_MAY_UNMAP
;
2125 return bdrv_co_pwritev(child
, offset
, bytes
, NULL
,
2126 BDRV_REQ_ZERO_WRITE
| flags
);
2130 * Flush ALL BDSes regardless of if they are reachable via a BlkBackend or not.
2132 int bdrv_flush_all(void)
2134 BdrvNextIterator it
;
2135 BlockDriverState
*bs
= NULL
;
2139 * bdrv queue is managed by record/replay,
2140 * creating new flush request for stopping
2141 * the VM may break the determinism
2143 if (replay_events_enabled()) {
2147 for (bs
= bdrv_first(&it
); bs
; bs
= bdrv_next(&it
)) {
2148 AioContext
*aio_context
= bdrv_get_aio_context(bs
);
2151 aio_context_acquire(aio_context
);
2152 ret
= bdrv_flush(bs
);
2153 if (ret
< 0 && !result
) {
2156 aio_context_release(aio_context
);
2163 * Returns the allocation status of the specified sectors.
2164 * Drivers not implementing the functionality are assumed to not support
2165 * backing files, hence all their sectors are reported as allocated.
2167 * If 'want_zero' is true, the caller is querying for mapping
2168 * purposes, with a focus on valid BDRV_BLOCK_OFFSET_VALID, _DATA, and
2169 * _ZERO where possible; otherwise, the result favors larger 'pnum',
2170 * with a focus on accurate BDRV_BLOCK_ALLOCATED.
2172 * If 'offset' is beyond the end of the disk image the return value is
2173 * BDRV_BLOCK_EOF and 'pnum' is set to 0.
2175 * 'bytes' is the max value 'pnum' should be set to. If bytes goes
2176 * beyond the end of the disk image it will be clamped; if 'pnum' is set to
2177 * the end of the image, then the returned value will include BDRV_BLOCK_EOF.
2179 * 'pnum' is set to the number of bytes (including and immediately
2180 * following the specified offset) that are easily known to be in the
2181 * same allocated/unallocated state. Note that a second call starting
2182 * at the original offset plus returned pnum may have the same status.
2183 * The returned value is non-zero on success except at end-of-file.
2185 * Returns negative errno on failure. Otherwise, if the
2186 * BDRV_BLOCK_OFFSET_VALID bit is set, 'map' and 'file' (if non-NULL) are
2187 * set to the host mapping and BDS corresponding to the guest offset.
2189 static int coroutine_fn
bdrv_co_block_status(BlockDriverState
*bs
,
2191 int64_t offset
, int64_t bytes
,
2192 int64_t *pnum
, int64_t *map
,
2193 BlockDriverState
**file
)
2196 int64_t n
; /* bytes */
2198 int64_t local_map
= 0;
2199 BlockDriverState
*local_file
= NULL
;
2200 int64_t aligned_offset
, aligned_bytes
;
2202 bool has_filtered_child
;
2206 total_size
= bdrv_getlength(bs
);
2207 if (total_size
< 0) {
2212 if (offset
>= total_size
) {
2213 ret
= BDRV_BLOCK_EOF
;
2221 n
= total_size
- offset
;
2226 /* Must be non-NULL or bdrv_getlength() would have failed */
2228 has_filtered_child
= bdrv_filter_child(bs
);
2229 if (!bs
->drv
->bdrv_co_block_status
&& !has_filtered_child
) {
2231 ret
= BDRV_BLOCK_DATA
| BDRV_BLOCK_ALLOCATED
;
2232 if (offset
+ bytes
== total_size
) {
2233 ret
|= BDRV_BLOCK_EOF
;
2235 if (bs
->drv
->protocol_name
) {
2236 ret
|= BDRV_BLOCK_OFFSET_VALID
;
2243 bdrv_inc_in_flight(bs
);
2245 /* Round out to request_alignment boundaries */
2246 align
= bs
->bl
.request_alignment
;
2247 aligned_offset
= QEMU_ALIGN_DOWN(offset
, align
);
2248 aligned_bytes
= ROUND_UP(offset
+ bytes
, align
) - aligned_offset
;
2250 if (bs
->drv
->bdrv_co_block_status
) {
2251 ret
= bs
->drv
->bdrv_co_block_status(bs
, want_zero
, aligned_offset
,
2252 aligned_bytes
, pnum
, &local_map
,
2255 /* Default code for filters */
2257 local_file
= bdrv_filter_bs(bs
);
2260 *pnum
= aligned_bytes
;
2261 local_map
= aligned_offset
;
2262 ret
= BDRV_BLOCK_RAW
| BDRV_BLOCK_OFFSET_VALID
;
2270 * The driver's result must be a non-zero multiple of request_alignment.
2271 * Clamp pnum and adjust map to original request.
2273 assert(*pnum
&& QEMU_IS_ALIGNED(*pnum
, align
) &&
2274 align
> offset
- aligned_offset
);
2275 if (ret
& BDRV_BLOCK_RECURSE
) {
2276 assert(ret
& BDRV_BLOCK_DATA
);
2277 assert(ret
& BDRV_BLOCK_OFFSET_VALID
);
2278 assert(!(ret
& BDRV_BLOCK_ZERO
));
2281 *pnum
-= offset
- aligned_offset
;
2282 if (*pnum
> bytes
) {
2285 if (ret
& BDRV_BLOCK_OFFSET_VALID
) {
2286 local_map
+= offset
- aligned_offset
;
2289 if (ret
& BDRV_BLOCK_RAW
) {
2290 assert(ret
& BDRV_BLOCK_OFFSET_VALID
&& local_file
);
2291 ret
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2292 *pnum
, pnum
, &local_map
, &local_file
);
2296 if (ret
& (BDRV_BLOCK_DATA
| BDRV_BLOCK_ZERO
)) {
2297 ret
|= BDRV_BLOCK_ALLOCATED
;
2298 } else if (bs
->drv
->supports_backing
) {
2299 BlockDriverState
*cow_bs
= bdrv_cow_bs(bs
);
2302 ret
|= BDRV_BLOCK_ZERO
;
2303 } else if (want_zero
) {
2304 int64_t size2
= bdrv_getlength(cow_bs
);
2306 if (size2
>= 0 && offset
>= size2
) {
2307 ret
|= BDRV_BLOCK_ZERO
;
2312 if (want_zero
&& ret
& BDRV_BLOCK_RECURSE
&&
2313 local_file
&& local_file
!= bs
&&
2314 (ret
& BDRV_BLOCK_DATA
) && !(ret
& BDRV_BLOCK_ZERO
) &&
2315 (ret
& BDRV_BLOCK_OFFSET_VALID
)) {
2319 ret2
= bdrv_co_block_status(local_file
, want_zero
, local_map
,
2320 *pnum
, &file_pnum
, NULL
, NULL
);
2322 /* Ignore errors. This is just providing extra information, it
2323 * is useful but not necessary.
2325 if (ret2
& BDRV_BLOCK_EOF
&&
2326 (!file_pnum
|| ret2
& BDRV_BLOCK_ZERO
)) {
2328 * It is valid for the format block driver to read
2329 * beyond the end of the underlying file's current
2330 * size; such areas read as zero.
2332 ret
|= BDRV_BLOCK_ZERO
;
2334 /* Limit request to the range reported by the protocol driver */
2336 ret
|= (ret2
& BDRV_BLOCK_ZERO
);
2342 bdrv_dec_in_flight(bs
);
2343 if (ret
>= 0 && offset
+ *pnum
== total_size
) {
2344 ret
|= BDRV_BLOCK_EOF
;
2357 bdrv_co_common_block_status_above(BlockDriverState
*bs
,
2358 BlockDriverState
*base
,
2365 BlockDriverState
**file
)
2368 BlockDriverState
*p
;
2371 assert(!include_base
|| base
); /* Can't include NULL base */
2373 if (!include_base
&& bs
== base
) {
2378 ret
= bdrv_co_block_status(bs
, want_zero
, offset
, bytes
, pnum
, map
, file
);
2379 if (ret
< 0 || *pnum
== 0 || ret
& BDRV_BLOCK_ALLOCATED
|| bs
== base
) {
2383 if (ret
& BDRV_BLOCK_EOF
) {
2384 eof
= offset
+ *pnum
;
2387 assert(*pnum
<= bytes
);
2390 for (p
= bdrv_filter_or_cow_bs(bs
); include_base
|| p
!= base
;
2391 p
= bdrv_filter_or_cow_bs(p
))
2393 ret
= bdrv_co_block_status(p
, want_zero
, offset
, bytes
, pnum
, map
,
2400 * The top layer deferred to this layer, and because this layer is
2401 * short, any zeroes that we synthesize beyond EOF behave as if they
2402 * were allocated at this layer.
2404 * We don't include BDRV_BLOCK_EOF into ret, as upper layer may be
2405 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2408 assert(ret
& BDRV_BLOCK_EOF
);
2413 ret
= BDRV_BLOCK_ZERO
| BDRV_BLOCK_ALLOCATED
;
2416 if (ret
& BDRV_BLOCK_ALLOCATED
) {
2418 * We've found the node and the status, we must break.
2420 * Drop BDRV_BLOCK_EOF, as it's not for upper layer, which may be
2421 * larger. We'll add BDRV_BLOCK_EOF if needed at function end, see
2424 ret
&= ~BDRV_BLOCK_EOF
;
2429 assert(include_base
);
2434 * OK, [offset, offset + *pnum) region is unallocated on this layer,
2435 * let's continue the diving.
2437 assert(*pnum
<= bytes
);
2441 if (offset
+ *pnum
== eof
) {
2442 ret
|= BDRV_BLOCK_EOF
;
2448 int bdrv_block_status_above(BlockDriverState
*bs
, BlockDriverState
*base
,
2449 int64_t offset
, int64_t bytes
, int64_t *pnum
,
2450 int64_t *map
, BlockDriverState
**file
)
2452 return bdrv_common_block_status_above(bs
, base
, false, true, offset
, bytes
,
2456 int bdrv_block_status(BlockDriverState
*bs
, int64_t offset
, int64_t bytes
,
2457 int64_t *pnum
, int64_t *map
, BlockDriverState
**file
)
2459 return bdrv_block_status_above(bs
, bdrv_filter_or_cow_bs(bs
),
2460 offset
, bytes
, pnum
, map
, file
);
2464 * Check @bs (and its backing chain) to see if the range defined
2465 * by @offset and @bytes is known to read as zeroes.
2466 * Return 1 if that is the case, 0 otherwise and -errno on error.
2467 * This test is meant to be fast rather than accurate so returning 0
2468 * does not guarantee non-zero data.
2470 int coroutine_fn
bdrv_co_is_zero_fast(BlockDriverState
*bs
, int64_t offset
,
2474 int64_t pnum
= bytes
;
2480 ret
= bdrv_common_block_status_above(bs
, NULL
, false, false, offset
,
2481 bytes
, &pnum
, NULL
, NULL
);
2487 return (pnum
== bytes
) && (ret
& BDRV_BLOCK_ZERO
);
2490 int coroutine_fn
bdrv_is_allocated(BlockDriverState
*bs
, int64_t offset
,
2491 int64_t bytes
, int64_t *pnum
)
2496 ret
= bdrv_common_block_status_above(bs
, bs
, true, false, offset
,
2497 bytes
, pnum
? pnum
: &dummy
, NULL
,
2502 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2506 * Given an image chain: ... -> [BASE] -> [INTER1] -> [INTER2] -> [TOP]
2508 * Return 1 if (a prefix of) the given range is allocated in any image
2509 * between BASE and TOP (BASE is only included if include_base is set).
2510 * BASE can be NULL to check if the given offset is allocated in any
2511 * image of the chain. Return 0 otherwise, or negative errno on
2514 * 'pnum' is set to the number of bytes (including and immediately
2515 * following the specified offset) that are known to be in the same
2516 * allocated/unallocated state. Note that a subsequent call starting
2517 * at 'offset + *pnum' may return the same allocation status (in other
2518 * words, the result is not necessarily the maximum possible range);
2519 * but 'pnum' will only be 0 when end of file is reached.
2521 int bdrv_is_allocated_above(BlockDriverState
*top
,
2522 BlockDriverState
*base
,
2523 bool include_base
, int64_t offset
,
2524 int64_t bytes
, int64_t *pnum
)
2526 int ret
= bdrv_common_block_status_above(top
, base
, include_base
, false,
2527 offset
, bytes
, pnum
, NULL
, NULL
);
2532 return !!(ret
& BDRV_BLOCK_ALLOCATED
);
2536 bdrv_co_readv_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2538 BlockDriver
*drv
= bs
->drv
;
2539 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2546 bdrv_inc_in_flight(bs
);
2548 if (drv
->bdrv_load_vmstate
) {
2549 ret
= drv
->bdrv_load_vmstate(bs
, qiov
, pos
);
2550 } else if (child_bs
) {
2551 ret
= bdrv_co_readv_vmstate(child_bs
, qiov
, pos
);
2554 bdrv_dec_in_flight(bs
);
2560 bdrv_co_writev_vmstate(BlockDriverState
*bs
, QEMUIOVector
*qiov
, int64_t pos
)
2562 BlockDriver
*drv
= bs
->drv
;
2563 BlockDriverState
*child_bs
= bdrv_primary_bs(bs
);
2570 bdrv_inc_in_flight(bs
);
2572 if (drv
->bdrv_save_vmstate
) {
2573 ret
= drv
->bdrv_save_vmstate(bs
, qiov
, pos
);
2574 } else if (child_bs
) {
2575 ret
= bdrv_co_writev_vmstate(child_bs
, qiov
, pos
);
2578 bdrv_dec_in_flight(bs
);
2583 int bdrv_save_vmstate(BlockDriverState
*bs
, const uint8_t *buf
,
2584 int64_t pos
, int size
)
2586 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2587 int ret
= bdrv_writev_vmstate(bs
, &qiov
, pos
);
2589 return ret
< 0 ? ret
: size
;
2592 int bdrv_load_vmstate(BlockDriverState
*bs
, uint8_t *buf
,
2593 int64_t pos
, int size
)
2595 QEMUIOVector qiov
= QEMU_IOVEC_INIT_BUF(qiov
, buf
, size
);
2596 int ret
= bdrv_readv_vmstate(bs
, &qiov
, pos
);
2598 return ret
< 0 ? ret
: size
;
2601 /**************************************************************/
2604 void bdrv_aio_cancel(BlockAIOCB
*acb
)
2607 bdrv_aio_cancel_async(acb
);
2608 while (acb
->refcnt
> 1) {
2609 if (acb
->aiocb_info
->get_aio_context
) {
2610 aio_poll(acb
->aiocb_info
->get_aio_context(acb
), true);
2611 } else if (acb
->bs
) {
2612 /* qemu_aio_ref and qemu_aio_unref are not thread-safe, so
2613 * assert that we're not using an I/O thread. Thread-safe
2614 * code should use bdrv_aio_cancel_async exclusively.
2616 assert(bdrv_get_aio_context(acb
->bs
) == qemu_get_aio_context());
2617 aio_poll(bdrv_get_aio_context(acb
->bs
), true);
2622 qemu_aio_unref(acb
);
2625 /* Async version of aio cancel. The caller is not blocked if the acb implements
2626 * cancel_async, otherwise we do nothing and let the request normally complete.
2627 * In either case the completion callback must be called. */
2628 void bdrv_aio_cancel_async(BlockAIOCB
*acb
)
2630 if (acb
->aiocb_info
->cancel_async
) {
2631 acb
->aiocb_info
->cancel_async(acb
);
2635 /**************************************************************/
2636 /* Coroutine block device emulation */
2638 int coroutine_fn
bdrv_co_flush(BlockDriverState
*bs
)
2640 BdrvChild
*primary_child
= bdrv_primary_child(bs
);
2645 bdrv_inc_in_flight(bs
);
2647 if (!bdrv_is_inserted(bs
) || bdrv_is_read_only(bs
) ||
2652 qemu_co_mutex_lock(&bs
->reqs_lock
);
2653 current_gen
= qatomic_read(&bs
->write_gen
);
2655 /* Wait until any previous flushes are completed */
2656 while (bs
->active_flush_req
) {
2657 qemu_co_queue_wait(&bs
->flush_queue
, &bs
->reqs_lock
);
2660 /* Flushes reach this point in nondecreasing current_gen order. */
2661 bs
->active_flush_req
= true;
2662 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2664 /* Write back all layers by calling one driver function */
2665 if (bs
->drv
->bdrv_co_flush
) {
2666 ret
= bs
->drv
->bdrv_co_flush(bs
);
2670 /* Write back cached data to the OS even with cache=unsafe */
2671 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_OS
);
2672 if (bs
->drv
->bdrv_co_flush_to_os
) {
2673 ret
= bs
->drv
->bdrv_co_flush_to_os(bs
);
2679 /* But don't actually force it to the disk with cache=unsafe */
2680 if (bs
->open_flags
& BDRV_O_NO_FLUSH
) {
2681 goto flush_children
;
2684 /* Check if we really need to flush anything */
2685 if (bs
->flushed_gen
== current_gen
) {
2686 goto flush_children
;
2689 BLKDBG_EVENT(primary_child
, BLKDBG_FLUSH_TO_DISK
);
2691 /* bs->drv->bdrv_co_flush() might have ejected the BDS
2692 * (even in case of apparent success) */
2696 if (bs
->drv
->bdrv_co_flush_to_disk
) {
2697 ret
= bs
->drv
->bdrv_co_flush_to_disk(bs
);
2698 } else if (bs
->drv
->bdrv_aio_flush
) {
2700 CoroutineIOCompletion co
= {
2701 .coroutine
= qemu_coroutine_self(),
2704 acb
= bs
->drv
->bdrv_aio_flush(bs
, bdrv_co_io_em_complete
, &co
);
2708 qemu_coroutine_yield();
2713 * Some block drivers always operate in either writethrough or unsafe
2714 * mode and don't support bdrv_flush therefore. Usually qemu doesn't
2715 * know how the server works (because the behaviour is hardcoded or
2716 * depends on server-side configuration), so we can't ensure that
2717 * everything is safe on disk. Returning an error doesn't work because
2718 * that would break guests even if the server operates in writethrough
2721 * Let's hope the user knows what he's doing.
2730 /* Now flush the underlying protocol. It will also have BDRV_O_NO_FLUSH
2731 * in the case of cache=unsafe, so there are no useless flushes.
2735 QLIST_FOREACH(child
, &bs
->children
, next
) {
2736 if (child
->perm
& (BLK_PERM_WRITE
| BLK_PERM_WRITE_UNCHANGED
)) {
2737 int this_child_ret
= bdrv_co_flush(child
->bs
);
2739 ret
= this_child_ret
;
2745 /* Notify any pending flushes that we have completed */
2747 bs
->flushed_gen
= current_gen
;
2750 qemu_co_mutex_lock(&bs
->reqs_lock
);
2751 bs
->active_flush_req
= false;
2752 /* Return value is ignored - it's ok if wait queue is empty */
2753 qemu_co_queue_next(&bs
->flush_queue
);
2754 qemu_co_mutex_unlock(&bs
->reqs_lock
);
2757 bdrv_dec_in_flight(bs
);
2761 int coroutine_fn
bdrv_co_pdiscard(BdrvChild
*child
, int64_t offset
,
2764 BdrvTrackedRequest req
;
2765 int max_pdiscard
, ret
;
2766 int head
, tail
, align
;
2767 BlockDriverState
*bs
= child
->bs
;
2769 if (!bs
|| !bs
->drv
|| !bdrv_is_inserted(bs
)) {
2773 if (bdrv_has_readonly_bitmaps(bs
)) {
2777 if (offset
< 0 || bytes
< 0 || bytes
> INT64_MAX
- offset
) {
2781 /* Do nothing if disabled. */
2782 if (!(bs
->open_flags
& BDRV_O_UNMAP
)) {
2786 if (!bs
->drv
->bdrv_co_pdiscard
&& !bs
->drv
->bdrv_aio_pdiscard
) {
2790 /* Discard is advisory, but some devices track and coalesce
2791 * unaligned requests, so we must pass everything down rather than
2792 * round here. Still, most devices will just silently ignore
2793 * unaligned requests (by returning -ENOTSUP), so we must fragment
2794 * the request accordingly. */
2795 align
= MAX(bs
->bl
.pdiscard_alignment
, bs
->bl
.request_alignment
);
2796 assert(align
% bs
->bl
.request_alignment
== 0);
2797 head
= offset
% align
;
2798 tail
= (offset
+ bytes
) % align
;
2800 bdrv_inc_in_flight(bs
);
2801 tracked_request_begin(&req
, bs
, offset
, bytes
, BDRV_TRACKED_DISCARD
);
2803 ret
= bdrv_co_write_req_prepare(child
, offset
, bytes
, &req
, 0);
2808 max_pdiscard
= QEMU_ALIGN_DOWN(MIN_NON_ZERO(bs
->bl
.max_pdiscard
, INT_MAX
),
2810 assert(max_pdiscard
>= bs
->bl
.request_alignment
);
2813 int64_t num
= bytes
;
2816 /* Make small requests to get to alignment boundaries. */
2817 num
= MIN(bytes
, align
- head
);
2818 if (!QEMU_IS_ALIGNED(num
, bs
->bl
.request_alignment
)) {
2819 num
%= bs
->bl
.request_alignment
;
2821 head
= (head
+ num
) % align
;
2822 assert(num
< max_pdiscard
);
2825 /* Shorten the request to the last aligned cluster. */
2827 } else if (!QEMU_IS_ALIGNED(tail
, bs
->bl
.request_alignment
) &&
2828 tail
> bs
->bl
.request_alignment
) {
2829 tail
%= bs
->bl
.request_alignment
;
2833 /* limit request size */
2834 if (num
> max_pdiscard
) {
2842 if (bs
->drv
->bdrv_co_pdiscard
) {
2843 ret
= bs
->drv
->bdrv_co_pdiscard(bs
, offset
, num
);
2846 CoroutineIOCompletion co
= {
2847 .coroutine
= qemu_coroutine_self(),
2850 acb
= bs
->drv
->bdrv_aio_pdiscard(bs
, offset
, num
,
2851 bdrv_co_io_em_complete
, &co
);
2856 qemu_coroutine_yield();
2860 if (ret
&& ret
!= -ENOTSUP
) {
2869 bdrv_co_write_req_finish(child
, req
.offset
, req
.bytes
, &req
, ret
);
2870 tracked_request_end(&req
);
2871 bdrv_dec_in_flight(bs
);
2875 int bdrv_co_ioctl(BlockDriverState
*bs
, int req
, void *buf
)
2877 BlockDriver
*drv
= bs
->drv
;
2878 CoroutineIOCompletion co
= {
2879 .coroutine
= qemu_coroutine_self(),
2883 bdrv_inc_in_flight(bs
);
2884 if (!drv
|| (!drv
->bdrv_aio_ioctl
&& !drv
->bdrv_co_ioctl
)) {
2889 if (drv
->bdrv_co_ioctl
) {
2890 co
.ret
= drv
->bdrv_co_ioctl(bs
, req
, buf
);
2892 acb
= drv
->bdrv_aio_ioctl(bs
, req
, buf
, bdrv_co_io_em_complete
, &co
);
2897 qemu_coroutine_yield();
2900 bdrv_dec_in_flight(bs
);
2904 void *qemu_blockalign(BlockDriverState
*bs
, size_t size
)
2906 return qemu_memalign(bdrv_opt_mem_align(bs
), size
);
2909 void *qemu_blockalign0(BlockDriverState
*bs
, size_t size
)
2911 return memset(qemu_blockalign(bs
, size
), 0, size
);
2914 void *qemu_try_blockalign(BlockDriverState
*bs
, size_t size
)
2916 size_t align
= bdrv_opt_mem_align(bs
);
2918 /* Ensure that NULL is never returned on success */
2924 return qemu_try_memalign(align
, size
);
2927 void *qemu_try_blockalign0(BlockDriverState
*bs
, size_t size
)
2929 void *mem
= qemu_try_blockalign(bs
, size
);
2932 memset(mem
, 0, size
);
2939 * Check if all memory in this vector is sector aligned.
2941 bool bdrv_qiov_is_aligned(BlockDriverState
*bs
, QEMUIOVector
*qiov
)
2944 size_t alignment
= bdrv_min_mem_align(bs
);
2946 for (i
= 0; i
< qiov
->niov
; i
++) {
2947 if ((uintptr_t) qiov
->iov
[i
].iov_base
% alignment
) {
2950 if (qiov
->iov
[i
].iov_len
% alignment
) {
2958 void bdrv_add_before_write_notifier(BlockDriverState
*bs
,
2959 NotifierWithReturn
*notifier
)
2961 notifier_with_return_list_add(&bs
->before_write_notifiers
, notifier
);
2964 void bdrv_io_plug(BlockDriverState
*bs
)
2968 QLIST_FOREACH(child
, &bs
->children
, next
) {
2969 bdrv_io_plug(child
->bs
);
2972 if (qatomic_fetch_inc(&bs
->io_plugged
) == 0) {
2973 BlockDriver
*drv
= bs
->drv
;
2974 if (drv
&& drv
->bdrv_io_plug
) {
2975 drv
->bdrv_io_plug(bs
);
2980 void bdrv_io_unplug(BlockDriverState
*bs
)
2984 assert(bs
->io_plugged
);
2985 if (qatomic_fetch_dec(&bs
->io_plugged
) == 1) {
2986 BlockDriver
*drv
= bs
->drv
;
2987 if (drv
&& drv
->bdrv_io_unplug
) {
2988 drv
->bdrv_io_unplug(bs
);
2992 QLIST_FOREACH(child
, &bs
->children
, next
) {
2993 bdrv_io_unplug(child
->bs
);
2997 void bdrv_register_buf(BlockDriverState
*bs
, void *host
, size_t size
)
3001 if (bs
->drv
&& bs
->drv
->bdrv_register_buf
) {
3002 bs
->drv
->bdrv_register_buf(bs
, host
, size
);
3004 QLIST_FOREACH(child
, &bs
->children
, next
) {
3005 bdrv_register_buf(child
->bs
, host
, size
);
3009 void bdrv_unregister_buf(BlockDriverState
*bs
, void *host
)
3013 if (bs
->drv
&& bs
->drv
->bdrv_unregister_buf
) {
3014 bs
->drv
->bdrv_unregister_buf(bs
, host
);
3016 QLIST_FOREACH(child
, &bs
->children
, next
) {
3017 bdrv_unregister_buf(child
->bs
, host
);
3021 static int coroutine_fn
bdrv_co_copy_range_internal(
3022 BdrvChild
*src
, uint64_t src_offset
, BdrvChild
*dst
,
3023 uint64_t dst_offset
, uint64_t bytes
,
3024 BdrvRequestFlags read_flags
, BdrvRequestFlags write_flags
,
3027 BdrvTrackedRequest req
;
3030 /* TODO We can support BDRV_REQ_NO_FALLBACK here */
3031 assert(!(read_flags
& BDRV_REQ_NO_FALLBACK
));
3032 assert(!(write_flags
& BDRV_REQ_NO_FALLBACK
));
3034 if (!dst
|| !dst
->bs
) {
3037 ret
= bdrv_check_byte_request(dst
->bs
, dst_offset
, bytes
);
3041 if (write_flags
& BDRV_REQ_ZERO_WRITE
) {
3042 return bdrv_co_pwrite_zeroes(dst
, dst_offset
, bytes
, write_flags
);
3045 if (!src
|| !src
->bs
) {
3048 ret
= bdrv_check_byte_request(src
->bs
, src_offset
, bytes
);
3053 if (!src
->bs
->drv
->bdrv_co_copy_range_from
3054 || !dst
->bs
->drv
->bdrv_co_copy_range_to
3055 || src
->bs
->encrypted
|| dst
->bs
->encrypted
) {
3060 bdrv_inc_in_flight(src
->bs
);
3061 tracked_request_begin(&req
, src
->bs
, src_offset
, bytes
,
3064 /* BDRV_REQ_SERIALISING is only for write operation */
3065 assert(!(read_flags
& BDRV_REQ_SERIALISING
));
3066 bdrv_wait_serialising_requests(&req
);
3068 ret
= src
->bs
->drv
->bdrv_co_copy_range_from(src
->bs
,
3072 read_flags
, write_flags
);
3074 tracked_request_end(&req
);
3075 bdrv_dec_in_flight(src
->bs
);
3077 bdrv_inc_in_flight(dst
->bs
);
3078 tracked_request_begin(&req
, dst
->bs
, dst_offset
, bytes
,
3079 BDRV_TRACKED_WRITE
);
3080 ret
= bdrv_co_write_req_prepare(dst
, dst_offset
, bytes
, &req
,
3083 ret
= dst
->bs
->drv
->bdrv_co_copy_range_to(dst
->bs
,
3087 read_flags
, write_flags
);
3089 bdrv_co_write_req_finish(dst
, dst_offset
, bytes
, &req
, ret
);
3090 tracked_request_end(&req
);
3091 bdrv_dec_in_flight(dst
->bs
);
3097 /* Copy range from @src to @dst.
3099 * See the comment of bdrv_co_copy_range for the parameter and return value
3101 int coroutine_fn
bdrv_co_copy_range_from(BdrvChild
*src
, uint64_t src_offset
,
3102 BdrvChild
*dst
, uint64_t dst_offset
,
3104 BdrvRequestFlags read_flags
,
3105 BdrvRequestFlags write_flags
)
3107 trace_bdrv_co_copy_range_from(src
, src_offset
, dst
, dst_offset
, bytes
,
3108 read_flags
, write_flags
);
3109 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3110 bytes
, read_flags
, write_flags
, true);
3113 /* Copy range from @src to @dst.
3115 * See the comment of bdrv_co_copy_range for the parameter and return value
3117 int coroutine_fn
bdrv_co_copy_range_to(BdrvChild
*src
, uint64_t src_offset
,
3118 BdrvChild
*dst
, uint64_t dst_offset
,
3120 BdrvRequestFlags read_flags
,
3121 BdrvRequestFlags write_flags
)
3123 trace_bdrv_co_copy_range_to(src
, src_offset
, dst
, dst_offset
, bytes
,
3124 read_flags
, write_flags
);
3125 return bdrv_co_copy_range_internal(src
, src_offset
, dst
, dst_offset
,
3126 bytes
, read_flags
, write_flags
, false);
3129 int coroutine_fn
bdrv_co_copy_range(BdrvChild
*src
, uint64_t src_offset
,
3130 BdrvChild
*dst
, uint64_t dst_offset
,
3131 uint64_t bytes
, BdrvRequestFlags read_flags
,
3132 BdrvRequestFlags write_flags
)
3134 return bdrv_co_copy_range_from(src
, src_offset
,
3136 bytes
, read_flags
, write_flags
);
3139 static void bdrv_parent_cb_resize(BlockDriverState
*bs
)
3142 QLIST_FOREACH(c
, &bs
->parents
, next_parent
) {
3143 if (c
->klass
->resize
) {
3144 c
->klass
->resize(c
);
3150 * Truncate file to 'offset' bytes (needed only for file protocols)
3152 * If 'exact' is true, the file must be resized to exactly the given
3153 * 'offset'. Otherwise, it is sufficient for the node to be at least
3154 * 'offset' bytes in length.
3156 int coroutine_fn
bdrv_co_truncate(BdrvChild
*child
, int64_t offset
, bool exact
,
3157 PreallocMode prealloc
, BdrvRequestFlags flags
,
3160 BlockDriverState
*bs
= child
->bs
;
3161 BdrvChild
*filtered
, *backing
;
3162 BlockDriver
*drv
= bs
->drv
;
3163 BdrvTrackedRequest req
;
3164 int64_t old_size
, new_bytes
;
3168 /* if bs->drv == NULL, bs is closed, so there's nothing to do here */
3170 error_setg(errp
, "No medium inserted");
3174 error_setg(errp
, "Image size cannot be negative");
3178 old_size
= bdrv_getlength(bs
);
3180 error_setg_errno(errp
, -old_size
, "Failed to get old image size");
3184 if (offset
> old_size
) {
3185 new_bytes
= offset
- old_size
;
3190 bdrv_inc_in_flight(bs
);
3191 tracked_request_begin(&req
, bs
, offset
- new_bytes
, new_bytes
,
3192 BDRV_TRACKED_TRUNCATE
);
3194 /* If we are growing the image and potentially using preallocation for the
3195 * new area, we need to make sure that no write requests are made to it
3196 * concurrently or they might be overwritten by preallocation. */
3198 bdrv_mark_request_serialising(&req
, 1);
3200 if (bs
->read_only
) {
3201 error_setg(errp
, "Image is read-only");
3205 ret
= bdrv_co_write_req_prepare(child
, offset
- new_bytes
, new_bytes
, &req
,
3208 error_setg_errno(errp
, -ret
,
3209 "Failed to prepare request for truncation");
3213 filtered
= bdrv_filter_child(bs
);
3214 backing
= bdrv_cow_child(bs
);
3217 * If the image has a backing file that is large enough that it would
3218 * provide data for the new area, we cannot leave it unallocated because
3219 * then the backing file content would become visible. Instead, zero-fill
3222 * Note that if the image has a backing file, but was opened without the
3223 * backing file, taking care of keeping things consistent with that backing
3224 * file is the user's responsibility.
3226 if (new_bytes
&& backing
) {
3227 int64_t backing_len
;
3229 backing_len
= bdrv_getlength(backing
->bs
);
3230 if (backing_len
< 0) {
3232 error_setg_errno(errp
, -ret
, "Could not get backing file size");
3236 if (backing_len
> old_size
) {
3237 flags
|= BDRV_REQ_ZERO_WRITE
;
3241 if (drv
->bdrv_co_truncate
) {
3242 if (flags
& ~bs
->supported_truncate_flags
) {
3243 error_setg(errp
, "Block driver does not support requested flags");
3247 ret
= drv
->bdrv_co_truncate(bs
, offset
, exact
, prealloc
, flags
, errp
);
3248 } else if (filtered
) {
3249 ret
= bdrv_co_truncate(filtered
, offset
, exact
, prealloc
, flags
, errp
);
3251 error_setg(errp
, "Image format driver does not support resize");
3259 ret
= refresh_total_sectors(bs
, offset
>> BDRV_SECTOR_BITS
);
3261 error_setg_errno(errp
, -ret
, "Could not refresh total sector count");
3263 offset
= bs
->total_sectors
* BDRV_SECTOR_SIZE
;
3265 /* It's possible that truncation succeeded but refresh_total_sectors
3266 * failed, but the latter doesn't affect how we should finish the request.
3267 * Pass 0 as the last parameter so that dirty bitmaps etc. are handled. */
3268 bdrv_co_write_req_finish(child
, offset
- new_bytes
, new_bytes
, &req
, 0);
3271 tracked_request_end(&req
);
3272 bdrv_dec_in_flight(bs
);